text
stringlengths
14
6.51M
// --- Copyright © 2020 Matias A. P. // --- All rights reserved // --- maperx@gmail.com unit uExcel; interface uses Winapi.Windows, System.SysUtils, Variants, ComObj, System.Classes; type TExcel = class(TObject) private FExcel, FActiveSheet: OleVariant; FFileName: string; FIsNew: Boolean; public constructor Create(const FileName: string = ''); destructor Destroy; override; procedure SetActiveSheet(const Idx: Integer); procedure Save; procedure SaveAs(const FileName: string); function GetCellData(const Row, Col: Integer): OleVariant; overload; function GetCellData(const Cell: string): OleVariant; overload; function GetCellFloat(const Row, Col: Integer): Double; overload; function GetCellFloat(const Cell: string): Double; overload; function GetCellInteger(const Row, Col: Integer): Integer; overload; function GetCellInteger(const Cell: string): Integer; overload; function GetCellDate(const Row, Col: Integer): TDate; overload; function GetCellDate(const Cell: string): TDate; overload; procedure SetCellData(const Row, Col: Integer; Data: OleVariant); overload; procedure SetCellData(const Cell: string; Data: OleVariant); overload; procedure SetColsStrings(const Row, Col: Integer; var Strs: TStringList); procedure SetRowsStrings(const Row, Col: Integer; var Strs: TStringList); procedure SetRangeBold(const Cell1, Cell2: string; Bold: Boolean = True); procedure NextRow; function GetActiveCell: string; published property FullPath: string read FFileName; end; implementation const Worksheet = -4167; constructor TExcel.Create(const FileName: string); begin FExcel := CreateOleObject('Excel.Application'); if VarIsNull(FExcel) then Exit; FExcel.Visible := False; FFileName := FileName; FIsNew := not FileExists(FFileName); if FIsNew then begin FExcel.Workbooks.Add(Worksheet); end else begin FExcel.Workbooks.Open(FFileName); end; SetActiveSheet(1); end; destructor TExcel.Destroy; begin try if not VarIsEmpty(FExcel) then begin FExcel.DisplayAlerts := False; FExcel.Quit; FExcel := Unassigned; FActiveSheet := Unassigned; end; except end; inherited; end; function TExcel.GetActiveCell: string; begin Result := FExcel.ActiveCell.Address; end; function TExcel.GetCellData(const Cell: string): OleVariant; begin REsult := FActiveSheet.Range[Cell].Value; end; function TExcel.GetCellDate(const Row, Col: Integer): TDate; begin REsult := StrToDateDef(FActiveSheet.Cells[Row, Col].Value, -1); end; function TExcel.GetCellDate(const Cell: string): TDate; begin REsult := StrToDateDef(FActiveSheet.Range[Cell].Value, -1); end; function TExcel.GetCellFloat(const Row, Col: Integer): Double; begin REsult := StrToFloatDef(FActiveSheet.Cells[Row, Col].Value, -1); end; function TExcel.GetCellFloat(const Cell: string): Double; begin REsult := StrToFloatDef(FActiveSheet.Range[Cell].Value, -1); end; function TExcel.GetCellInteger(const Cell: string): Integer; begin REsult := -1; try REsult := StrToIntDef(FActiveSheet.Range[Cell].Value, -1); except end; end; function TExcel.GetCellInteger(const Row, Col: Integer): Integer; begin REsult := StrToIntDef(FActiveSheet.Cells[Row, Col].Value, -1); end; procedure TExcel.NextRow; begin FExcel.ActiveCell.Offset(1, 0).Select; end; function TExcel.GetCellData(const Row, Col: Integer): OleVariant; begin REsult := FActiveSheet.Cells[Row, Col].Value; end; procedure TExcel.Save; begin if FFileName = EmptyStr then Exit; try if FIsNew then FExcel.Workbooks[1].SaveAs(FFileName) else FExcel.Workbooks[1].Save; except on E: Exception do raise Exception.Create(E.Message); end; end; procedure TExcel.SaveAs(const FileName: string); begin if FileName = EmptyStr then Exit; try FExcel.Workbooks[1].SaveAs(FileName); FFileName := FileName; except on E: Exception do raise Exception.Create(E.Message); end; end; procedure TExcel.SetActiveSheet(const Idx: Integer); begin FActiveSheet := FExcel.Workbooks[1].WorkSheets[Idx]; end; procedure TExcel.SetCellData(const Cell: string; Data: OleVariant); begin FActiveSheet.Range[Cell].Value := Data; end; procedure TExcel.SetColsStrings(const Row, Col: Integer; var Strs: TStringList); var i: Integer; begin for i := 0 to Strs.Count - 1 do FActiveSheet.Cells[Row, Col + i].Value := Strs[i]; end; procedure TExcel.SetRowsStrings(const Row, Col: Integer; var Strs: TStringList); var i: Integer; begin for i := 0 to Strs.Count - 1 do FActiveSheet.Cells[Row + i, Col].Value := Strs[i]; end; procedure TExcel.SetRangeBold(const Cell1, Cell2: string; Bold: Boolean); begin FActiveSheet.Range[Cell1, Cell2].Font.Bold := Bold; end; procedure TExcel.SetCellData(const Row, Col: Integer; Data: OleVariant); begin FActiveSheet.Cells[Row, Col].Value := Data; end; end.
unit uConexao; interface uses SysUtils,ZAbstractConnection, ZConnection, DB, ZAbstractRODataset, ZAbstractDataset, ZDataset; type TConexao = class private FConn : TZConnection; procedure ConfiguraConexao; public constructor Create; destructor Destroy;override; function GetConn:TZConnection; function CriaQuery:TZQuery; end; implementation { TConexao } procedure TConexao.ConfiguraConexao; begin FConn.Database := 'CURSOBASICO'; FConn.HostName := 'Localhost'; FConn.LibraryLocation:='C:\Windows\SysWOW64\libmysql.dll'; FConn.Port := 3306; FConn.Protocol := 'mysql'; FConn.User := 'root'; FConn.Password := 'cursomysql'; FConn.Connect; end; constructor TConexao.Create; begin FConn := TZConnection.Create(nil); Self.ConfiguraConexao; end; function TConexao.CriaQuery: TZQuery; var VQuery:TZQuery; begin VQuery := TZQuery.Create(nil); VQuery.Connection := GetConn; Result:= VQuery; end; destructor TConexao.Destroy; begin inherited; FConn.Free; end; function TConexao.GetConn: TZConnection; begin Result := FConn; end; end.
//******************************************************************* // // Program Name : AT Library // Platform(s) : Android, iOS, Linux, MacOS, Windows // Framework : Console, FMX, VCL // // Filename : AT.Data.ZRF.pas // Date Created : 22-JUL-2014 // Author : Matthew S. Vesperman // // Description: // // Zipped-Resource-File class. // // Revision History: // // v1.00 : (22-JUL-2014) // Initial version // // v2.00 : (30-OCT-2014) // * Changed to TComponent based class. // + Added file type & version validation capability. // //******************************************************************* // // COPYRIGHT © 2014 Angelic Technology // ALL RIGHTS RESERVED WORLDWIDE // //******************************************************************* /// <summary> /// Defines a class to use resources stored in external Zipped /// Resource Files. /// </summary> unit AT.Data.ZRF; interface uses System.SysUtils, System.Classes, System.Zip; type TATZRF = class(TComponent) strict private FActive: Boolean; FFilename: string; FMsgProc: TProc<String>; FZRFFile: TZipFile; procedure _DoStartMessage(AValue: String); function _GetActive: Boolean; function _GetResourcesLoaded: Boolean; function _GetResourceString(AResourceName: String; AStripSpecialChars: Boolean = True): string; function _StripSpecialChars(AValue: String): string; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure CloseResourceFile; function GetHTMLResourceString(AResourceName: String; AStripSpecialChars: Boolean = True): string; function GetTextResourceString(AResourceName: String; AStripSpecialChars: Boolean = True): string; function GetXMLResourceString(AResourceName: String; AStripSpecialChars: Boolean = True): string; function IsValidZRF(AApp, AVersion: string): Boolean; function LoadResourceFile(AFilename: String): Boolean; function LoadResourceIntoStream(AResourceName: string; var AStream: TStream): Boolean; procedure RegisterStartMessageHandler(AMsgProc: TProc<String>); function ResourceExists(AResourceName: String): Boolean; published property Active: Boolean read _GetActive; property ResourcesLoaded: Boolean read _GetResourcesLoaded; end; var ATZRF: TATZRF; implementation uses AT.GarbageCollector; { ************************************ TATZRF ************************************ } constructor TATZRF.Create(AOwner: TComponent); begin inherited Create(AOwner); FActive := False; FFilename := ''; FZRFFile := TZipFile.Create; end; destructor TATZRF.Destroy; begin FreeAndNil(FZRFFile); inherited Destroy; end; procedure TATZRF.CloseResourceFile; begin if (Assigned(FZRFFile)) then begin FZRFFile.Close; FActive := False; end; end; function TATZRF.GetHTMLResourceString(AResourceName: String; AStripSpecialChars: Boolean = True): string; begin Result := _GetResourceString(AResourceName, AStripSpecialChars); end; function TATZRF.GetTextResourceString(AResourceName: String; AStripSpecialChars: Boolean = True): string; begin Result := _GetResourceString(AResourceName, AStripSpecialChars); end; function TATZRF.GetXMLResourceString(AResourceName: String; AStripSpecialChars: Boolean = True): string; begin Result := _GetResourceString(AResourceName, AStripSpecialChars); end; function TATZRF.IsValidZRF(AApp, AVersion: string): Boolean; var AComment: string; ARecord: TStringList; AGC: IATGarbageCollector; AFileType: string; AAppCode: string; AVer: string; begin Result := ( (Assigned(FZRFFile)) AND (FZRFFile.Comment <> '') ); if (Result) then begin AComment := FZRFFile.Comment; AComment := Trim(AComment); AComment := StringReplace(AComment, #13, '', [rfReplaceAll]); AComment := StringReplace(AComment, #10, '', [rfReplaceAll]); if (AComment = '') then Exit(False); ARecord := TATGC.Collect(TStringList.Create, AGC); ARecord.Delimiter := '|'; ARecord.StrictDelimiter := True; ARecord.DelimitedText := AComment; if (ARecord.IndexOfName('type') < 0) then Exit(False); if (ARecord.IndexOfName('app') < 0) then Exit(False); if (ARecord.IndexOfName('ver') < 0) then Exit(False); AFileType := ARecord.Values['type']; AAppCode := ARecord.Values['app']; AVer := ARecord.Values['ver']; Result := ( (AFileType.ToLower = 'zrf') AND (AAppCode.ToLower = AApp.ToLower) AND (AVer.ToLower = AVersion.ToLower) ); end; end; function TATZRF.LoadResourceFile(AFilename: String): Boolean; begin if (NOT Assigned(FZRFFile)) then Exit(False); if (AFilename = '') then Exit(False); if (NOT FileExists(AFilename)) then Exit(False); if (AFilename = FFilename) then Exit(False); if (NOT FZRFFile.IsValid(AFilename)) then Exit(False); _DoStartMessage('Loading application resources.'); CloseResourceFile; FZRFFile.Open(AFilename, zmRead); FActive := (FZRFFile.Mode <> zmClosed); if (FActive) then FFilename := FFilename else FFilename := ''; Result := FActive; end; function TATZRF.LoadResourceIntoStream(AResourceName: string; var AStream: TStream): Boolean; var ALocalHeader: TZipHeader; begin if (NOT Assigned(AStream)) then Exit(False); if (NOT Active) then Exit(False); if (NOT ResourceExists(AResourceName)) then Exit(False); FZRFFile.Read(AResourceName, AStream, ALocalHeader); Result := True; end; procedure TATZRF.RegisterStartMessageHandler(AMsgProc: TProc<String>); begin FMsgProc := AMsgProc; end; function TATZRF.ResourceExists(AResourceName: String): Boolean; begin if (NOT Active) then Exit(False); if (NOT ResourcesLoaded) then Exit(False); Result := (FZRFFile.IndexOf(AResourceName) > -1); end; procedure TATZRF._DoStartMessage(AValue: String); begin if (Assigned(FMsgProc)) then FMsgProc(AValue); end; function TATZRF._GetActive: Boolean; begin Result := FActive; end; function TATZRF._GetResourcesLoaded: Boolean; begin Result := (Assigned(FZRFFile) AND Active); end; function TATZRF._GetResourceString(AResourceName: String; AStripSpecialChars: Boolean = True): string; var AGC: IATGarbageCollector; AStrm: TStream; ALocalHeader: TZipHeader; begin if (NOT ResourcesLoaded) then Exit(''); if (NOT ResourceExists(AResourceName)) then Exit (''); AStrm := TATGC.Collect(TStringStream.Create(''), AGC); FZRFFile.Read(AResourceName, AStrm, ALocalHeader); if (AStrm.Size <= 0) then Exit(''); AStrm.Seek(0, 0); Result := (AStrm AS TStringStream).DataString; if (AStripSpecialChars) then Result := _StripSpecialChars(Result); end; function TATZRF._StripSpecialChars(AValue: String): string; var ACh: Char; begin Result := ''; for ACh in AValue do begin if ((ACh <> #9) AND (ACh <> #10) AND (ACh <> #13)) then Result := Result + ACh; end; end; initialization ATZRF := TATZRF.Create(NIL); finalization ATZRF.Free; end.
{program : AplikasiListrik.pas deskripsi : Untuk simulasi penginputan data pelanggan listrik dan simulasi tagihan listrik per bulan dalam bahasa Indonesia tanggal : Desember 2016} PROGRAM IF4009_1301164136; USES crt, sysutils; TYPE waktu = record bulan: word; tahun: word; end; tarif = record adm: real; kwh: real; denda: real; reduksi: real; total: real; end; pelanggan = record daya: integer; nama: string; alamat: string; pemakaian: real; kupon: integer; tagihan: tarif; periode: waktu; end; tabel = array of pelanggan; CONST garis='================================================'; adm1=11000; adm2=20000; kwh1=415; kwh2=605; kwh3=790; kwh4=795; kwh5=890; kwh6=1330; dendabulanan=10000; reduk=2000; VAR {Global} tab: tabel; f: file of pelanggan; g: textfile; procedure Boot(); {IS. - FS. Menampilkan splash screen} begin clrscr; writeln(garis); writeln('= ='); writeln('= SELAMAT DATANG DI APLIKASI LISTRIK ='); writeln('= ='); writeln('= Wikan Kuncara Jati ='); writeln('= IF-40-09 ='); writeln('= 1301164136 ='); writeln('= ='); writeln(garis); writeln('Tekan enter...'); readln; end; function kategori(i:integer):string; begin case i of 1: kategori:='450VA'; 2: kategori:='900VA'; 3: kategori:='1300VA'; 4: kategori:='2200VA'; 5: kategori:='3500VA'; 6: kategori:='6600VA'; end; end; procedure printToFile(A: pelanggan); {IS. Terdefinisi data pembayaran pelanggan FS. Menyimpan data pembayaran ke dalam sebuah file .txt} var s: string; begin s:='tagihan.txt'; assign(g,s); rewrite(g); writeln(g,garis); writeln(g,'Nama: : ',A.nama); writeln(g,'Alamat: : ',A.alamat); writeln(g,'Daya Listrik : ',kategori(A.daya)); writeln(g,'Periode: : ',A.periode.bulan,'/',A.periode.tahun); writeln(g,garis); writeln(g,'Rincian Biaya'); writeln(g,garis); writeln(g,'Biaya Administrasi : Rp',A.tagihan.adm:0:2); writeln(g,'Biaya Pemakaian : Rp',A.tagihan.kwh:0:2); writeln(g,'Biaya Denda : Rp',A.tagihan.denda:0:2); writeln(g,'Reduksi Kupon Sampah: Rp',A.tagihan.reduksi:0:2); writeln(g,''); writeln(g,'TOTAL : Rp',A.tagihan.total:0:2); close(g); end; procedure saveToFile(var A: tabel); {IS. Terdefinisi data pelanggan dalam array FS. Mengosongkan file, menyimpan array data pelanggan dalam sebuah file .dat, dan menutup file-nya} var i: integer; temp: pelanggan; begin rewrite(f); for i:=0 to length(A)-1 do begin temp := A[i]; write(f, temp); end; close(f); end; procedure readFromFile(var A: tabel); {IS. - FS. Membuka file .dat yang sudah ada, atau membuat file .dat jika belum ada dan menyimpan datanya ke dalam array pelanggan} var i: integer; temp: pelanggan; begin if fileExists('data.dat') then assign(f,'data.dat') else begin fileCreate('data.dat'); assign(f,'data.dat'); end; reset(f); i:=0; while not eof(f) do begin read(f, temp); setLength(A,i+1); A[i]:= temp; i:=i+1; end; end; function search(nama: string; A: tabel):integer; {IS. Input string yang akan dicari dari array yang akan dicari FS. Jika ketemu maka output nomor indeks data, jika tidak maka output -1} var found: boolean; i: integer; begin i:=0; found:=false; while (i <= length(A)-1) and (not found) do begin if nama = A[i].nama then begin search:=i; found:= true; end else i:= i + 1; end; if not found then begin search:=-1; end; end; function SelisihBulan(bulan,tahun: word):integer; {IS. Terdefinisi bulan dan tahun yang ingin diselisihkan FS. Menghasilkan nilai selisih bulan dalam satuan waktu bulan} var DD,MM,YY: word; begin DeCodeDate (Date,YY,MM,DD); SelisihBulan:=(MM+(12*YY))-(bulan+(12*tahun)); end; procedure hitungTagihan(var A:pelanggan); {IS. Terdefinisi pemakaian listrik seorang pelanggan FS. Menampilkan biaya-biaya yang harus dibayarkan} var telat: integer; opt: char; begin telat:=SelisihBulan(A.periode.bulan, A.periode.tahun); case A.daya of 1: begin A.tagihan.adm:=adm1; A.tagihan.kwh:=kwh1*A.pemakaian; end; 2: begin A.tagihan.adm:=adm2; A.tagihan.kwh:=kwh2*A.pemakaian; end; 3: begin A.tagihan.adm:=0; A.tagihan.kwh:=kwh3*A.pemakaian; end; 4: begin A.tagihan.adm:=0; A.tagihan.kwh:=kwh4*A.pemakaian; end; 5: begin A.tagihan.adm:=0; A.tagihan.kwh:=kwh5*A.pemakaian; end; 6: begin A.tagihan.adm:=0; A.tagihan.kwh:=kwh6*A.pemakaian; end; end; if telat>0 then A.tagihan.denda:=telat*dendabulanan else A.tagihan.denda:=0; if A.kupon>0 then A.tagihan.reduksi:= (-reduk)*A.kupon else A.tagihan.reduksi:= 0; A.tagihan.total := A.tagihan.adm + A.tagihan.kwh + A.tagihan.denda + A.tagihan.reduksi; writeln(garis); writeln('Rincian Biaya'); writeln(garis); writeln('Biaya Administrasi : Rp',A.tagihan.adm:0:2); writeln('Biaya Pemakaian : Rp',A.tagihan.kwh:0:2); writeln('Biaya Denda : Rp',A.tagihan.denda:0:2); writeln('Reduksi Kupon Sampah: Rp',A.tagihan.reduksi:0:2); writeln; writeln('TOTAL : Rp',A.tagihan.total:0:2); repeat write('Apakah anda ingin mencetak struk tagihan ini? (y/n): '); readln(opt); if lowercase(opt) = 'y' then printToFile(A); until (lowercase(opt)='y') or (lowercase(opt)='n'); end; procedure searchData(var A: tabel); {IS. Terdefinisi data pelanggan dalam array dan kata kunci berupa yang akan dicari FS. Output data pelanggan dalam array} var nama: string; i: integer; begin writeln(garis); write('Nama pelanggan yang dicari: '); readln(nama); writeln('Mencari data...'); i:=search(nama,tab); writeln(garis); if i>=0 then begin writeln(nama,' ditemukan pada indeks ke-',i+1); writeln('menampilkan data...'); writeln(garis); writeln('Nama : ',A[i].nama); writeln('Alamat : ',A[i].alamat); writeln('Daya Listrik : ',kategori(A[i].daya)); end else writeln('Nama tidak ditemukan...'); readln; end; procedure sortName(var A: tabel); {IS. Terdefinisi data pelanggan dalam array FS. Mengurutkan data pelanggan dalam array berdasarkan nama pelanggan} var i,pass,ix: integer; temp: pelanggan; opt: char; begin writeln(garis); writeln('Data akan diurutkan berdasarkan nama'); writeln('[1]Dari A-Z'); writeln('[2]Dari Z-A'); write('Masukkan pilihan :'); repeat readln(opt); until (opt='1') or (opt='2'); for pass:=0 to length(A)-2 do begin ix:=pass; for i:=pass+1 to length(A)-1 do begin if (A[i].nama<A[ix].nama) and (opt='1') then ix:=i; if (A[i].nama>A[ix].nama) and (opt='2') then ix:=i; end; temp:=A[pass]; A[pass]:=A[ix]; A[ix]:=temp; end; end; procedure sortGol(var A: tabel); {IS. Terdefinisi data pelanggan dalam array FS. Mengurutkan data pelanggan dalam array berdasarkan golongan listrik pelanggan} var i,pass,ix: integer; temp: pelanggan; opt: char; begin writeln(garis); writeln('Data akan diurutkan berdasarkan golongan'); writeln('[1]Dari besar ke kecil'); writeln('[2]Dari kecil ke besar'); write('Masukkan pilihan: '); repeat readln(opt); until (opt='1') or (opt='2'); for pass:=0 to length(A)-2 do begin ix:=pass; for i:=pass+1 to length(A)-1 do begin if (A[i].daya>A[ix].daya) and (opt='1') then ix:=i; if (A[i].daya<A[ix].daya) and (opt='2') then ix:=i; end; temp:=A[pass]; A[pass]:=A[ix]; A[ix]:=temp; end; end; procedure sortDataOption(opsi: char); {IS. Pilihan dari menu sort FS. Memanggil prosedur yang bersangkutan} begin case opsi of '1': sortName(tab); '2': sortGol(tab); end; end; procedure sortData(var A: tabel); {IS. Terdefinisi data pelanggan dalam array FS. Mengurutkan data pelanggan dalam array} var opsi: char; begin writeln(garis); writeln('[1]Berdasarkan Nama'); writeln('[2]Berdasarkan Golongan'); write('Masukkan pilihan: '); readln(opsi); sortDataOption(opsi); end; procedure editData(var A: tabel); {IS. Terdefinisi data pelanggan dalam array FS. Mengubah data pelanggan dalam array tersebut} var p: char; opsi: integer; temp: pelanggan; begin writeln(garis); writeln('Edit Data'); repeat write('Data yang akan di Edit: '); readln(opsi); until opsi<=length(A); opsi:=opsi-1; repeat write('Nama : '); readln(temp.nama); write('Alamat : '); readln(temp.alamat); writeln('Daya Listrik'); repeat writeln(' 1. 450VA'); writeln(' 2. 900VA'); writeln(' 3. 1300VA'); writeln(' 4. 2200VA'); writeln(' 5. 3500VA'); writeln(' 6. 6600VA'); writeln('Pilih golongan: '); readln(temp.daya); until (temp.daya=1) or (temp.daya=2) or (temp.daya=3) or (temp.daya=4) or (temp.daya=5) or (temp.daya=6); write('Apakah anda yakin dengan inputan anda? [y/n]'); readln(p); until (lowercase(p)='y'); A[opsi]:=temp; end; procedure deleteData(var A: tabel); {IS. Terdefinisi data pelanggan dalam array FS. Menghapus data pelanggan dalam array tersebut} var i,n,opsi: integer; p: char; begin n:=length(A); writeln('Delete Data'); repeat write('Data yang akan dihapus: '); readln(opsi); until(opsi>=1) and (opsi<=length(A)); repeat write('Yakin akan menghapus data no.',opsi,'? (y/n): '); readln(p); until (lowercase(p)='y') or (lowercase(p)='n'); if (lowercase(p)='y') then begin i:=opsi-1; while(i<n-1) do begin if opsi-1<>n-1 then A[i]:=A[i+1]; i:=i+1; end; setlength(A,n-1); end; end; procedure viewMenuOption(pil: char); {IS. Pilihan dari menu view FS. Memanggil prosedur yang bersangkutan} begin case pil of '1' : editData(tab); '2' : deleteData(tab); '3' : sortData(tab); '4' : searchData(tab); end; end; procedure viewBill(var A: tabel); {IS. Terdefinisi data pelanggan dalam array FS. Menyimpan data pemakaian listrik seorang pelanggan} var nama: string; i: integer; p: char; begin clrscr; writeln(garis); writeln('DATA TAGIHAN LISTRIK'); writeln(garis); write('Masukkan Nama : '); readln(nama); i:=search(nama,tab); if i>=0 then begin writeln('Periode Pemakaian'); repeat write(' Bulan (1-12) : '); readln(A[i].periode.bulan); until (A[i].periode.bulan>0) and (A[i].periode.bulan<=12); repeat write(' Tahun : '); readln(A[i].periode.tahun); until (A[i].periode.tahun>2015) and (A[i].periode.tahun<=2020); write('Daya yang terpakai (kWh) : '); readln(A[i].pemakaian); repeat write('Punya kupon sampah? (y/n) : '); readln(p); until (lowercase(p)='y') or (lowercase(p)='n'); if lowercase(p)='y' then begin write('Jumlah kupon yang dimiliki: '); readln(A[i].kupon); end; hitungTagihan(A[i]); end else writeln('Nama tidak ditemukan, kembali ke menu utama...'); readln; end; procedure viewMenu(var A: tabel); {IS. Terdefinisi data pelanggan dalam array FS. Menampilkan data pelanggan} var i: integer; option: char; begin repeat repeat clrscr; for i:=0 to length(A)-1 do begin if (i mod 4 = 0) then begin writeln(garis); writeln('DATA PELANGGAN'); writeln(garis); end; writeln('No. : ',i+1); writeln('Nama : ',A[i].nama); writeln('Alamat : ',A[i].alamat); writeln('Daya Listrik : ',kategori(A[i].daya)); writeln; if ((i+1) mod 4 = 0) then begin writeln(garis); writeln('Hal ',((i div 4)+1),'/',(((length(A)-1) div 4)+1)); writeln(garis); writeln('Tekan [1] menyunting, [2] menghapus,'); writeln('[3] mengurutkan, [4] mencari'); writeln(garis); write('Masukkan pilihan: '); readln(option); viewMenuOption(option); clrscr; end else if (i = length(A)-1) then begin writeln(garis); writeln('Hal ',((i div 4)+1),'/',(((length(A)-1) div 4)+1)); writeln(garis); writeln('Tekan [1] menyunting, [2] menghapus,'); writeln('[3] mengurutkan, [4] mencari, [5] menu utama'); writeln(garis); write('Masukkan pilihan: '); readln(option); viewMenuOption(option); clrscr; end; end; until (option='1') or (option='2') or (option='3') or (option='4') or (option='5'); until (option='5') end; procedure inputMenu(var A: tabel); {IS. - FS. Menyimpan data pelanggan pada array} var N: integer; begin clrscr; N:=length(A); setlength(A,N+1); writeln(garis); writeln('INPUT DATA'); writeln(garis); write('Nama : '); readln(A[N].nama); write('Alamat : '); readln(A[N].alamat); writeln('Daya Listrik'); repeat writeln(' 1. 450VA'); writeln(' 2. 900VA'); writeln(' 3. 1300VA'); writeln(' 4. 2200VA'); writeln(' 5. 3500VA'); writeln(' 6. 6600VA'); writeln('Pilih golongan: '); readln(A[N].daya); until (A[N].daya=1) or (A[N].daya=2) or (A[N].daya=3) or (A[N].daya=4) or (A[N].daya=5) or (A[N].daya=6); write('Data berhasil ditambahkan...'); readln; end; procedure optionMenu(opsi:integer); {IS. Pilihan dari menu utama FS. Memanggil prosedur yang bersangkutan} begin case opsi of 1: inputMenu(tab); 2: viewMenu(tab); 3: viewBill(tab); end; end; procedure mainMenu(); {IS. - FS. Menampilkan menu utama} var opsi:integer; begin repeat clrscr; writeln(garis); writeln('MENU UTAMA'); writeln(garis); writeln('1. Input Data '); writeln('2. View Data '); writeln('3. Lihat tagihan '); writeln('4. Exit '); writeln(garis); write('Masukkan pilihan: '); readln(opsi); until (opsi=1) or (opsi=2) or (opsi=3) or (opsi=4); if opsi<>4 then begin optionMenu(opsi); mainMenu; end else begin writeln('Yakin akan keluar dari program? (y/n)'); readln; end; end; BEGIN readFromFile(tab); clrscr; Boot; mainMenu; saveToFile(tab); END.
unit uCustomer; interface uses System.SysUtils; type TCustomer = class private FName: string; FState: string; FID: integer; FCity: string; public property ID: integer read FID; property Name: string read FName; property City: string read FCity; property State: string read FState; procedure Load(AID: string); overload; procedure Load(AID: integer); overload; end; implementation { TCustomer } uses dmMain, uDefs; procedure TCustomer.Load(AID: integer); begin dtmMain.qryCustomer.ParamByName('id').Value := AID; dtmMain.qryCustomer.Open; try if dtmMain.qryCustomer.RecordCount = 0 then raise Exception.Create(sErrorCustomerNotFound); FID := AID; FName := dtmMain.qryCustomername.Value; FCity := dtmMain.qryCustomercity.Value; FState := dtmMain.qryCustomerstate.Value; finally dtmMain.qryCustomer.Close; end; end; procedure TCustomer.Load(AID: string); begin try FID := StrToInt(AID); except raise Exception.Create(sErrorCustomerInvalidCode); end; Load(FID); end; end.
program hash_table; uses crt; const MAX_SIZE = 10; BUCKET_MAX_SIZE = 10; type key_t = integer; bucket_t = array[1..BUCKET_MAX_SIZE] of key_t; hashtable_t = array[1..MAX_SIZE] of bucket_t; list_t = array[1..MAX_SIZE*BUCKET_MAX_SIZE] of key_t; var hashtable: hashtable_t; bsizes: array[1..MAX_SIZE] of integer; size: integer; logger : text; function Hash(key: key_t): integer; begin hash := 1; end; function Find(key: key_t): boolean; begin Find := false; end; function Add(key: key_t): boolean; begin Add := false; end; function Delete(key: key_t): boolean; begin Delete := false; end; function GetSize(): integer; begin GetSize := -1; end; procedure MakePPrintLog(log_name: string); begin end; procedure Clear(); begin end; function test(): boolean; var TEST_NAME: string; KEEP_RUNNING: boolean; procedure cprint(text: string; c: integer); begin textcolor(c); writeln(text); normvideo end; function ASSERT_EQ(got, expected: integer) : boolean; begin ASSERT_EQ := got = expected; if not (ASSERT_EQ) then begin cprint(TEST_NAME + ' failed with assertion error:', red); writeln('got: ', got); writeln('expected: ', expected); KEEP_RUNNING := false end end; function ASSERT_EQ(got, expected : string) : boolean; begin ASSERT_EQ := got = expected; if not (ASSERT_EQ) then begin cprint(TEST_NAME + ' failed with assertion error:', red); writeln('got: ', got); writeln('expected: ', expected); KEEP_RUNNING := false end end; function ASSERT_TRUE(got: boolean): boolean; begin ASSERT_TRUE := got; if not(ASSERT_TRUE) then begin cprint(TEST_NAME + ' failed with assertion error:', red); writeln('got: false'); writeln('expected: true'); KEEP_RUNNING := false end end; function ASSERT_FALSE(got: boolean): boolean; begin ASSERT_FALSE := not(got); if not(ASSERT_FALSE) then begin cprint(TEST_NAME + ' failed with assertion error:', red); writeln('got: true'); writeln('expected: false'); KEEP_RUNNING := false end end; procedure empty(); begin TEST_NAME := 'empty'; Clear(); ASSERT_EQ( GetSize(), 0 ); if (KEEP_RUNNING) then writeln(TEST_NAME, ': OK') end; procedure simple(); begin TEST_NAME := 'simple'; Clear(); ASSERT_EQ( GetSize(), 0 ); ASSERT_TRUE( Add(1) ); ASSERT_EQ( GetSize(), 1 ); ASSERT_TRUE( Find(1) ); ASSERT_FALSE( Find(2) ); ASSERT_FALSE( Add(1) ); ASSERT_EQ( GetSize(), 1 ); ASSERT_TRUE( Delete(1) ); ASSERT_FALSE( Delete(2) ); ASSERT_FALSE( Find(1) ); ASSERT_EQ( GetSize(), 0 ); if (KEEP_RUNNING) then writeln(TEST_NAME, ': OK') end; procedure add_correctness(); var i: integer; begin TEST_NAME := 'add_correctness'; Clear(); ASSERT_EQ( GetSize(), 0 ); for i:=1 to maxint do if i <= MAX_SIZE * BUCKET_MAX_SIZE then ASSERT_TRUE( Add(i) ) else ASSERT_FALSE( Add(i) ); ASSERT_EQ( GetSize(), MAX_SIZE * BUCKET_MAX_SIZE ); if (KEEP_RUNNING) then writeln(TEST_NAME, ': OK') end; procedure delete_correctness(); var i: integer; begin TEST_NAME := 'delete_correctness'; Clear(); ASSERT_EQ( GetSize(), 0 ); for i:=1 to MAX_SIZE * BUCKET_MAX_SIZE do ASSERT_TRUE( Add(i) ); ASSERT_EQ( GetSize(), MAX_SIZE * BUCKET_MAX_SIZE ); for i:=1 to maxint do if i <= MAX_SIZE * BUCKET_MAX_SIZE then ASSERT_TRUE( Delete(i) ) else ASSERT_FALSE( Delete(i) ); if (KEEP_RUNNING) then writeln(TEST_NAME, ': OK') end; procedure find_correctness(); var i: integer; begin TEST_NAME := 'find_correctness'; Clear(); ASSERT_EQ( GetSize(), 0 ); for i:=1 to MAX_SIZE * BUCKET_MAX_SIZE do ASSERT_TRUE( Add(i) ); ASSERT_EQ( GetSize(), MAX_SIZE * BUCKET_MAX_SIZE ); for i:=1 to MAX_SIZE * BUCKET_MAX_SIZE do if i mod 2 = 0 then ASSERT_TRUE( Delete(i) ); for i:=1 to MAX_SIZE * BUCKET_MAX_SIZE do if i mod 2 = 0 then ASSERT_FALSE( Find(i) ) else ASSERT_TRUE( Find(i) ); if (KEEP_RUNNING) then writeln(TEST_NAME, ': OK') end; procedure check_log_state(expected_log_name: string); var logger_expected, logger : text; line_expected, line: string; begin assign(logger_expected, 'logs/' + expected_log_name); assign(logger, 'state_logger.txt'); reset(logger_expected); reset(logger); while not eof(logger_expected) and (KEEP_RUNNING) do begin readln(logger_expected, line_expected); readln(logger, line); ASSERT_EQ(line, line_expected) end end; procedure logger_append_correctness(); var i: integer; begin Clear(); MakePPrintLog('empty'); Add(5); MakePPrintLog('single five'); for i:=1 to 10 do Add(i); MakePPrintLog('some additions'); end; procedure test_run(); begin KEEP_RUNNING := true; if (KEEP_RUNNING) then empty(); if (KEEP_RUNNING) then simple(); if (KEEP_RUNNING) then add_correctness(); if (KEEP_RUNNING) then delete_correctness(); if (KEEP_RUNNING) then find_correctness(); end; procedure logger_test_run(); begin if (KEEP_RUNNING) then cprint('logger tests iteration', Cyan); if (KEEP_RUNNING) then empty(); if (KEEP_RUNNING) then MakePPrintLog('empty table'); if (KEEP_RUNNING) then check_log_state('empty_log.txt'); if (KEEP_RUNNING) then simple(); if (KEEP_RUNNING) then MakePPrintLog('empty simple'); if (KEEP_RUNNING) then check_log_state('simple_log.txt'); if (KEEP_RUNNING) then add_correctness(); if (KEEP_RUNNING) then MakePPrintLog('Add'); if (KEEP_RUNNING) then check_log_state('add_log.txt'); if (KEEP_RUNNING) then delete_correctness(); if (KEEP_RUNNING) then MakePPrintLog('Delete'); if (KEEP_RUNNING) then check_log_state('delete_log.txt'); if (KEEP_RUNNING) then find_correctness(); if (KEEP_RUNNING) then MakePPrintLog('Find'); if (KEEP_RUNNING) then check_log_state('find_log.txt'); if (KEEP_RUNNING) then logger_append_correctness(); if (KEEP_RUNNING) then check_log_state('logger_append_log.txt'); end; begin test_run(); logger_test_run(); if (KEEP_RUNNING) then cprint('Job succed.', green) else cprint('Testing failed.', red); test := KEEP_RUNNING end; BEGIN test() END.
unit GerberImport; interface uses Board; procedure GerberImportBoard( Board : TbrBoard ); implementation uses Registry, Dialogs, Globals, SysUtils, Forms, Controls, GerberImporter; procedure GerberImportBoard( Board : TbrBoard ); var RegIniFile : TRegIniFile; OpenDialog : TOpenDialog; FileName : string; Importer : TgrGerberImport; begin RegIniFile := GetRegIniFile; try OpenDialog := TOpenDialog.Create( nil ); try FileName := RegIniFile.ReadString( 'Tracks', 'GerberImportFile', '' ); OpenDialog.FileName := ExtractFileName( FileName ); OpenDialog.InitialDir := ExtractFilePath( FileName ); OpenDialog.Filter := 'Gerber Files|*.*'; OpenDialog.Options := [ofEnableSizing, ofFileMustExist, ofHideReadOnly]; if not OpenDialog.Execute then begin exit; end; FileName := OpenDialog.FileName; finally OpenDialog.Free; end; RegIniFile.WriteString( 'Tracks', 'GerberImportFile', FileName ); finally RegIniFile.Free; end; Importer := TgrGerberImport.Create; try Screen.Cursor := crHourGlass; try Importer.ReadFileToBoard( FileName, Board ); finally Screen.Cursor := crDefault; end; finally Importer.Free; end; end; end.
{ *************************************************************************** * * * This source is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This code is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * General Public License for more details. * * * * A copy of the GNU General Public License is available on the World * * Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also * * obtain it by writing to the Free Software Foundation, * * Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA. * * * *************************************************************************** } unit MainUnit; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LCLProc, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls, Buttons; type { TMyComponent } TMyComponent = class(TCheckBox) private FDefaultText: WideString; FInteger1: integer; FWideStr1: widestring; function Integer1IsStored: boolean; procedure SetDefaultText(const AValue: WideString); procedure SetInteger1(const AValue: integer); procedure SetWideStr1(const AValue: widestring); function WideStr1IsStored: boolean; procedure ReadText(Reader: TReader); procedure WriteText(Writer: TWriter); protected procedure DefineProperties(Filer: TFiler); override; public constructor Create(TheOwner: TComponent); override; published property WideStr1: widestring read FWideStr1 write SetWideStr1 stored WideStr1IsStored; property DefaultText: WideString read FDefaultText write SetDefaultText stored False; property Integer1: integer read FInteger1 write SetInteger1; end; { TStreamDemoForm } TStreamDemoForm = class(TForm) AGroupBox: TGroupBox; StreamAsLFMCheckBox: TCheckBox; Note2Label: TLabel; Note1Label: TLabel; ReadStreamButton: TButton; StreamMemo: TMemo; StreamGroupBox: TGroupBox; WriteToStreamButton: TButton; SourceGroupBox: TGroupBox; DestinationGroupBox: TGroupBox; procedure FormCreate(Sender: TObject); procedure ReadStreamButtonClick(Sender: TObject); procedure StreamAsLFMCheckBoxChange(Sender: TObject); procedure WriteToStreamButtonClick(Sender: TObject); public StreamAsString: string; procedure ShowStreamInMemo; procedure SaveStreamAsString(AStream: TStream); procedure ReadStreamFromString(AStream: TStream); function ReadStringFromStream(AStream: TStream): string; procedure ClearDestinationGroupBox; procedure OnFindClass(Reader: TReader; const AClassName: string; var ComponentClass: TComponentClass); end; var StreamDemoForm: TStreamDemoForm; implementation {$R mainunit.lfm} { TStreamDemoForm } procedure TStreamDemoForm.WriteToStreamButtonClick(Sender: TObject); var AStream: TMemoryStream; begin AStream:=TMemoryStream.Create; try WriteComponentAsBinaryToStream(AStream,AGroupBox); SaveStreamAsString(AStream); finally AStream.Free; end; end; procedure TStreamDemoForm.ReadStreamButtonClick(Sender: TObject); var NewComponent: TComponent; AStream: TMemoryStream; begin ClearDestinationGroupBox; AStream:=TMemoryStream.Create; try ReadStreamFromString(AStream); NewComponent:=nil; ReadComponentFromBinaryStream(AStream,NewComponent, @OnFindClass,DestinationGroupBox); if NewComponent is TControl then TControl(NewComponent).Parent:=DestinationGroupBox; finally AStream.Free; end; end; procedure TStreamDemoForm.FormCreate(Sender: TObject); var MyComponent: TMyComponent; begin // create a checkbox with Owner = AGroupBox // because TWriter writes all components owned by AGroupBox MyComponent:=TMyComponent.Create(AGroupBox); with MyComponent do begin Name:='MyComponent'; Parent:=AGroupBox; end; end; procedure TStreamDemoForm.StreamAsLFMCheckBoxChange(Sender: TObject); begin ShowStreamInMemo; end; procedure TStreamDemoForm.ShowStreamInMemo; var LRSStream: TMemoryStream; LFMStream: TMemoryStream; begin if StreamAsLFMCheckBox.Checked then begin // convert the stream to LFM LRSStream:=TMemoryStream.Create; LFMStream:=TMemoryStream.Create; try ReadStreamFromString(LRSStream); LRSObjectBinaryToText(LRSStream,LFMStream); StreamMemo.Lines.Text:=ReadStringFromStream(LFMStream); finally LRSStream.Free; LFMStream.Free; end; end else begin // the stream is in binary format and contains characters, that can not be // shown in the memo. Convert all special characters to hexnumbers. StreamMemo.Lines.Text:=DbgStr(StreamAsString); end; end; procedure TStreamDemoForm.SaveStreamAsString(AStream: TStream); begin StreamAsString:=ReadStringFromStream(AStream); ShowStreamInMemo; end; procedure TStreamDemoForm.ReadStreamFromString(AStream: TStream); begin AStream.Size:=0; if StreamAsString<>'' then AStream.Write(StreamAsString[1],length(StreamAsString)); AStream.Position:=0; end; function TStreamDemoForm.ReadStringFromStream(AStream: TStream): string; begin AStream.Position:=0; SetLength(Result,AStream.Size); if Result<>'' then AStream.Read(Result[1],length(Result)); end; procedure TStreamDemoForm.ClearDestinationGroupBox; { free all components owned by DestinationGroupBox Do not confuse 'Owner' and 'Parent'; The 'Owner' of a TComponent is responsible for freeing the component. All components owned by a component can be found in its 'Components' property. The 'Parent' of a TControl is the visible container. For example DestinationGroupBox has as Parent the form (StreamDemoForm). All controls with the same parent are gathered in Parent.Controls. In this simple example the created component has as Owner and Parent the DestinationGroupBox. } begin while DestinationGroupBox.ComponentCount>0 do DestinationGroupBox.Components[0].Free; end; procedure TStreamDemoForm.OnFindClass(Reader: TReader; const AClassName: string; var ComponentClass: TComponentClass); begin Reader:=Reader;//lcl forces to use unneeded variables in event functions if CompareText(AClassName,'TGroupBox')=0 then ComponentClass:=TGroupBox else if CompareText(AClassName,'TCheckBox')=0 then ComponentClass:=TCheckBox else if CompareText(AClassName,'TMyComponent')=0 then ComponentClass:=TMyComponent; end; { TMyComponent } procedure TMyComponent.SetWideStr1(const AValue: widestring); begin if FWideStr1=AValue then exit; FWideStr1:=AValue; end; procedure TMyComponent.SetDefaultText(const AValue: WideString); begin if FDefaultText=AValue then exit; FDefaultText:=AValue; end; function TMyComponent.Integer1IsStored: boolean; begin Result:=FInteger1=3; end; procedure TMyComponent.SetInteger1(const AValue: integer); begin if FInteger1=AValue then exit; FInteger1:=AValue; end; function TMyComponent.WideStr1IsStored: boolean; begin Result:=WideStr1<>'Node'; end; procedure TMyComponent.ReadText(Reader: TReader); begin case Reader.NextValue of vaLString, vaString: SetDefaultText(widestring(Reader.ReadString)); else SetDefaultText(Reader.ReadWideString); end; end; procedure TMyComponent.WriteText(Writer: TWriter); begin Writer.WriteWideString(FDefaultText); end; procedure TMyComponent.DefineProperties(Filer: TFiler); begin inherited DefineProperties(Filer); Filer.DefineProperty('WideDefaultText', @ReadText, @WriteText, FDefaultText <> 'Node'); end; constructor TMyComponent.Create(TheOwner: TComponent); begin inherited Create(TheOwner); FWideStr1:=''; FInteger1:=3; end; end.
{***************************************************************************} { } { DUnitX } { } { Copyright (C) 2017 Vincent Parrett & Contributors } { } { vincent@finalbuilder.com } { http://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DUnitX.Timeout; interface {$I DUnitX.inc} uses {$IFDEF USE_NS} System.Classes; {$ELSE} Classes; {$ENDIF} //TODO : This is currently only supported on Windows, need to investigate osx etc. type ITimeout = interface(IUnknown) ['{0A380F7B-9CEE-4FD7-9D86-60CE05B97C1A}'] procedure Stop; end; function InitialiseTimeout(const ATime: cardinal): ITimeout; implementation uses {$IFDEF USE_NS} WinAPI.Windows, System.Diagnostics, System.SysUtils, {$ELSE} Windows, Diagnostics, SysUtils, {$ENDIF} DUnitX.ResStrs, DUnitX.TestFramework, DUnitX.Exceptions; // The following TimeOut code is based on the code found at // https://code.google.com/p/delphitimeouts/ // DelphiTimeouts version 1.1 // Copyright (c) 2007-2008 Szymon Jachim type TTimeoutThread = class(TThread) private procedure TimeoutThread; public ThreadHandle: Cardinal; Timeout: Cardinal; procedure Execute; override; end; TTimeout = class(TInterfacedObject, ITimeout) private FTimeoutThread: TTimeoutThread; public constructor Create(const ATimeout: Cardinal; AThreadHandle: THandle); destructor Destroy; override; procedure Stop; end; function InitialiseTimeout(const ATime: cardinal): ITimeout; var ThisThreadHandle: THandle; begin DuplicateHandle(GetCurrentProcess, GetCurrentThread, GetCurrentProcess, @ThisThreadHandle, 0, True, DUPLICATE_SAME_ACCESS); Result := TTimeout.Create(ATime, ThisThreadHandle); end; procedure RaiseTimeOutException; begin raise ETimedOut.Create(SOperationTimedOut); end; procedure TTimeoutThread.TimeoutThread; var Ctx: _CONTEXT; begin SuspendThread(ThreadHandle); Ctx.ContextFlags := CONTEXT_FULL; GetThreadContext(ThreadHandle, Ctx); {$IFDEF CPUX64} Ctx.Rip := Cardinal(@RaiseTimeOutException); {$ELSE} Ctx.Eip := Cardinal(@RaiseTimeOutException); {$ENDIF} SetThreadContext(ThreadHandle, Ctx); ResumeThread(ThreadHandle); end; { TTimeout } procedure TTimeout.Stop; begin FTimeoutThread.Terminate; end; constructor TTimeout.Create(const ATimeout: Cardinal; AThreadHandle: THandle); begin FTimeoutThread := TTimeoutThread.Create(true); FTimeoutThread.FreeOnTerminate := false; FTimeoutThread.ThreadHandle := AThreadHandle; FTimeoutThread.Timeout := ATimeout; FTimeoutThread.Start; end; destructor TTimeout.Destroy; begin //Unwinding and we need to stop the thread, as it may still raise an exception Stop; FTimeoutThread.WaitFor; FTimeoutThread.Free; inherited; end; { TTimeoutThread } procedure TTimeoutThread.Execute; var elapsedTime : Int64; stopwatch : TStopWatch; begin inherited; stopwatch := TStopWatch.Create; stopwatch.Reset; stopwatch.Start; {$IFDEF DELPHI_XE100_DOWN} // <- H2077 Value assigned to 'elapsedTime' never used 10.1 Berlin and up elapsedTime := 0; {$ENDIF} if Terminated then exit; repeat //Give some time back to the system to process the test. Sleep(20); if Terminated then Break; elapsedTime := stopwatch.ElapsedMilliseconds; until (elapsedTime >= Timeout); //If we haven't been terminated then we have timed out. if not Terminated then TimeoutThread; CloseHandle(ThreadHandle); end; end.
unit SmdOutlines; interface uses Outlines, Painter, Contnrs, Classes, Types; // Board Cells are divided into Fine Divisions - shapes are located by MiniCell // coords, while pins are located by ordinary Cell coords. type TsmShape = class protected FXDiv : integer; FYDiv : integer; FSelected : boolean; procedure SetXDiv( value : integer ); virtual; procedure SetYDiv( value : integer ); virtual; public property XDiv : integer read FXDiv write SetXDiv; property YDiv : integer read FYDiv write SetYDiv; property Selected : boolean read FSelected write FSelected; // bounding rectangle which contains item procedure GetRectangle( var Left, Top, Right, Bottom : integer ); virtual; abstract; procedure GetDivRectangle( var Left, Top, Right, Bottom : integer ); virtual; abstract; procedure Paint( Item : TveBoardItem; Info : TvePainter ); virtual; abstract; function DistanceToPoint( Item : TveBoardItem; PointX, PointY : integer ) : integer; virtual; abstract; function Clone : TsmShape; virtual; abstract; function Identical( Shape : TsmShape ) : boolean; virtual; abstract; end; type TsmLine = class( TsmShape ) FEndDeltaXDiv : integer; FEndDeltaYDiv : integer; procedure SetEndDeltaXDiv( value : integer ); procedure SetEndDeltaYDiv( value : integer ); public property EndDeltaXDiv : integer read FEndDeltaXDiv write SetEndDeltaXDiv; property EndDeltaYDiv : integer read FEndDeltaYDiv write SetEndDeltaYDiv; procedure GetRectangle( var Left, Top, Right, Bottom : integer ); override; procedure GetDivRectangle( var Left, Top, Right, Bottom : integer ); override; procedure Paint( Item : TveBoardItem; Info : TvePainter ); override; function DistanceToPoint( Item : TveBoardItem; PointX, PointY : integer ) : integer; override; function StartIsNearestPoint( Item : TveBoardItem; PointX, PointY : integer ) : boolean; function Clone : TsmShape; override; function Identical( Shape : TsmShape ) : boolean; override; end; type TsmPin = class( TsmShape ) protected procedure SetXDiv( value : integer ); override; procedure SetYDiv( value : integer ); override; public Name : string; WidthDiv : integer; HeightDiv : integer; procedure GetRectangle( var Left, Top, Right, Bottom : integer ); override; procedure GetDivRectangle( var Left, Top, Right, Bottom : integer ); override; procedure Paint( Item : TveBoardItem; Info : TvePainter ); override; function DistanceToPoint( Item : TveBoardItem; PointX, PointY : integer ) : integer; override; function Clone : TsmShape; override; function Identical( Shape : TsmShape ) : boolean; override; end; type TveSmdOutline = class( TveOutline ) protected NextShapeIndex : integer; NextPinIndex : integer; FShapes : TObjectList; function GetShape( index : integer ) : TsmShape; function GetShapeCount : integer; function GetPin( index : integer ) : TvePin; override; public property Shapes[index : integer] : TsmShape read GetShape; property ShapeCount : integer read GetShapeCount; function CreateLine : TsmLine; function CreatePin : TsmPin; procedure AddShape( Shape : TsmShape ); procedure DeleteShape( Shape : TsmShape ); procedure BuildPinList; constructor Create; override; destructor Destroy; override; function Clone : TveOutline; override; function Identical( Outline : TveOutline ) : boolean; override; procedure Paint( Item : TveBoardItem; Info : TvePainter ); override; function OccupiesCell( Item : TveBoardItem; CellX, CellY : integer ) : boolean; override; procedure RotateAboutCenter( Item : TveBoardItem ); override; function PinIndexAt( Item : TveBoardItem; CellX, CellY : integer ) : integer; override; procedure GetScreenRectR( Item : TveBoardItem; var R : TRect ); override; function PinIndexByName( const Name : string ) : integer; override; procedure ToFirstPin; override; function GetNextPin( Item : TveBoardItem; var X, Y, PinIndex : integer ) : boolean; override; function GetNextPinDiv( Item : TveBoardItem; var Rect : TRect; var PinIndex : integer ) : boolean; procedure WriteToStream( S : TStream ); override; procedure ReadFromStream( S : TStream ); override; { // outline editor functions function GetSpecifiedShapeAtSubCellXY( Item : TveBoardItem; SubCellX, SubCellY : integer; ShapeClass : TClass ) : TsmShape; function GetShapeAtSubCellXY( Item : TveBoardItem; SubCellX, SubCellY : integer ) : TsmShape; procedure UnselectAllShapes; function GetSelectedCount : integer; property SelectedCount : integer read GetSelectedCount; function SelectionIncludesPin : boolean; } end; implementation uses Rotations, SysUtils, Windows, ParseCSV, Rectangles; // ************************************************** // TcoShape // ************************************************** procedure TsmShape.SetXDiv( value : integer ); begin FXDiv := value; end; procedure TsmShape.SetYDiv( value : integer ); begin FYDiv := value; end; // ************************************************** // TcoLine // ************************************************** procedure TsmLine.SetEndDeltaXDiv( value : integer ); begin // do not allow zero length if (value = 0) and (FEndDeltaYDiv = 0) then begin FEndDeltaYDiv := 100; end; FEndDeltaXDiv := value; end; procedure TsmLine.SetEndDeltaYDiv( value : integer ); begin // do not allow zero length if (value = 0) and (FEndDeltaXDiv = 0) then begin FEndDeltaXDiv := 100; end; FEndDeltaYDiv := value; end; // Get Rectangle Enclosing Line, in Un-Rotated Position, in Cell Units, // with origin at 0,0 procedure TsmLine.GetRectangle( var Left, Top, Right, Bottom : integer ); begin if EndDeltaXDiv > 0 then begin Left := (XDiv + (DIVS_PER_CELL div 2)) div DIVS_PER_CELL; Right := (XDiv + EndDeltaXDiv + (DIVS_PER_CELL div 2)) div DIVS_PER_CELL; end else begin Left := (XDiv + EndDeltaXDiv + (DIVS_PER_CELL div 2)) div DIVS_PER_CELL; Right := (XDiv + (DIVS_PER_CELL div 2)) div DIVS_PER_CELL; end; if EndDeltaYDiv > 0 then begin Top := (YDiv + (DIVS_PER_CELL div 2)) div DIVS_PER_CELL; Bottom:= ((YDiv + EndDeltaYDiv) + (DIVS_PER_CELL div 2)) div DIVS_PER_CELL; end else begin Top := ((YDiv + EndDeltaYDiv) + (DIVS_PER_CELL div 2)) div DIVS_PER_CELL; Bottom := (YDiv + (DIVS_PER_CELL div 2)) div DIVS_PER_CELL; end; end; // get rectangle in sub cell units, not relative to any component, but // unrotated with origin at 0,0 . Not a bounding rectangle procedure TsmLine.GetDivRectangle( var Left, Top, Right, Bottom : integer ); begin if EndDeltaXDiv > 0 then begin Left := XDiv; Right := XDiv + EndDeltaXDiv; end else begin Left := XDiv + EndDeltaXDiv; Right := XDiv; end; if EndDeltaYDiv > 0 then begin Top := YDiv; Bottom := YDiv + EndDeltaYDiv; end else begin Top := YDiv + EndDeltaYDiv; Bottom := YDiv; end; end; procedure TsmLine.Paint( Item : TveBoardItem; Info : TvePainter ); var BodyLines : TPolyLines; ComponentXDiv, ComponentYDiv : integer; // LDiv coords between start x1, y1 and end x2, y2 X1, Y1, X2, Y2 : integer; PixelsPerCell : integer; Rotation : TRotation; RotationX, RotationY : integer; procedure Line( X1, Y1, X2, Y2 : integer ); begin Rotate( X1, Y1, RotationX, RotationY, Rotation ); Rotate( X2, Y2, RotationX, RotationY, Rotation ); X1 := ((X1 + (DIVS_PER_CELL div 2)) * PixelsPerCell) div DIVS_PER_CELL; Y1 := ((Y1 + (DIVS_PER_CELL div 2)) * PixelsPerCell) div DIVS_PER_CELL; X2 := ((X2 + (DIVS_PER_CELL div 2)) * PixelsPerCell) div DIVS_PER_CELL; Y2 := ((Y2 + (DIVS_PER_CELL div 2)) * PixelsPerCell) div DIVS_PER_CELL; BodyLines.AddLine( X1, Y1, X2, Y2 ); end; begin BodyLines := Info.BodyLines; PixelsPerCell := Info.PixelsPerCell; Rotation := Item.Rotation; // Div coords of referece point of Component ComponentXDiv := Item.XDiv; ComponentYDiv := Item.YDiv; // rotation point of Component RotationX := ComponentXDiv; RotationY := ComponentYDiv; // calculate line coords in Div units X1 := ComponentXDiv + XDiv; Y1 := ComponentYDiv + YDiv; X2 := ComponentXDiv + XDiv + EndDeltaXDiv; Y2 := ComponentYDiv + YDiv + EndDeltaYDiv; Line( X1, Y1, X2, Y2 ); end; //Compute the dot product AB . BC of the two vectors AB and BC function dot( A, B, C : TPoint ) : integer; var AB : TPoint; BC : TPoint; begin AB.X := B.X - A.X; AB.Y := B.Y - A.Y; BC.X := C.X - B.X; BC.Y := C.Y - B.Y; result := (AB.X * BC.X) + (AB.Y * BC.Y); end; //Compute the cross product AB x AC function cross( A, B, C : TPoint ) : integer; var AB : TPoint; AC : TPoint; begin AB.X := B.X - A.X; AB.Y := B.Y - A.Y; AC.X := C.X - A.X; AC.Y := C.Y - A.Y; result := (AB.X * AC.Y) - (AB.Y * AC.X); end; //Compute the distance from A to B function distance( A, B : TPoint ) : single; var d1 : integer; d2 : integer; begin d1 := A.X - B.X; d2 := A.Y - B.Y; result := sqrt( (d1 * d1) + (d2 * d2) ); end; //Compute the distance from line segment AB to point C // AB is a segment, not an infinitely long line, so if line is too short, // distance is taken to the nearest line end. function linePointDist( A, B, C : TPoint ) : single; var dist : single; dot1 : integer; dot2 : integer; begin dot1 := dot( A,B,C ); if( dot1 > 0 ) then begin result := distance(B,C); exit; end; dot2 := dot(B,A,C); if( dot2 > 0 ) then begin result := distance(A,C); exit; end; dist := cross( A,B,C) / distance(A,B); result := abs( dist ); end; function TsmLine.DistanceToPoint( Item : TveBoardItem; PointX, PointY : integer ) : integer; var PX, PY : integer; begin // make point coords relative to component reference point, sub cell units PX := PointX - (Item.X * DIVS_PER_CELL); PY := PointY - (Item.Y * DIVS_PER_CELL); // reverse rotate point about component reference point RotateReverse( PX, PY, 0, 0, Item.Rotation ); // calculate distance between line and point result := abs( round( linePointDist( Point(XDiv, YDiv), Point((XDiv + EndDeltaXDiv), (YDiv + EndDeltaYDiv)), Point(PX, PY) ) )); end; function TsmLine.StartIsNearestPoint( Item : TveBoardItem; PointX, PointY : integer ) : boolean; var XDist, YDist : integer; // work in distance^2 to save square roots StartDistance2 : integer; EndDistance2 : integer; begin // distance to start XDist := PointX - FXDiv; YDist := PointY - FYDiv; StartDistance2 := (XDist * XDist) + (YDist * YDist); // distance to end XDist := PointX - (FXDiv + EndDeltaXDiv); YDist := PointY - (FYDiv + EndDeltaYDiv); EndDistance2 := (XDist * XDist) + (YDist * YDist); // which distance is shorter? result := StartDistance2 < EndDistance2; end; function TsmLine.Clone : TsmShape; begin result := TsmLine.Create; result.XDiv := FXDiv; result.YDiv := FYDiv; TsmLine( result ).EndDeltaXDiv := FEndDeltaXDiv; TsmLine( result ).EndDeltaYDiv := FEndDeltaYDiv; end; function TsmLine.Identical( Shape : TsmShape ) : boolean; begin result := (Shape is TsmLine) and (TsmLine(Shape).XDiv = FXDiv) and (TsmLine(Shape).YDiv = FYDiv) and (TsmLine(Shape).EndDeltaXDiv = FEndDeltaXDiv) and (TsmLine(Shape).EndDeltaYDiv = FEndDeltaYDiv); end; // ************************************************** // TcoPin // ************************************************** procedure TsmPin.SetXDiv( value : integer ); begin FXDiv := value; end; procedure TsmPin.SetYDiv( value : integer ); begin FYDiv := value; end; // Get Rectangle Enclosing Pin, in Un-Rotated Position, in Cell Units, // with origin at 0,0 procedure TsmPin.GetRectangle( var Left, Top, Right, Bottom : integer ); var LeftDiv, RightDiv : integer; TopDiv, BottomDiv : integer; begin // calculate pin extents LeftDiv := XDiv - (WidthDiv div 2); RightDiv := XDiv + (WidthDiv div 2); TopDiv := YDiv - (HeightDiv div 2); BottomDiv := YDiv + (HeightDiv div 2); // convert divs to cells Left := (LeftDiv + (DIVS_PER_CELL div 2)) div DIVS_PER_CELL; Right := (RightDiv + (DIVS_PER_CELL div 2)) div DIVS_PER_CELL; Top := (TopDiv + (DIVS_PER_CELL div 2)) div DIVS_PER_CELL; Bottom := (BottomDiv + (DIVS_PER_CELL div 2)) div DIVS_PER_CELL; // convert to bounding rectangle Inc( Right ); Inc( Bottom ); end; // get rectangle in div cell units, not relative to any component, but // unrotated with origin at 0,0 . Not a bounding rectangle. procedure TsmPin.GetDivRectangle( var Left, Top, Right, Bottom : integer ); begin Left := FXDiv - (WidthDiv div 2); Right := FxDiv + (WidthDiv div 2); Top := FYDiv - (HeightDiv div 2); Bottom := FYDiv + (HeightDiv div 2); end; procedure TsmPin.Paint( Item : TveBoardItem; Info : TvePainter ); var PinLines : TPolyLines; PixelsPerCell : integer; Rotation : TRotation; RotationX, RotationY : integer; // Div coords of reference point of this component ComponentXDiv, ComponentYDiv : integer; procedure Rectangle( Rect : TRect ); begin Rotate( Rect.Left, Rect.Top, RotationX, RotationY, Rotation ); Rotate( Rect.Right, Rect.Bottom, RotationX, RotationY, Rotation ); // convert Div coords to pixels Rect.Left := ((Rect.Left + (DIVS_PER_CELL div 2)) * PixelsPerCell) div DIVS_PER_CELL; Rect.Right := ((Rect.Right + (DIVS_PER_CELL div 2)) * PixelsPerCell) div DIVS_PER_CELL; Rect.Top := ((Rect.Top + (DIVS_PER_CELL div 2)) * PixelsPerCell) div DIVS_PER_CELL; Rect.Bottom := ((Rect.Bottom + (DIVS_PER_CELL div 2)) * PixelsPerCell) div DIVS_PER_CELL; // plot rectangle PinLines.AddPoint( Rect.Left, Rect.Top ); PinLines.AddPoint( Rect.Right, Rect.Top ); PinLines.AddPoint( Rect.Right, Rect.Bottom ); PinLines.AddPoint( Rect.Left, Rect.Bottom ); PinLines.AddPoint( Rect.Left, Rect.Top ); PinLines.EndShape; end; var PinXDiv, PinYDiv : integer; PinRect : TRect; begin PinLines := Info.PinLines; PixelsPerCell := Info.PixelsPerCell; Rotation := Item.Rotation; //locate reference point of outline in Divs //*** this value will become high precision later on // ComponentXDiv := Item.X * TsmDivisionsPerCell; //+ (TsmDivisionsPerCell div 2); // ComponentYDiv := Item.Y * TsmDivisionsPerCell; //+ (TsmDivisionsPerCell div 2); ComponentXDiv := Item.XDiv; ComponentYDiv := Item.YDiv; // rotate about this point RotationX := ComponentXDiv; RotationY := ComponentYDiv; // calculate pin position in Divs PinXDiv := Item.XDiv + XDiv; PinYDiv := Item.YDiv + YDiv; // draw pin as rectangle PinRect.Left := PinXDiv - (WidthDiv div 2); PinRect.Right := PinXDiv + (WidthDiv div 2); PinRect.Top := PinYDiv - (HeightDiv div 2); PinRect.Bottom := PinYDiv + (HeightDiv div 2); Rectangle( PinRect ); end; function TsmPin.DistanceToPoint( Item : TveBoardItem; PointX, PointY : integer ) : integer; var PinSX, PinSY : integer; SideX, SideY : integer; begin // (we work in SubCell units in this function) PinSX := XDiv; PinSY := YDiv; // rotate pin position around the item reference point Rotate( PinSX, PinSY, 0, 0, Item.Rotation ); // add in component position PinSX := PinSX + (Item.X * DIVS_PER_CELL); PinSY := PinSY + (Item.Y * DIVS_PER_CELL); // find distance to pin centre in SubCell units SideX := PointX - PinSX; SideY := PointY - PinSY; result := round( sqrt((SideX * SideX) + (SideY * SideY)) ); // treating pin as a circle, subtract its radius to give distance from point // to circle Dec( result, DIVS_PER_CELL div 3 ); end; function TsmPin.Clone : TsmShape; begin result := TsmPin.Create; result.XDiv := FXDiv; result.YDiv := FYDiv; TsmPin(result).WidthDiv := WidthDiv; TsmPin(result).HeightDiv := HeightDiv; TsmPin(result).Name := Name; end; function TsmPin.Identical( Shape : TsmShape ) : boolean; begin result := (Shape is TsmPin) and (TsmPin(Shape).XDiv = FXDiv) and (TsmPin(Shape).YDiv = FYDiv) and (TsmPin(Shape).WidthDiv = WidthDiv) and (TsmPin(Shape).HeightDiv = HeightDiv) and (TsmPin(Shape).Name = Name); end; // ************************************************** // TveCustomOutline // ************************************************** constructor TveSmdOutline.Create; begin inherited; FShapes := TObjectList.Create; FRotatable := True; FUserDefined := True; FShowsDesignator := True; FShowsValue := True; end; destructor TveSmdOutline.Destroy; begin FShapes.Free; inherited; end; function TveSmdOutline.GetShape( index : integer ) : TsmShape; begin result := TsmShape( FShapes[index] ); end; function TveSmdOutline.GetShapeCount : integer; begin result := FShapes.Count; end; function TveSmdOutline.CreateLine : TsmLine; begin result := TsmLine.Create; FShapes.Add( result ); BuildPinList; end; function TveSmdOutline.CreatePin : TsmPin; begin result := TsmPin.Create; FShapes.Add( result ); BuildPinList; end; procedure TveSmdOutline.AddShape( Shape : TsmShape ); begin FShapes.Add( Shape ); BuildPinList; end; procedure TveSmdOutline.DeleteShape( Shape : TsmShape ); begin if FShapes.Remove( Shape ) = -1 then begin raise EOutlineStream.Create( 'Deleting non-existant shape' ); end; BuildPinList; end; function TveSmdOutline.Clone : TveOutline; var i : integer; begin result := TveSmdOutline.Create; // duplicate data TveSmdOutline(result).Name := Name; // duplicate shapes for i := 0 to FShapes.Count -1 do begin TveSmdOutline(result).AddShape( TsmShape(FShapes[i]).Clone ); end; TveSmdOutline(result).BuildPinList; end; function TveSmdOutline.Identical( Outline : TveOutline ) : boolean; var i : integer; begin // assume different result := False; if not ( (Outline is TveSmdOutline) and (TveSmdOutline(Outline).PinCount = PinCount) and (TveSmdOutline(Outline).ShapeCount = ShapeCount) ) then begin exit end; // compare the pins arrays for i := 0 to PinCount - 1 do begin if TveSmdOutline(Outline).Pins[i].Name <> Pins[i].Name then begin exit; end; end; // compare shapes for i := 0 to ShapeCount - 1 do begin if not Shapes[i].Identical( TveSmdOutline(Outline).Shapes[i] ) then begin exit; end; end; // passed all tests result := True; end; procedure TveSmdOutline.Paint( Item : TveBoardItem; Info : TvePainter ); var PixelsPerCell : integer; Rotation : TRotation; RotationX, RotationY : integer; var i : integer; Shape : TsmShape; // pixel coords of reference point of this component ComponentX, ComponentY : integer; // component text DesignatorX, DesignatorY : integer; begin // setup local variables PixelsPerCell := Info.PixelsPerCell; Rotation := Item.Rotation; //locate TCanvas pixels containing top left of outline (+1 pixel for border ComponentX := (Item.X * PixelsPerCell) + Info.Border; ComponentY := (Item.Y * PixelsPerCell) + Info.Border; // find centre of reference pin : ie perfboard hole at top left RotationX := ComponentX + (PixelsPerCell div 2); RotationY := ComponentY + (PixelsPerCell div 2); // draw every shape in list for i := 0 to FShapes.Count -1 do begin Shape := TsmShape(FShapes[i]); Shape.Paint( Item, Info ); end; // print designator if not Item.TextVisible then begin exit; end; DesignatorX := (Item.TextX * PixelsPerCell) + ComponentX + (PixelsPerCell div 2); DesignatorY := (Item.TextY * PixelsPerCell) + ComponentY + (PixelsPerCell div 2);; // text position is rotated along with the rest of the component // around the item (0.0) reference point Rotate( DesignatorX, DesignatorY, RotationX, RotationY, Rotation ); // text orientation is never changed by item rotation case Info.TextDisplay of tdDesignator : Info.SmallText.Add( Item.Designator, DesignatorX, DesignatorY, Item.TextRotation ); tdValue : Info.SmallText.Add( Item.Value, DesignatorX, DesignatorY, Item.TextRotation ); end; end; function TveSmdOutline.OccupiesCell( Item : TveBoardItem; CellX, CellY : integer ) : boolean; var ItemRect : TRect; begin // rough : see if cell is inside screen rectangle. // We should actually trace the outer outline of our component - quite a // complicated task GetScreenRectR( Item, ItemRect ); result := (CellX >= ItemRect.Left) and (CellX < ItemRect.Right) and (CellY >= ItemRect.Top) and (CellY < ItemRect.Bottom); end; { function TveCustomOutline.InsideRectangle( Item : TveBoardItem; CellX1, CellY1, CellX2, CellY2 : integer ) : boolean; var ItemRect : TRect; begin // find rectangle occupied by our outline GetScreenRectR( Item, ItemRect ); // see if our location is inside rectangle result := (ItemRect.Left >= CellX1) and (ItemRect.Right <= CellX2) and (ItemRect.Top >= CellY1) and (ItemRect.Bottom <= CellY2); end; } procedure TveSmdOutline.RotateAboutCenter( Item : TveBoardItem ); var ItemRect : TRect; Width, Height : integer; Angle : TRotation; begin // find cells we occupy on screen GetScreenRectR( Item, ItemRect ); // calc twice width and height Width := ItemRect.Right - ItemRect.Left; Height := ItemRect.Bottom - ItemRect.Top; // Calculate new location point for outline. // Adjust position of outline origin so that top left of Item // width x height rectangle is always at same square. case Item.Rotation of rot0 : begin Item.Y := Item.Y + Width - 1; end; rot90 : begin Item.X := Item.X + Height - 1; Item.Y := Item.Y + Width - Height; end; rot180 : begin Item.X := Item.X - Width + Height; Item.Y := Item.Y - Height + 1; end; rot270 : begin Item.X := Item.X - Width + 1; end end; // calculate new rotation for Item Angle := Item.Rotation; Item.Rotation := TRotation( (Ord(Angle) + 1) mod 4 ); end; function TveSmdOutline.PinIndexAt( Item : TveBoardItem; CellX, CellY : integer ) : integer; begin // hide all pins result := -1; end; (* var CompX, CompY : integer; i : integer; Shape : TsmShape; begin // convert screen cell coords to outline cell coords CompX := CellX - Item.X; CompY := CellY - Item.Y; // rotate cell coords to follow outline rotation RotateReverse( CompX, CompY, 0, 0, Item.Rotation ); // see if our location hits a cell used by our outline //.. Set result ready for first Pin Index. (Pins[] are in same index order //.. as pins in Shapes[], so we work thru shapes to find our pin, tracking //.. the index in result as we go. result := 0; for i := 0 to FShapes.Count -1 do begin Shape := TsmShape( FShapes[i] ); if (Shape is TsmPin) then begin if ((Shape.XDiv div DIVS_PER_CELL) = CompX) and ((Shape.YDiv div DIVS_PER_CELL) = CompY) then begin // result holds the correct pin index, so exit exit; end; // index of next pin in Pins[] inc( result ); end; end; // return -1 if no pin found in Shapes[] result := -1; end; *) procedure TveSmdOutline.GetScreenRectR( Item : TveBoardItem; var R : TRect ); var Left, Top, Right, Bottom : integer; i : integer; Shape : TsmShape; ShapeLeft, ShapeTop, ShapeRight, ShapeBottom : integer; begin // create rectangle which includes all div extents in this outline // this is not a bounding rectangle, ie. Right, Bottom cells rows include // drawn things like lines, circles, pins - whereas a bounding rectangle has // Right, Bottom as incremented by 1 so as to *enclose* // create a rectangle which includes all cells in this outline // start with a rectangle extents which must trigger changes if any shape exists Left := High(Left); Top := High(Top); Right := Low(Right); Bottom := Low(Bottom); for i := 0 to FShapes.Count -1 do begin Shape := TsmShape( FShapes[i] ); Shape.GetDivRectangle( ShapeLeft, ShapeTop, ShapeRight, ShapeBottom ); if ShapeLeft < Left then begin Left := ShapeLeft; end; if ShapeRight > Right then begin Right := ShapeRight; end; if ShapeTop < Top then begin Top := ShapeTop; end; if ShapeBottom > Bottom then begin Bottom := ShapeBottom; end; end; // if the outline is empty, invent a bounding rectangle of zero area if (Left = High(Left)) or (Top = High(Top)) or (Right = Low(Right)) or (Bottom = Low(Bottom)) then begin Left := 0; Right := 0; Top := 0; Bottom := 0; end; // rotate the item around its reference point Rotate( Left, Top, 0, 0, Item.Rotation ); Rotate( Right, Bottom, 0, 0, Item.Rotation ); // we now have offsets from the item reference point, so we add in the // reference point screen coords to get item rect in screen coords. Inc( Left, Item.XDiv ); Inc( Right, Item.XDiv ); Inc( Top, Item.YDiv ); Inc( Bottom, Item.YDiv ); // tranfer rectangle to result vars - converting to cells R.Left := (Left + (DIVS_PER_CELL div 2)) div DIVS_PER_CELL; R.Right := (Right + (DIVS_PER_CELL div 2)) div DIVS_PER_CELL; R.Top := (Top + (DIVS_PER_CELL div 2)) div DIVS_PER_CELL; R.Bottom := (Bottom + (DIVS_PER_CELL div 2)) div DIVS_PER_CELL; // arrange rotated coords to give left,top and right,bottom of rectangle. NormalizeRect( R ); // turn into bounding rectangle Inc( R.Right ); Inc( R.Bottom ); end; function TveSmdOutline.PinIndexByName( const Name : string ) : integer; begin result := inherited PinIndexByName( Name ); end; procedure TveSmdOutline.ToFirstPin; begin NextShapeIndex := 0; NextPinIndex := 0; end; function TveSmdOutline.GetNextPin( Item : TveBoardItem; var X, Y, PinIndex : integer ) : boolean; var i : integer; Shape : TsmShape; Found : boolean; begin // prevent uninitialised variable warning Shape := nil; // search for next pin Found := False; for i := NextPinIndex to FShapes.Count -1 do begin Shape := TsmShape( FShapes[i] ); if Shape is TsmPin then begin PinIndex := NextPinIndex; Found := True; // ready for continued search of shapes on next function call NextShapeIndex := i + 1; // remember new pin index for next time Inc( NextPinIndex ); break; end; end; // no more pins if not Found then begin PinIndex := FShapes.Count; result := False; exit; end; // get info from pin X := TsmPin(Shape).XDiv div DIVS_PER_CELL; Y := TsmPin(Shape).YDiv div DIVS_PER_CELL; // rotate X,Y for Item Rotate( X, Y, 0, 0, Item.Rotation ); // add offset for item position Inc( X, Item.X ); Inc( Y, Item.Y ); result := True; end; function TveSmdOutline.GetNextPinDiv( Item : TveBoardItem; var Rect : TRect; var PinIndex : integer ) : boolean; var i : integer; Shape : TsmShape; Found : boolean; begin // prevent uninitialised variable warning Shape := nil; // search for next pin Found := False; for i := NextPinIndex to FShapes.Count -1 do begin Shape := TsmShape( FShapes[i] ); if Shape is TsmPin then begin PinIndex := NextPinIndex; Found := True; // ready for continued search of shapes on next function call NextShapeIndex := i + 1; // remember new pin index for next time Inc( NextPinIndex ); break; end; end; // no more pins if not Found then begin PinIndex := FShapes.Count; result := False; exit; end; // get pin rectangle in div cell units, not relative to any component, but // unrotated with origin at 0,0 . Not a bounding rectangle. TsmPin(Shape).GetDivRectangle( Rect.Left, Rect.Top, Rect.Right, Rect.Bottom ); // rotate the rectangle around the component reference point RotateRect( Rect, Point(0, 0), Item.Rotation ); { // get pin rectangle in div cell units, not relative to any component, but // unrotated with origin at 0,0 . Not a bounding rectangle. TsmPin(Shape).GetDivRectangle( Left, Top, Right, Bottom ); // rotate the rectangle around the component reference point Rotate( Left, Top, 0, 0, Item.Rotation ); Rotate( Right, Bottom, 0, 0, Item.Rotation ); // we will return a pin Rect Rect.Left := Left; Rect.Top := Top; Rect.Right := Right; Rect.Bottom := Bottom; // get top, left & bottom right in correct order NormalizeRect( Rect ); } // add offset for item position Inc( Rect.Left, Item.XDiv ); Inc( Rect.Right, Item.XDiv ); Inc( Rect.Top, Item.YDiv ); Inc( Rect.Bottom, Item.YDiv ); // found a pin result := True; end; // ********** Outline Creates an Array of TvePins *********** { Pins[] - the lists of TvePin objects is required to make the TveCustomOutline compatible with other TveOutline descendants. However, it is not required for the TveCustomOutline to operate internally. We inherite from TveOutline the FPins member, a TObjectList. We fill the object list with our TvePin objects which match the pins held in the Shapes array. } procedure TveSmdOutline.BuildPinList; var // manage Shapes[] i : Integer; coPin : TsmPin; // manage Pins[] PinIndex : integer; Pin : TvePin; begin PinIndex := 0; // for every TcoShape in Shapes[] for i := 0 to FShapes.Count - 1 do begin // if this TcoShape is a TcoPin if Shapes[i] is TsmPin then begin coPin := TsmPin( Shapes[i] ); // if we need a new TvePin in the list if PinIndex = PinCount then begin Pin := TvePin.Create; FPins.Add( Pin ); end // else we can reuse an existing TvePin else begin Pin := Pins[PinIndex]; end; // make the TvePin reflect the data in the TcoPin Pin.Name := coPin.Name; // housekeeping - remember index of next pin // to use in this loop inc( PinIndex ); end; end; // remove any unused items in Pins[] for i := PinCount -1 downto PinIndex do begin FPins.Delete(i); end; end; function TveSmdOutline.GetPin( index : integer ) : TvePin; begin result := TvePin( FPins[index] ); end; // ********** Outline writes its properties to a stream *********** { TO-220,1 Pin,1,2,2 Pin,2,2,7 Pin,3,2,12 Line,0,0,7,0 Line,7,0,0,14 Line,7,14,-7,0 Line,0,14,0,-14 Line,5,0,0,14 end } procedure TveSmdOutline.WriteToStream( S : TStream ); procedure LineOut( const text : string ); begin LineToStream( S, text ); end; var i : integer; Shape : TsmShape; begin LineOut( Format( 'Outline=%s', [ClassName] ) ); LineOut( Format('Name=%s', [Name]) ); // susequent lines are shape data eg. "Line=3,2,4,8" // output shapes - one shape per line: for i := 0 to FShapes.Count -1 do begin Shape := TsmShape(FShapes[i]); if Shape is TsmLine then begin LineOut( Format( 'Line=%d,%d,%d,%d', [TsmLine(Shape).XDiv, TsmLine(Shape).YDiv, TsmLine(Shape).EndDeltaXDiv, TsmLine(Shape).EndDeltaYDiv] )); end else if Shape is TsmPin then begin LineOut( Format( 'Pin=%d,%d,%d,%d,%s', [TsmPin(Shape).XDiv, TsmPin(Shape).YDiv, TsmPin(Shape).WidthDiv, TsmPin(Shape).HeightDiv, TsmPin(Shape).Name] )); end; end; LineOut( 'end' ); end; procedure TveSmdOutline.ReadFromStream( S : TStream ); var AName, AValue : string; Shape : TsmShape; ScanIndex : integer; Field : string; begin while NameValueFromStream( S, AName, AValue ) do begin if AName = 'Name' then begin FName := AValue; end else if AName = 'Line' then begin Shape := TsmLine.Create; FShapes.Add( Shape ); // x, y, EndDeltaX, EndDeltaY ScanIndex := 0; ParseCSVValue( AValue, Field, ScanIndex ); Shape.FXDiv := StrToIntDef( Field, 1 ); ParseCSVValue( AValue, Field, ScanIndex ); Shape.FYDiv := StrToIntDef( Field, 1 ); ParseCSVValue( AValue, Field, ScanIndex ); TsmLine(Shape).FEndDeltaXDiv := StrToIntDef( Field, 1 ); ParseCSVValue( AValue, Field, ScanIndex ); TsmLine(Shape).FEndDeltaYDiv := StrToIntDef( Field, 1 ); end else if AName = 'Pin' then begin Shape := TsmPin.Create; FShapes.Add( Shape ); // x, y, number ScanIndex := 0; ParseCSVValue( AValue, Field, ScanIndex ); Shape.FXDiv := StrToIntDef( Field, 1 ); ParseCSVValue( AValue, Field, ScanIndex ); Shape.FYDiv := StrToIntDef( Field, 1 ); ParseCSVValue( AValue, Field, ScanIndex ); TsmPin(Shape).WidthDiv := StrToIntDef( Field, 1 ); ParseCSVValue( AValue, Field, ScanIndex ); TsmPin(Shape).HeightDiv := StrToIntDef( Field, 1 ); ParseCSVValue( AValue, Field, ScanIndex ); TsmPin(Shape).Name := Field; end else if AName = 'end' then begin Break; end; end; BuildPinList; end; end.
(*************************************************************************) (* *) (* Z80 Hard Disk v1.00 *) (* (C) Copyright S.J.Kay 6th December 1993 *) (* *) (* Creates a disk file to be used by the Z80 Emulator *) (* program as a hard disk. *) (* *) (*************************************************************************) uses crt, dos; const HDDMEG = 4; { size of HDD file in Mbytes } SECSZE = 512; SECTRK = 64; HDDSEC = (HDDMEG * 1024) * (1024 div SECSZE); FLENME = 'Z80HDD.DSK'; MkeDrv : boolean = true; var F : file; i : integer; Sector : array [0..SECSZE-1] of byte; DrvPth : string[80]; ChkUsr : string[1]; begin clrscr; writeln; writeln('==================================================='); writeln('Z80 Hard Disk v1.00 (C) Copyright S.J.Kay 6/12/93'); writeln; writeln('Creates a disk file to be used by the Z80 Emulator'); writeln(' program as a hard disk'); writeln('==================================================='); writeln; writeln('Hard disk size: ', HDDMEG, ' Megabytes'); writeln; write('Enter drive path: '); readln(DrvPth); writeln; if (DrvPth <> '') and (not(DrvPth[length(DrvPth)] in [':', '\'])) then DrvPth := DrvPth + '\'; assign(F, DrvPth + FLENME); Setfattr(F, 0); { make file read/write } {$I-} reset(F); if ioresult = 0 then begin close(F); {$I+} writeln('WARNING - ', DrvPth + FLENME, ' will be lost forever'); write( 'Do you wish to continue (y/n) ?: '); readln(ChkUsr); MkeDrv := (ChkUsr= 'Y') or (ChkUsr = 'y'); writeln end; if MkeDrv then begin writeln('Creating ', DrvPth + FLENME); writeln; rewrite(F, SECSZE); fillchar(Sector, SECSZE, $E5); for i := 1 to HDDSEC do begin blockwrite(F, Sector, 1); if i mod SECTRK = 0 then write(^M, i:5, ' of ', HDDSEC) end; close(F); writeln; writeln; writeln('Z80 hard disk file created') end; Setfattr(F, ReadOnly); end.
unit main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Registry, ExtCtrls; const VERSION = 'Visual Patcher 1.0'; type TfmMain = class(TForm) Label1: TLabel; Label2: TLabel; edFile: TEdit; btBrowse: TButton; odFile: TOpenDialog; Bevel1: TBevel; btPatch: TButton; btQuit: TButton; Label3: TLabel; btUnpatch: TButton; Label4: TLabel; procedure FormActivate(Sender: TObject); procedure btBrowseClick(Sender: TObject); procedure btQuitClick(Sender: TObject); procedure btPatchClick(Sender: TObject); procedure btUnpatchClick(Sender: TObject); private { Private declarations } public { Public declarations } inited :boolean; end; var fmMain: TfmMain; implementation {$R *.dfm} type PFileData = ^TFileData; TFileData = array[0..3000000] of char; function iswin9x :boolean; var reg :TRegistry; ver :String; begin reg := TRegistry.Create; try reg.RootKey := HKEY_LOCAL_MACHINE; if reg.OpenKeyReadOnly('SOFTWARE\Microsoft\Windows NT\CurrentVersion') then begin ver := reg.ReadString ('CurrentVersion'); result := trim(ver) = ''; end else Result := true; finally reg.Free; end; // ReadRegStr $0 HKLM "SOFTWARE\Microsoft\Windows NT\CurrentVersion" CurrentVersion end; function Find (st :string; data :PFileData; size :integer) :integer; var pos, findpos :integer; tmp :char; begin pos := 0; findpos := 1; st := lowercase (st); while (pos < size) do begin tmp := data^[pos]; if tmp in ['A'..'Z'] then tmp := char ( byte (data^[pos]) + (byte ('a') - byte('A'))); if (tmp = st [findpos]) then Inc (findpos) else findpos := 1; Inc (pos); if (findpos > Length (st)) then begin Result := pos - findpos; exit; end; end; Result := -1; end; function PatchTA (fn :String; unpatch :boolean) :boolean; var fd :PFileData; f :file; br :integer; i, j :integer; fs, ts :string; begin if unpatch then begin fs := 'spank.dll'; ts := 'ddraw.dll'; end else begin fs := 'ddraw.dll'; ts := 'spank.dll'; end; // ShowMessage (version); // ShowMessage ('Patching ' + fn); New (fd); Result := false; try // ShowMessage ('Starting patch process'); AssignFile (f, fn); Reset (f, 1); BlockRead (f, fd^, 3000000, br); CloseFile (f); // ShowMessage ('Read file'); if br <> 1178624 then begin ShowMessage (version + ': Incorrect filesize. This patcher requires TA 3.1c to work!'); exit; end; i := Find (ts, fd, br); if i <> -1 then begin if unpatch then ShowMEssage (version + ': File is already unpatched!') else ShowMEssage (version + ': File is already patched!'); Result := true; exit; end; i := Find (fs, fd, br); if i = -1 then begin ShowMessage (version + ': Could not find location to patch'); exit; end; for j := 1 to 5 do fd[i+j] := ts[j]; { fd[i+1] := 's'; fd[i+2] := 'p'; fd[i+3] := 'a'; fd[i+4] := 'n'; fd[i+5] := 'k';} AssignFile (f, fn); Rewrite (f, 1); BlockWrite (f, fd^, br); CloseFile (f); Result := true; except on e: exception do begin ShowMessage (version + ': Exception occured (' + e.Message + ')'); Result := false; end; end; Dispose (fd); end; procedure TfmMain.FormActivate(Sender: TObject); var reg :TRegistry; tadir :string; begin if inited then exit; if (not iswin9x) then begin if (paramstr (1) <> '-silent') then begin if MessageDlg ('You are not running Windows 9x. Therefore it is not necessary to run this patcher. Do you still want to continue?', mtError, [mbYes, mbNo], 0) <> mrYes then Application.Terminate; end else application.terminate; end; tadir := ''; reg := TRegistry.Create; try reg.RootKey := HKEY_LOCAL_MACHINE; if reg.OpenKeyReadOnly('SOFTWARE\Yankspankers\TA Demo') then tadir := reg.ReadString ('TA_Dir') else if reg.OpenKeyReadOnly('SOFTWARE\Microsoft\DirectPlay\Applications\Total Annihilation') then tadir := reg.ReadString ('Path'); finally reg.Free; end; if (tadir = '') then tadir := 'C:\Cavedog\Totala'; if tadir[length(tadir)] = '\' then SetLength (tadir, length(tadir) - 1); tadir := tadir + '\totala.exe'; odFile.Filename := tadir; edFile.Text := tadir; inited := true; end; procedure TfmMain.btBrowseClick(Sender: TObject); begin if odFile.Execute then begin edFile.Text := odfile.FileName; end; end; procedure TfmMain.btQuitClick(Sender: TObject); begin Application.Terminate; end; procedure TfmMain.btPatchClick(Sender: TObject); begin if not FileExists (edFile.Text) then begin MessageDlg ('The specified file does not exist', mtError, [mbok], 0); exit; end; if PatchTA (edFile.Text, false) then begin MessageDlg ('Patching successful! A reboot may be required for the patch to take effect.', mtInformation, [mbok], 0); Application.Terminate; end else begin end; end; procedure TfmMain.btUnpatchClick(Sender: TObject); begin if not FileExists (edFile.Text) then begin MessageDlg ('The specified file does not exist', mtError, [mbok], 0); exit; end; if PatchTA (edFile.Text, true) then begin MessageDlg ('Removal of patch successful! A reboot may be required for the removal to take effect.', mtInformation, [mbok], 0); Application.Terminate; end else begin end; end; end.
program News; {$mode objfpc}{$H+} uses {$IFDEF UNIX} {$IFDEF UseCThreads} cthreads, {$ENDIF} {$ENDIF} Classes, sysutils { you can add units after this }; type TNews = record ATime: TDateTime; Title: string[100]; end; procedure AddTitle; var F: file of TNews; News: TNews; begin AssignFile(F, 'news.dat'); Write('Input current news title: '); Readln(News.Title); News.ATime := Now; if FileExists('news.dat') then begin FileMode := 2; // Read/Write Reset(F); Seek(F, System.FileSize(F)); // Go to last record to append end else Rewrite(F); Write(F, News); CloseFile(F); end; procedure ReadAllNews; var F: file of TNews; News: TNews; begin AssignFile(F, 'news.dat'); if FileExists('news.dat') then begin Reset(F); while not EOF(F) do begin Read(F, News); Writeln('------------------------------'); Writeln('Title: ', News.Title); Writeln('Time : ', DateTimeToStr(News.ATime)); end; CloseFile(F); end else Writeln('Empty database'); end; procedure Search; var F: file of TNews; News: TNews; Keyword: string; Found: boolean; begin AssignFile(F, 'news.dat'); Write('Input keyword to search for: '); Readln(Keyword); Found := False; if FileExists('news.dat') then begin Reset(F); while not EOF(F) do begin Read(F, News); if Pos(LowerCase(Keyword), LowerCase(News.Title)) > 0 then begin Found := True; Writeln('------------------------------'); Writeln('Title: ', News.Title); Writeln('Time : ', DateTimeToStr(News.ATime)); end; end; CloseFile(F); if not Found then Writeln(Keyword, ' Not found'); end else Writeln('Empty database'); end; function Menu: char; begin Writeln; Writeln('...........News database..........'); Writeln('1. Add news title'); Writeln('2. Display all news'); Writeln('3. Search'); Writeln('x. Exit'); Write('Please input a selection : '); Readln(Result); end; // Main application var Selection: char; begin repeat Selection := Menu; case Selection of '1': AddTitle; '2': ReadAllNews; '3': Search; end; until LowerCase(Selection) = 'x'; end.
{ LazPackager preview window for generated files Copyright (C) 2012 Bernd Kreuss prof7bit@gmail.com This source is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy of the GNU General Public License is available on the World Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit frmLazPackagerPreview; {$mode objfpc}{$H+} interface uses SysUtils, SynEdit, Forms; type { TFFilePreview } TFFilePreview = class(TForm) EdPreview: TSynEdit; procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure SetText(Title, Txt: String); private { private declarations } public { public declarations } end; var FFilePreview: TFFilePreview; implementation {$R *.lfm} { TFFilePreview } procedure TFFilePreview.SetText(Title, Txt: String); begin Caption := Format('Preview of %s', [Title]); EdPreview.Text := Txt; end; procedure TFFilePreview.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin CloseAction := caFree; end; end.
(*============================================================================ -----BEGIN PGP SIGNED MESSAGE----- This code (c) 1994, 1997 Graham THE Ollis GENERAL NOTES ============= This is 16bit DOS TURBO PASCAL source code. It has been tested using TURBO PASCAL 7.0. You will need AT LEAST version 5.0 to compile this source code. You may need 7.0. This is a generic pascal header for all my old pascal programs. Most of these programs were written before I really got excited enough about 32bit operating systems. In general this code dates back to 1994. Some of it is important enough that I still work on it. For the most part though, it's not the best code and it's probably the worst example of documentation in all of computer science. oh well, you've been warned. PGP NOTES ========= This PGP signed message is provided in the hopes that it will prove useful and informative. My name is Graham THE Ollis <ollisg@ns.arizona.edu> and my public PGP key can be found by fingering my university account: finger ollisg@u.arizona.edu LEGAL NOTES =========== You are free to use, modify and distribute this source code provided these headers remain in tact. If you do make modifications to these programs, i'd appreciate it if you documented your changes and leave some contact information so that others can blame you and me, rather than just me. If you maintain a anonymous ftp site or bbs feel free to archive this stuff away. If your pressing CDs for commercial purposes again have fun. It would be nice if you let me know about it though. HOWEVER- there is no written or implied warranty. If you don't trust this code then delete it NOW. I will in no way be held responsible for any losses incurred by your using this software. CONTACT INFORMATION =================== You may contact me for just about anything relating to this code through e-mail. Please put something in the subject line about the program you are working with. The source file would be best in this case (e.g. frag.pas, hexed.pas ... etc) ollisg@ns.arizona.edu ollisg@idea-bank.com ollisg@lanl.gov The first address is the most likely to work. all right. that all said... HAVE FUN! -----BEGIN PGP SIGNATURE----- Version: 2.6.2 iQCVAwUBMv1UFoazF2irQff1AQFYNgQAhjiY/Dh3gSpk921FQznz4FOwqJtAIG6N QTBdR/yQWrkwHGfPTw9v8LQHbjzl0jjYUDKR9t5KB7vzFjy9q3Y5lVHJaaUAU4Jh e1abPhL70D/vfQU3Z0R+02zqhjfsfKkeowJvKNdlqEe1/kSCxme9mhJyaJ0CDdIA 40nefR18NrA= =IQEZ -----END PGP SIGNATURE----- ============================================================================== | gshift.pas | some kind of assembly function. don't ask me, i only work here. | | History: | Date Author Comment | ---- ------ ------- | -- --- 94 G. Ollis created and developed program ============================================================================*) {$I-} Unit GShift; INTERFACE Const KBRShift =$01; KBLShift =$02; KBCtrl =$04; KBAlt =$08; KBScroll =$10; KBNum =$20; KBCaps =$40; KBInsert =$80; {++PROCEDURES++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} Function GetShiftByte:Byte; {++FUNCTIONS+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} {++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} IMPLEMENTATION {----------------------------------------------------------------------} Function GetShiftByte:Byte; Var Temp:Byte; Begin asm mov ah,02h int 16h mov Temp,al End; GetShiftByte:=Temp; End; {======================================================================} End.
Program SimulationPrairie; {$IFDEF FPC}{$MODE OBJFPC}{H$H+}{$ENDIF} USES Crt, sysutils, classes; Const N = 5; VIE = 1; MORT = 0; Type Position = record x,y : integer; {position des objets en vie} end; listePositions = array of Position; typeGrille = array[0..N-1,0..N-1] of Integer; procedure afficherGrille(grille: typeGrille); forward; procedure GetInitialPositions(var positioninitale : listePositions; strCoords: string); forward; { fonction supplémentaire, Initialisation, Remettre à Zero toutes les cellules de la grille à l'état MORT } Function RAZGrille : typeGrille; Var i, j : integer; Mat : typeGrille; Begin for i := 0 to (N-1) do Begin for j := 0 to (N-1) do Mat[i,j] := MORT; End; RAZGrille := Mat; End; { procedure supplémentaire, pour pouvoir voir l'évolution pendant la simulation, avec ou sans effacer les données précédentes} Procedure afficheMessageGrille(message : string; Mat : typeGrille; doitEffacer :boolean ); Begin if ( doitEffacer = True ) then ClrScr; writeln(message); writeln('******************************************************'); afficherGrille(Mat); End; // procédure qui affiche les arguments nécessaires dans la ligne de commande pour le bon fonctionmment . Aide à l'utilisateur procedure afficherUtilisation; Begin Writeln('***** Utilisation du programme *******'); writeln; writeln('SimulationPrairie -i ficin -o ficout'); writeln; writeln('************* ou ********************'); writeln; writeln('SimulationPrairie -o ficout -i ficin'); writeln; writeln(' -i ficin => -i NOM DU FICHIER D''ENTREE A LIRE OU A SAUVEGARDER'); writeln('AVEC LES COORDONNEES DES POSITIONS DE VIE INITIALE'); writeln; writeln(' -o ficout => NOM DU FICHIER DE SORTIE A SAUVEGARDER'); writeln('APRES LA SIMULATION D''UNE NOUVELLE GENERATION'); writeln; End; // récuperer les nom des fichiers d'entrée et de sortie selon les paramètres de commandes saisies par l'utilisateur procedure GetFileNames(var input_filename, output_filename: string); Begin input_filename := ''; output_filename := ''; case lowercase(ParamStr(1)) of '-i' : begin input_filename := ParamStr(2); end; '-o' : begin output_filename := ParamStr(2); end; end; case lowercase(ParamStr(3)) of '-i' : begin input_filename := ParamStr(4); end; '-o' : begin output_filename := ParamStr(4); end; end; if ( length(output_filename) <= 0 ) or ( length(input_filename) <= 0 ) then begin writeln('LE NOM DU FICHIER D''ENTREE ET/OU SORTIE N''EST PAS VALIDE !'); exit; end; End; {fonction supplémentaire} function InitPositions(var nbIteration : integer): listePositions; var positioninitale: listePositions; strCoord: string; Begin write('VEUILLEZ DONNER LE NOMBRE D''ITERATIONS POUR LA SIMULATION : '); readln(nbIteration); clrscr; Writeln('VEUILLEZ SAISIR LES COORDONEES DES CELLULES VIVANTES DANS CE FORMAT (x y) : '); writeln('X et Y ENTRE PARENTHESE SEPARE PAR UN ESPACE'); Writeln('EXEMPLE D''UTILISATION : POUR TROIS CELLULES VIVANTES AYANT LES COORDONNEES'); writeln('0,0 2,3 et 4,4 SAISIR : (0 0) (2 3) (4 4) '); Writeln('LE NON RESPECT DE CETTE REGLE INITIALISERA LES POSITIONS A -1 !'); readln(strCoord); GetInitialPositions(positioninitale,strCoord); InitPositions := positioninitale; End; // strcoords : chaine des coordonnées sous forme de (x y) (x y) etc... procedure GetInitialPositions(var positioninitale : listePositions; strCoords: string); var separateur,str : string; i, p,x, y, len: Integer; OutPutList: TStringList; Begin // Creation d'une liste pour recuperer les coord separateur := ' '; // espace pour separer les coord x et y OutPutList := TStringList.Create; len := length(positioninitale); try // Utiliser le caractère fermeture de parenthèse pour decouper OutPutList.Delimiter := ')'; OutPutList.StrictDelimiter := true; // oui, ce format est attendu, (x y) (x y) // Fournir la chaine saisie par l'utilisateur pour decouper OutPutList.DelimitedText := strCoords; // si la saisie est correcte, nous obtenons (x,y (x,y etc.. dans outputList for i := 0 to OutPutList.Count - 1 do // attention, il y a toujours un élément en trop après decoupage begin x := -1; y := -1; // nous ne savons pas si les valeurs sont correctes, par précaution initialisation à un état non supporté str := Trim(OutPutList[i]); // suppression des espaces du début et fin if ( length(str) > 0 ) and (str[1] = '(') then // attention, l'indice de string commence tjrs à 1 non à zero comme le tableau (array) begin str := copy(str,2,length(str)); // supprime le premier caractère '(' et copier le retse p := Pos(separateur,str); // trouvé la position du caractère espace dans la chaine str if p > 0 then begin // p > 0 vaut x := strToInt(Copy(str, 1, p-1)); y := strToInt(Copy(str, p + length(separateur), length(str))); // writeln('x :' + IntToStr(x) + ' y :' + IntToStr(y)); end; if ( x >= 0) and (x < N) and ( y >= -1) and (y <N) then begin setlength(positioninitale,len+1); positioninitale[len].x := x; positioninitale[len].y := y; len := len +1; end end // fin if end; // fin for finally // liberation de la mémoire OutPutList.Free; end; End; procedure SaveToDisk( positioninitale : listePositions; nb : integer; fileName, msg: string); var i, len : integer; ch : char; strCoords : string; tfIn: TextFile; Begin write('Voulez-vous sauvegarder ' + msg + ' dans un fichier (O/N) ? : '); ch:=ReadKey; if ( ch = 'o' ) or (ch = 'O') then begin try len := length(positioninitale); strCoords := 'Position = ['; for i := 0 to len-1 do begin strCoords := strCoords + '(' + IntToStr(positioninitale[i].x) + ' ' + IntToStr(positioninitale[i].y) + ') '; end; if ( len > 0 ) then strCoords := copy(strCoords,1,length(strCoords)-1) + ']' // pour supprimer le dernier espace, si il y a au moins une vie else strCoords := strCoords + ']'; // aucune vie après la simulation , la ligne reste comme celle ci : Position =[] // Set the name of the file that will be created AssignFile(tfIn, fileName); rewrite(tfIn); // Creation du fichier. writeln(tfIn, 'Vie'); writeln(tfIn, strCoords); writeln(tfIn,'NombreGeneration = ' + IntToStr(nb)); CloseFile(tfIn); // Information à l'utilisateur et attendre la saisie d'une touche writeln('Fichier ', fileName, ' A ETE CREE AVCE SUCCES ! APPUYEZ SUR UNE TOUCHE POUR CONTINUER.'); readkey; except // If there was an error the reason can be found here on E: EInOutError do writeln('ERREUR FICHIER DETAILS: ', E.ClassName, '/', E.Message); end; end; End; function IsValidPositions(var s : string;var posCoord: listePositions): boolean; var isvalid : boolean; tmp : string; Begin isvalid := true; // au depart , on dit tout va bien avant de tester le contenu de la ligne 2 lu dans le fichier // la ligne 2 doit commencer par 'Position = [' => minimum 12 caractères if ( length(s) < 12 ) then isvalid := false else begin tmp := copy(s,1,12); tmp := upcase(tmp); s := copy(s,13,length(s)-13); // pour supprimer le dernier caracctère ']' if ( tmp <> 'POSITION = [' ) then begin s := 'FORMAT NON VALIDE, VALEUR ATTENDU LIGNE 2 => POSITION = [(x,y)]'; isvalid := false; end; GetInitialPositions(posCoord,s); end; IsValidPositions := isvalid; End; function IsValidIteration(var s : string;var nbIteration: integer): boolean; var isvalid : boolean; tmp : string; Begin isvalid := true; // au depart , on dit tout va bien avant de tester le contenu de la ligne 3 lu dans le fichier // la ligne 3 doit commencer par 'NombreGeneration = ' => minimum 19 caractères if ( length(s) < 19 ) then isvalid := false else begin tmp := copy(s,1,19); tmp := upcase(tmp); // convertir en majuscule et stock la même valeur dans tmp s := copy(s,20,length(s)); // copier le reste après le mot 'NombreGeneration = ' s := Trim(s); writeln(s); writeln(tmp); if ( tmp <> 'NOMBREGENERATION = ' ) then begin s := 'FORMAT NON VALIDE, VALEUR ATTENDU LIGNE 3 => NOMBREGENERATION = Valeur'; isvalid := false; end else nbIteration := strToInt(s); end; IsValidIteration := isvalid; End; function GetInputFromFile(input_filename: string; var nbIteration : integer): listePositions; var posCoord : listePositions ; tfIn: TextFile; s : string; count : integer; Begin count := 0; nbIteration := 0; writeln('Lecture du contenu du fichier : ', input_filename); writeln('========================================='); // Définir le nom du fichier que on va lire AssignFile(tfIn, input_filename); // Incorporer le traitement des fichiers dans un bloc try / except pour gérer les erreurs avec élégance try // Ouvrez le fichier à lire reset(tfIn); // Continuez à lire les lignes jusqu'à la fin du fichier while not eof(tfIn) do begin readln(tfIn, s); count := count + 1; case count of 1 : begin if ( s <> 'Vie' ) then raise exception.create('FORMAT INCORRECTE : VALEUR ATTENDU LIGNE 1=> Vie'); end; 2 : begin if ( IsValidPositions(s, posCoord) = false ) then raise exception.create(s); end; 3 : begin if ( IsValidIteration(s, nbIteration) = false ) then raise exception.create(s); end; end; end; finally // Dans tous les cas , nous fermons le fichier avec ou sans exceptions CloseFile(tfIn); end; { efin du bloc try} GetInputFromFile := posCoord; End; // fonction remplissage de grille Function remplirGrille(tableau: listePositions) : typeGrille; Var Mat : typeGrille; k, len: integer; Begin Mat := RAZGrille; len := length(tableau); For k := 0 to len-1 do begin if ( (tableau[k].x >= 0) and (tableau[k].x < N) and (tableau[k].y >=0 ) and (tableau[k].y < N) ) then Mat[tableau[k].x,tableau[k].y] := 1; end; afficheMessageGrille('VALEURS DES CELLULES DE LA GRILLE APRES REMPLISSAGE', Mat, True); remplirGrille := Mat; End; Function calculerValeurCellule(grille: typeGrille; x,y: Integer) : Integer; Var nbvivante, i, j,coord_i,coord_j, valeurcellule : integer; Begin nbvivante := 0; For i:= x-1 to x+1 do begin For j:=y-1 to y+1 do begin coord_i:= i; coord_j:= j; if (i < 0) then coord_i := N-1 { changement de coord de x et y si en dehors de la limite du tableau càd < 0 ou > N-1} else if (i > N-1) then coord_i:= 0; if (j < 0) then coord_j := N-1 else if (j > N-1) then coord_j :=0; if ( ((i <> x) or (j <> y)) and (grille[coord_i,coord_j] = VIE) ) then nbvivante := nbvivante+1; end; end; if ( (grille[x,y]= VIE) and (nbvivante >= 2) and (nbvivante <= 3) ) then valeurcellule := VIE { règle 1 } else if ( (grille[x,y]= VIE) and (nbvivante >= 4) ) then valeurcellule := MORT { règle 2 } else if ( (grille[x,y]= VIE) and (nbvivante <= 1) ) then valeurcellule := MORT { règle 2 } else if ( (grille[x,y]= MORT) and (nbvivante = 3) ) then valeurcellule := VIE { règle 3 } else valeurcellule := grille[x,y]; calculerValeurCellule := valeurcellule; End; Function calculerNouvelleGrille(grille: typeGrille) : typeGrille; Var nouvelleGrille : typeGrille; x, y : integer; Begin For x:= 0 to N-1 do Begin For y:=0 to N-1 do Begin nouvelleGrille[x,y] := calculerValeurCellule(grille, x, y); end; End; calculerNouvelleGrille := nouvelleGrille; End; procedure afficherGrille(grille: typeGrille); var x, y : integer; affichetext: string; Begin For x:= 0 to N-1 do begin affichetext := ' '; For y:=0 to N-1 do begin if ( grille[x,y] = MORT ) then affichetext := affichetext + ' . ' else if ( grille[x,y] = VIE ) then affichetext := affichetext + ' v ' else affichetext := affichetext + ' ? '; end; writeln(affichetext); end; readln; End; function run(grilleInitiale: typeGrille; n: Integer) : typeGrille; Var i : integer; Begin if ( n > 0 ) then begin For i:=1 to n do Begin grilleInitiale := calculerNouvelleGrille(grilleInitiale); afficheMessageGrille('VALEURS DES CELLULES DE LA GRILLE APRES L''ITERATION ' + IntToStr(i), grilleInitiale, False); end; end else While(n <= 0) do Begin grilleInitiale := calculerNouvelleGrille(grilleInitiale); afficheMessageGrille('VALEURS DES CELLULES DE LA GRILLE - ITERATION EN BOUCLE', grilleInitiale, False); End; run := grilleInitiale; End; Procedure SaveTheGame(positionInitiale: listepositions;grille:typeGrille;nbiteration: integer; input_filename, output_filename: string); var posFinale: listepositions; x,y, len : integer; Begin SaveToDisk( positionInitiale, nbiteration, input_filename, 'les coordonnées de la grille initiale '); len := 0; setlength(posFinale,0); // on part à zero, posfInale contient aucun objet en vie For y:= 0 to N-1 do begin For x:=0 to N-1 do begin if ( grille[x,y] = VIE ) then begin setlength(posFinale,len+1); posFinale[len].x := x; posFinale[len].y := y; len := len +1; end end; end; SaveToDisk( posFinale, nbiteration, output_filename, 'les coordonnées de la grille finale après la simulation '); End; // programme principale Var positionInitiale : listePositions; nbiteration : integer; input_filename, output_filename: string; Var grille : typeGrille; Begin try // si le valeurs attendues des arguments de 1 ou 3 est différents de -i ou -o, nous informons l'utilsateur le fonctionnement du programme if ( ParamCount < 4 ) or ( ( lowercase(ParamStr(1)) <> '-i') and ( lowercase(ParamStr(1)) <> '-o') ) or ( ( lowercase(ParamStr(3)) <> '-i') and ( lowercase(ParamStr(3)) <> '-o') ) then begin afficherUtilisation; end else begin GetFileNames(input_filename, output_filename); // on recupère le nom du fichier d'entrée et sortie à partir du argument 2 et 4 , les arguments peuvent être inversés, cette fn doit le traiter correctement If FileExists(input_filename) Then positionInitiale := GetInputFromFile(input_filename,nbiteration) // si le fichier d'entrée est présent, on recupère les valeurs initiales à partir de ce fichier dans le tableau positionInitiale else positionInitiale := InitPositions(nbiteration); // si non, on demande l'utilisatur de les saisir dans un format attendu grille := remplirGrille(positionInitiale); grille := run(grille,nbiteration); afficheMessageGrille('VALEURS DES CELLULES DE LA GRILLE FINALE APRES LA SIMULATION', grille, true); SaveTheGame(positionInitiale,grille,nbiteration,input_filename, output_filename); // sauvegarde de jeu d'entrée et sortie avec les noms des fichiers saisie par l'utilisateur dans la ligne de commande end; Except on E :Exception do begin writeln(E.message); readkey; end end; end. { fin du programme }
/////////////////////////////////////////////////////////////////////////// // Project: CW // Program: aboutu.pas // Language: Object Pascal - Delphi ver 3.0 // Support: David Fahey // Date: 01Oct97 // Purpose: Displays a dialog that allows the user to learn the // International Morse code. // History: 10Oct97 Initial coding DAF // Notes: None /////////////////////////////////////////////////////////////////////////// unit aboutu; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TAbout = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var About: TAbout; implementation {$R *.DFM} procedure TAbout.Button1Click(Sender: TObject); begin About.Close ; end; end.
{ * This source code accompanies the article "How to load and save documents in * TWebBrowser in a Delphi-like way" which can be found at * http://www.delphidabbler.com/articles?article=14 * * The code is merely a proof of concept and is intended only to illustrate the * article. It is not designed for use in its current form in finished * applications. The code is provided on an "AS IS" basis, WITHOUT WARRANTY OF * ANY KIND, either express or implied. * * $Rev: 38 $ * $Date: 2010-02-06 15:36:08 +0000 (Sat, 06 Feb 2010) $ } {$BOOLEVAL OFF} unit FmMain; interface {$IFDEF CONDITIONALEXPRESSIONS} {$IF CompilerVersion >= 15.0} // >= Delphi 7 {$WARN UNSAFE_TYPE OFF} {$IFEND} {$ENDIF} uses SysUtils, Forms, Dialogs, OleCtrls, SHDocVw, StdCtrls, ExtCtrls, Controls, Classes, ComCtrls, UWebBrowserWrapper; type TMainForm = class(TForm) pnlCtrl: TPanel; btnSaveString: TButton; btnSaveStream: TButton; btnSaveFile: TButton; btnLoadString: TButton; btnLoadStream: TButton; btnLoadFile: TButton; edURL: TEdit; lblURL: TLabel; btnNavigateURL: TButton; btnNavigateLocal: TButton; pnlLeft: TPanel; pnlHelp: TPanel; wbHelp: TWebBrowser; pnlSource: TPanel; lblSource: TLabel; splitHoriz: TSplitter; edSource: TMemo; lblHelp: TLabel; pnlOutput: TPanel; lblTest: TLabel; pnlWB: TPanel; wbTest: TWebBrowser; lblSourceGen: TLabel; btnNavigateResource: TButton; dlgOpen: TOpenDialog; dlgSave: TSaveDialog; sbMain: TStatusBar; procedure FormCreate(Sender: TObject); procedure btnLoadFileClick(Sender: TObject); procedure btnLoadStreamClick(Sender: TObject); procedure btnLoadStringClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnSaveStringClick(Sender: TObject); procedure btnSaveStreamClick(Sender: TObject); procedure btnSaveFileClick(Sender: TObject); procedure btnNavigateURLClick(Sender: TObject); procedure btnNavigateLocalClick(Sender: TObject); procedure lblSourceGenClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnNavigateResourceClick(Sender: TObject); private fWBW: TWebBrowserWrapper; {$IFDEF UNICODE} fSampleEncoding: TEncoding; {$ENDIF} procedure UpdateStatusBar; end; var MainForm: TMainForm; implementation uses MSHTML, Windows, FmSaveEncodingDlg, FmSampleCodeEncodingDlg; {$R *.dfm} {$IFDEF UNICODE} function EncodingName(const Encoding: TEncoding): string; begin if TEncoding.IsStandardEncoding(Encoding) then begin if Encoding = TEncoding.ASCII then Result := 'ASCII' else if Encoding = TEncoding.BigEndianUnicode then Result := 'Unicode (BE)' else if Encoding = TEncoding.Default then Result := 'Default' else if Encoding = TEncoding.Unicode then Result := 'Unicode (LE)' else if Encoding = TEncoding.UTF7 then Result := 'UTF7' else if Encoding = TEncoding.UTF8 then Result := 'UTF8'; end else begin if Encoding is TMBCSEncoding then Result := 'MBCS' else Result := 'Unknown'; end; end; {$ENDIF} { TMainForm } procedure TMainForm.btnLoadFileClick(Sender: TObject); begin if dlgOpen.Execute then begin fWBW.LoadFromFile(dlgOpen.FileName); UpdateStatusBar; end; end; procedure TMainForm.btnLoadStreamClick(Sender: TObject); var Stm: TMemoryStream; begin Stm := TMemoryStream.Create; try {$IFDEF UNICODE} edSource.Lines.SaveToStream(Stm, fSampleEncoding); {$ELSE} edSource.Lines.SaveToStream(Stm); {$ENDIF} Stm.Position := 0; fWBW.LoadFromStream(Stm); finally Stm.Free; end; UpdateStatusBar; end; procedure TMainForm.btnLoadStringClick(Sender: TObject); begin {$IFDEF UNICODE} fWBW.LoadFromString(edSource.Text, fSampleEncoding); {$ELSE} fWBW.LoadFromString(edSource.Text); {$ENDIF} UpdateStatusBar; end; procedure TMainForm.btnNavigateLocalClick(Sender: TObject); begin if dlgOpen.Execute then begin fWBW.NavigateToLocalFile(dlgOpen.FileName); UpdateStatusBar; end; end; procedure TMainForm.btnNavigateResourceClick(Sender: TObject); begin fWBW.NavigateToResource(HInstance, 'HTMLRES_HTML'); UpdateStatusBar; end; procedure TMainForm.btnNavigateURLClick(Sender: TObject); begin if edURL.Text <> '' then begin fWBW.NavigateToURL(edURL.Text); UpdateStatusBar; end; end; procedure TMainForm.btnSaveFileClick(Sender: TObject); begin if dlgSave.Execute then begin {$IFDEF UNICODE} if SaveEncodingDlg.ShowModal <> mrOK then Exit; if Assigned(SaveEncodingDlg.Encoding) then fWBW.SaveToFile(dlgSave.FileName, SaveEncodingDlg.Encoding) else fWBW.SaveToFile(dlgSave.FileName); {$ELSE} fWBW.SaveToFile(dlgSave.FileName); {$ENDIF} end; end; procedure TMainForm.btnSaveStreamClick(Sender: TObject); var Stm: TMemoryStream; begin Stm := TMemoryStream.Create; try {$IFDEF UNICODE} if SaveEncodingDlg.ShowModal <> mrOK then Exit; if Assigned(SaveEncodingDlg.Encoding) then begin fWBW.SaveToStream(Stm, SaveEncodingDlg.Encoding); fSampleEncoding := SaveEncodingDlg.Encoding; end else begin fWBW.SaveToStream(Stm); fSampleEncoding := fWBW.Encoding; end; {$ELSE} fWBW.SaveToStream(Stm); {$ENDIF} Stm.Position := 0; edSource.Lines.LoadFromStream(Stm); finally Stm.Free; end; end; procedure TMainForm.btnSaveStringClick(Sender: TObject); begin edSource.Text := fWBW.SaveToString; end; procedure TMainForm.FormCreate(Sender: TObject); begin wbTest.Silent:=true; fWBW := TWebBrowserWrapper.Create(wbTest); {$IFDEF UNICODE} Caption := 'Article#14 Demo [Unicode version]'; fSampleEncoding := TEncoding.Default; // ANSI {$ELSE} Caption := 'Article#14 Demo [ANSI version]'; {$ENDIF} end; procedure TMainForm.FormDestroy(Sender: TObject); begin fWBW.Free; end; procedure TMainForm.FormShow(Sender: TObject); var Wrapper: TWebBrowserWrapper; begin // Load help html from resources to r/h browser window Wrapper := TWebBrowserWrapper.Create(wbHelp); try Wrapper.NavigateToResource(HInstance, 'HELP_HTML'); finally Wrapper.Free; end; // Load blank document into test browser Wrapper := TWebBrowserWrapper.Create(wbTest); try Wrapper.NavigateToURL('about:blank'); finally Wrapper.Free; end; end; procedure TMainForm.lblSourceGenClick(Sender: TObject); var RS: TResourceStream; ResName: string; begin if SampleCodeEncodingDlg.ShowModal <> mrOK then Exit; ResName := SampleCodeEncodingDlg.ResourceName; // Display sample HTML code in edSource memo RS := TResourceStream.Create(HInstance, PChar(ResName), RT_RCDATA); try {$IFDEF UNICODE} edSource.Lines.LoadFromStream(RS, SampleCodeEncodingDlg.Encoding); fSampleEncoding := SampleCodeEncodingDlg.Encoding; {$ELSE} edSource.Lines.LoadFromStream(RS); {$ENDIF} finally RS.Free; end; end; procedure TMainForm.UpdateStatusBar; var Doc: IHTMLDocument2; begin if not Assigned(fWBW.WebBrowser.Document) then exit; // wait for document to load while fWBW.WebBrowser.ReadyState <> READYSTATE_COMPLETE do Application.ProcessMessages; if fWBW.WebBrowser.Document.QueryInterface(IHTMLDocument2, Doc) = S_OK then {$IFDEF UNICODE} sbMain.SimpleText := Format( 'Charset: %s Encoding: %s', [Doc.charset, EncodingName(fWBW.Encoding)] ); {$ELSE} sbMain.SimpleText := Format('Charset: %s', [Doc.charset]); {$ENDIF} end; end.
unit UMouseKeyboard; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Windows, Clipbrd; type TPixelColor = class position: TPoint; color: COLORREF; end; Actions = class class function getColorHexPositionPix(x,y: Integer):String; class function getPositionPix(x,y: Integer):TPixelColor; class function getMousePix():TPixelColor; class procedure MouseClick(x,y: Integer); class procedure MouseMove(x,y: Integer); class procedure MouseMoveRelative(x,y: Integer); class procedure MouseDown(x,y: Integer); class procedure MouseUp(x,y: Integer); class function IsControlKeyPressed(): Boolean; class function IsKeyPressed(key:longint): Boolean; class procedure waitColorHexPositionPix2(x,y: Integer; hex:String; x2,y2: Integer; hex2:String); class procedure waitColorHexPositionPix(x,y: Integer; hex:String); class procedure waitNotColorHexPositionPix(x,y: Integer; hex:String); class procedure waitNotColorHexPositionPix2(x,y: Integer; hex:String; x2,y2: Integer; hex2:String); class function IsShiftlKeyPressed(): Boolean; class procedure PressControlA; class procedure PressControlC; class procedure PressControlV; end; Game = class class function play(x1,y1: Integer; c1:String; x2,y2: Integer; c2:String; x,y:Integer):Boolean; end; implementation procedure SplitStr(const Source, Delimiter: String; var DelimitedList: TStringList); var s: PChar; DelimiterIndex: Integer; Item: String; begin s:=PChar(Source); repeat DelimiterIndex:=Pos(Delimiter, s); if DelimiterIndex=0 then Break; Item:=Copy(s, 1, DelimiterIndex-1); DelimitedList.Add(Item); inc(s, DelimiterIndex + Length(Delimiter)-1); until DelimiterIndex = 0; DelimitedList.Add(s); end; class function Actions.getPositionPix(x,y: Integer):TPixelColor; begin if (GetDC(0) = 0) then Exit; result := TPixelColor.Create; result.position := TPoint.Create(x, y); result.color:= GetPixel(GetDC(0), x, y); result.position.x := x; result.position.y := y; end; class function Actions.getMousePix():TPixelColor; var CursorPos: TPoint; begin if (GetDC(0) = 0) then Exit; if not GetCursorPos(CursorPos) then Exit; result := TPixelColor.Create; result.position := TPoint.Create(0,0); result := Actions.getPositionPix(CursorPos.x, CursorPos.y); end; class procedure Actions.MouseClick(x,y: Integer); begin SetCursorPos(x, y); Mouse_Event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); Mouse_Event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); end; class procedure Actions.MouseMove(x,y: Integer); begin SetCursorPos(x, y); end; class procedure Actions.MouseMoveRelative(x,y: Integer); begin mouse_event(MOUSEEVENTF_MOVE, x, y, 0, 0); end; class procedure Actions.MouseDown(x,y: Integer); begin Mouse_Event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0); end; class procedure Actions.MouseUp(x,y: Integer); begin Mouse_Event(MOUSEEVENTF_ABSOLUTE + MOUSEEVENTF_MOVE + MOUSEEVENTF_LEFTDOWN + MOUSEEVENTF_LEFTUP, x, y, 0, 0); end; class function Actions.IsControlKeyPressed(): Boolean; begin Result := GetKeyState(VK_SHIFT) < 0; end; class function Actions.IsKeyPressed(key:longint): Boolean; begin Result := GetKeyState(key) < 0; end; class function Actions.getColorHexPositionPix(x,y: Integer):String; var DC: HDC; begin DC := GetDC(0); if (DC = 0) then Exit; result := GetPixel(DC, x, y).ToHexString; ReleaseDC(0, DC); end; class procedure Actions.waitColorHexPositionPix(x,y: Integer; hex:String); begin while Actions.getColorHexPositionPix(x,y) = hex do begin Sleep(1000); end; Sleep(1000); while Actions.getColorHexPositionPix(x,y) = hex do begin Sleep(1000); end; end; class procedure Actions.waitColorHexPositionPix2(x,y: Integer; hex:String; x2,y2: Integer; hex2:String); var i: Integer; begin i := 0; while (Actions.getColorHexPositionPix(x,y) = hex) or (Actions.getColorHexPositionPix(x2,y2) = hex2) and (i < 10) do begin Sleep(1000); inc(i); end; Sleep(1000); while (Actions.getColorHexPositionPix(x,y) = hex) or (Actions.getColorHexPositionPix(x2,y2) = hex2) and (i < 10) do begin Sleep(1000); end; end; class procedure Actions.waitNotColorHexPositionPix(x,y: Integer; hex:String); //var i: Integer; begin //i := 0; //while (Actions.getColorHexPositionPix(x,y) <> hex) and (i < 100) do while (Actions.getColorHexPositionPix(x,y) <> hex) do begin Sleep(200); //inc(i); end; Sleep(100); { while (Actions.getColorHexPositionPix(x,y) <> hex) and (i < 10) do begin Sleep(1000); inc(i); end; } end; class procedure Actions.waitNotColorHexPositionPix2(x,y: Integer; hex:String; x2,y2: Integer; hex2:String); begin while (Actions.getColorHexPositionPix(x,y) <> hex) or (Actions.getColorHexPositionPix(x2,y2) <> hex2) do begin Sleep(1000); end; //Sleep(1000); while (Actions.getColorHexPositionPix(x,y) <> hex) or (Actions.getColorHexPositionPix(x2,y2) <> hex2) do begin Sleep(1000); end; end; class function Actions.IsShiftlKeyPressed(): Boolean; begin Result := GetKeyState(VK_SHIFT) < 0; end; class procedure Actions.PressControlA; begin Keybd_Event(VK_CONTROL, 1, 0, 0); Keybd_Event(VK_A, 1, 0, 0); Keybd_Event(VK_A, 1, KEYEVENTF_KEYUP, 0); Keybd_Event(VK_CONTROL, 1, KEYEVENTF_KEYUP, 0); end; class procedure Actions.PressControlC; begin Keybd_Event(VK_CONTROL, 1, 0, 0); Keybd_Event(VK_C, 1, 0, 0); Keybd_Event(VK_C, 1, KEYEVENTF_KEYUP, 0); Keybd_Event(VK_CONTROL, 1, KEYEVENTF_KEYUP, 0); end; class procedure Actions.PressControlV; begin Keybd_Event(VK_CONTROL, 1, 0, 0); Keybd_Event(VK_V, 1, 0, 0); Keybd_Event(VK_V, 1, KEYEVENTF_KEYUP, 0); Keybd_Event(VK_CONTROL, 1, KEYEVENTF_KEYUP, 0); end; class function Game.play(x1,y1: Integer; c1:String; x2,y2: Integer; c2:String; x,y:Integer):Boolean; begin result := False; if (Actions.getColorHexPositionPix(x1, y1) = c1) and (Actions.getColorHexPositionPix(x2, y2) = c2) then begin Actions.MouseClick(x,y); result := True; end; end; end.
unit Item; interface uses SysUtils, Contnrs, Produto, Usuario, AdicionalItem, Generics.Collections, MateriaDoProduto, QuantidadePorValidade; type TItem = class private Fcodigo_pedido: integer; Fcodigo: integer; Fcodigo_produto: integer; Fhora: TDateTime; Fvalor: Real; FProduto :TProduto; Fquantidade: Real; FAdicionais :TObjectList<TAdicionalItem>; FMateriasDoProduto :TObjectList<TMateriaDoProduto>; Fimpresso :String; FvalorUnitario :Real; FCodigo_usuario :integer; FUsuario :TUsuario; FFracionado :String; FQuantidade_pg :Real; FQtd_fracionado: Integer; FCancelado :String; FMotivoCancelamento :String; FCodigo_validade: integer; FQuantidadesPorValidade :TObjectList<TQuantidadePorValidade>; function GetProduto: TProduto; function GetAdicionais: TObjectList<TAdicionalItem>; destructor Destroy;override; function GetUsuario: TUsuario; function GetTotalAdicionais: Real; function GetTotalBruto: Real; function GetTotalLiquido: Real; function GetMateriasDoProduto: TObjectList<TMateriaDoProduto>; function GetQuantidadesPorValidade: TObjectList<TQuantidadePorValidade>; public property codigo :integer read Fcodigo write Fcodigo; property codigo_pedido :integer read Fcodigo_pedido write Fcodigo_pedido; property codigo_produto :integer read Fcodigo_produto write Fcodigo_produto; property hora :TDateTime read Fhora write Fhora; property quantidade :Real read Fquantidade write Fquantidade; property Adicionais :TObjectList<TAdicionalItem> read GetAdicionais write FAdicionais; property impresso :String read Fimpresso write Fimpresso; property valor_Unitario :Real read FvalorUnitario write FvalorUnitario; property codigo_usuario :integer read FCodigo_usuario write FCodigo_usuario; property Fracionado :String read FFracionado write FFracionado; property quantidade_pg :Real read FQuantidade_pg write FQuantidade_pg; property qtd_fracionado :Integer read FQtd_fracionado write FQtd_fracionado; property Cancelado :String read FCancelado write FCancelado; property MotivoCancelamento :String read FMotivoCancelamento write FMotivoCancelamento; property totalAdicionais :Real read GetTotalAdicionais; property totalBruto :Real read GetTotalBruto; property totalLiquido :Real read GetTotalLiquido; public property Produto :TProduto read GetProduto; property MateriasDoProduto :TObjectList<TMateriaDoProduto> read GetMateriasDoProduto write FMateriasDoProduto; property Usuario :TUsuario read GetUsuario; property quantidadesPorValidade :TObjectList<TQuantidadePorValidade> read GetQuantidadesPorValidade write FQuantidadesPorValidade; end; implementation uses Repositorio, FabricaRepositorio, EspecificacaoAdicionalDoItem, EspecificacaoMateriaDoProdutoItem, EspecificacaoQuantidadesDoItem; { TItem } destructor TItem.Destroy; begin if assigned(FAdicionais) then FreeAndNil(FAdicionais); inherited; end; function TItem.GetAdicionais: TObjectList<TAdicionalItem>; var Repositorio :TRepositorio; Especificacao :TEspecificacaoAdicionalDoItem; begin Repositorio := nil; Especificacao := nil; try if not Assigned(self.FAdicionais) then begin Especificacao := TEspecificacaoAdicionalDoItem.Create(self); Repositorio := TFabricaRepositorio.GetRepositorio(TAdicionalItem.ClassName); self.FAdicionais := Repositorio.GetListaPorEspecificacao<TAdicionalItem>(Especificacao, 'CODIGO_ITEM ='+IntToStr(self.Codigo)); end; result := self.FAdicionais; finally FreeAndNil(Especificacao); FreeAndNil(Repositorio); end; end; function TItem.GetMateriasDoProduto: TObjectList<TMateriaDoProduto>; var Repositorio :TRepositorio; Especificacao :TEspecificacaoMateriaDoProdutoItem; begin Repositorio := nil; Especificacao := nil; try if not Assigned(self.FMateriasDoProduto) then begin Especificacao := TEspecificacaoMateriaDoProdutoItem.Create(self); Repositorio := TFabricaRepositorio.GetRepositorio(TMateriaDoProduto.ClassName); self.FMateriasDoProduto := Repositorio.GetListaPorEspecificacao<TMateriaDoProduto>(Especificacao, 'CODIGO_ITEM ='+IntToStr(self.Codigo)); end; result := self.FMateriasDoProduto; finally FreeAndNil(Especificacao); FreeAndNil(Repositorio); end; end; function TItem.GetProduto: TProduto; var Repositorio :TRepositorio; begin Repositorio := nil; try if not Assigned(self.FProduto) then begin Repositorio := TFabricaRepositorio.GetRepositorio(TProduto.ClassName); self.FProduto := TProduto(Repositorio.Get(self.Fcodigo_produto)); end; result := self.FProduto; finally FreeAndNil(Repositorio); end; end; function TItem.GetQuantidadesPorValidade: TObjectList<TQuantidadePorValidade>; var Repositorio :TRepositorio; Especificacao :TEspecificacaoQuantidadesDoItem; begin Repositorio := nil; Especificacao := nil; try if not Assigned(self.FQuantidadesPorValidade) then begin Especificacao := TEspecificacaoQuantidadesDoItem.Create(self); Repositorio := TFabricaRepositorio.GetRepositorio(TQuantidadePorValidade.ClassName); self.FQuantidadesPorValidade := Repositorio.GetListaPorEspecificacao<TQuantidadePorValidade>(Especificacao, 'CODIGO_ITEM = '+IntToStr(self.Codigo)); end; result := self.FQuantidadesPorValidade; finally FreeAndNil(Especificacao); FreeAndNil(Repositorio); end; end; function TItem.GetTotalAdicionais: Real; var i :integer; begin result := 0; if assigned(Adicionais) and (Adicionais.Count > 0) then begin for i := 0 to Adicionais.Count -1 do result := result + (Adicionais.Items[i].quantidade * Adicionais.Items[i].valor_unitario); end; end; function TItem.GetTotalBruto: Real; begin result := (self.quantidade * self.valor_Unitario) + (self.quantidade * self.totalAdicionais); end; function TItem.GetTotalLiquido: Real; begin result := (self.quantidade * self.valor_Unitario) + (self.quantidade * self.totalAdicionais);//- self.Desconto; end; function TItem.GetUsuario: TUsuario; var Repositorio :TRepositorio; begin Repositorio := nil; try if not Assigned(self.FUsuario) then begin Repositorio := TFabricaRepositorio.GetRepositorio(TUsuario.ClassName); self.FUsuario := TUsuario(Repositorio.Get(self.FCodigo_usuario)); end; result := self.FUsuario; finally FreeAndNil(Repositorio); end; end; end.
unit StringInspectors; // The contents of this file are subject to the Mozilla Public License // Version 1.1 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // http://www.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the // License for the specific language governing rights and limitations // under the License. // // The Original Code is DUnitLite. // // The Initial Developer of the Original Code is Joe White. // Portions created by Joe White are Copyright (C) 2007 // Joe White. All Rights Reserved. // // Contributor(s): // // Alternatively, the contents of this file may be used under the terms // of the LGPL license (the "LGPL License"), in which case the // provisions of LGPL License are applicable instead of those // above. If you wish to allow use of your version of this file only // under the terms of the LGPL License and not to allow others to use // your version of this file under the MPL, indicate your decision by // deleting the provisions above and replace them with the notice and // other provisions required by the LGPL License. If you do not delete // the provisions above, a recipient may use your version of this file // under either the MPL or the LGPL License. interface uses SysUtils; const Apostrophe = ''''; type TStringInspector = class public class function Inspect(AString: string; AStartIndex, ALength: Integer): string; static; end; IStringBuilder = interface ['{9FB96139-B4F7-47E4-820E-15857F60E912}'] procedure Append(const Value: string); function AsString: string; end; TStringBuilder = class(TInterfacedObject, IStringBuilder) strict private FValue: string; public procedure Append(const Value: string); function AsString: string; end; IStringInspectorState = interface ['{F013CA74-BADC-4E3C-BD83-B580861D1552}'] function Handle(Ch: Char): IStringInspectorState; procedure HandleEndOfString; end; TStringInspectorStateBase = class(TInterfacedObject, IStringInspectorState) strict private FBuilder: IStringBuilder; strict protected function HandleLowAscii(Ch: Char): IStringInspectorState; virtual; function HandleNormal(Ch: Char): IStringInspectorState; virtual; function InQuoteState: IStringInspectorState; virtual; function OuterState: IStringInspectorState; virtual; procedure TransitionAway; virtual; property Builder: IStringBuilder read FBuilder; public constructor Create(ABuilder: IStringBuilder); function Handle(Ch: Char): IStringInspectorState; procedure HandleEndOfString; virtual; end; TStringInspectorInitialState = class(TStringInspectorStateBase) public procedure HandleEndOfString; override; end; TStringInspectorOuterState = class(TStringInspectorStateBase) strict protected function HandleLowAscii(Ch: Char): IStringInspectorState; override; function OuterState: IStringInspectorState; override; end; TStringInspectorInQuoteState = class(TStringInspectorStateBase) strict protected function HandleNormal(Ch: Char): IStringInspectorState; override; function InQuoteState: IStringInspectorState; override; procedure TransitionAway; override; public constructor Create(ABuilder: IStringBuilder); end; implementation { TStringInspector } class function TStringInspector.Inspect(AString: string; AStartIndex, ALength: Integer): string; var Builder: IStringBuilder; State: IStringInspectorState; Ch: Char; begin Builder := TStringBuilder.Create; if AStartIndex > 1 then Builder.Append('...'); State := TStringInspectorInitialState.Create(Builder); for Ch in Copy(AString, AStartIndex, ALength) do State := State.Handle(Ch); State.HandleEndOfString; if (AStartIndex + ALength - 1) < Length(AString) then Builder.Append('...'); Result := Builder.AsString; end; { TStringBuilder } procedure TStringBuilder.Append(const Value: string); begin FValue := FValue + Value; end; function TStringBuilder.AsString: string; begin Result := FValue; end; { TStringInspectorStateBase } constructor TStringInspectorStateBase.Create(ABuilder: IStringBuilder); begin inherited Create; FBuilder := ABuilder; end; function TStringInspectorStateBase.Handle(Ch: Char): IStringInspectorState; begin if Ch in [#0..#31] then Result := HandleLowAscii(Ch) else Result := HandleNormal(Ch); end; procedure TStringInspectorStateBase.HandleEndOfString; begin TransitionAway; end; function TStringInspectorStateBase.HandleLowAscii(Ch: Char): IStringInspectorState; begin Result := OuterState; Result.Handle(Ch); end; function TStringInspectorStateBase.HandleNormal(Ch: Char): IStringInspectorState; begin Result := InQuoteState; Result.Handle(Ch); end; function TStringInspectorStateBase.InQuoteState: IStringInspectorState; begin TransitionAway; Result := TStringInspectorInQuoteState.Create(Builder); end; function TStringInspectorStateBase.OuterState: IStringInspectorState; begin TransitionAway; Result := TStringInspectorOuterState.Create(Builder); end; procedure TStringInspectorStateBase.TransitionAway; begin end; { TStringInspectorInitialState } procedure TStringInspectorInitialState.HandleEndOfString; begin inherited; Builder.Append(Apostrophe + Apostrophe); end; { TStringInspectorOuterState } function TStringInspectorOuterState.HandleLowAscii( Ch: Char): IStringInspectorState; begin Builder.Append('#' + IntToStr(Ord(Ch))); Result := Self; end; function TStringInspectorOuterState.OuterState: IStringInspectorState; begin Result := Self; end; { TStringInspectorInQuoteState } constructor TStringInspectorInQuoteState.Create(ABuilder: IStringBuilder); begin inherited; Builder.Append(Apostrophe); end; function TStringInspectorInQuoteState.HandleNormal(Ch: Char): IStringInspectorState; begin if Ch = Apostrophe then Builder.Append(Apostrophe + Apostrophe) else Builder.Append(Ch); Result := Self; end; function TStringInspectorInQuoteState.InQuoteState: IStringInspectorState; begin Result := Self; end; procedure TStringInspectorInQuoteState.TransitionAway; begin Builder.Append(Apostrophe); end; end.
unit gBullets; {$IfDef FPC} {$mode objfpc}{$H+} {$ModeSwitch advancedrecords} {$EndIf} interface uses gWorld, gTypes, UPhysics2D, UPhysics2DTypes, mutils, avRes, avContnrs, intfUtils; type TBulletOwnerKind = (bokPlayer, bokBot); TOwnerInfo = packed record obj : IWeakRef; //TGameObject weak ref kind: TBulletOwnerKind; procedure Init(const AGameObject: TGameObject; const AKind: TBulletOwnerKind); end; TBullet = class (TGameDynamicBody) private FDeadTime: Int64; FOwner: TOwnerInfo; protected procedure UpdateStep; override; function GetLiveTime: Integer; virtual; abstract; public procedure SetDefaultState(AStartPos, AEndPos: TVec2; ADir: TVec2; AStartVel: TVec2); virtual; property Owner : TOwnerInfo read FOwner write FOwner; procedure AfterConstruction; override; end; TRocket = class (TBullet) private FExtraPower: Boolean; protected function Filter_UnitsOnly(const AObj: TGameBody): Boolean; procedure UpdateStep; override; function GetLiveTime: Integer; override; function CreateBodyDef(const APos: TVector2; const AAngle: Double): Tb2BodyDef; override; protected procedure OnHit(const AFixture: Tb2Fixture; const ThisFixture: Tb2Fixture; const AManifold: Tb2WorldManifold); override; public function GetTransform(): TMat3; property ExtraPower: Boolean read FExtraPower write FExtraPower; procedure DrawLightSources(const ALights: ILightInfoArr); override; procedure AfterConstruction; override; end; TSimpleGun = class (TBullet) protected // function Filter_UnitsOnly(const AObj: TGameBody): Boolean; procedure UpdateStep; override; function CreateFixutreDefForShape(const AShape: Tb2Shape): Tb2FixtureDef; override; function GetLiveTime: Integer; override; function CreateBodyDef(const APos: TVector2; const AAngle: Double): Tb2BodyDef; override; protected procedure OnHit(const AFixture: Tb2Fixture; const ThisFixture: Tb2Fixture; const AManifold: Tb2WorldManifold); override; public procedure SetDefaultState(AStartPos, AEndPos: TVec2; ADir: TVec2; AStartVel: TVec2); override; procedure DrawLightSources(const ALights: ILightInfoArr); override; procedure AfterConstruction; override; end; TTeslaRay = class (TGameSprite) public const TESLA_RANGE = 8; TESLA_SNAP_RANGE = 4; private type IRayPoints = {$IfDef FPC}specialize{$EndIf} IArray<TVec2>; TRayPoints = {$IfDef FPC}specialize{$EndIf} TArray<TVec2>; private FDeadTime: Int64; FOwner: TOwnerInfo; FRayPoints: IRayPoints; FRayPointsVel: IRayPoints; FLightingColor: TVec4; function Filter_ExcludeOwner(const AObj: TGameBody): Boolean; protected procedure UpdateStep; override; function GetLiveTime: Integer; public procedure SetDefaultState(AStartPos, AEndPos: TVec2); property Owner : TOwnerInfo read FOwner write FOwner; procedure AfterConstruction; override; function HasSpineTris: Boolean; override; procedure Draw(const ASpineVertices: ISpineExVertices); override; procedure DrawLightSources(const ALights: ILightInfoArr); override; end; TGrenade = class (TBullet) protected function Filter_UnitsOnly(const AObj: TGameBody): Boolean; protected procedure UpdateStep; override; function CreateFixutreDefForShape(const AShape: Tb2Shape): Tb2FixtureDef; override; function GetLiveTime: Integer; override; function CreateBodyDef(const APos: TVector2; const AAngle: Double): Tb2BodyDef; override; public procedure SetDefaultState(AStartPos, AEndPos: TVec2; ADir: TVec2; AStartVel: TVec2); override; procedure AfterConstruction; override; end; implementation uses Math, gEffects, gUnits; { TBullet } procedure TRocket.AfterConstruction; const H : Single = 0.1; W : Single = 0.3; var res: TGameResource; begin inherited; res.Clear; SetLength(res.spine, 1); res.spine[0].LoadFromDir('rocket', World.Atlas); SetLength(res.fixtures_poly, 1); SetLength(res.fixtures_poly[0], 3); res.fixtures_poly[0][0] := Vec(0, H); res.fixtures_poly[0][1] := Vec(W, 0); res.fixtures_poly[0][2] := Vec(0, -H); SetResource(res); end; function TRocket.CreateBodyDef(const APos: TVector2; const AAngle: Double): Tb2BodyDef; begin Result := Tb2BodyDef.Create; Result.bodyType := b2_dynamicBody; Result.userData := Self; Result.position := APos; Result.angle := AAngle; Result.linearDamping := 0.2; Result.angularDamping := 0.2; Result.allowSleep := True; end; procedure TRocket.DrawLightSources(const ALights: ILightInfoArr); var ls: TLightInfo; k : Single; begin inherited; k := 0.3 + Sin(World.Time * 0.1)*0.1; ls.LightKind := 0; ls.LightPos := Vec(-0.6, 0) * GetTransform(); ls.LightDist := 3; ls.LightColor := Vec(0.988235294117647, 0.792156862745098, 0.0117647058823529, 1.0)*k; ALights.Add(ls); end; function TRocket.Filter_UnitsOnly(const AObj: TGameBody): Boolean; begin Result := AObj is TUnit; end; function TRocket.GetLiveTime: Integer; begin Result := 4000; end; function TRocket.GetTransform: TMat3; begin if FExtraPower then Result := Mat3(Vec(2,2),0,Vec(0,0)) * inherited GetTransform() else Result := inherited GetTransform(); end; procedure TRocket.OnHit(const AFixture, ThisFixture: Tb2Fixture; const AManifold: Tb2WorldManifold); const ROCKET_MAX_DMG: array [Boolean] of Integer = (30, 50); ROCKET_MAX_RAD: array [Boolean] of Integer = (7, 11); var hittedBody: TGameBody; objs: IGameObjArr; unt: TUnit; i: Integer; dmgPower: Single; dmgDir : TVec2; k: Single; explosion: TExplosion; begin inherited; if AFixture.IsSensor then Exit; objs := QueryObjects(ROCKET_MAX_RAD[FExtraPower], {$IfDef FPC}@{$EndIf}Filter_UnitsOnly); hittedBody := TGameBody(AFixture.GetBody.UserData); for i := 0 to objs.Count - 1 do begin unt := objs[i] as TUnit; if unt = hittedBody then begin dmgPower := ROCKET_MAX_DMG[FExtraPower]; dmgDir := unt.Pos - Pos + Dir; end else begin dmgDir := unt.Pos - Pos; k := 1 - clamp(Len(dmgDir)/ROCKET_MAX_RAD[FExtraPower], 0, 1); k := k * k; dmgPower := ROCKET_MAX_DMG[FExtraPower] * k; end; unt.DealDamage(dmgPower, normalize(dmgDir), dmgPower*100, Owner); end; explosion := TExplosion.Create(World); explosion.Layer := glGameFore; explosion.ZIndex := 0; explosion.Pos := Pos - Dir*0.25; explosion.Angle := Random * 2 * Pi; World.SafeDestroy(Self); end; procedure TRocket.UpdateStep; var v: TVec2; begin inherited; v := Dir * 40.0; MainBody.ApplyForceToCenter(TVector2.From(v.x, v.y)); end; procedure TBullet.SetDefaultState(AStartPos, AEndPos, ADir, AStartVel: TVec2); begin Pos := AStartPos; if LenSqr(ADir) = 0 then Dir := Vec(1, 0) else Dir := ADir; Velocity := AStartVel; end; procedure TBullet.UpdateStep; begin inherited; if FDeadTime < World.Time then World.SafeDestroy(Self); end; { TBullet } procedure TBullet.AfterConstruction; begin inherited; FDeadTime := World.Time + GetLiveTime(); SubscribeForUpdateStep; end; { TOwnerInfo } procedure TOwnerInfo.Init(const AGameObject: TGameObject; const AKind: TBulletOwnerKind); begin obj := nil; if AGameObject <> nil then obj := AGameObject.WeakRef; kind := AKind; end; { TSimpleGun } procedure TSimpleGun.AfterConstruction; var res: TGameResource; lsize: TVec2; begin inherited; res.Clear; SetLength(res.images, 1); res.images[0] := World.GetCommonTextures^.BulletTrace; lsize := Vec(res.images[0].Data.Width, res.images[0].Data.Height) / 80; res.tris := TSpineExVertices.Create; Draw_Sprite(res.tris, Vec(-lsize.x*0.5+lsize.y,0), Vec(1,0), lsize, res.images[0]); //Draw_Sprite(res.tris, Vec(0,0), Vec(1,0), lsize, res.images[0]); SetLength(res.fixtures_cir, 1); res.fixtures_cir[0] := Vec(0,0,lsize.y*0.5); SetResource(res); end; function TSimpleGun.CreateBodyDef(const APos: TVector2; const AAngle: Double): Tb2BodyDef; begin Result := Tb2BodyDef.Create; Result.bodyType := b2_dynamicBody; Result.userData := Self; Result.position := APos; Result.angle := AAngle; Result.linearDamping := 0.05; Result.angularDamping := 0.05; Result.allowSleep := True; end; function TSimpleGun.CreateFixutreDefForShape(const AShape: Tb2Shape): Tb2FixtureDef; begin Result := inherited CreateFixutreDefForShape(AShape); Result.restitution := 0.3; Result.density := 13.0; end; procedure TSimpleGun.DrawLightSources(const ALights: ILightInfoArr); var ls: TLightInfo; k : Single; m : TMat3; begin inherited; m := GetTransform(); k := 0.1; ls.LightKind := 0; ls.LightPos := Vec(-0.2, 0)*m; ls.LightDist := 1.0; ls.LightColor := Vec(0.988235294117647, 0.792156862745098, 0.0117647058823529, 1.0)*k; ALights.Add(ls); end; function TSimpleGun.GetLiveTime: Integer; begin Result := 3000; end; procedure TSimpleGun.OnHit(const AFixture, ThisFixture: Tb2Fixture; const AManifold: Tb2WorldManifold); const BULLET_MAX_DMG = 2; var hittedBody: TGameBody; unt: TUnit; hitpower: Single; begin inherited; if AFixture.IsSensor then Exit; hittedBody := TGameBody(AFixture.GetBody.UserData); if hittedBody is TUnit then begin unt := hittedBody as TUnit; hitpower := Len(Velocity)/80 * BULLET_MAX_DMG; hitpower := min(hitpower, BULLET_MAX_DMG); unt.DealDamage(hitpower, unt.Pos - Pos, 0, Owner); end; end; procedure TSimpleGun.SetDefaultState(AStartPos, AEndPos: TVec2; ADir, AStartVel: TVec2); var shootDir: TVec2; fi: Single; begin fi := (Random()-0.5)*0.07; shootDir := AEndPos - AStartPos; shootDir := Rotate(shootDir, fi); AEndPos := AStartPos + shootDir; ADir := Rotate(ADir, fi); AStartVel := Rotate(AStartVel, fi); inherited; end; procedure TSimpleGun.UpdateStep; var v: TVec2; begin inherited; v := Velocity; Dir := v; if LenSqr(v) < Sqr(20) then World.SafeDestroy(Self); end; { TTeslaRay } procedure TTeslaRay.AfterConstruction; begin inherited; FDeadTime := World.Time + GetLiveTime; SubscribeForUpdateStep; FLightingColor := Vec(0.5,1.0,1.0,1.0); end; procedure TTeslaRay.Draw(const ASpineVertices: ISpineExVertices); var sprite: ISpriteIndex; i: Integer; begin inherited; sprite := World.GetCommonTextures^.WhitePix; for i := 0 to FRayPoints.Count - 2 do Draw_Line(ASpineVertices, sprite, FRayPoints[i], FRayPoints[i+1], 0.1, FLightingColor); end; procedure TTeslaRay.DrawLightSources(const ALights: ILightInfoArr); var i: Integer; ls: TLightInfo; begin inherited; ls.LightKind := 0; ls.LightColor := FLightingColor*0.15; ls.LightDist := 5.0; for i := 0 to FRayPoints.Count - 1 do begin ls.LightPos := FRayPoints[i]; ALights.Add(ls); end; end; function TTeslaRay.Filter_ExcludeOwner(const AObj: TGameBody): Boolean; begin if not (AObj is TUnit) then Exit(False); if AObj is TBox then Exit(False); if FOwner.obj <> nil then if FOwner.obj.Obj = AObj then Exit(False); Result := True; end; function TTeslaRay.GetLiveTime: Integer; begin Result := PHYS_STEP * 15; end; function TTeslaRay.HasSpineTris: Boolean; begin Result := (FRayPoints <> nil) and (FRayPoints.Count > 1); end; procedure TTeslaRay.SetDefaultState(AStartPos, AEndPos: TVec2); procedure GenerateRay(const Pt1, Pt2, Vel: TVec2); var midPt: TVec2; n: TVec2; s: Single; begin n := Rotate90(Pt2 - Pt1, Random(2) = 0); if LenSqr(n) < sqr(2.0) then Exit; n := n * 0.08; midPt := Lerp(Pt1, Pt2, 0.5 + Random()*0.2 - 0.1) + n; if Random(2) = 0 then s := -1 else s := 1; s := s * (Random()*3); n := n * s + Vel; GenerateRay(Pt1, midPt, n); FRayPoints.Add(midPt); FRayPointsVel.Add(n); GenerateRay(midPt, Pt2, n); end; var objs: IGameObjArr; minDist, Dist: Single; obj: TGameObject; I: Integer; v1, v2: TVec2; shootDir: TVec2; begin shootDir := AEndPos - AStartPos; if LenSqr(shootDir) > sqr(TESLA_RANGE) then begin shootDir := SetLen(shootDir, TESLA_RANGE); AEndPos := AStartPos + shootDir; end; obj := nil; minDist := TESLA_SNAP_RANGE; objs := World.QueryObjects(AEndPos, minDist, {$IfDef FPC}@{$EndIf}Filter_ExcludeOwner); for I := 0 to objs.Count-1 do begin Dist := Len(AEndPos - objs[i].Pos); if Dist < minDist then begin obj := objs[i]; minDist := Dist; end; end; if obj <> nil then AEndPos := obj.Pos; if FOwner.obj <> nil then v1 := TUnit(FOwner.obj.Obj).Velocity else v1 := Vec(0,0); if obj is TGameDynamicBody then v2 := TGameDynamicBody(obj).Velocity else v2 := Vec(0,0); FRayPoints := TRayPoints.Create; FRayPointsVel := TRayPoints.Create; FRayPoints.Add(AStartPos); FRayPointsVel.Add(v1); GenerateRay(AStartPos, AEndPos, (v1+v2)*0.5); FRayPoints.Add(AEndPos); FRayPointsVel.Add(v2); if (obj <> nil) and (obj is TUnit) then TUnit(obj).DealDamage(2, Normalize(AEndPos - AStartPos), 0, FOwner); end; procedure TTeslaRay.UpdateStep; var i, n: Integer; kk: Single; begin inherited; if FDeadTime <= World.Time then World.SafeDestroy(Self); n := FRayPoints.Count - 1; for i := 0 to n do begin kk := 1.0 - abs(i/n - 0.5)*2.0; FRayPoints[i] := FRayPoints[i] + FRayPointsVel[i] * (PHYS_STEP/1000*(kk*Random*2)); end; end; { TGrenade } procedure TGrenade.AfterConstruction; var res: TGameResource; lsize: TVec2; begin inherited; res.Clear; SetLength(res.images, 1); res.images[0] := World.GetCommonTextures^.Grenade; lsize := Vec(res.images[0].Data.Width, res.images[0].Data.Height) / 80; res.tris := TSpineExVertices.Create; Draw_Sprite(res.tris, Vec(0,0), Vec(1,0), lsize, res.images[0]); //Draw_Sprite(res.tris, Vec(0,0), Vec(1,0), lsize, res.images[0]); SetLength(res.fixtures_cir, 1); res.fixtures_cir[0] := Vec(0,0,lsize.y*0.5); SetResource(res); end; function TGrenade.CreateBodyDef(const APos: TVector2; const AAngle: Double): Tb2BodyDef; begin Result := Tb2BodyDef.Create; Result.bodyType := b2_dynamicBody; Result.userData := Self; Result.position := APos; Result.angle := AAngle; Result.linearDamping := 3.5; Result.angularDamping := 3.5; Result.allowSleep := True; end; function TGrenade.CreateFixutreDefForShape(const AShape: Tb2Shape): Tb2FixtureDef; begin Result := inherited CreateFixutreDefForShape(AShape); Result.restitution := 0.6; Result.density := 13.0; end; function TGrenade.Filter_UnitsOnly(const AObj: TGameBody): Boolean; begin Result := AObj is TGameDynamicBody; end; function TGrenade.GetLiveTime: Integer; begin Result := 2000; end; procedure TGrenade.SetDefaultState(AStartPos, AEndPos, ADir, AStartVel: TVec2); begin inherited; MainBody.SetAngularVelocity(Random()*10); end; procedure TGrenade.UpdateStep; const GRENADE_MAX_DMG = 60; GRENADE_MAX_RAD = 7; var objs: IGameObjArr; body: TGameDynamicBody; i: Integer; dmgPower: Single; dmgDir : TVec2; k: Single; explosion: TExplosion; begin inherited; if FDeadTime < World.Time then begin objs := QueryObjects(GRENADE_MAX_RAD, {$IfDef FPC}@{$EndIf}Filter_UnitsOnly); for i := 0 to objs.Count - 1 do begin body := objs[i] as TGameDynamicBody; dmgDir := body.Pos - Pos; if LenSqr(dmgDir) = 0 then Continue; k := 1 - clamp(Len(dmgDir)/GRENADE_MAX_RAD, 0, 1); k := k * k; dmgPower := GRENADE_MAX_DMG * k; if body is TUnit then begin TUnit(body).DealDamage(dmgPower, normalize(dmgDir), dmgPower*100, Owner); end else begin dmgDir := normalize(dmgDir)*dmgPower*100; body.MainBody.ApplyForceToCenter(TVector2.From(dmgDir.x, dmgDir.y)); end; end; explosion := TExplosion.Create(World); explosion.Layer := glGameFore; explosion.ZIndex := 0; explosion.Pos := Pos - Dir*0.25; explosion.Angle := Random * 2 * Pi; end; end; end.
{****************************************************************************** PROYECTO FACTURACION ELECTRONICA Copyright (C) 2010-2014 - Bambu Code SA de CV - Ing. Luis Carrasco Clase usada para generar la Cadena Original del XML del Timbre Fiscal recibido cuando se manda el comprobante a un PAC para su timbrado. Este archivo pertenece al proyecto de codigo abierto de Bambu Code: http://bambucode.com/codigoabierto La licencia de este codigo fuente se encuentra en: http://github.com/bambucode/tfacturaelectronica/blob/master/LICENCIA ******************************************************************************} unit CadenaOriginalTimbre; interface // Incluimos el recurso que guarda el archivo XSLT para cuando se compile // esta unidad en cualquier proyecto que la use, se incluya en el ejecutable // Ref: http://delphi.about.com/od/objectpascalide/a/embed_resources.htm {$R 'CadenaOriginalTimbre.res' 'CadenaOriginalTimbre.rc'} uses FacturaTipos, Classes, XMLDoc, XMLIntf, //XSLProd, System.SysUtils; type {$REGION 'Documentation'} /// <summary> /// Clase que se encarga de generar la Cadena Original del Timbre para /// mostrarla en la representación gráfica. /// </summary> {$ENDREGION} TCadenaOriginalDeTimbre = class private fXMLTimbre: TStringCadenaOriginal; fXSLT: string; function LeerXSLTDeRecurso(const aNombreRecurso: string): string; public constructor Create(const aXMLTimbre: WideString; const aRutaXSLT: WideString); overload; function Generar: TStringCadenaOriginal; end; implementation constructor TCadenaOriginalDeTimbre.Create(const aXMLTimbre: WideString; const aRutaXSLT: WideString); const _NOMBRE_DEL_RECURSO_XSLT = 'CADENA_ORIGINAL_TFD_1_0'; begin fXMLTimbre := aXMLTimbre; // Obtenemos el archivo XSLT para transformar el XML del timbre a cadena original usando // el XSLT proveido por el SAT de la direccion: // ftp://ftp2.sat.gob.mx/asistencia_servicio_ftp/publicaciones/solcedi/cadenaoriginal_TFD_1_0.xslt fXSLT := LeerXSLTDeRecurso(_NOMBRE_DEL_RECURSO_XSLT); Assert(fXMLTimbre <> '', 'El XML del timbre no debe ser vacio'); Assert(fXSLT <> '', 'El XSLT de transformacion del timbre no debe ser vacio'); end; function TCadenaOriginalDeTimbre.Generar: TStringCadenaOriginal; var XML : IXMLDocument; XSL : IXMLDocument; res: WideString; begin XML := LoadXMLData(fXMLTimbre); XSL := LoadXMLData(fXSLT); // Transformamos el XML del timbre usando el XSLT proveido por el SAT XML.DocumentElement.TransformNode(XSL.DocumentElement, res); // Fix temporal debido a que por alguna razon el XSLT no aplica correctamente las cadenas de inicio y terminacion Result := '|' + res + '||'; end; function TCadenaOriginalDeTimbre.LeerXSLTDeRecurso(const aNombreRecurso: string): string; var RS: TResourceStream; sl: TStringList; begin RS := TResourceStream.Create(HInstance, aNombreRecurso, 'TEXT'); try SL := TStringList.Create; SL.LoadFromStream(RS); Result := sl.Text; finally RS.Free; sl.Free; end; end; end.
(* Copyright (c) 2011, Stefan Glienke 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 this library 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. *) unit DSharp.Logging.CodeSite; interface uses DSharp.Logging; type TCodeSiteLog = class(TLogBase) protected procedure LogEntry(const ALogEntry: TLogEntry); override; end; implementation uses CodeSiteLogging, DSharp.Core.Reflection, DSharp.Logging.CodeSite.Helper, SysUtils; { TCodeSiteLog } procedure TCodeSiteLog.LogEntry(const ALogEntry: TLogEntry); begin case ALogEntry.LogKind of lkEnterMethod: begin if not ALogEntry.Value.IsEmpty then begin if ALogEntry.Value.IsClass then CodeSite.EnterMethod(ALogEntry.Value.AsClass.ClassName + '.' + ALogEntry.Text) else if ALogEntry.Value.IsObject then CodeSite.EnterMethod(ALogEntry.Value.AsObject, ALogEntry.Text) else CodeSite.EnterMethod(UTF8ToString(ALogEntry.Value.TypeInfo.Name) + '.' + ALogEntry.Text); end else CodeSite.EnterMethod(ALogEntry.Text); end; lkLeaveMethod: begin if not ALogEntry.Value.IsEmpty then begin if ALogEntry.Value.IsClass then CodeSite.ExitMethod(ALogEntry.Value.AsClass.ClassName + '.' + ALogEntry.Text) else if ALogEntry.Value.IsObject then CodeSite.ExitMethod(ALogEntry.Value.AsObject, ALogEntry.Text) else CodeSite.ExitMethod(UTF8ToString(ALogEntry.Value.TypeInfo.Name) + '.' + ALogEntry.Text); end else CodeSite.ExitMethod(ALogEntry.Text); end; lkMessage: begin CodeSite.SendFmtMsg(ALogEntry.Text, TValue.ToVarRecs(ALogEntry.Values)); end; lkWarning: begin CodeSite.SendWarning(Format(ALogEntry.Text, TValue.ToVarRecs(ALogEntry.Values))); end; lkError: begin CodeSite.SendError(Format(ALogEntry.Text, TValue.ToVarRecs(ALogEntry.Values))); end; lkException: begin CodeSite.SendException(ALogEntry.Text, ALogEntry.Value.AsType<Exception>); end; lkValue: begin CodeSite.Send(ALogEntry.Text, ALogEntry.Value); end; end; end; initialization RegisterLogging(TCodeSiteLog.Create); end.
{ @abstract(Sets for GMLib.) @author(Xavier Martinez (cadetill) <cadetill@gmail.com>) @created(August 2, 2022) @lastmod(August 11, 2022) The GMLib.Sets unit contains all sets used by GMLib. } unit GMLib.Sets; {$I ..\gmlib.inc} interface type // @include(..\Help\docs\GMLib.Sets.TGMLang.txt) TGMLang = (// unknown exception language lnUnknown, // Spanish exception language lnEspanol, // English exception language lnEnglish, // French exception language lnFrench); // @include(..\Help\docs\GMLib.Sets.TGMAPIVer.txt) TGMAPIVer = (av347, av348, av349, avWeekly, avQuarterly, avBeta); // @include(..\Help\docs\GMLib.Sets.TGMAPILang.txt) TGMAPILang = (lAfrikaans, lAlbanian, lAmharic, lArabic, lArmenian, lAzerbaijani, lBasque, lBelarusian, lBengali, lBosnian, lBulgarian, lBurmese, lCatalan, lChinese, lChinese_Simp, lChinese_HK, lChinese_Trad, lCroatian, lCzech, lDanish, lDutch, lEnglish, lEnglish_Aust, lEnglish_GB, lEstonian, lFarsi, lFinnish, lFilipino, lFrench, lFrench_Ca, lGalician, lGeorgian, lGerman, lGreek, lGujarati, lHebrew, lHindi, lHungarian, lIcelandic, lIndonesian, lItalian, lJapanese, lKannada, lKazakh, lKhmer, lKorean, lKyrgyz, lLao, lLatvian, lLithuanian, lMacedonian, lMalay, lMalayalam, lMarathi, lMongolian, lNepali, lNorwegian, lPolish, lPortuguese, lPortuguese_Br, lPortuguese_Ptg, lPunjabi, lRomanian, lRussian, lSerbian, lSinhalese, lSlovak, lSlovenian, lSpanish, lSpanish_LA, lSwahili, lSwedish, lTamil, lTelugu, lThai, lTurkish, lUkrainian, lUrdu, lUzbek, lVietnamese, lZulu, lUndefined); // @include(..\Help\docs\GMLib.Sets.TGMAPIRegion.txt) TGMAPIRegion = (rAfghanistan, rAlbania, rAlgeria, rAmerican_Samoa, rAndorra, rAngola, rAnguilla, rAntarctica, rAntigua_Barbuda, rArgentina, rArmenia, rAruba, rAscension_Island, rAustralia, rAustriam, rAzerbaijan, rBahamas, rBahrain, rBangladesh, rBarbados, rBelarus, rBelgium, rBelize, rBenin, rBermuda, rBhutan, rBolivia, rBosnia_Herzegovina, rBotswana, rBouvet_Island, rBrazil, rBritish_Indian_OT, rBritish_Virgin_Is, rBrunei, rBulgaria, rBurkina_Faso, rBurundi, rCambodia, rCameroon, rCanada, rCanary_Islands, rCape_Verde, rCaribbean_Netherlands, rCayman_Islands, rCentral_African_Rep, rCeuta_Melilla, rChad, rChile, rChina, rChristmas_Island, rClipperton_Island, rCocos_Islands, rColombia, rComoros, rCongo_Brazzaville, rCongo_Kinshasa, rCook_Islands, rCosta_Rica, rCroatia, rCuba, rCuracao, rCyprus, rCzechia, rCote_Ivoire, rDenmark, rDiego_Garcia, rDjibouti, rDominica, rDominican_Republic, rEcuador, rEgypt, rEl_Salvador, rEquatorial_Guinea, rEritrea, rEstonia, rEswatini, rEthiopia, rFalkland_Islands, rFaroe_Islands, rFiji, rFinland, rFrance, rFrench_Guiana, rFrench_Polynesia, rFrench_Southern_Territories, rGabon, rGambia, rGeorgia, rGermany, rGhana, rGibraltar, rGreece, rGreenland, rGrenada, rGuadeloupe, rGuam, rGuatemala, rGuernsey, rGuinea, rGuinea_Bissau, rGuyana, rHaiti, rHeard_McDonald, rHonduras, rHong_Kong, rHungary, rIceland, rIndia, rIndonesia, rIran, rIraq, rIreland, rIsle_Man, rIsrael, rItaly, rJamaica, rJapan, rJersey, rJordan, rKazakhstan, rKenya, rKiribati, rKosovo, rKuwait, rKyrgyzstan, rLaos, rLatvia, rLebanon, rLesotho, rLiberia, rLibya, rLiechtenstein, rLithuania, rLuxembourg, rMacao, rMadagascar, rMalawi, rMalaysia, rMaldives, rMali, rMalta, rMarshall_Islands, rMartinique, rMauritania, rMauritius, rMayotte, rMexico, rMicronesia, rMoldova, rMonaco, rMongolia, rMontenegro, rMontserrat, rMorocco, rMozambique, rMyanmar, rNamibia, rNauru, rNepal, rNetherlands, rNew_Caledonia, rNew_Zealand, rNicaragua, rNiger, rNigeria, rNiue, rNorfolk_Island, rNorth_Korea, rNorth_Macedonia, rNorthern_Mariana, rNorway, rOman, rPakistan, rPalau, rPalestine, rPanama, rPapua_New_Guinea, rParaguay, rPeru, rPhilippines, rPitcairn_Islands, rPoland, rPortugal, rPuerto_Rico, rQatar, rRomania, rRussia, rRwanda, rReunion, rSamoa, rSan_Marino, rSaudi_Arabia, rSenegal, rSerbia, rSeychelles, rSierra_Leone, rSingapore, rSint_Maarten, rSlovakia, rSlovenia, rSolomon_Islands, rSomalia, rSouth_Africa, rSouth_Georgia_South_Sandwich, rSouth_Korea, rSouth_Sudan, rSpain, rSri_Lanka, rSt_Barthelemy, rSt_Helena, rSt_Kitts_Nevis, rSt_Lucia, rSt_Martin, rSt_Pierre_Miquelon, rSt_Vincent_Grenadines, rSudan, rSuriname, rSvalbard_Jan_Mayen, rSweden, rSwitzerland, rSyria, rSao_Tome_Principe, rTaiwan, rTajikistan, rTanzania, rThailand, rTimor_Leste, rTogo, rTokelau, rTonga, rTrinidad_Tobago, rTristan_da_Cunha, rTunisia, rTurkey, rTurkmenistan, rTurks_Caicos_Islands, rTuvalu, rUS_Outlying_Islands, rUS_Virgin_Islands, rUganda, rUkraine, rUnited_Arab_Emirates, rUnited_Kingdom, rUnited_States, rUruguay, rUzbekistan, rVanuatu, rVatican_City, rVenezuela, rVietnam, rWallis_Futuna, rWestern_Sahara, rYemen, rZambia, rZimbabwe, rAland_Islands, rUndefined); // @include(..\Help\docs\GMLib.Sets.TGMControlPosition.txt) TGMControlPosition = (cpBOTTOM_CENTER, cpBOTTOM_LEFT, cpBOTTOM_RIGHT, cpLEFT_BOTTOM, cpLEFT_CENTER, cpLEFT_TOP, cpRIGHT_BOTTOM, cpRIGHT_CENTER, cpRIGHT_TOP, cpTOP_CENTER, cpTOP_LEFT, cpTOP_RIGHT); // @include(..\Help\docs\GMLib.Sets.TGMGestureHandling.txt) TGMGestureHandling = (ghCooperative, ghGreedy, ghNone, ghAuto); // @include(..\Help\docs\GMLib.Sets.TGMMapTypeId.txt) TGMMapTypeId = (mtHYBRID, mtROADMAP, mtSATELLITE, mtTERRAIN); // @include(..\Help\docs\GMLib.Sets.TGMMapTypeIds.txt) TGMMapTypeIds = set of TGMMapTypeId; // @include(..\Help\docs\GMLib.Sets.TGMMapTypeControlStyle.txt) TGMMapTypeControlStyle = (mtcDEFAULT, mtcDROPDOWN_MENU, mtcHORIZONTAL_BAR); // @include(..\Help\docs\GMLib.Sets.TGMScaleControlStyle.txt) TGMScaleControlStyle = (scsDEFAULT); // @include(..\Help\docs\GMLib.Sets.TGMAnimation.txt) TGMAnimation = (aniBOUNCE, aniDROP, aniNONE); // @include(..\Help\docs\GMLib.Sets.TGMCollisionBehavior.txt) TGMCollisionBehavior = (cbNONE, cbOPTIONAL_AND_HIDES_LOWER_PRIORITY, cbREQUIRED, cbREQUIRED_AND_HIDES_OPTIONAL); // @include(..\Help\docs\GMLib.Sets.TGMSymbolPath.txt) TGMSymbolPath = (spBACKWARD_CLOSED_ARROW, spBACKWARD_OPEN_ARROW, spCIRCLE, spFORWARD_CLOSED_ARROW, spFORWARD_OPEN_ARROW); implementation end.
unit EspecificacaoNotaFiscalPorPeriodoEStatus; interface uses Especificacao, Dialogs, SysUtils; type TEspecificacaoNotaFiscalPorPeriodoEStatus = class(TEspecificacao) private FDataInicial :TDateTime; FDataFinal :TDateTime; FComStatusAguardandoEnvio :Boolean; FComStatusAutorizada :Boolean; FComStatusRejeitada :Boolean; FComStatusCancelada :Boolean; FTipoDaNota :String; FCNPJ_empresa_selecionada :String; public constructor Create(DataInicial, DataFinal :TDateTime; ComStatusAguardandoEnvio :Boolean; ComStatusAutorizada :Boolean; ComStatusRejeitada :Boolean; ComStatusCancelada :Boolean; const CNPJ_empresa_selecionada :String = '0'; const TipoDaNota :String = 'A'); public function SatisfeitoPor(NotaFiscal :TObject) :Boolean; override; end; implementation uses NotaFiscal, TipoStatusNotaFiscal; { TEspecificacaoNotaFiscalPorPeriodoEStatus } constructor TEspecificacaoNotaFiscalPorPeriodoEStatus.Create(DataInicial, DataFinal: TDateTime; ComStatusAguardandoEnvio, ComStatusAutorizada, ComStatusRejeitada, ComStatusCancelada: Boolean; const CNPJ_empresa_selecionada :String; const TipoDaNota :String); begin FDataInicial := DataInicial; FDataFinal := DataFinal; FComStatusAguardandoEnvio := ComStatusAguardandoEnvio; FComStatusAutorizada := ComStatusAutorizada; FComStatusRejeitada := ComStatusRejeitada; FComStatusCancelada := ComStatusCancelada; FCNPJ_empresa_selecionada := CNPJ_empresa_selecionada; FTipoDaNota := TipoDaNota; end; function TEspecificacaoNotaFiscalPorPeriodoEStatus.SatisfeitoPor( NotaFiscal: TObject): Boolean; var NF :TNotaFiscal; begin NF := (NotaFiscal as TNotaFiscal); if FTipoDaNota <> 'A' then if (NF.Entrada_saida <> FTipoDaNota) then begin result := false; exit; end; //Verifico se a nota é de entrada e se a especificação nao esta sendo chamada pelo GeradorSintegra ou foi nota de importacao pelo xml if ( NF.Entrada_saida = 'E' ) and (( self.FCNPJ_empresa_selecionada = '0' ) or NF.notaDeImportacao) then begin result := false; exit; end; //verifico se a nota pertence ou não a empresa especificada if Length(self.FCNPJ_empresa_selecionada) > 10 then if ((Nf.Entrada_saida = 'E') and (NF.Destinatario.CPF_CNPJ <> self.FCNPJ_empresa_selecionada)) or ((NF.Entrada_saida <> 'E') and (NF.Emitente.CPF_CNPJ <> self.FCNPJ_empresa_selecionada)) then begin result := false; exit; end; // if (Nf.Entrada_saida = 'E') and ((NF.DataEmissao >= self.FDataInicial) and (NF.DataEmissao <= self.FDataFinal)) then // showmessage(IntToStr(Nf.CodigoNotaFiscal)+' - '+DateToStr(NF.DataEmissao)); // Verifico se nota fiscal satisfaz o período de emissão da especificação result := ((self.FDataInicial = 0) and (self.FDataFinal = 0)) or ((NF.DataEmissao >= self.FDataInicial) and (NF.DataEmissao <= self.FDataFinal)); // Se não satisfaz a data sai do método e retorna falso if not result then exit; //se for nota de entrada e for de importacao por XML ja esta com status de enviada if (NF.Entrada_saida = 'E') and ( length(self.FCNPJ_empresa_selecionada) > 10) then begin result := true; exit; end; // Verifico se a nota fiscal satistaz o status de aguardando envio if self.FComStatusAguardandoEnvio then begin result := (NF.Status = snfAguardandoEnvio); if result then exit; end; // Verifico se a nota fiscal satistaz o status de autorizada if self.FComStatusAutorizada then begin result := (NF.Status = snfAutorizada); if result then exit; end; // Verifico se a nota fiscal satistaz o status de rejeitada if self.FComStatusRejeitada then begin result := (NF.Status = snfRejeitada); if result then exit; end; // Verifico se a nota fiscal satistaz o status de cancelada if self.FComStatusCancelada then begin result := (NF.Status = snfCancelada); if result then exit; end; end; end.
unit Roadster; {$mode objfpc}{$H+} interface uses Classes, SysUtils, BaseModel; type IBaseRoadster = interface(IBaseModel) ['{02467D77-738F-4B1D-BBE2-3C44A86231D9}'] function GetApoapsisAu: Double; function GetDetails: string; function GetDateTimeUnix: UInt64; function GetDateTimeUtc: TDateTime; function GetEarthDistanceKilometers: Double; function GetEarthDistanceMiles: Double; function GetEccentricity: Double; function GetEpochJd: Double; function GetFlickrImages: TStringList; function GetId: string; function GetInclination: Double; function GetLaunchMassKilograms: Double; function GetLaunchMassPounds: Double; function GetLongitude: Double; function GetMarsDistanceKilometers: Double; function GetMarsDistanceMiles: Double; function GetName: string; function GetNoradId: LongWord; function GetOrbitType: string; function GetPeriapsisArg: Double; function GetPeriapsisAu: Double; function GetPeriodDays: Double; function GetSemiMajorAxisAu: Double; function GetSpeedKph: Double; function GetSpeedMph: Double; function GetVideo: string; function GetWikipedia: string; procedure SetApoapsisAu(AValue: Double); procedure SetDetails(AValue: string); procedure SetDateTimeUnix(AValue: UInt64); procedure SetDateTimeUtc(AValue: TDateTime); procedure SetEarthDistanceKilometers(AValue: Double); procedure SetEarthDistanceMiles(AValue: Double); procedure SetEccentricity(AValue: Double); procedure SetEpochJd(AValue: Double); procedure SetFlickrImages(AValue: TStringList); procedure SetId(AValue: string); procedure SetInclination(AValue: Double); procedure SetLaunchMassKilograms(AValue: Double); procedure SetLaunchMassPounds(AValue: Double); procedure SetLongitude(AValue: Double); procedure SetMarsDistanceKilometers(AValue: Double); procedure SetMarsDistanceMiles(AValue: Double); procedure SetName(AValue: string); procedure SetNoradId(AValue: LongWord); procedure SetOrbitType(AValue: string); procedure SetPeriapsisArg(AValue: Double); procedure SetPeriapsisAu(AValue: Double); procedure SetPeriodDays(AValue: Double); procedure SetSemiMajorAxisAu(AValue: Double); procedure SetSpeedKph(AValue: Double); procedure SetSpeedMph(AValue: Double); procedure SetVideo(AValue: string); procedure SetWikipedia(AValue: string); end; IRoadster = interface(IBaseRoadster) ['{27BD5051-841A-4ADF-BF94-CDD8D59175A0}'] property ApoapsisAu: Double read GetApoapsisAu write SetApoapsisAu; property Details: string read GetDetails write SetDetails; property DateTimeUnix: UInt64 read GetDateTimeUnix write SetDateTimeUnix; property DateTimeUtc: TDateTime read GetDateTimeUtc write SetDateTimeUtc; property EarthDistanceKilometers: Double read GetEarthDistanceKilometers write SetEarthDistanceKilometers; property EarthDistanceMiles: Double read GetEarthDistanceMiles write SetEarthDistanceMiles; property Eccentricity: Double read GetEccentricity write SetEccentricity; property EpochJd: Double read GetEpochJd write SetEpochJd; property FlickrImages: TStringList read GetFlickrImages write SetFlickrImages; property Id: string read GetId write SetId; property Inclination: Double read GetInclination write SetInclination; property LaunchMassKilograms: Double read GetLaunchMassKilograms write SetLaunchMassKilograms; property LaunchMassPounds: Double read GetLaunchMassPounds write SetLaunchMassPounds; property Longitude: Double read GetLongitude write SetLongitude; property MarsDistanceKilometers: Double read GetMarsDistanceKilometers write SetMarsDistanceKilometers; property MarsDistanceMiles: Double read GetMarsDistanceMiles write SetMarsDistanceMiles; property Name: string read GetName write SetName; property NoradId: LongWord read GetNoradId write SetNoradId; property OrbitType: string read GetOrbitType write SetOrbitType; property PeriapsisArg: Double read GetPeriapsisArg write SetPeriapsisArg; property PeriapsisAu: Double read GetPeriapsisAu write SetPeriapsisAu; property PeriodDays: Double read GetPeriodDays write SetPeriodDays; property SemiMajorAxisAu: Double read GetSemiMajorAxisAu write SetSemiMajorAxisAu; property SpeedKph: Double read GetSpeedKph write SetSpeedKph; property SpeedMph: Double read GetSpeedMph write SetSpeedMph; property Video: string read GetVideo write SetVideo; property Wikipedia: string read GetWikipedia write SetWikipedia; end; function NewRoadster: IRoadster; type { TRoadster } TRoadster = class(TBaseModel, IRoadster) private FApoapsisAu: Double; FDetails: string; FDateTimeUnix: UInt64; FDateTimeUtc: TDateTime; FEarthDistanceKilometers: Double; FEarthDistanceMiles: Double; FEccentricity: Double; FEpochJd: Double; FFlickrImages: TStringList; FId: string; FInclination: Double; FLaunchMassKilograms: Double; FLaunchMassPounds: Double; FLongitude: Double; FMarsDistanceKilometers: Double; FMarsDistanceMiles: Double; FName: string; FNoradId: LongWord; FOrbitType: string; FPeriapsisArg: Double; FPeriapsisAu: Double; FPeriodDays: Double; FSemiMajorAxisAu: Double; FSpeedKph: Double; FSpeedMph: Double; FVideo: string; FWikipedia: string; private function GetApoapsisAu: Double; function GetDetails: string; function GetDateTimeUnix: UInt64; function GetDateTimeUtc: TDateTime; function GetEarthDistanceKilometers: Double; function GetEarthDistanceMiles: Double; function GetEccentricity: Double; function GetEpochJd: Double; function GetFlickrImages: TStringList; function GetId: string; function GetInclination: Double; function GetLaunchMassKilograms: Double; function GetLaunchMassPounds: Double; function GetLongitude: Double; function GetMarsDistanceKilometers: Double; function GetMarsDistanceMiles: Double; function GetName: string; function GetNoradId: LongWord; function GetOrbitType: string; function GetPeriapsisArg: Double; function GetPeriapsisAu: Double; function GetPeriodDays: Double; function GetSemiMajorAxisAu: Double; function GetSpeedKph: Double; function GetSpeedMph: Double; function GetVideo: string; function GetWikipedia: string; private procedure SetApoapsisAu(AValue: Double); procedure SetApoapsisAu(AValue: Variant); procedure SetDetails(AValue: string); procedure SetDetails(AValue: Variant); procedure SetDateTimeUnix(AValue: UInt64); procedure SetDateTimeUnix(AValue: Variant); procedure SetDateTimeUtc(AValue: TDateTime); procedure SetDateTimeUtc(AValue: Variant); procedure SetEarthDistanceKilometers(AValue: Double); procedure SetEarthDistanceKilometers(AValue: Variant); procedure SetEarthDistanceMiles(AValue: Double); procedure SetEarthDistanceMiles(AValue: Variant); procedure SetEccentricity(AValue: Double); procedure SetEccentricity(AValue: Variant); procedure SetEpochJd(AValue: Double); procedure SetEpochJd(AValue: Variant); procedure SetFlickrImages(AValue: TStringList); procedure SetFlickrImages(AValue: Variant); procedure SetId(AValue: string); procedure SetId(AValue: Variant); procedure SetInclination(AValue: Double); procedure SetInclination(AValue: Variant); procedure SetLaunchMassKilograms(AValue: Double); procedure SetLaunchMassKilograms(AValue: Variant); procedure SetLaunchMassPounds(AValue: Double); procedure SetLaunchMassPounds(AValue: Variant); procedure SetLongitude(AValue: Double); procedure SetLongitude(AValue: Variant); procedure SetMarsDistanceKilometers(AValue: Double); procedure SetMarsDistanceKilometers(AValue: Variant); procedure SetMarsDistanceMiles(AValue: Double); procedure SetMarsDistanceMiles(AValue: Variant); procedure SetName(AValue: string); procedure SetName(AValue: Variant); procedure SetNoradId(AValue: LongWord); procedure SetNoradId(AValue: Variant); procedure SetOrbitType(AValue: string); procedure SetOrbitType(AValue: Variant); procedure SetPeriapsisArg(AValue: Double); procedure SetPeriapsisArg(AValue: Variant); procedure SetPeriapsisAu(AValue: Double); procedure SetPeriapsisAu(AValue: Variant); procedure SetPeriodDays(AValue: Double); procedure SetPeriodDays(AValue: Variant); procedure SetSemiMajorAxisAu(AValue: Double); procedure SetSemiMajorAxisAu(AValue: Variant); procedure SetSpeedKph(AValue: Double); procedure SetSpeedKph(AValue: Variant); procedure SetSpeedMph(AValue: Double); procedure SetSpeedMph(AValue: Variant); procedure SetVideo(AValue: string); procedure SetVideo(AValue: Variant); procedure SetWikipedia(AValue: string); procedure SetWikipedia(AValue: Variant); public constructor Create; destructor destroy; override; function ToString(): string; override; published property apoapsis_au: Variant write SetApoapsisAu; property details: Variant write SetDetails; property launch_date_unix: Variant write SetDateTimeUnix; property launch_date_utc: TDateTime write SetDateTimeUtc; property earth_distance_km: Variant write SetEarthDistanceKilometers; property earth_distance_mi: Variant write SetEarthDistanceMiles; property eccentricity: Variant write SetEccentricity; property epoch_jd: Variant write SetEpochJd; property flickr_images: Variant write SetFlickrImages; property id: Variant write SetId; property inclination: Variant write SetInclination; property launch_mass_kg: Variant write SetLaunchMassKilograms; property launch_mass_lbs: Variant write SetLaunchMassPounds; property longitude: Variant write SetLongitude; property mars_distance_km: Variant write SetMarsDistanceKilometers; property mars_distance_mi: Variant write SetMarsDistanceMiles; property name: Variant write SetName; property norad_id: Variant write SetNoradId; property orbit_type: Variant write SetOrbitType; property periapsis_arg: Variant write SetPeriapsisArg; property periapsis_au: Variant write SetPeriapsisAu; property period_days: Variant write SetPeriodDays; property semi_major_axis_au: Variant write SetSemiMajorAxisAu; property speed_kph: Variant write SetSpeedKph; property speed_mph: Variant write SetSpeedMph; property video: Variant write SetVideo; property wikipedia: Variant write SetWikipedia; end; implementation uses Variants; function NewRoadster: IRoadster; begin Result := TRoadster.Create; end; { TRoadster } function TRoadster.GetApoapsisAu: Double; begin Result := FApoapsisAu; end; function TRoadster.GetDetails: string; begin Result := FDetails; end; function TRoadster.GetDateTimeUnix: UInt64; begin Result := FDateTimeUnix; end; function TRoadster.GetDateTimeUtc: TDateTime; begin Result := FDateTimeUtc; end; function TRoadster.GetEarthDistanceKilometers: Double; begin Result := FEarthDistanceKilometers; end; function TRoadster.GetEarthDistanceMiles: Double; begin Result := FEarthDistanceMiles; end; function TRoadster.GetEccentricity: Double; begin Result := FEccentricity; end; function TRoadster.GetEpochJd: Double; begin Result := FEpochJd; end; function TRoadster.GetFlickrImages: TStringList; begin Result := FFlickrImages; end; function TRoadster.GetId: string; begin Result := FId; end; function TRoadster.GetInclination: Double; begin Result := FInclination; end; function TRoadster.GetLaunchMassKilograms: Double; begin Result := FLaunchMassKilograms; end; function TRoadster.GetLaunchMassPounds: Double; begin Result := FLaunchMassPounds; end; function TRoadster.GetLongitude: Double; begin Result := FLongitude; end; function TRoadster.GetMarsDistanceKilometers: Double; begin Result := FMarsDistanceKilometers; end; function TRoadster.GetMarsDistanceMiles: Double; begin Result := FMarsDistanceMiles; end; function TRoadster.GetName: string; begin Result := FName; end; function TRoadster.GetNoradId: LongWord; begin Result := FNoradId; end; function TRoadster.GetOrbitType: string; begin Result := FOrbitType; end; function TRoadster.GetPeriapsisArg: Double; begin Result := FPeriapsisArg; end; function TRoadster.GetPeriapsisAu: Double; begin Result := FPeriapsisAu; end; function TRoadster.GetPeriodDays: Double; begin Result := FPeriodDays; end; function TRoadster.GetSemiMajorAxisAu: Double; begin Result := FSemiMajorAxisAu; end; function TRoadster.GetSpeedKph: Double; begin Result := FSpeedKph; end; function TRoadster.GetSpeedMph: Double; begin Result := FSpeedMph; end; function TRoadster.GetVideo: string; begin Result := FVideo; end; function TRoadster.GetWikipedia: string; begin Result := FWikipedia; end; procedure TRoadster.SetApoapsisAu(AValue: Double); begin FApoapsisAu := AValue; end; procedure TRoadster.SetApoapsisAu(AValue: Variant); begin if VarIsNull(AValue) then begin FApoapsisAu := -0; end else if VarIsNumeric(AValue) then FApoapsisAu := AValue; end; procedure TRoadster.SetDetails(AValue: string); begin FDetails := AValue; end; procedure TRoadster.SetDetails(AValue: Variant); begin if VarIsNull(AValue) then begin FDetails := ''; end else if VarIsStr(AValue) then FDetails := AValue; end; procedure TRoadster.SetDateTimeUnix(AValue: UInt64); begin FDateTimeUnix := AValue; end; procedure TRoadster.SetDateTimeUnix(AValue: Variant); begin if VarIsNull(AValue) then begin FDateTimeUnix := -0; end else if VarIsNumeric(AValue) then FDateTimeUnix := AValue; end; procedure TRoadster.SetDateTimeUtc(AValue: TDateTime); begin FDateTimeUtc := AValue; end; procedure TRoadster.SetDateTimeUtc(AValue: Variant); begin if VarIsNull(AValue) then begin FDateTimeUtc := MinDateTime; end else if VarIsStr(AValue) then FDateTimeUtc := AValue; end; procedure TRoadster.SetEarthDistanceKilometers(AValue: Double); begin FEarthDistanceKilometers := AValue; end; procedure TRoadster.SetEarthDistanceKilometers(AValue: Variant); begin if VarIsNull(AValue) then begin FEarthDistanceKilometers := -0; end else if VarIsNumeric(AValue) then FEarthDistanceKilometers := AValue; end; procedure TRoadster.SetEarthDistanceMiles(AValue: Double); begin FEarthDistanceMiles := AValue; end; procedure TRoadster.SetEarthDistanceMiles(AValue: Variant); begin if VarIsNull(AValue) then begin FEarthDistanceMiles := -0; end else if VarIsNumeric(AValue) then FEarthDistanceMiles := AValue; end; procedure TRoadster.SetEccentricity(AValue: Double); begin FEccentricity := AValue; end; procedure TRoadster.SetEccentricity(AValue: Variant); begin if VarIsNull(AValue) then begin FEccentricity := -0; end else if VarIsNumeric(AValue) then FEccentricity := AValue; end; procedure TRoadster.SetEpochJd(AValue: Double); begin FEpochJd := AValue; end; procedure TRoadster.SetEpochJd(AValue: Variant); begin if VarIsNull(AValue) then begin FEpochJd := -0; end else if VarIsNumeric(AValue) then FEpochJd := AValue; end; procedure TRoadster.SetFlickrImages(AValue: TStringList); begin FFlickrImages := AValue; end; procedure TRoadster.SetFlickrImages(AValue: Variant); begin if VarIsNull(AValue) then begin FFlickrImages := TStringList.Create; end else if VarIsStr(AValue) then FFlickrImages.AddDelimitedtext(AValue); end; procedure TRoadster.SetId(AValue: string); begin FId := AValue; end; procedure TRoadster.SetId(AValue: Variant); begin if VarIsNull(AValue) then begin FId := ''; end else if VarIsStr(AValue) then FId := AValue; end; procedure TRoadster.SetInclination(AValue: Double); begin FInclination := AValue; end; procedure TRoadster.SetInclination(AValue: Variant); begin if VarIsNull(AValue) then begin FInclination := -0; end else if VarIsNumeric(AValue) then FInclination := AValue; end; procedure TRoadster.SetLaunchMassKilograms(AValue: Double); begin FLaunchMassKilograms := AValue; end; procedure TRoadster.SetLaunchMassKilograms(AValue: Variant); begin if VarIsNull(AValue) then begin FLaunchMassKilograms := -0; end else if VarIsNumeric(AValue) then FLaunchMassKilograms := AValue; end; procedure TRoadster.SetLaunchMassPounds(AValue: Double); begin FLaunchMassPounds := AValue; end; procedure TRoadster.SetLaunchMassPounds(AValue: Variant); begin if VarIsNull(AValue) then begin FLaunchMassPounds := -0; end else if VarIsNumeric(AValue) then FLaunchMassPounds := AValue; end; procedure TRoadster.SetLongitude(AValue: Double); begin FLongitude := AValue; end; procedure TRoadster.SetLongitude(AValue: Variant); begin if VarIsNull(AValue) then begin FLongitude := -0; end else if VarIsNumeric(AValue) then FLongitude := AValue; end; procedure TRoadster.SetMarsDistanceKilometers(AValue: Double); begin FMarsDistanceKilometers := AValue; end; procedure TRoadster.SetMarsDistanceKilometers(AValue: Variant); begin if VarIsNull(AValue) then begin FMarsDistanceKilometers := -0; end else if VarIsNumeric(AValue) then FMarsDistanceKilometers := AValue; end; procedure TRoadster.SetMarsDistanceMiles(AValue: Double); begin FMarsDistanceMiles := AValue; end; procedure TRoadster.SetMarsDistanceMiles(AValue: Variant); begin if VarIsNull(AValue) then begin FMarsDistanceMiles := -0; end else if VarIsNumeric(AValue) then FMarsDistanceMiles := AValue; end; procedure TRoadster.SetName(AValue: string); begin FName := AValue; end; procedure TRoadster.SetName(AValue: Variant); begin if VarIsNull(AValue) then begin FName := ''; end else if VarIsStr(AValue) then FName := AValue; end; procedure TRoadster.SetNoradId(AValue: LongWord); begin FNoradId := AValue; end; procedure TRoadster.SetNoradId(AValue: Variant); begin if VarIsNull(AValue) then begin FNoradId := -0; end else if VarIsNumeric(AValue) then FNoradId := AValue; end; procedure TRoadster.SetOrbitType(AValue: string); begin FOrbitType := AValue; end; procedure TRoadster.SetOrbitType(AValue: Variant); begin if VarIsNull(AValue) then begin FOrbitType := ''; end else if VarIsStr(AValue) then FOrbitType := AValue; end; procedure TRoadster.SetPeriapsisArg(AValue: Double); begin FPeriapsisArg := AValue; end; procedure TRoadster.SetPeriapsisArg(AValue: Variant); begin if VarIsNull(AValue) then begin FPeriapsisArg := -0; end else if VarIsNumeric(AValue) then FPeriapsisArg := AValue; end; procedure TRoadster.SetPeriapsisAu(AValue: Double); begin FPeriapsisAu := AValue; end; procedure TRoadster.SetPeriapsisAu(AValue: Variant); begin if VarIsNull(AValue) then begin FPeriapsisAu := -0; end else if VarIsNumeric(AValue) then FPeriapsisAu := AValue; end; procedure TRoadster.SetPeriodDays(AValue: Double); begin FPeriodDays := AValue; end; procedure TRoadster.SetPeriodDays(AValue: Variant); begin if VarIsNull(AValue) then begin FPeriodDays := -0; end else if VarIsNumeric(AValue) then FPeriodDays := AValue; end; procedure TRoadster.SetSemiMajorAxisAu(AValue: Double); begin FSemiMajorAxisAu := AValue; end; procedure TRoadster.SetSemiMajorAxisAu(AValue: Variant); begin if VarIsNull(AValue) then begin FSemiMajorAxisAu := -0; end else if VarIsNumeric(AValue) then FSemiMajorAxisAu := AValue; end; procedure TRoadster.SetSpeedKph(AValue: Double); begin FSpeedKph := AValue; end; procedure TRoadster.SetSpeedKph(AValue: Variant); begin if VarIsNull(AValue) then begin FSpeedKph := -0; end else if VarIsNumeric(AValue) then FSpeedKph := AValue; end; procedure TRoadster.SetSpeedMph(AValue: Double); begin FSpeedMph := AValue; end; procedure TRoadster.SetSpeedMph(AValue: Variant); begin if VarIsNull(AValue) then begin FSpeedMph := -0; end else if VarIsNumeric(AValue) then FSpeedMph := AValue; end; procedure TRoadster.SetVideo(AValue: string); begin FVideo := AValue; end; procedure TRoadster.SetVideo(AValue: Variant); begin if VarIsNull(AValue) then begin FVideo := ''; end else if VarIsStr(AValue) then FVideo := AValue; end; procedure TRoadster.SetWikipedia(AValue: string); begin FWikipedia := AValue; end; procedure TRoadster.SetWikipedia(AValue: Variant); begin if VarIsNull(AValue) then begin FWikipedia := ''; end else if VarIsStr(AValue) then FWikipedia := AValue; end; constructor TRoadster.Create; begin inherited Create; FFlickrImages := TStringList.Create; FFlickrImages.SkipLastLineBreak := True; end; destructor TRoadster.destroy; begin FreeAndNil(FFlickrImages); inherited destroy; end; function TRoadster.ToString(): string; begin Result := Format('' + 'Apoapsis Au: %f' + LineEnding + 'Details: %s' + LineEnding + 'Date Time Unix: %u' + LineEnding + 'Date Time Utc: %s' + LineEnding + 'Earth Distance(km): %f' + LineEnding + 'Earth Distance(mi): %f' + LineEnding + 'Eccentricity: %f' + LineEnding + 'Epoch Jd: %f' + LineEnding + 'Flickr Images: %s' + LineEnding + 'ID: %s' + LineEnding + 'Inclination: %f' + LineEnding + 'Launch Mass(kg): %f' + LineEnding + 'Launch Mass(lbs): %f' + LineEnding + 'Longitude: %f' + LineEnding + 'Mars Distance(km): %f' + LineEnding + 'Mars Distance(mi): %f' + LineEnding + 'Name: %s' + LineEnding + 'Norad ID: %u' + LineEnding + 'Orbit Type: %s' + LineEnding + 'Periapsis Arg: %f' + LineEnding + 'Periapsis Au: %f' + LineEnding + 'Period Days: %f' + LineEnding + 'Semi Major Axis Au: %f' + LineEnding + 'Speed(kph): %f' + LineEnding + 'Speed(mph): %f' + LineEnding + 'Video: %s' + LineEnding + 'Wikipedia: %s' , [ GetApoapsisAu, GetDetails, GetDateTimeUnix, DateToStr(GetDateTimeUtc), GetEarthDistanceKilometers, GetEarthDistanceMiles, GetEccentricity, GetEpochJd, GetFlickrImages.Text, GetId, GetInclination, GetLaunchMassKilograms, GetLaunchMassPounds, GetLongitude, GetMarsDistanceKilometers, GetMarsDistanceMiles, GetName, GetNoradId, GetOrbitType, GetPeriapsisArg, GetPeriapsisAu, GetPeriodDays, GetSemiMajorAxisAu, GetSpeedKph, GetSpeedMph, GetVideo, GetWikipedia ]); end; end.
unit PLabelMaskEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, stdctrls, dbtables, extctrls, RxCtrls, dbctrls, db, SelectDlg, PLabelPanel, LookupControls, Mask; type TPLabelMaskEdit = class(TCustomControl) private FEdit: TMaskEdit; FLabel: TRxLabel; FLabelStyle: TLabelStyle; FParentFont: Boolean; protected function GetCaption:TCaption; function GetEditAutoSelect:Boolean; function GetEditBorderStyle:TBorderStyle; function GetEditCharCase:TEditCharCase; function GetEditClick:TNotifyEvent; function GetEditCtl3D:Boolean; function GetEditDblClick:TNotifyEvent; function GetEditEditText: string; function GetEditEnter:TNotifyEvent; function GetEditExit:TNotifyEvent; function GetEditKeyDown:TKeyEvent ; function GetEditKeyPress:TKeyPressEvent; function GetEditKeyUp:TKeyEvent; function GetEditEditMask: string; function GetEditMasked: Boolean; function GetEditMaxLength:Integer; function GetEditModified:Boolean; function GetEditMouseDown:TMouseEvent ; function GetEditMouseMove:TMouseMoveEvent; function GetEditMouseUp:TMouseEvent; function GetEditOnChange:TNotifyEvent; function GetEditPasswordChar:Char; function GetEditSelLength:Integer; function GetEditSelStart:Integer; function GetEditSelText:string; function GetEditShowHint:Boolean; function GetEditTabOrder:TTabOrder; function GetEditTabStop:Boolean; function GetEditText:TCaption; function GetEditWidth:integer; function GetFont:TFont; function GetLabelFont: TFont; function GetRdOnly:Boolean; procedure Paint;override; procedure SetCaption(Value: TCaption); procedure SetEditAutoSelect(Value:Boolean); procedure SetEditBorderStyle(Value:TBorderStyle); procedure SetEditCharCase(Value:TEditCharCase); procedure SetEditClick(Value:TNotifyEvent); procedure SetEditCtl3D(Value:Boolean); procedure SetEditDblClick(Value:TNotifyEvent); procedure SetEditEditText(Value: string); procedure SetEditEnter(Value:TNotifyEvent); procedure SetEditExit(Value:TNotifyEvent); procedure SetEditKeyDown(Value:TKeyEvent); procedure SetEditKeyPress(Value:TKeyPressEvent); procedure SetEditKeyUp(Value:TKeyEvent); procedure SetEditEditMask(Value : string); procedure SetEditMaxLength(Value:Integer); procedure SetEditModified(Value:Boolean); procedure SetEditMouseDown(Value:TMouseEvent); procedure SetEditMouseMove(Value:TMouseMoveEvent); procedure SetEditMouseUp(Value:TMouseEvent); procedure SetEditOnChange(Value:TNotifyEvent); procedure SetParentFont(Value: Boolean); procedure SetEditPasswordChar(Value:Char); procedure SetEditSelLength(Value:Integer); procedure SetEditSelStart(Value:Integer); procedure SetEditSelText(Value:string); procedure SetEditShowHint(Value:Boolean); procedure SetEditTabOrder(Value: TTabOrder); procedure SetEditTabStop(Value:Boolean); procedure SetEditText(Value:TCaption); procedure SetEditWidth(Value: integer); procedure SetLabelFont(Value: TFont); procedure SetFont(Value: TFont); procedure SetLabelStyle(Value: TLabelStyle); procedure SetRdOnly(Value: Boolean); public constructor Create(AOwner: TComponent); override; destructor Destroy;override; function EditCanFocus: Boolean; function EditFocused: Boolean; function EditGetTextLen: Integer; function EditGetSelTextBuf(Buffer: PChar; BufSize: Integer): Integer; procedure EditCopyToClipboard; procedure EditClear; procedure EditClearSelection; procedure EditCutToClipboard; procedure EditSelectAll; procedure EditSetFocus; procedure EditSetSelTextBuf(Buffer: PChar); procedure EditPasteFromClipboard; procedure EditValidateEdit; property EditEditText: string read GetEditEditText write SetEditEditText; property EditIsMasked: Boolean read GetEditMasked; property EditModified: Boolean read GetEditModified write SetEditModified; property EditSelLength: Integer read GetEditSelLength write SetEditSelLength; property EditSelStart: Integer read GetEditSelStart write SetEditSelStart; property EditSelText: string read GetEditSelText write SetEditSelText; published property Caption:TCaption read GetCaption write SetCaption; property EditAutoSelect: Boolean read GetEditAutoSelect write SetEditAutoSelect; property EditBorderStyle: TBorderStyle read GetEditBorderStyle write SetEditBorderStyle; property EditCharCase: TEditCharCase read GetEditCharCase write SetEditCharCase; property EditCtl3D:Boolean read GetEditCtl3D write SetEditCtl3D; property EditEditMask: string read GetEditEditMask write SetEditEditMask; property EditMaxLength: Integer read GetEditMaxLength write SetEditMaxLength; property EditPasswordChar: Char read GetEditPasswordChar write SetEditPasswordChar; property EditShowHint:Boolean read GetEditShowHint write SetEditShowHint; property EditTabOrder:TTabOrder read GetEditTabOrder write SetEditTabOrder; property EditTabStop:Boolean read GetEditTabStop write SetEditTabStop; property EditText:TCaption read GetEditText write SetEditText; property EditWidth:integer read GetEditWidth write SetEditWidth; property Enabled; property Font:TFont read GetFont write SetFont; property LabelStyle: TLabelStyle read FLabelStyle write SetLabelStyle default Normal; property LabelFont: TFont read GetLabelFont write SetLabelFont; property ParentColor; property ParentCtl3D; property ParentFont : Boolean read FParentFont write SetParentFont; property ParentShowHint; property RdOnly: Boolean read GetRdOnly write SetRdOnly; property Visible; property OnEditChange: TNotifyEvent read GetEditOnChange write SetEditOnChange; property OnEditClick:TNotifyEvent read GetEditClick write SetEditClick; property OnEditDblClick:TNotifyEvent read GetEditDblClick write SetEditDblClick; property OnEditEnter:TNotifyEvent read GetEditEnter write SetEditEnter; property OnEditExit:TNotifyEvent read GetEditExit write SetEditExit; property OnEditKeyDown:TKeyEvent read GetEditKeyDown write SetEditKeyDown; property OnEditKeyPress:TKeyPressEvent read GetEditKeyPress write SetEditKeyPress; property OnEditKeyUp:TKeyEvent read GetEditKeyUp write SetEditKeyUp; property OnEditMouseDown:TMouseEvent read GetEditMouseDown write SetEditMouseDown; property OnEditMouseMove:TMouseMoveEvent read GetEditMouseMove write SetEditMouseMove; property OnEditMouseUp:TMouseEvent read GetEditMouseUp write SetEditMouseUp; end; procedure Register; implementation constructor TPLabelMaskEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); FLabel := TRxLabel.Create(Self); FLabel.Parent := Self; FLabel.ShadowSize := 0; FLabel.Layout := tlCenter; FLabel.AutoSize := False; FLabel.Visible := True; FLabel.Font.Size := 11; FLabel.Font.Name := 'ËÎÌå'; FLabel.ParentFont := False; LabelStyle := Normal; FEdit := TMaskEdit.Create(Self); FEdit.Parent := Self; FEdit.Visible := True; FEdit.Font.Size := 9; FEdit.Font.Name := 'ËÎÌå'; FEdit.ParentFont := False; FLabel.FocusControl := FEdit; Height := 24; FLabel.Height := Height; FEdit.Height := Height; Width := 200; FEdit.Width := 140; FLabel.Width := Width-FEdit.Width; FEdit.Left := FLabel.Width; ParentFont := False; end; procedure TPLabelMaskEdit.SetParentFont(Value: Boolean); begin inherited; FLabel.ParentFont := Value; Flabel.ParentFont := Value; FParentFont := Value; end; destructor TPLabelMaskEdit.Destroy ; begin FEdit.Free; FLabel.Free; inherited Destroy; end; function TPLabelMaskEdit.GetLabelFont: TFont; begin Result := FLabel.Font; end; procedure TPLabelMaskEdit.SetLabelFont(Value: TFont); begin FLabel.Font := Value; end; function TPLabelMaskEdit.GetRdOnly:Boolean; begin Result := FEdit.ReadOnly; end; procedure TPLabelMaskEdit.SetRdOnly(Value: Boolean); begin FEdit.ReadOnly := Value; if Value then FEdit.Color := clSilver else FEdit.Color := clWhite; end; function TPLabelMaskEdit.GetEditWidth:integer; begin Result := FEdit.Width; end; procedure TPLabelMaskEdit.SetEditWidth(Value: integer); begin FEdit.Width := Value; FEdit.Left := Width-Value; FLabel.Width := FEdit.Left; end; function TPLabelMaskEdit.GetFont:TFont; begin Result := FEdit.Font; end; procedure TPLabelMaskEdit.SetFont(Value: TFont); begin FEdit.Font := Value; FLabel.Font := Value; FLabel.Height := FEdit.Height; Height := FEdit.Height; SetLabelStyle(LabelStyle); end; function TPLabelMaskEdit.GetCaption:TCaption; begin Result := FLabel.Caption; end; procedure TPLabelMaskEdit.SetCaption(Value: TCaption); begin FLabel.Caption := Value; end; procedure TPLabelMaskEdit.SetLabelStyle (Value: TLabelStyle); begin FLabelStyle := Value; case Value of Normal: begin FLabel.Font.Color := clBlack; FLabel.Font.Style := []; end; Notnil: begin FLabel.Font.Color := clTeal; FLabel.Font.Style := []; end; Conditional: begin FLabel.Font.Color := clBlack; FLabel.Font.Style := [fsUnderline]; end; NotnilAndConditional: begin FLabel.Font.Color := clTeal; FLabel.Font.Style := [fsUnderline]; end; end; end; procedure TPLabelMaskEdit.Paint; begin inherited Paint; FLabel.Height := Height; FEdit.Height := Height; FLabel.Width := Width-FEdit.Width; FEdit.Left := FLabel.Width; end; function TPLabelMaskEdit.GetEditModified:Boolean; begin Result := FEdit.Modified; end; procedure TPLabelMaskEdit.SetEditModified(Value:Boolean); begin FEdit.Modified:= Value; end; function TPLabelMaskEdit.GetEditSelLength:Integer; begin Result := FEdit.SelLength; end; procedure TPLabelMaskEdit.SetEditSelLength(Value:Integer); begin FEdit.SelLength:= Value; end; function TPLabelMaskEdit.GetEditSelStart:Integer; begin Result := FEdit.SelStart; end; procedure TPLabelMaskEdit.SetEditSelStart(Value:Integer); begin FEdit.SelStart:= Value; end; function TPLabelMaskEdit.GetEditSelText:string; begin Result := FEdit.SelText; end; procedure TPLabelMaskEdit.SetEditSelText(Value:string); begin FEdit.SelText:= Value; end; function TPLabelMaskEdit.GetEditAutoSelect:Boolean; begin Result := FEdit.AutoSelect; end; procedure TPLabelMaskEdit.SetEditAutoSelect(Value:Boolean); begin FEdit.AutoSelect:= Value; end; function TPLabelMaskEdit.GetEditBorderStyle:TBorderStyle; begin Result := FEdit.BorderStyle; end; procedure TPLabelMaskEdit.SetEditBorderStyle(Value:TBorderStyle); begin FEdit.BorderStyle:= Value; end; function TPLabelMaskEdit.GetEditCharCase:TEditCharCase; begin Result := FEdit.CharCase; end; procedure TPLabelMaskEdit.SetEditCharCase(Value:TEditCharCase); begin FEdit.CharCase:= Value; end; function TPLabelMaskEdit.GetEditMaxLength:Integer; begin Result := FEdit.MaxLength; end; procedure TPLabelMaskEdit.SetEditMaxLength(Value:Integer); begin FEdit.MaxLength:= Value; end; function TPLabelMaskEdit.GetEditPasswordChar:Char; begin Result := FEdit.PasswordChar; end; procedure TPLabelMaskEdit.SetEditPasswordChar(Value:Char); begin FEdit.PasswordChar:= Value; end; function TPLabelMaskEdit.GetEditCtl3D:Boolean; begin Result := FEdit.Ctl3D; end; procedure TPLabelMaskEdit.SetEditCtl3D(Value:Boolean); begin FEdit.Ctl3D:= Value; end; function TPLabelMaskEdit.GetEditShowHint:Boolean; begin Result := FEdit.ShowHint; end; procedure TPLabelMaskEdit.SetEditShowHint(Value:Boolean); begin FEdit.ShowHint:= Value; end; function TPLabelMaskEdit.GetEditTabOrder:TTabOrder; begin Result := FEdit.TabOrder; end; procedure TPLabelMaskEdit.SetEditTabOrder(Value: TTabOrder); begin FEdit.TabOrder := Value; end; function TPLabelMaskEdit.GetEditTabStop:Boolean; begin Result := FEdit.TabStop; end; procedure TPLabelMaskEdit.SetEditTabStop(Value:Boolean); begin FEdit.TabStop := Value; end; function TPLabelMaskEdit.GetEditText:TCaption; begin Result := FEdit.Text; end; procedure TPLabelMaskEdit.SetEditText(Value:TCaption); begin FEdit.Text:= Value; end; function TPLabelMaskEdit.GetEditEditMask: string; begin Result := FEdit.EditMask; end; procedure TPLabelMaskEdit.SetEditEditMask(Value : string); begin FEdit.EditMask := Value; end; function TPLabelMaskEdit.GetEditMasked: Boolean; begin Result := FEdit.IsMasked; end; function TPLabelMaskEdit.GetEditEditText: string; begin Result := FEdit.EditText; end; procedure TPLabelMaskEdit.SetEditEditText(Value: string); begin FEdit.EditText := Value; end; function TPLabelMaskEdit.GetEditOnChange:TNotifyEvent; begin Result := FEdit.OnChange; end; procedure TPLabelMaskEdit.SetEditOnChange(Value:TNotifyEvent); begin FEdit.OnChange:= Value; end; function TPLabelMaskEdit.GetEditClick:TNotifyEvent; begin Result := FEdit.OnClick; end; procedure TPLabelMaskEdit.SetEditClick(Value:TNotifyEvent); begin FEdit.OnClick:= Value; end; function TPLabelMaskEdit.GetEditDblClick:TNotifyEvent; begin Result := FEdit.OnDblClick; end; procedure TPLabelMaskEdit.SetEditDblClick(Value:TNotifyEvent); begin FEdit.OnDblClick:= Value; end; function TPLabelMaskEdit.GetEditEnter:TNotifyEvent; begin Result := FEdit.OnEnter; end; procedure TPLabelMaskEdit.SetEditEnter(Value:TNotifyEvent); begin FEdit.OnEnter:= Value; end; function TPLabelMaskEdit.GetEditExit:TNotifyEvent; begin Result := FEdit.OnExit; end; procedure TPLabelMaskEdit.SetEditExit(Value:TNotifyEvent); begin FEdit.OnExit:= Value; end; function TPLabelMaskEdit.GetEditKeyDown:TKeyEvent ; begin Result := FEdit.OnKeyDown; end; procedure TPLabelMaskEdit.SetEditKeyDown(Value:TKeyEvent); begin FEdit.OnKeyDown:= Value; end; function TPLabelMaskEdit.GetEditKeyPress:TKeyPressEvent; begin Result := FEdit.OnKeyPress; end; procedure TPLabelMaskEdit.SetEditKeyPress(Value:TKeyPressEvent); begin FEdit.OnKeyPress:= Value; end; function TPLabelMaskEdit.GetEditKeyUp:TKeyEvent; begin Result := FEdit.OnKeyUp; end; procedure TPLabelMaskEdit.SetEditKeyUp(Value:TKeyEvent); begin FEdit.OnKeyUp:= Value; end; function TPLabelMaskEdit.GetEditMouseDown:TMouseEvent ; begin Result := FEdit.OnMouseDown; end; procedure TPLabelMaskEdit.SetEditMouseDown(Value:TMouseEvent); begin FEdit.OnMouseDown:= Value; end; function TPLabelMaskEdit.GetEditMouseMove:TMouseMoveEvent; begin Result := FEdit.OnMouseMove; end; procedure TPLabelMaskEdit.SetEditMouseMove(Value:TMouseMoveEvent); begin FEdit.OnMouseMove:= Value; end; function TPLabelMaskEdit.GetEditMouseUp:TMouseEvent; begin Result := FEdit.OnMouseUp; end; procedure TPLabelMaskEdit.SetEditMouseUp(Value:TMouseEvent); begin FEdit.OnMouseUp:= Value; end; procedure TPLabelMaskEdit.EditClear; begin FEdit.Clear; end; procedure TPLabelMaskEdit.EditClearSelection; begin FEdit.ClearSelection; end; procedure TPLabelMaskEdit.EditCopyToClipboard; begin FEdit.CopyToClipboard; end; procedure TPLabelMaskEdit.EditCutToClipboard; begin FEdit.CutToClipboard; end; procedure TPLabelMaskEdit.EditPasteFromClipboard; begin FEdit.PasteFromClipboard; end; function TPLabelMaskEdit.EditGetSelTextBuf(Buffer: PChar; BufSize: Integer): Integer; begin Result := FEdit.GetSelTextBuf(Buffer,BufSize) end; procedure TPLabelMaskEdit.EditSelectAll; begin FEdit.SelectAll; end; procedure TPLabelMaskEdit.EditSetSelTextBuf(Buffer: PChar); begin FEdit.SetSelTextBuf(Buffer); end; function TPLabelMaskEdit.EditCanFocus: Boolean; begin Result := FEdit.CanFocus; end; function TPLabelMaskEdit.EditFocused: Boolean; begin Result := FEdit.Focused; end; procedure TPLabelMaskEdit.EditSetFocus; begin FEdit.SetFocus; end; procedure TPLabelMaskEdit.EditValidateEdit; begin FEdit.ValidateEdit; end; function TPLabelMaskEdit.EditGetTextLen: Integer; begin Result := FEdit.GetTextLen; end; procedure Register; begin RegisterComponents('PosControl', [TPLabelMaskEdit]); end; end.
unit DIOTA.Utils.BundleValidator; interface uses DIOTA.Model.Bundle, DIOTA.Pow.ICurl, DIOTA.Pow.SpongeFactory; type TBundleValidator = class public { * Validates all signatures of a bundle * @param bundle the bundle * @param customCurl * @return true if all signatures are valid. Otherwise false } class function ValidateSignatures(bundle: IBundle; customCurl: ICurl): Boolean; { * Checks if a bundle is syntactically valid. * Validates signatures and overall structure * @param bundle the bundle to verify * @return true if the bundle is valid. * @throws ArgumentException if there is an error with the bundle } class function IsBundle(bundle: IBundle): Boolean; overload; { * Checks if a bundle is syntactically valid. * Validates signatures and overall structure * @param bundle the bundle to verify * @param customCurlMode * @return true if the bundle is valid. * @throws ArgumentException if there is an error with the bundle } class function IsBundle(bundle: IBundle; customCurlMode: TSpongeFactory.Mode): Boolean; overload; end; implementation uses System.Classes, System.SysUtils, DIOTA.Utils.Constants, DIOTA.Utils.Signing, DIOTA.Utils.Converter, DIOTA.Model.Transaction, DIOTA.Pow.JCurl; { TBundleValidator } class function TBundleValidator.ValidateSignatures(bundle: IBundle; customCurl: ICurl): Boolean; var i, j: Integer; ATrx: ITransaction; AOtherTrx: ITransaction; AFragments: TStringList; ASigning: TSigning; begin Result := True; for i := 0 to bundle.Transactions.Count - 1 do begin ATrx:= bundle.Transactions[i]; // check whether input transaction if ATrx.Value >= 0 then Continue; AFragments := TStringList.Create; try AFragments.Add(ATrx.SignatureFragments); // find the subsequent txs containing the remaining signature // message fragments for this input transaction for j := i to bundle.Transactions.Count - 2 do begin AOtherTrx := bundle.Transactions[j + 1]; if (AOtherTrx.Value <> 0) or (AOtherTrx.Address <> ATrx.Address) then Continue; AFragments.Add(AOtherTrx.SignatureFragments); end; ASigning := TSigning.Create(customCurl); try if not ASigning.ValidateSignatures(ATrx.Address, AFragments.ToStringArray, ATrx.Bundle) then begin Result := False; Break; end; finally ASigning.Free; end; finally AFragments.Free; end; end; end; class function TBundleValidator.IsBundle(bundle: IBundle): Boolean; begin Result := IsBundle(bundle, TSpongeFactory.Mode.KERL); end; class function TBundleValidator.IsBundle(bundle: IBundle; customCurlMode: TSpongeFactory.Mode): Boolean; var ACurl: ICurl; i, j: Integer; ATotalSum: Integer; ALastIndex: Integer; ATrx, ATrx2: ITransaction; ATrxTrits: TArray<Integer>; AFragments: TStringList; ASigning: TSigning; ABundleHashTrits: TArray<Integer>; begin Result := True; ACurl := TSpongeFactory.Create(customCurlMode); ATotalSum := 0; ALastIndex := bundle.Transactions.Count - 1; for i := 0 to bundle.Transactions.Count - 1 do begin ATrx := bundle.Transactions[i]; Inc(ATotalSum, ATrx.Value); if ATrx.CurrentIndex <> i then raise Exception.Create(INVALID_BUNDLE_ERROR); if ATrx.LastIndex <> ALastIndex then raise Exception.Create(INVALID_BUNDLE_ERROR); ATrxTrits := TConverter.Trits(Copy(ATrx.ToTrytes, 2188, 162)); ACurl.Absorb(ATrxTrits); // continue if output or signature tx if ATrx.Value >= 0 then Continue; // here we have an input transaction (negative value) AFragments := TStringList.Create; try AFragments.Add(ATrx.SignatureFragments); // find the subsequent txs containing the remaining signature // message fragments for this input transaction for j := i to bundle.Transactions.Count - 2 do begin ATrx2 := bundle.Transactions[j + 1]; // check if the tx is part of the input transaction if (ATrx.Address = ATrx2.Address) and (ATrx2.Value = 0) then // append the signature message fragment AFragments.Add(ATrx2.SignatureFragments); end; ASigning := TSigning.Create(ACurl.Clone); try if not ASigning.ValidateSignatures(ATrx.Address, AFragments.ToStringArray, ATrx.Bundle) then raise Exception.Create(INVALID_SIGNATURES_ERROR); finally ASigning.Free; end; finally AFragments.Free; end; end; // sum of all transaction must be 0 if ATotalSum <> 0 then raise Exception.Create(INVALID_BUNDLE_SUM_ERROR); SetLength(ABundleHashTrits, TJCurl.HASH_LENGTH); ACurl.Squeeze(ABundleHashTrits, 0, TJCurl.HASH_LENGTH); if TConverter.Trytes(ABundleHashTrits) <> bundle.Transactions[0].Bundle then raise Exception.Create(INVALID_BUNDLE_HASH_ERROR); end; end.
unit Alcinoe.HTTP.Client.Net.Pool; interface {$I Alcinoe.inc} uses System.classes, System.Net.HttpClient, System.Net.URLClient, Alcinoe.Common; type {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} TALNetHttpClientPoolCanStartProc = reference to function (var AExtData: Tobject): boolean; TALNetHttpClientPoolOnSuccessProc = reference to procedure (const AResponse: IHTTPResponse; var AContentStream: TMemoryStream; var AExtData: TObject); TALNetHttpClientPoolOnErrorProc = reference to procedure (const AErrMessage: string; var AExtData: Tobject); TALNetHttpClientPoolCacheDataProc = reference to procedure(const aUrl: String; const AHTTPResponse: IHTTPResponse; const aData: TMemoryStream); TALNetHttpClientPoolRetrieveCachedDataProc = reference to function(const aUrl: String; out AHTTPResponse: IHTTPResponse; const aData: TMemoryStream): boolean; {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} TALNetHttpClientPoolRequest = Class(Tobject) private FUrl: String; FCanStartCallBack: TALNetHttpClientPoolCanStartProc; FOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; FOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; FExtData: Tobject; FUseCache: Boolean; public constructor Create( const AUrl: String; const ACanStartCallBack: TALNetHttpClientPoolCanStartProc; const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; const AExtData: Tobject; const AUseCache: Boolean); destructor Destroy; override; Property Url: String read FUrl; Property CanStartCallBack: TALNetHttpClientPoolCanStartProc read FCanStartCallBack; Property OnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc read FOnSuccessCallBack; Property OnErrorCallBack: TALNetHttpClientPoolOnErrorProc read FOnErrorCallBack; Property ExtData: Tobject read FExtData; Property UseCache: Boolean read FUseCache; end; {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} TALNetHttpClientPool = Class(TALWorkerThreadPool) private class function CreateInstance: TALNetHttpClientPool; class function GetInstance: TALNetHttpClientPool; static; protected class var FInstance: TALNetHttpClientPool; public type TCreateInstanceFunct = function: TALNetHttpClientPool; class var CreateInstanceFunct: TCreateInstanceFunct; class property Instance: TALNetHttpClientPool read GetInstance; private FCacheData: TALNetHttpClientPoolCacheDataProc; FRetrieveCachedData: TALNetHttpClientPoolRetrieveCachedDataProc; procedure DoGet(var AExtData: Tobject); protected public procedure Get( const AUrl: String; const ACanStartCallBack: TALNetHttpClientPoolCanStartProc; // [MultiThread] const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; // [MultiThread] const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; // [MultiThread] const AExtData: Tobject; // ExtData will be free by the worker thread const AUseCache: Boolean; const APriority: Int64; const AAsync: Boolean = True); overload; procedure Get( const AUrl: String; const ACanStartCallBack: TALNetHttpClientPoolCanStartProc; // [MultiThread] const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; // [MultiThread] const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; // [MultiThread] const AExtData: Tobject; // ExtData will be free by the worker thread const AUseCache: Boolean; const APriority: TALWorkerThreadGetPriorityFunc; // [MultiThread] const AAsync: Boolean = True); overload; procedure Get( const AUrl: String; const ACanStartCallBack: TALNetHttpClientPoolCanStartProc; // [MultiThread] const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; // [MultiThread] const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; // [MultiThread] const AExtData: Tobject; // ExtData will be free by the worker thread const AAsync: Boolean = True); overload; procedure Get( const AUrl: String; const ACanStartCallBack: TALNetHttpClientPoolCanStartProc; // [MultiThread] const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; // [MultiThread] const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; // [MultiThread] const AAsync: Boolean = True); overload; procedure Get( const AUrl: String; const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; // [MultiThread] const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; // [MultiThread] const AExtData: Tobject; // ExtData will be free by the worker thread const AUseCache: Boolean; const APriority: Int64; const AAsync: Boolean = True); overload; procedure Get( const AUrl: String; const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; // [MultiThread] const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; // [MultiThread] const AExtData: Tobject; // ExtData will be free by the worker thread const AUseCache: Boolean; const APriority: TALWorkerThreadGetPriorityFunc; // [MultiThread] const AAsync: Boolean = True); overload; procedure Get( const AUrl: String; const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; // [MultiThread] const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; // [MultiThread] const AExtData: Tobject; // ExtData will be free by the worker thread const AAsync: Boolean = True); overload; procedure Get( const AUrl: String; const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; // [MultiThread] const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; // [MultiThread] const AAsync: Boolean = True); overload; Property CacheData: TALNetHttpClientPoolCacheDataProc read FCacheData write FCacheData; Property RetrieveCachedData: TALNetHttpClientPoolRetrieveCachedDataProc read FRetrieveCachedData write FRetrieveCachedData; end; implementation uses system.SysUtils, Alcinoe.HTTP.Client.Net, Alcinoe.HTTP.Client, Alcinoe.Cipher, Alcinoe.StringUtils; {*********************************************} constructor TALNetHttpClientPoolRequest.Create( const AUrl: String; const ACanStartCallBack: TALNetHttpClientPoolCanStartProc; const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; const AExtData: Tobject; const AUseCache: Boolean); begin inherited create; FUrl := AUrl; FCanStartCallBack := ACanStartCallBack; FOnSuccessCallBack := AOnSuccessCallBack; FOnErrorCallBack := AOnErrorCallBack; FExtData := AExtData; FUseCache := AUseCache; end; {*********************************************} destructor TALNetHttpClientPoolRequest.Destroy; begin ALFreeAndNil(FExtData); inherited Destroy; end; {***********************************************************************} class function TALNetHttpClientPool.CreateInstance: TALNetHttpClientPool; begin //https://stackoverflow.com/questions/70054035/what-the-ideal-maximum-parallels-http-connections-an-android-app-can-have result := TALNetHttpClientPool.Create(8); end; {********************************************************************} class function TALNetHttpClientPool.GetInstance: TALNetHttpClientPool; begin if FInstance = nil then begin var LInstance := CreateInstanceFunct; if AtomicCmpExchange(Pointer(FInstance), Pointer(LInstance), nil) <> nil then ALFreeAndNil(LInstance) end; Result := FInstance; end; {**********************************************************} procedure TALNetHttpClientPool.DoGet(var AExtData: Tobject); {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} function _HttpGetUrl(const aUrl: String; const LResponseContent: TStream): IHTTPResponse; begin Var LUri := Turi.Create(aUrl); var LNetHttpClient := ALAcquireKeepAliveNetHttpClient(LUri); try //in case we cut the connection I already see this returning sucess with //a partial content. What a sheet!! result := LNetHttpClient.Get(aUrl, LResponseContent); finally ALReleaseKeepAliveNetHttpClient(LUri, LNetHttpClient); end; end; begin var LNetHttpClientPoolRequest := TALNetHttpClientPoolRequest(AExtData); //protect the following code from exception try //init the http if (not assigned(LNetHttpClientPoolRequest.CanStartCallBack)) or (LNetHttpClientPoolRequest.CanStartCallBack(LNetHttpClientPoolRequest.FExtData)) then begin //create the http var LHTTPResponse: IHTTPResponse := nil; var LResponseContent := TMemoryStream.Create; try //get from the url if LNetHttpClientPoolRequest.Url <> '' then begin var LLowerUrl := LNetHttpClientPoolRequest.Url.ToLower; if (ALPosW('http://',LLowerUrl) = 1) or (ALPosW('https://',LLowerUrl) = 1) then begin if LNetHttpClientPoolRequest.UseCache then begin if (not assigned(RetrieveCachedData)) or (not RetrieveCachedData(LNetHttpClientPoolRequest.Url, LHTTPResponse, LResponseContent)) then begin LHTTPResponse := _HttpGetUrl(LNetHttpClientPoolRequest.Url, LResponseContent); if (assigned(CacheData)) then CacheData(LNetHttpClientPoolRequest.Url, LHTTPResponse, LResponseContent); end; end else LHTTPResponse := _HttpGetUrl(LNetHttpClientPoolRequest.Url, LResponseContent); end else LResponseContent.LoadFromFile(LNetHttpClientPoolRequest.Url); end; //decode the result if necessary if (LHTTPResponse <> nil) then ALDecompressHttpResponseContent(LHTTPResponse.ContentEncoding, LResponseContent); //fire the OnSuccess LNetHttpClientPoolRequest.OnSuccessCallBack(LHTTPResponse, LResponseContent, LNetHttpClientPoolRequest.FExtData); finally LHTTPResponse := nil; ALFreeandNil(LResponseContent); end; end; except on E: exception do begin if assigned(LNetHttpClientPoolRequest.OnErrorCallBack) then LNetHttpClientPoolRequest.OnErrorCallBack(E.Message, LNetHttpClientPoolRequest.FExtData); end; end; end; {*********************************} procedure TALNetHttpClientPool.Get( const AUrl: String; const ACanStartCallBack: TALNetHttpClientPoolCanStartProc; const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; const AExtData: Tobject; // ExtData will be free by the worker thread const AUseCache: Boolean; const APriority: Int64; const AAsync: Boolean = True); begin ExecuteProc( DoGet, // const AProc: TALWorkerThreadProc; TALNetHttpClientPoolRequest.Create( AUrl, ACanStartCallBack, AOnSuccessCallBack, AOnErrorCallBack, AExtData, AUseCache), // const AExtData: Tobject; APriority, // const APriority: Int64; AAsync); // const AAsync: Boolean = True end; {*********************************} procedure TALNetHttpClientPool.Get( const AUrl: String; const ACanStartCallBack: TALNetHttpClientPoolCanStartProc; const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; const AExtData: Tobject; // ExtData will be free by the worker thread const AUseCache: Boolean; const APriority: TALWorkerThreadGetPriorityFunc; const AAsync: Boolean = True); begin ExecuteProc( DoGet, // const AProc: TALWorkerThreadProc; TALNetHttpClientPoolRequest.Create( AUrl, ACanStartCallBack, AOnSuccessCallBack, AOnErrorCallBack, AExtData, AUseCache), // const AExtData: Tobject; APriority, // const APriority: TALWorkerThreadGetPriorityFunc; AAsync); // const AAsync: Boolean = True end; {*********************************} procedure TALNetHttpClientPool.Get( const AUrl: String; const ACanStartCallBack: TALNetHttpClientPoolCanStartProc; const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; const AExtData: Tobject; // ExtData will be free by the worker thread const AAsync: Boolean = True); begin ExecuteProc( DoGet, // const AProc: TALWorkerThreadProc; TALNetHttpClientPoolRequest.Create( AUrl, ACanStartCallBack, AOnSuccessCallBack, AOnErrorCallBack, AExtData, true{AUseCache}), // const AExtData: Tobject; AAsync); // const AAsync: Boolean = True end; {*********************************} procedure TALNetHttpClientPool.Get( const AUrl: String; const ACanStartCallBack: TALNetHttpClientPoolCanStartProc; const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; const AAsync: Boolean = True); begin ExecuteProc( DoGet, // const AProc: TALWorkerThreadProc; TALNetHttpClientPoolRequest.Create( AUrl, ACanStartCallBack, AOnSuccessCallBack, AOnErrorCallBack, nil{AExtData}, true{AUseCache}), // const AExtData: Tobject; AAsync); // const AAsync: Boolean = True end; {*********************************} procedure TALNetHttpClientPool.Get( const AUrl: String; const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; const AExtData: Tobject; // ExtData will be free by the worker thread const AUseCache: Boolean; const APriority: Int64; const AAsync: Boolean = True); begin Get( AUrl, // const AUrl: String; nil, // const ACanStartCallBack: TALNetHttpClientPoolCanStartProc; AOnSuccessCallBack, // const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; AOnErrorCallBack, // const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; AExtData, // const AExtData: Tobject; // ExtData will be free by the worker thread AUseCache, // const AUseCache: Boolean; APriority, // const APriority: Int64; AAsync); // const AAsync: Boolean = True end; {*********************************} procedure TALNetHttpClientPool.Get( const AUrl: String; const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; const AExtData: Tobject; // ExtData will be free by the worker thread const AUseCache: Boolean; const APriority: TALWorkerThreadGetPriorityFunc; const AAsync: Boolean = True); begin Get( AUrl, // const AUrl: String; nil, // const ACanStartCallBack: TALNetHttpClientPoolCanStartProc; AOnSuccessCallBack, // const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; AOnErrorCallBack, // const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; AExtData, // const AExtData: Tobject; // ExtData will be free by the worker thread AUseCache, // const AUseCache: Boolean; APriority, // const APriority: TALWorkerThreadGetPriorityFunc; AAsync); // const AAsync: Boolean = True end; {*********************************} procedure TALNetHttpClientPool.Get( const AUrl: String; const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; const AExtData: Tobject; // ExtData will be free by the worker thread const AAsync: Boolean = True); begin Get( AUrl, // const AUrl: String; nil, // const ACanStartCallBack: TALNetHttpClientPoolCanStartProc; AOnSuccessCallBack, // const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; AOnErrorCallBack, // const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; AExtData, // const AExtData: Tobject; // ExtData will be free by the worker thread AAsync); // const AAsync: Boolean = True end; {*********************************} procedure TALNetHttpClientPool.Get( const AUrl: String; const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; const AAsync: Boolean = True); begin Get( AUrl, // const AUrl: String; nil, // const ACanStartCallBack: TALNetHttpClientPoolCanStartProc; AOnSuccessCallBack, // const AOnSuccessCallBack: TALNetHttpClientPoolOnSuccessProc; AOnErrorCallBack, // const AOnErrorCallBack: TALNetHttpClientPoolOnErrorProc; AAsync); // const AAsync: Boolean = True end; initialization TALNetHttpClientPool.FInstance := nil; TALNetHttpClientPool.CreateInstanceFunct := @TALNetHttpClientPool.CreateInstance; finalization ALFreeAndNil(TALNetHttpClientPool.FInstance); end.
{$ifdef license} (* Copyright 2020 ChapmanWorld LLC ( https://chapmanworld.com ) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder 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. *) {$endif} unit cwStatus; {$ifdef fpc} {$mode delphiunicode} {$MODESWITCH ADVANCEDRECORDS} {$MODESWITCH TYPEHELPERS} {$endif} interface uses sysutils // for Exception & TGUID , cwStatus.Parameterized ; {$region ' Exceptions which may be raised by cwStatus'} type /// <summary> /// Exception raised when the TStatus.Raize method is called. /// </summary> EStatus = class(Exception) private function getMessage: string; procedure setMessage( const value: string ); public property Message: string read getMessage write setMessage; end; /// <summary> /// This exception is raised if an attempt is made to set a status /// using an ansi-string which does not contain a valid guid. /// </summary> EInvalidStatusGUID = class(Exception); {$endregion} {$region ' The TStatus data type.'} type /// <summary> /// </summary> TStatus = record private GUID: TGUID; Parameterized: IStatusParameterizedMessage; private procedure ParameterizeMessage(const Parameters: array of string); function GetText: string; overload; public class operator Implicit(const a: TStatus): string; class operator Explicit(const a: TStatus): string; class operator Implicit(const a: ansistring): TStatus; class operator Explicit(const a: ansistring): TStatus; class operator Implicit(const a: string): TStatus; class operator Explicit(const a: string): TStatus; class operator Implicit(const a: TStatus): Boolean; class operator Explicit(const a: TStatus): Boolean; class operator LogicalNot(const a: TStatus): Boolean; class operator Equal( const a: TStatus; const b: TStatus ): boolean; class operator NotEqual( const a: TStatus; const b: TStatus ): boolean; class operator Equal( const a: TStatus; const b: ansistring ): boolean; class operator NotEqual( const a: TStatus; const b: ansistring ): boolean; class operator Equal( const a: ansistring; const b: TStatus ): boolean; class operator NotEqual( const a: ansistring; const b: TStatus ): boolean; class function Unknown: TStatus; static; class function Success: TStatus; static; procedure Raize; overload; procedure Raize( const Parameters: array of string ); overload; function Return: TStatus; overload; function Return( const Parameters: array of string ): TStatus; overload; {$ifdef fpc} class procedure Register(const a: ansistring); static; {$else} class procedure Register(const a: string); static; {$endif} end; {$endregion} implementation uses cwStatus.Messages , cwStatus.Placeholders ; const {$hints off} stSuccess = '{00000000-0000-0000-0000-000000000000} SUCCESS'; {$hints on} {$hints off} stUnknown = '{01010101-0101-0101-0101-010101010101} UNKNOWN'; {$hints on} const cSuccess : TGUID = '{00000000-0000-0000-0000-000000000000}'; cUnknown : TGUID = '{01010101-0101-0101-0101-010101010101}'; function EStatus.getMessage: string; begin Result := string(inherited Message); end; procedure EStatus.setMessage(const value: string); begin {$ifdef fpc} inherited Message := ansistring(value); {$else} inherited Message := value; {$endif} end; class operator TStatus.Implicit(const a: TStatus): string; begin Result := a.GetText; end; class operator TStatus.Explicit(const a: TStatus): string; begin Result := a.GetText; end; class operator TStatus.Implicit(const a: ansistring): TStatus; begin if not TMessageDictionary.ReadGUID(a,Result.GUID) then begin {$ifdef fpc} raise EInvalidStatusGUID.Create(a); {$else} raise EInvalidStatusGUID.Create(string(a)); {$endif} end; end; class operator TStatus.Explicit(const a: ansistring): TStatus; begin if not TMessageDictionary.ReadGUID(a,Result.GUID) then begin {$ifdef fpc} raise EInvalidStatusGUID.Create(a); {$else} raise EInvalidStatusGUID.Create(string(a)); {$endif} end; end; class operator TStatus.Implicit(const a: TStatus): Boolean; begin Result := IsEqualGUID(cSuccess,a.GUID); end; class operator TStatus.Implicit(const a: string): TStatus; begin if not TMessageDictionary.ReadGUID(ansistring(a),Result.GUID) then begin {$ifdef fpc} raise EInvalidStatusGUID.Create(ansistring(a)); {$else} raise EInvalidStatusGUID.Create(a); {$endif} end; end; class operator TStatus.Explicit(const a: TStatus): Boolean; begin Result := IsEqualGUID(cSuccess,a.GUID); end; class operator TStatus.Explicit(const a: string): TStatus; begin if not TMessageDictionary.ReadGUID(ansistring(a),Result.GUID) then begin {$ifdef fpc} raise EInvalidStatusGUID.Create(ansistring(a)); {$else} raise EInvalidStatusGUID.Create(a); {$endif} end; end; class operator TStatus.LogicalNot(const a: TStatus): Boolean; begin Result := not IsEqualGUID(a.GUID,cSuccess); end; class operator TStatus.Equal(const a: TStatus; const b: TStatus): boolean; begin Result := IsEqualGUID(a.GUID,b.GUID); end; class operator TStatus.NotEqual(const a: TStatus; const b: TStatus): boolean; begin Result := not IsEqualGUID(a.GUID,b.GUID); end; class operator TStatus.Equal(const a: TStatus; const b: ansistring): boolean; var bGUID: TGUID; begin if not TMessageDictionary.ReadGUID(b,bGUID) then begin {$ifdef fpc} raise EInvalidStatusGUID.Create(b); {$else} raise EInvalidStatusGUID.Create(string(b)); {$endif} end; Result := IsEqualGUID(a.GUID,bGUID); end; class operator TStatus.NotEqual(const a: TStatus; const b: ansistring): boolean; var bGUID: TGUID; begin if not TMessageDictionary.ReadGUID(b,bGUID) then begin {$ifdef fpc} raise EInvalidStatusGUID.Create(b); {$else} raise EInvalidStatusGUID.Create(string(b)); {$endif} end; Result := not IsEqualGUID(a.GUID,bGUID); end; class operator TStatus.Equal(const a: ansistring; const b: TStatus): boolean; var aGUID: TGUID; begin if not TMessageDictionary.ReadGUID(a,aGUID) then begin {$ifdef fpc} raise EInvalidStatusGUID.Create(a); {$else} raise EInvalidStatusGUID.Create(string(a)); {$endif} end; Result := IsEqualGUID(aGUID,b.GUID); end; class operator TStatus.NotEqual(const a: ansistring; const b: TStatus): boolean; var aGUID: TGUID; begin if not TMessageDictionary.ReadGUID(a,aGUID) then begin {$ifdef fpc} raise EInvalidStatusGUID.Create(a); {$else} raise EInvalidStatusGUID.Create(string(a)); {$endif} end; Result := not IsEqualGUID(aGUID,b.GUID); end; class function TStatus.Unknown: TStatus; begin Result.GUID := cUnknown; end; class function TStatus.Success: TStatus; begin Result.GUID := cSuccess; end; procedure TStatus.ParameterizeMessage(const Parameters: array of string); var S: string; begin //- Get the text to be parameterized. Parameterized := nil; S := GetText; Parameterized := TStatusParameterizedMessage.Create; Parameterized.Message := S; Parameterized.Message := TPlaceholders.ParameterizeString(Parameterized.Message,Parameters); end; function TStatus.Return(const Parameters: array of string): TStatus; begin ParameterizeMessage( Parameters ); Result := Self; end; function TStatus.Return: TStatus; begin Result := Return([]); end; function TStatus.GetText: string; begin if assigned(Parameterized) then begin Result := Parameterized.Message; exit; end; if not TMessageDictionary.FindEntry(GUID,Result) then begin Result := string(GUIDToString(GUID)); end; end; procedure TStatus.Raize(const Parameters: array of string); begin {$hints off} if IsEqualGUID(GUID,cSuccess) then exit; {$hints on} if Length(Parameters)<>0 then begin ParameterizeMessage( Parameters ); end; {$ifdef fpc} raise EStatus.Create(ansistring(GetText())); {$else} raise EStatus.Create(GetText()); {$endif} end; procedure TStatus.Raize; begin Raize([]); end; {$ifdef fpc} class procedure TStatus.Register(const a: ansistring); {$else} class procedure TStatus.Register(const a: string); {$endif} var GUID: TGUID; StatusText: string; begin try {$ifdef fpc} if not TMessageDictionary.SplitStatusText(a,GUID,StatusText) then exit; {$else} if not TMessageDictionary.SplitStatusText(ansistring(a),GUID,StatusText) then exit; {$endif} except on E: Exception do exit; else exit; end; TMessageDictionary.RegisterEntry(GUID,StatusText); end; initialization TStatus.Register(stSuccess); TStatus.Register(stUnknown); end.
{******************************************************************************* Модуль SysLogUtils Разработчик: Арбузов М.В. Назначение: Ряд классов для ведения логов. *******************************************************************************} unit SysLogUtils; interface uses Classes; const ReportError = 87.0; ReportWarning = 62.0; ReportMessage = 37.0; FilterAll = 100.0; FilterError = 75.0; FilterWarning = 50.0; FilterMessage = 25.0; FilterNone = 00.0; MaxCountRecord = 20000; type ILogNode = Interface; IHandler = interface; {: Сообщение } IReport = interface(IUnknown) ['{129F7648-9B35-488A-94D8-623D6E5A4833}'] function GetLevel: Single; function GetSender: ILogNode; stdcall; function GetText: string; function GetTime: TDateTime; stdcall; end; {: Интерфейс для логирования } ILog = interface(IUnknown) ['{8B669415-FB6E-43C8-BB5B-C77C4FC1BB87}'] procedure Attach(AHandler: IHandler); stdcall; procedure Error(AError: string); stdcall; function GetActive: Boolean; stdcall; function GetFilter: Single; stdcall; function GetName: string; stdcall; function GetPathToLogFile: string; stdcall; function GetSubLogs(AName: string): ILog; stdcall; procedure Msg(AMessage: string); procedure Report(ALevel: Single; AText: string); overload; stdcall; procedure SetActive(const Value: Boolean); stdcall; procedure SetFilter(const Value: Single); stdcall; procedure Warning(AWarning: string); stdcall; property Active: Boolean read GetActive write SetActive; property Filter: Single read GetFilter write SetFilter; property Name: string read GetName; property PathToLogFile: string read GetPathToLogFile; property SubLogs[AName: string]: ILog read GetSubLogs; default; end; {: Инетрфейс очереди работающей внутри обработчика } IQueue = interface(IUnknown) ['{45D733A9-7828-4E55-A5FA-13344407E3F0}'] procedure Post(AReport: IReport); stdcall; procedure SetQueue(AQueue: IQueue); stdcall; end; {: Интерфейс точки стыковки лога и его записи, филтрации и очередей } IHandler = interface(IUnknown) ['{90A9B2A5-CCD7-4057-98B9-2A8F72722500}'] procedure AddQueue(AQueue: IQueue); stdcall; procedure Detach; stdcall; function GetFilter: Single; stdcall; procedure Reported(AReport: IReport); procedure SetAddr(AAddr: ILogNode); stdcall; procedure SetFilter(const Value: Single); stdcall; property Filter: Single read GetFilter write SetFilter; end; {: Расширение интерфейса ILog для служебных функций обслуживающих дерево логов. } ILogNode = interface(ILog) ['{C7D8AD62-BD22-405B-810D-0059EA102643}'] procedure Breake; function ChildrenCount: Integer; stdcall; function GetChildren(AIndex: Integer): ILogNode; stdcall; function GetHeight: Integer; stdcall; function GetParent: ILogNode; stdcall; function IsRoot: Boolean; stdcall; procedure RemoveHandler(AHandler: IHandler); stdcall; procedure Report(AReport: IReport); overload; stdcall; property Children[AIndex: Integer]: ILogNode read GetChildren; default; end; {: Абстарктный класс - интерфейс записи события в лог } TLogWriter = class(TObject) public procedure BeginWrites; virtual; abstract; procedure Clear; virtual; abstract; procedure EndWrites; virtual; abstract; procedure Write(AReport: IReport; AHandlerAddr: ILogNode); virtual; abstract; end; {: Базовый класс для текстового логироваия. Наследники должны переопределить метод Write для записи строки лога. } TTxtLog = class(TLogWriter) public procedure Write(AReport: IReport; AHandlerAddr: ILogNode); override; procedure WriteLine(AString: string); virtual; abstract; end; {: Буффер для хранения лога } TLogBuffer = class(TLogWriter) private FFilter: Single; procedure SetFilter(const AValue: Single); public constructor Create(AWriter: TLogWriter); procedure BeginWrites; override; procedure Clear; override; procedure EndWrites; override; procedure Write(AReport: IReport; AHandlerAddr: ILogNode); override; property Filter: Single read FFilter write SetFilter; end; GetLogFunction = function: ILog; {: Получить корневой лог } function GetLog: ILog; function CreateHandler(AWriter: TLogWriter; AQueue: IQueue = nil): IHandler; procedure LogStrings(AStrings: TStrings; ALog: ILog = nil; ALevel: Single = ReportMessage); procedure GetPath(ASenderAddr, AHandlerAddr: ILogNode; AStrings: TStrings); function GetPathAsStr(ASenderAddr, AHandlerAddr: ILogNode): string; implementation uses SysUtils, SyncObjs, MyDocUnit; var RootLog: ILogNode; type TLogList = class(TObject) private FList: TList; constructor Create; destructor Destroy; override; function Add(AParent: ILogNode; AName: string): Integer; function Count: Integer; function GetItems(AIndex: Integer): ILogNode; property Items[AIndex: Integer]: ILogNode read GetItems; default; end; TLog = class(TInterfacedObject, ILog, ILogNode) private FActive: Boolean; FChildList: TLogList; FCriticalSection: TCriticalSection; FFilter: Single; FHandlerList: TInterfaceList; FName: string; FParent: ILogNode; constructor Create(AParent: ILogNode; AName: string); destructor Destroy; override; procedure Attach(AHandler: IHandler); stdcall; procedure Breake; function ChildrenCount: Integer; stdcall; procedure Error(AError: string); stdcall; function GetActive: Boolean; stdcall; function GetChildren(AIndex: Integer): ILogNode; stdcall; function GetFilter: Single; stdcall; function GetHandlers(AIndex: Integer): IHandler; function GetHeight: Integer; stdcall; function GetName: string; stdcall; function GetPathToLogFile: string; stdcall; function GetParent: ILogNode; stdcall; function GetSubLogs(AName: string): ILog; stdcall; function IsRoot: Boolean; stdcall; procedure SetActive(const Value: Boolean); stdcall; procedure Msg(AMessage: string); procedure RemoveHandler(AHandler: IHandler); stdcall; procedure Report(ALevel: Single; AText: string); overload; stdcall; procedure Report(AReport: IReport); overload; stdcall; procedure SetFilter(const Value: Single); stdcall; procedure Warning(AWarning: string); stdcall; property Active: Boolean read GetActive write SetActive; end; {: Реализует фильтрацию и регистрацию } THandler = class(TInterfacedObject, IHandler, IQueue) private FAddr: ILogNode; FFilter: Single; FQueue: IQueue; FWriter: TLogWriter; constructor Create(AWriter: TLogWriter); destructor Destroy; override; procedure AddQueue(AQueue: IQueue); stdcall; procedure Detach; stdcall; function GetFilter: Single; stdcall; procedure Post(AReport: IReport); stdcall; procedure Reported(AReport: IReport); procedure SetAddr(AAddr: ILogNode); stdcall; procedure SetFilter(const Value: Single); stdcall; procedure SetQueue(AQueue: IQueue); stdcall; end; TReport = class(TInterfacedObject, IReport) private FLevel: Single; FSender: ILogNode; FText: string; FTime: TDateTime; constructor Create(ALevel: Single; AText: string; ASender: ILogNode); destructor Destroy; override; function GetLevel: Single; function GetSender: ILogNode; stdcall; function GetText: string; function GetTime: TDateTime; stdcall; end; function GetLog: ILog; begin if not Assigned(RootLog) then RootLog := TLog.Create(nil, ''); Result := RootLog; end; function CreateHandler(AWriter: TLogWriter; AQueue: IQueue): IHandler; begin Result := THandler.Create(AWriter); Result.AddQueue(AQueue); end; function GetPathAsStr(ASenderAddr, AHandlerAddr: ILogNode): string; var Strings: TStrings; I: Integer; begin Strings := TStringList.Create; try Getpath(ASenderAddr, AHandlerAddr, Strings); Result := ''; for I := 0 to Strings.Count - 1 do Result := Result + '\' + Strings[i]; finally Strings.Free; end; end; procedure LogStrings(AStrings: TStrings; ALog: ILog = nil; ALevel: Single = ReportMessage); var I: Integer; begin if not Assigned(ALog) then ALog := GetLog; try for I := 0 to AStrings.Count - 1 do ALog.Msg(AStrings[i]); except on E: Exception do ALog.Warning('Ошибка записи в лог TStrings: ' + E.Message); end; end; { ********************************** TLogBuffer ********************************** } constructor TLogBuffer.Create(AWriter: TLogWriter); begin end; procedure TLogBuffer.BeginWrites; begin end; procedure TLogBuffer.Clear; begin end; procedure TLogBuffer.EndWrites; begin end; procedure TLogBuffer.SetFilter(const AValue: Single); begin FFilter := AValue; FFilter := AValue; end; procedure TLogBuffer.Write(AReport: IReport; AHandlerAddr: ILogNode); begin end; { *********************************** TLogList *********************************** } constructor TLogList.Create; begin FList := TList.Create; end; destructor TLogList.Destroy; var I: Integer; begin for I := 0 to FList.Count - 1 do ILog(FList.List[I]) := nil; FList.Free; end; function TLogList.Add(AParent: ILogNode; AName: string): Integer; begin Result := FList.Add(nil); ILogNode(FList.List[Result]) := TLog.Create(AParent, AName); end; function TLogList.Count: Integer; begin Result := FList.Count; end; function TLogList.GetItems(AIndex: Integer): ILogNode; begin Result := ILogNode(FList.List[AIndex]); end; { ************************************* TLog ************************************* } constructor TLog.Create(AParent: ILogNode; AName: string); begin FActive := True; FCriticalSection := TCriticalSection.Create; if Assigned(AParent) then FFilter := AParent.Filter else FFilter := FilterNone; FParent := AParent; FName := AName; FChildList := TLogList.Create; FHandlerList := TInterfaceList.Create; end; destructor TLog.Destroy; begin FChildList.Free; FHandlerList.Free; FCriticalSection.Free; end; procedure TLog.Attach(AHandler: IHandler); begin AHandler.Detach; // Хандлер сам себя удалит из FHandlerList AHandler.SetAddr(self); FHandlerList.Add(AHandler); end; procedure TLog.Breake; var I: Integer; begin FParent := nil; while FHandlerList.Count > 0 do GetHandlers(0).Detach; // Хандлер сам себя удалит из FHandlerList for I := 0 to FChildList.Count - 1 do FChildList.Items[I].Breake; end; function TLog.ChildrenCount: Integer; begin Result := FChildList.Count; end; procedure TLog.Error(AError: string); begin Report(ReportError, AError); end; function TLog.GetChildren(AIndex: Integer): ILogNode; begin Result := FChildList[AIndex]; end; function TLog.GetFilter: Single; begin Result := FFilter; end; function TLog.GetHandlers(AIndex: Integer): IHandler; begin Result := FHandlerList[AIndex] as IHandler; end; function TLog.GetHeight: Integer; var Log: ILogNode; begin Log := self; Result := 0; while not Log.IsRoot do begin Log := Log.GetParent; Inc(Result); end; end; function TLog.GetName: string; begin Result := FName; end; function TLog.GetParent: ILogNode; begin if Assigned(FParent) then Result := FParent else Result := self; end; function TLog.GetSubLogs(AName: string): ILog; var I: Integer; begin FCriticalSection.Enter; try Result := nil; I := 0; while (not Assigned(Result)) and (I < FChildList.Count) do begin if FChildList[i].Name = AName then Result := FChildList[i]; Inc(i); end; if not Assigned(Result) then Result := FChildList[FChildList.Add(self, AName)]; finally FCriticalSection.Leave; end; end; function TLog.IsRoot: Boolean; begin Result := not Assigned(FParent); end; procedure TLog.Msg(AMessage: string); begin Report(ReportMessage, AMessage); end; procedure TLog.RemoveHandler(AHandler: IHandler); begin FHandlerList.Remove(AHandler); end; procedure TLog.Report(ALevel: Single; AText: string); begin if (ALevel > FFilter) and Active then Report(TReport.Create(ALevel, AText, self)); end; procedure TLog.Report(AReport: IReport); var i: Integer; begin if Active then begin if Assigned(FParent) then FParent.Report(AReport); for i := 0 to FHandlerList.Count - 1 do GetHandlers(i).Reported(AReport); end; end; procedure TLog.SetFilter(const Value: Single); var i: Integer; begin FCriticalSection.Enter; try FFilter := Value; finally FCriticalSection.Leave; end; for i := 0 to FChildList.Count - 1 do FChildList[i].Filter := Value; end; procedure TLog.Warning(AWarning: string); begin Report(ReportWarning, AWarning); end; { *********************************** THandler *********************************** } constructor THandler.Create(AWriter: TLogWriter); begin FWriter := AWriter; SetQueue(Self); // Уменьшаем на еденицу счетчик - поскольку создаем цыклическую ссылку, // которая если не уменьшить счетчик не даст самоубиться обьекту _Release; end; destructor THandler.Destroy; begin FreeAndNil(FWriter); FQueue := nil; end; procedure THandler.AddQueue(AQueue: IQueue); begin if Assigned(AQueue) then begin // Порядок присвоения важен - поскольку счетчик Self исскуственно // уменьшен на единицу. AQueue.SetQueue(Self); FQueue.SetQueue(AQueue); end end; procedure THandler.Detach; begin if Assigned(FAddr) then FAddr.RemoveHandler(self); FAddr := nil; end; function THandler.GetFilter: Single; begin Result := FFilter; end; procedure THandler.Post(AReport: IReport); begin FWriter.Write(AReport, FAddr); end; procedure THandler.Reported(AReport: IReport); begin if AReport.GetLevel > FFilter then FQueue.Post(AReport) end; procedure THandler.SetAddr(AAddr: ILogNode); begin FAddr := AAddr; end; procedure THandler.SetFilter(const Value: Single); begin FFilter := Value; end; procedure THandler.SetQueue(AQueue: IQueue); begin FQueue := AQueue; end; { *********************************** TReport ************************************ } constructor TReport.Create(ALevel: Single; AText: string; ASender: ILogNode); begin FText := AText; FTime := Now; FLevel := ALevel; FSender := ASender; end; destructor TReport.Destroy; begin try FText := ''; FSender := nil; except end; end; function TReport.GetLevel: Single; begin Result := FLevel; end; function TReport.GetSender: ILogNode; begin Result := FSender; end; function TReport.GetText: string; begin Result := FText; end; function TReport.GetTime: TDateTime; begin Result := FTime; end; procedure GetPath(ASenderAddr, AHandlerAddr: ILogNode; AStrings: TStrings); var Log: ILogNode; begin Log := ASenderAddr; while (not Log.IsRoot) and (Log <> AHandlerAddr) do begin AStrings.Insert(0, Log.Name); Log := Log.GetParent; end; end; { *********************************** TTxtLog ************************************ } procedure TTxtLog.Write(AReport: IReport; AHandlerAddr: ILogNode); var Path: string; begin Path := GetPathAsStr(AReport.GetSender, AHandlerAddr); if Path <> '' then Path := Path + ': '; WriteLine(Path + AReport.GetText); end; function TLog.GetActive: Boolean; begin Result := FActive end; procedure TLog.SetActive(const Value: Boolean); begin FActive := Value; end; function TLog.GetPathToLogFile: string; begin Result := AppDocPath + 'logs\' + FName + '.log'; end; initialization RootLog := nil; finalization if Assigned(RootLog) then RootLog.Breake; end.
program gadtoolsgadgets; {$IFNDEF HASAMIGA} {$FATAL This source is compatible with Amiga, AROS and MorphOS only !} {$ENDIF} {$MODE OBJFPC}{$H+}{$HINTS ON} {$UNITPATH ../../../Base/CHelpers} {$UNITPATH ../../../Base/Trinity} {$UNITPATH ../../../Base/Sugar} {$IFDEF AMIGA} {$UNITPATH ../../../Sys/Amiga} {$ENDIF} {$IFDEF AROS} {$UNITPATH ../../../Sys/AROS} {$ENDIF} {$IFDEF MORPHOS} {$UNITPATH ../../../Sys/MorphOS} {$ENDIF} { Project : gadtoolsgadgets Source : RKRM } {* ** Simple example of using a number of gadtools gadgets. *} Uses Exec, AGraphics, Intuition, Gadtools, Utility, {$IFDEF AMIGA} systemvartags, {$ENDIF} CHelpers, Trinity; //Type // PPGadget = ^PGadget; Const {/* Gadget defines of our choosing, to be used as GadgetID's, ** also used as the index into the gadget array my_gads[]. *} MYGAD_SLIDER = (0); MYGAD_STRING1 = (1); MYGAD_STRING2 = (2); MYGAD_STRING3 = (3); MYGAD_BUTTON = (4); //* Range for the slider: */ SLIDER_MIN = (1); SLIDER_MAX = (20); Topaz80 : TTextAttr = ( ta_Name : 'topaz.font'; ta_YSize : 8; ta_Style : 0; ta_Flags : 0; ); {* Print any error message. We could do more fancy handling (like ** an EasyRequest()), but this is only a demo. *} procedure errorMessage(error: STRPTR); begin if assigned(error) then WriteLn('Error: ', error); end; {* ** Function to handle a GADGETUP or GADGETDOWN event. For GadTools gadgets, ** it is possible to use this function to handle MOUSEMOVEs as well, with ** little or no work. *} procedure handleGadgetEvent(win: PWindow; gad: PGadget; code: UWORD; slider_level: PSmallInt; my_gads: Array of PGadget); begin case (gad^.GadgetID) of MYGAD_SLIDER: begin //* Sliders report their level in the IntuiMessage Code field: */ WriteLn('Slider at level ', code); slider_level^ := code; end; MYGAD_STRING1: begin //* String gadgets report GADGETUP's */ WriteLn('String gadget 1: "', PStringInfo(gad^.SpecialInfo)^.Buffer ,'".'); end; MYGAD_STRING2: begin //* String gadgets report GADGETUP's */ WriteLn('String gadget 2: "', PStringInfo(gad^.SpecialInfo)^.Buffer ,'".'); end; MYGAD_STRING3: begin //* String gadgets report GADGETUP's */ WriteLn('String gadget 3: "', PStringInfo(gad^.SpecialInfo)^.Buffer ,'".'); end; MYGAD_BUTTON: begin //* Buttons report GADGETUP's (button resets slider to 10) */ WriteLn('Button was pressed, slider reset to 10.'); slider_level^ := 10; GT_SetGadgetAttrs(my_gads[MYGAD_SLIDER], win, nil, [ TAG_(GTSL_Level), slider_level^, TAG_END ]); end; end; end; {* ** Function to handle vanilla keys. *} procedure handleVanillaKey(win: PWindow; code: UWORD; slider_level: PSmallInt; my_gads: Array of PGadget); begin case Chr(code) of 'v': begin //* increase slider level, but not past maximum */ inc(slider_level^); if (slider_level^ > SLIDER_MAX) then slider_level^ := SLIDER_MAX; GT_SetGadgetAttrs(my_gads[MYGAD_SLIDER], win, nil, [ TAG_(GTSL_Level), slider_level^, TAG_END ]); end; 'V': begin //* decrease slider level, but not past minimum */ dec(slider_level^); if (slider_level^ < SLIDER_MIN) then slider_level^ := SLIDER_MIN; GT_SetGadgetAttrs(my_gads[MYGAD_SLIDER], win, nil, [ TAG_(GTSL_Level), slider_level^, TAG_END ]); end; 'c', 'C': begin //* button resets slider to 10 */ slider_level^ := 10; GT_SetGadgetAttrs(my_gads[MYGAD_SLIDER], win, nil, [ TAG_(GTSL_Level), slider_level^, TAG_END ]); end; 'f', 'F': begin ActivateGadget(my_gads[MYGAD_STRING1], win, nil); end; 's', 'S': begin ActivateGadget(my_gads[MYGAD_STRING2], win, nil); end; 't', 'T': begin ActivateGadget(my_gads[MYGAD_STRING3], win, nil); end; end; end; {* ** Here is where all the initialization and creation of GadTools gadgets ** take place. This function requires a pointer to a NULL-initialized ** gadget list pointer. It returns a pointer to the last created gadget, ** which can be checked for success/failure. *} function createAllGadgets(glistptr: PPGadget; vi: Pointer; topborder: UWORD; slider_level: SmallInt; var my_gads: Array of PGadget): PGadget; var ng : TNewGadget; gad : PGadget; begin {* All the gadget creation calls accept a pointer to the previous gadget, and ** link the new gadget to that gadget's NextGadget field. Also, they exit ** gracefully, returning NULL, if any previous gadget was NULL. This limits ** the amount of checking for failure that is needed. You only need to check ** before you tweak any gadget structure or use any of its fields, and finally ** once at the end, before you add the gadgets. *} {* The following operation is required of any program that uses GadTools. ** It gives the toolkit a place to stuff context data. *} gad := CreateContext(glistptr); {* Since the NewGadget structure is unmodified by any of the CreateGadget() ** calls, we need only change those fields which are different. *} ng.ng_LeftEdge := 140; ng.ng_TopEdge := 20 + topborder; ng.ng_Width := 200; ng.ng_Height := 12; ng.ng_GadgetText := '_Volume: '; ng.ng_TextAttr := @Topaz80; ng.ng_VisualInfo := vi; ng.ng_GadgetID := MYGAD_SLIDER; ng.ng_Flags := NG_HIGHLABEL; my_gads[MYGAD_SLIDER] := SetAndGet(gad, CreateGadget(SLIDER_KIND, gad, @ng, [ TAG_(GTSL_Min) , SLIDER_MIN, TAG_(GTSL_Max) , SLIDER_MAX, TAG_(GTSL_Level) , slider_level, TAG_(GTSL_LevelFormat) , TAG_(PChar('%2ld')), TAG_(GTSL_MaxLevelLen) , 2, TAG_(GT_Underscore) , Ord('_'), TAG_END ])); ng.ng_TopEdge := ng.ng_TopEdge + 20; ng.ng_Height := 14; ng.ng_GadgetText := '_First:'; ng.ng_GadgetID := MYGAD_STRING1; my_gads[MYGAD_STRING1] := SetAndGet(gad, CreateGadget(STRING_KIND, gad, @ng, [ TAG_(GTST_String) , TAG_(PChar('Try pressing')), TAG_(GTST_MaxChars) , 50, TAG_(GT_Underscore) , Ord('_'), TAG_END ])); ng.ng_TopEdge := ng.ng_TopEdge + 20; ng.ng_GadgetText := '_Second:'; ng.ng_GadgetID := MYGAD_STRING2; my_gads[MYGAD_STRING2] := SetAndGet(gad, CreateGadget(STRING_KIND, gad, @ng, [ TAG_(GTST_String) , TAG_(PChar('TAB or Shift-TAB')), TAG_(GTST_MaxChars) , 50, TAG_(GT_Underscore) , Ord('_'), TAG_END ])); ng.ng_TopEdge := ng.ng_TopEdge + 20; ng.ng_GadgetText := '_Third:'; ng.ng_GadgetID := MYGAD_STRING3; my_gads[MYGAD_STRING3] := SetAndGet(gad, CreateGadget(STRING_KIND, gad, @ng, [ TAG_(GTST_String) , TAG_(PChar('To see what happens!')), TAG_(GTST_MaxChars) , 50, TAG_(GT_Underscore) , Ord('_'), TAG_END ])); ng.ng_LeftEdge := ng.ng_LeftEdge + 50; ng.ng_TopEdge := ng.ng_TopEdge + 20; ng.ng_Width := 100; ng.ng_Height := 12; ng.ng_GadgetText := '_Click Here'; ng.ng_GadgetID := MYGAD_BUTTON; ng.ng_Flags := 0; gad := CreateGadget(BUTTON_KIND, gad, @ng, [ TAG_(GT_Underscore) , Ord('_'), TAG_END ]); Result := (gad); end; {* ** Standard message handling loop with GadTools message handling functions ** used (GT_GetIMsg() and GT_ReplyIMsg()). *} procedure process_window_events(mywin: PWindow; slider_level: PSmallInt; my_gads: Array of PGadget); var imsg : PIntuiMessage; imsgClass : ULONG; imsgCode : UWORD; gad : PGadget; terminated : Boolean = FALSE; begin while not(terminated) do begin Wait(1 shl mywin^.UserPort^.mp_SigBit); {* GT_GetIMsg() returns an IntuiMessage with more friendly information for ** complex gadget classes. Use it wherever you get IntuiMessages where ** using GadTools gadgets. *} while ( not(terminated) and SetAndTest(imsg, GT_GetIMsg(mywin^.UserPort))) do begin {* Presuming a gadget, of course, but no harm... ** Only dereference this value (gad) where the Class specifies ** that it is a gadget event. *} gad := PGadget(imsg^.IAddress); imsgClass := imsg^.IClass; imsgCode := imsg^.Code; //* Use the toolkit message-replying function here... */ GT_ReplyIMsg(imsg); case (imsgClass) of {* --- WARNING --- WARNING --- WARNING --- WARNING --- WARNING --- ** GadTools puts the gadget address into IAddress of IDCMP_MOUSEMOVE ** messages. This is NOT true for standard Intuition messages, ** but is an added feature of GadTools. *} IDCMP_GADGETDOWN, IDCMP_MOUSEMOVE, IDCMP_GADGETUP: begin handleGadgetEvent(mywin, gad, imsgCode, slider_level, my_gads); end; IDCMP_VANILLAKEY: begin handleVanillaKey(mywin, imsgCode, slider_level, my_gads); end; IDCMP_CLOSEWINDOW: begin terminated := TRUE; end; IDCMP_REFRESHWINDOW: begin {* With GadTools, the application must use GT_BeginRefresh() ** where it would normally have used BeginRefresh() *} GT_BeginRefresh(mywin); GT_EndRefresh(mywin, Ord(TRUE)); end; end; end; end; end; {* ** Prepare for using GadTools, set up gadgets and open window. ** Clean up and when done or on error. *} procedure gadtoolsWindow; var font : PTextFont; mysc : PScreen; mywin : PWindow; glist : PGadget; slider_level : SmallInt = 5; vi : Pointer; topborder : UWORD; my_gads : Array[0..Pred(4)] of PGadget; begin {* Open topaz 8 font, so we can be sure it's openable ** when we later set ng_TextAttr to &Topaz80: *} if (nil = SetAndGet(font, OpenFont(@Topaz80))) then errorMessage('Failed to open Topaz 80') else begin if (nil = SetAndGet(mysc, LockPubScreen(nil))) then errorMessage('Couldn''t lock default public screen"') else begin // if (nil = SetAndGet(vi, GetVisualInfo(mysc, [TAG_END]))) if (nil = SetAndGet(vi, GetVisualInfo(mysc, [TAG_END, 0]))) // aros bug in tagitems then errorMessage('GetVisualInfo() failed') else begin //* Here is how we can figure out ahead of time how tall the */ //* window's title bar will be: */ topborder := mysc^.WBorTop + (mysc^.Font^.ta_YSize + 1); if (nil = createAllGadgets(@glist, vi, topborder, slider_level, my_gads)) then errorMessage('createAllGadgets() failed') else begin if (nil = SetAndGet(mywin, OpenWindowTags(nil, [ TAG_(WA_Title) , TAG_(PChar('GadTools Gadget Demo')), TAG_(WA_Gadgets) , TAG_(glist), TAG_(WA_AutoAdjust) , TAG_(TRUE), TAG_(WA_Width ) , 400, TAG_(WA_MinWidth) , 50, TAG_(WA_InnerHeight) , 140, TAG_(WA_MinHeight) , 50, TAG_(WA_DragBar) , TAG_(TRUE), TAG_(WA_DepthGadget) , TAG_(TRUE), TAG_(WA_Activate) , TAG_(TRUE), TAG_(WA_CloseGadget) , TAG_(TRUE), TAG_(WA_SizeGadget) , TAG_(TRUE), TAG_(WA_SimpleRefresh), TAG_(TRUE), TAG_(WA_IDCMP) , IDCMP_CLOSEWINDOW or IDCMP_REFRESHWINDOW or IDCMP_VANILLAKEY or SLIDERIDCMP or STRINGIDCMP or BUTTONIDCMP, TAG_(WA_PubScreen) , TAG_(mysc), TAG_END ]))) then errorMessage('OpenWindow() failed') else begin {* After window is open, gadgets must be refreshed with a ** call to the GadTools refresh window function. *} GT_RefreshWindow(mywin, nil); process_window_events(mywin, @slider_level, my_gads); CloseWindow(mywin); end; end; {* FreeGadgets() even if createAllGadgets() fails, as some ** of the gadgets may have been created...If glist is NULL ** then FreeGadgets() will do nothing. *} FreeGadgets(glist); FreeVisualInfo(vi); end; UnlockPubScreen(nil, mysc); end; CloseFont(font); end; end; {* ** Open all libraries and run. Clean up when finished or on error.. *} procedure main; begin {$IF DEFINED(MORPHOS)} if (nil = SetAndGet(IntuitionBase, OpenLibrary('intuition.library', 37))) then errorMessage('Requires V37 intuition.library') else {$ENDIF} begin {$IF DEFINED(AMIGA) or DEFINED(MORPHOS)} if (nil = SetAndGet(GfxBase, OpenLibrary('graphics.library', 37))) then errorMessage('Requires V37 graphics.library') else {$ENDIF} begin {$IF DEFINED(MORPHOS) or DEFINED(AMIGA)} if (nil = SetAndGet(GadtoolsBase, OpenLibrary('gadtools.library', 37))) then errorMessage('Requires V37 gadtools.library') else {$ENDIF} begin gadtoolsWindow; {$IF DEFINED(MORPHOS) or DEFINED(AMIGA)} CloseLibrary(GadToolsBase); {$ENDIF} end; {$IF DEFINED(MORPHOS) or DEFINED(AMIGA)} CloseLibrary(GfxBase); {$ENDIF} end; {$IF DEFINED(MORPHOS)} CloseLibrary(PLibrary(IntuitionBase)); {$ENDIF} end; end; begin Main; end.
unit WelTests; interface uses TestFrameWork, Wel; type TTestWelBasic = class(TTestCase) fC: TWel; private procedure TestDivideByZero; procedure TestExistsNoParams; procedure TestExistsMoreParams; public procedure SetUp; override; procedure TearDown; override; published // operators procedure TestPlus; procedure TestMinus; procedure TestMultiply; procedure TestDivide; procedure TestConcat; procedure TestPower; procedure TestCompare; procedure TestMath; procedure TestArrayCreate; procedure TestArrayGet; procedure TestAggregate; procedure TestAlign; procedure TestIn; procedure TestExists; end; TTestWelComplex = class(TTestCase) fC: TWel; public procedure SetUp; override; procedure TearDown; override; published procedure TestBrackets; procedure TestOperatorPriority; end; implementation uses SysUtils; procedure TTestWelBasic.SetUp; begin inherited; // end; procedure TTestWelBasic.TearDown; begin inherited; // end; procedure TTestWelBasic.TestPlus; begin // plus operator can be used with numbers, strings and arrays fC := TWel.Create; // num + num CheckEquals('3', fC.Calc('1+2'), 'fails on 1+2'); CheckEquals('124', fC.Calc('99 + 25 '), 'fails on 99 + 25'); CheckEquals('45.25', fC.Calc(' 1.25 + 44'), 'fails on 99 + 25'); CheckEquals('-1.8585', fC.Calc('3.1415+-5'), 'fails on 3.1415+-5'); CheckEquals('-2', fC.Calc('plus(3., -5)'), 'fails on plus(3.1415, -5)'); // num and str CheckEquals('"12.345hello"', fC.Calc('12.345+"hello"'), 'fails on 12.345+"hello"'); CheckEquals('"world123"', fC.Calc('"world" + 123'), 'fails on "world" + 123'); // str + str CheckEquals('"Hello World"', fC.Calc('"Hello " + "World"'), 'fails on "Hello " + "World"'); // num + array CheckEquals('[124,125,126]', fC.Calc('123+[1,2,3]'), 'fails on 123+[1,2,3]'); CheckEquals('[3.65,3.968,4.95428,5.377]', fC.Calc('2.236 + [1.414 1.7320 2.71828, 3.141]'), 'fails on 2.236 + [1.414 1.7320 2.71828, 3.141]'); // array + str CheckEquals('["6 kV","10 kV","35 kV","110 kV","220 kV"]', fC.Calc('[6 10 35 110 220] + " kV"'), 'fails on [6 10 35 110 220] + " kV"'); // str + array CheckEquals('["Age is 18","Age is 6"]', fC.Calc('"Age is " + [18,6]'), 'fails on "Age is " + [18,6]'); // array with subarray + num CheckEquals('[2,3,[3,4]]', fC.Calc('[1,2,[2,3]]+1'), 'fails on [1,2,[2,3]]+1'); // array + array // TODO: only if length of arrays equal summ by elements FreeAndNil(fC); end; procedure TTestWelBasic.TestMinus; begin // minus operator can be used with numbers or arrays fC := TWel.Create; // num - num CheckEquals('-1', fC.Calc('1-2'), 'fails on 1-2'); CheckEquals('-1', fC.Calc('99-100'), 'fails on 99-100'); CheckEquals('3', fC.Calc('1--2'), 'fails on 1--2'); // num - array CheckEquals('[0,-2,-3,-4]', fC.Calc('1-[1 3, 4 5]'), 'fails on 1-[1 3, 4 5]'); // array - num CheckEquals('[0.4,1.2,-10.1]', fC.Calc('[5.5, 6.3, -5]-5.1'), 'fails on [5.5, 6.3, -5]-5.1'); FreeAndNil(fC); end; procedure TTestWelBasic.TestMultiply; begin // multiply operator can be used with numbers or arrays fC := TWel.Create; // WARNING: floating point arithmetic may differ // on different processors and compilers! // num * num CheckEquals('2.44948974278322', fC.Calc('1.4142135623731 * 1.7320508075689'), 'fails on 1.4142135623731 * 1.7320508075689'); CheckEquals('192.301846064983', fC.Calc('86 * 2.2360679774998'), 'fails on 86 * 2.2360679774998'); // array * num (or num * array) CheckEquals('[2,3]', fC.Calc('1*[2,3]'), 'fails on 1*[2,3]'); CheckEquals('[24,30]', fC.Calc('[4,5]*6'), 'fails on [4,5]*6'); FreeAndNil(fC); end; procedure TTestWelBasic.TestDivideByZero; begin fC.Calc('1/0'); end; procedure TTestWelBasic.TestDivide; begin // devide (/) is a floating point operator, // (\) is a integer devide and (%) is a remainder operators fC := TWel.Create; // num / num CheckEquals('2', fC.Calc('10/5'), 'fails on 10/5'); CheckEquals('0.5', fC.Calc('5 /10'), 'fails on 5 /10'); CheckEquals('-10', fC.Calc('-30/ 3'), 'fails on -30/ 3'); CheckEquals('-3', fC.Calc('15/-5'), 'fails on 15/-5'); // num \ num CheckEquals('3', fC.Calc('10\3'), 'fails on 10\3'); CheckEquals('0', fC.Calc('5 \10'), 'fails on 5 \10'); CheckEquals('0', fC.Calc('0\ 9.532'), 'fails on 0\ 9.532'); CheckEquals('2', fC.Calc('0.3\0.1'), 'fails on 0.3\0.1'); // FP bug! it's normall // num % num CheckEquals('1', fC.Calc('10%3'), 'fails on 10%3'); CheckEquals('5', fC.Calc('5%10'), 'fails on 5%10'); CheckEquals('0', fC.Calc('0%9.532'), 'fails on 0%9.532'); CheckEquals('0.1', fC.Calc('0.3%0.1'), 'fails on 0.3%0.1'); // FP bug! it's normall // div by zero CheckException(TestDivideByZero, EWelException, 'falis on divide by zero, it must raise exceprion'); // nums and arrays CheckEquals('[3,22,0.2]', fC.Calc('[9,66,0.6]/3'), '[9,66,0.6]/3'); CheckEquals('[44,6,660]', fC.Calc('132/[3,22,0.2]'), '132/[3,22,0.2]'); CheckEquals('[3,22,0]', fC.Calc('[9,66,0.6]\3'), '[9,66,0.6]\3'); CheckEquals('[51,7,769]', fC.Calc('154\[3,22,0.2]'), '154\[3,22,0.2]'); CheckEquals('[9,6,0.6]', fC.Calc('[9,66,0.6]%10'), '[9,66,0.6]%10'); CheckEquals('[0,0,0]', fC.Calc('132%[3,22,2]'), '132%[3,22,2]'); FreeAndNil(fC); end; procedure TTestWelBasic.TestConcat; begin // string concatenation (&) operator, it can be used with // strings ot numbers or arrays, like a (+) fC := TWel.Create; // str & str CheckEquals('"Hello World!"', fC.Calc('"Hello " & "World" & "!"'), 'fails on "Hello " & "World" & "!"'); // str & num CheckEquals('"My age is 18"', fC.Calc('"My age is " & 12+6'), 'fails on "My age is " & 12+6'); CheckEquals('"5 tests completed"', fC.Calc('5 + " tests completed"'), 'fails on 5 + " tests completed"'); // num & num CheckEquals('"37"', fC.Calc('1 + 2 & 3 + 4'), 'fails on 1 + 2 & 3 + 4'); FreeAndNil(fC); end; procedure TTestWelBasic.TestPower; begin // power fC := TWel.Create; CheckEquals('8', fC.Calc('2^3'), 'fails on 2^3'); CheckEquals('3.16227766016838', fC.Calc('10^0.5'), 'fails on 10^0.5'); CheckEquals('1', fC.Calc('0^0'), 'fails on 0^0'); CheckEquals('1', fC.Calc('125.15^0'), 'fails on 125.15^0'); //CheckEquals('256', fC.Calc('2^2^3'), 'fails on 2^2^4'); // FreeAndNil(fC); end; procedure TTestWelBasic.TestCompare; begin fC := TWel.Create; CheckEquals('1', fC.Calc('2*2 = 4'), 'fails on 2*2 = 4'); // = eq CheckEquals('0', fC.Calc('"answer" = 42'), 'fails on "answer" = 42'); // <> ne CheckEquals('1', fC.Calc('4.99 <> 25/5'), 'fails on 4.99 <> 25/5'); // < lt CheckEquals('1', fC.Calc('"first" <> "second"'), 'fails on "first" <> "second"'); // > gt CheckEquals('0', fC.Calc('1 < -1'), 'fails on 1 < -1'); // <= le CheckEquals('1', fC.Calc('99 < 99.1'), 'fails on 99 < 99.1'); // >= ge CheckEquals('1', fC.Calc('"0" < "1"'), 'fails on "0" < "1"'); CheckEquals('0', fC.Calc('75>122'), 'fails on 75>122'); CheckEquals('1', fC.Calc('11>=11'), 'fails on 11>=11'); CheckEquals('0', fC.Calc('11>=88'), 'fails on 11>=88'); CheckEquals('0', fC.Calc('"0123" <= "012"'), 'fails on "0123" <= "012"'); FreeAndNil(fC); end; procedure TTestWelBasic.TestMath; begin // test Math functions with number arguments only. this is a light weight tests fC := TWel.Create; CheckEquals('0.564642473395035', fC.Calc('sin(0.6)'), 'fails on sin(0.6)'); CheckEquals('0.955336489125606', fC.Calc('cos(0.3)'), 'fails on cos(0.3)'); CheckEquals('1.73205080756888', fC.Calc('a:=sqrt(3)'), 'fails on a:=sqrt(3)'); CheckEquals('2', fC.Calc('round(a)'), 'fails on round(a)'); CheckEquals('1.73205', fC.Calc('round(a,5)'), 'fails on round(a,5)'); CheckEquals('0.73205080756888', fC.Calc('frac(a)'), 'fails on frac(a)'); CheckEquals('1', fC.Calc('trunc(a)'), 'fails on trunc(a)'); CheckEquals('8.6602540378444', fC.Calc('abs(-5*a)'), 'fails on abs(-5*a)'); FreeAndNil(fC); end; procedure TTestWelBasic.TestArrayCreate; begin fC := TWel.Create; CheckEquals('[1,2,4,6]',fC.Calc('A:=[1 2 4 6]'),'fails on "A:=[1 2 4 6]"'); CheckEquals('[1,2,4,6]',fC.Calc('A:=[1,2,4,6]'),'fails on "A:=[1,2,4,6]"'); CheckEquals('[1,2,4,6]',fC.Calc('A:=[1, 2, 4, 6]'),'fails on "A:=[1, 2, 4, 6]"'); CheckEquals('[1,2,4,6]',fC.Calc('A:=[1 2,4 6]'),'fails on "A:=[1 2,4 6]"'); CheckEquals('[1,2,4,6]',fC.Calc('A:=[1, 2, 4, 6, ]'),'fails on "A:=[1 2 4 6, ]"'); CheckEquals('[1,[1,2,3],4,6]',fC.Calc('A:=[1, [1 2 3], 4, 6, ]'),'fails on "A:=[1 2 4 6, ]"'); CheckEquals('[1,[1,2,3],4,"cat"]',fC.Calc('A:=[1 [1 2,3,], 4"cat"]'),'fails on "A:=[1 [1 2,3,], 4"cat"]"'); FreeAndNil(fC); end; procedure TTestWelBasic.TestArrayGet; begin fC := TWel.Create; CheckEquals('[1,2,[4,6,7,[8,9]],10]',fC.Calc('A:=[1,2,[4,6,7,[8,9]],10]'),'fails on A:=[1,2,[4,6,7,[8,9]],10]'); CheckEquals('1',fC.Calc('A[0]'),'fails on A[0]'); CheckEquals('2',fC.Calc('A[1]'),'fails on A[1]'); CheckEquals('[4,6,7,[8,9]]',fC.Calc('A[2]'),'fails on A[2]'); CheckEquals('10',fC.Calc('A[3]'),'fails on A[3]'); CheckEquals('nil',fC.Calc('A[4]'),'fails on A[4]'); CheckEquals('4',fC.Calc('A[2,0]'),'fails on A[2,0]'); CheckEquals('6',fC.Calc('A[2,1]'),'fails on A[2,1]'); CheckEquals('7',fC.Calc('A[2,2]'),'fails on A[2,2]'); CheckEquals('[8,9]',fC.Calc('A[2,3]'),'fails on A[2,3]'); CheckEquals('nil',fC.Calc('A[2,4]'),'fails on A[2,4]'); CheckEquals('8',fC.Calc('A[2,3,0]'),'fails on A[2,3,0]'); CheckEquals('9',fC.Calc('A[2,3,1]'),'fails on A[2,3,1]'); CheckEquals('nil',fC.Calc('A[2,3,2]'),'fails on A[2,3,2]'); FreeAndNil(fC); end; procedure TTestWelBasic.TestAggregate; begin // aggregate functions: min, max, sum and avg, this functions accept variable count // of argumens - number or array with number elements fC := TWel.Create; CheckEquals('1', fC.Calc('min(1,2,3)'), 'fails on min(1,2,3)'); CheckEquals('0.1', fC.Calc('min(0.3,0.2,0.1)'), 'fails on min(0.3,0.2,0.1)'); CheckEquals('3', fC.Calc('max(1,[2,3],0)'), 'fails on max(1,[2,3],0)'); CheckEquals('6', fC.Calc('max(1,[2,[3,4,5],6]'), 'fails on max(1,[2,[3,4,5],6],0)'); CheckEquals('6', fC.Calc('sum(2,2,[2])'), 'fails on sum(2,2,[2])'); CheckEquals('2', fC.Calc('avg(2,2,[])'), 'fails on avg(2,2,[])'); FreeAndNil(fC); end; procedure TTestWelBasic.TestAlign; begin // align is a function to round number value to a nearest of array elemets fC := TWel.Create; CheckEquals('0', fC.Calc('align(0.1, [0,0.5,1])'), 'fails on align(0.1, [0,0.5,1])'); CheckEquals('0', fC.Calc('align(0.5, [0,1])'), 'fails on align(0.5, [0,1])'); CheckEquals('1', fC.Calc('align(0.51, [0,1])'), 'fails on align(0.51, [0,1])'); CheckEquals('99.9', fC.Calc('align(99, [98,99.9])'), 'fails on align(99, [98,99.9])'); CheckEquals('0', fC.Calc('align(-1, [5,9,-0,3])'), 'fails on align(-1, [5,9,-0,3])'); CheckEquals('-10', fC.Calc('align(-9, [10,-10,+5,1-9])'), 'fails on align(-9, [10,-10,+5,1-9])'); FreeAndNil(fC); end; procedure TTestWelBasic.TestIn; begin // in( functions check presence first argument value at second argument array fC := TWel.Create; CheckEquals('0', fC.Calc('in(99,[1,2,3])'), 'fails on in(99,[1,2,3])'); CheckEquals('1', fC.Calc('in(99,[1,2,3,99])'), 'fails on in(99,[1,2,3,99])'); CheckEquals('1', fC.Calc('in(0.1,[0.1,0.2,0.3])'), 'fails on in(0.1,[0.1,0.2,0.3])'); CheckEquals('1', fC.Calc('in("world",["hello", "world"])'), 'fails on in("world",["hello", "world"])'); CheckEquals('0', fC.Calc('in(42,[1,2,3,[5,42]])'), 'fails on in(42,[1,2,3,[5,42]])'); CheckEquals('0', fC.Calc('in(0.07,[])'), 'fails on in(0.07,[])'); FreeAndNil(fC); end; { TTestWelComplex } procedure TTestWelComplex.SetUp; begin inherited; // end; procedure TTestWelComplex.TearDown; begin inherited; // end; procedure TTestWelComplex.TestBrackets; begin fC := TWel.Create; CheckEquals('1.125',fC.Calc('1+2*3/4^2+5-6*7/8'),'fails on 1+2*3/4^2+5-6*7/8'); CheckEquals('0.3125',fC.Calc('(1+2)*3/4^2+5-6*7/8'),'fails on (1+2)*3/4^2+5-6*7/8'); CheckEquals('1.125',fC.Calc('1+(2*3/4^2+5)-6*7/8'),'fails on 1+(2*3/4^2+5)-6*7/8'); CheckEquals('2.3125',fC.Calc('1+2*3/4^(2+5-6)*7/8'),'fails on 1+2*3/4^(2+5-6)*7/8'); CheckEquals('1.125',fC.Calc('1+2*3/4^2+5-(6*7/8)'),'fails on 1+2*3/4^2+5-(6*7/8)'); CheckEquals('1.875',fC.Calc('(1+2*(3/4)^2+5)-6*7/8'),'fails on (1+2*(3/4)^2+5)-6*7/8'); CheckEquals('1.39669421487603',fC.Calc('1+2*3/(4^2+((5-6)*7)/8)'),'fails on 1+2*3/(4^2+((5-6)*7)/8)'); CheckEquals('2.80338347992535',fC.Calc('(1+(2*3)/4)^(2+(5-6)*7/8)'),'fails on (1+(2*3)/4)^(2+(5-6)*7/8)'); FreeAndNil(fC); end; procedure TTestWelComplex.TestOperatorPriority; begin // we use classic operators priority // calc from left to right // operator calculation order: // ^ power, we calc it from left to right, then 4^3^2 = (4^3)^2 = 4096, // some math calculation systems and programming languages have differents order of // power calculation. we do it also as in Matlab // * / \ % division operators // + - ariphmetic operators // & string concatenation // <>= comparison operations fC := TWel.Create; CheckEquals('"2.55"',fC.Calc('1+2*3/4&"5"'),'fails on 1+2*3/4&"5"'); CheckEquals('4096',fC.Calc('4^3^2'),'fails on 4^3^2'); FreeAndNil(fC); end; procedure TTestWelBasic.TestExists; begin // exists( is a spec function, if it exists in calculation tree unexpected variables // do not rise 'Unknown variable' exception fC := TWel.Create; CheckException(TestExistsNoParams, EWelException, 'falis on eists( without params, it must raise exceprion'); CheckException(TestExistsMoreParams, EWelException, 'falis on eists( with more params, it must raise exceprion'); CheckEquals('1',fC.Calc('exists(1)'),'fails on exists(1)'); CheckEquals('1',fC.Calc('exists(3.14)'),'fails on exists(3.14)'); CheckEquals('1',fC.Calc('exists("test")'),'fails on exists("test")'); CheckEquals('1',fC.Calc('exists([])'),'fails on exists([])'); fC.Calc('a:=1'); CheckEquals('1',fC.Calc('exists(a)'),'fails on exists(a)'); CheckEquals('0',fC.Calc('exists(b)'),'fails on exists(b)'); CheckEquals('0',fC.Calc('b:=exists(b)'),'fails on b:=exists(b)'); CheckEquals('1',fC.Calc('if(exists(a),a,"err")'),'fails on if(exists(a),a,"err")'); CheckEquals('"err"',fC.Calc('if(exists(c),c,"err")'),'fails on if(exists(c),c,"err")'); FreeAndNil(fC); end; procedure TTestWelBasic.TestExistsNoParams; begin fC.Calc('exists()') end; procedure TTestWelBasic.TestExistsMoreParams; begin fC.Calc('exists(1,2)') end; initialization TestFramework.RegisterTest(TTestWelBasic.Suite); TestFramework.RegisterTest(TTestWelComplex.Suite); end.
unit ServerMethodsUnit; interface uses System.SysUtils, System.Classes, Datasnap.DSServer, Datasnap.DSAuth, System.SyncObjs; type {$METHODINFO ON} TServerMethods = class(TComponent) private // class vars - área de memória compartilhada entre as threads class var FCriticalSection: TCriticalSection; class var FContagemGeral: Int64; public class constructor Create; class destructor Destroy; { Public declarations } function EchoString(Value: string): string; function ReverseString(Value: string): string; function GetThreadID: Int64; function GetContagemGeral: Int64; end; {$METHODINFO OFF} implementation uses System.StrUtils; class constructor TServerMethods.Create; begin FCriticalSection := TCriticalSection.Create; end; class destructor TServerMethods.Destroy; begin FCriticalSection.Free; end; function TServerMethods.EchoString(Value: string): string; begin Result := Value; end; function TServerMethods.GetContagemGeral: Int64; begin // região crítica garante a correta atualização da variável compartilhada // (remove o paralelismo) FCriticalSection.Enter; try Inc(FContagemGeral); Result := FContagemGeral; finally FCriticalSection.Leave; end; end; function TServerMethods.GetThreadID: Int64; begin // o sleep força uma parada na thread para que uma segunda chamada, // durante o sleep, gere a criação de uma nova thread Sleep(5000); Result := TThread.CurrentThread.ThreadID; end; function TServerMethods.ReverseString(Value: string): string; begin Result := System.StrUtils.ReverseString(Value); end; end.
(* Unit : PaintShader Author : Kordal <A.V.Krivoshein> E-mail : av@unimods.club Homepage : http://unimods.club Version : 0.01 Description: PaintShader.pas is part of the JPaintShader graphics component that works with the JCanvas and JDrawingView components to expand their capabilities. The component includes a set of functions that work with java classes: BitmapShader, ComposeShader, LinearGradient, RadialGradient, SweepGradient. History : 08.11.2019 - First public release. *) unit paintshader; {$mode delphi} interface uses Classes, SysUtils, And_jni, AndroidWidget; type TTileMode = (tmCLAMP, tmMIRROR, tmREPEAT); // https://developer.android.com/reference/android/graphics/PorterDuff.Mode.html TPorterDuff = (pdADD, pdDARKEN, pdDST, pdDST_ATOP, pdDST_IN, pdDST_OUT, pdDST_OVER, pdLIGHTEN, pdMULTIPLY, pdOVERLAY, pdSCREEN, pdSRC, pdSRC_ATOP, pdSRC_IN, pdSRC_OUT, pdSRC_OVER, pdXOR); TGradientColors = array of TAlphaColor; TGradientPositions = array of Single; JPaintShader = class(JControl) private FShaderCount: Integer; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Init(Paint: JObject); reintroduce; procedure Bind(const ID: Integer); procedure Clear(); procedure Combine(shdrA, shdrB: Integer; Mode: TPorterDuff; dstID: Integer); procedure Disable(); function GetColor(): Integer; procedure SetCount(Value: Integer); procedure SetIndex(Value: Integer); procedure SetPaint(Value: JObject); procedure SetIdentity(ID: Integer); procedure SetZeroCoords(ID: Integer); procedure SetMatrix(X, Y, scaleX, scaleY, Rotate: Single; ID: Integer); procedure SetRotate(Degree: Single; ID: Integer); overload; procedure SetRotate(Degree, PointX, PointY: Single; ID: Integer); overload; procedure SetScale(X, Y: Single; ID: Integer); procedure SetTranslate(X, Y: Single; ID: Integer); function NewBitmapShader(Bitmap: JOBject; tileX, tileY: TTileMode; ID: Integer=-1): Integer; overload; function NewBitmapShader(Bitmap: JOBject; tileX, tileY: TTileMode; scaleX, scaleY, Rotate: Single; ID: Integer=-1): Integer; overload; function NewLinearGradient(X0, Y0, X1, Y1: Single; Color0, Color1: TAlphaColor; tMode: TTileMode; ID: Integer=-1): Integer; overload; function NewLinearGradient(X0, Y0, X1, Y1: Single; Colors: TGradientColors; Positions: TGradientPositions; tMode: TTileMode; ID: Integer=-1): Integer; overload; function NewLinearGradient(X, Y, Wh, Ht, Rotate: Single; Color0, Color1: TAlphaColor; tMode: TTileMode; ID: Integer=-1): Integer; overload; function NewLinearGradient(X, Y, Wh, Ht, Rotate: Single; Colors: TGradientColors; Positions: TGradientPositions; tMode: TTileMode; ID: Integer=-1): Integer; overload; function NewRadialGradient(cX, cY, Radius: Single; cColor, eColor: TAlphaColor; tMode: TTileMode; ID: Integer=-1): Integer; overload; function NewRadialGradient(cX, cY, Radius: Single; Colors: TGradientColors; Stops: TGradientPositions; tMode: TTileMode; ID: Integer=-1): Integer; overload; function NewSweepGradient(cX, cY: Single; Color0, Color1: TAlphaColor; ID: Integer=-1): Integer; overload; function NewSweepGradient(cX, cY: Single; Colors: TGradientColors; Positions: TGradientPositions; ID: Integer=-1): Integer; overload; published property ShaderCount: Integer read FShaderCount write SetCount; end; function jPaintShader_jCreate (env: PJNIEnv;_Self: int64; _Paint, this: jObject): jObject; procedure jPaintShader_SetPaint(env: PJNIEnv; _jpaintshader, _Paint: JObject); procedure jPaintShader_Combine (env: PJNIEnv; _jpaintshader: JObject; _shdrA, _shdrB: Integer; _Mode: JByte; _dstID: Integer); // gradients, bitmap shaders function jPaintShader_NewBitmapShader (env: PJNIEnv; _jpaintshader: JObject; _Bitmap: JOBject; _tileX, _tileY: JByte; _ID: Integer): Integer; overload; function jPaintShader_NewBitmapShader (env: PJNIEnv; _jpaintshader: JObject; _Bitmap: JOBject; _tileX, _tileY: JByte; _scaleX, _scaleY, _Rotate: Single; _ID: Integer): Integer; overload; function jPaintShader_NewLinearGradient(env: PJNIEnv; _jpaintshader: JObject; _X0, _Y0, _X1, _Y1: Single; _Color0, _Color1: Integer; _tMode: JByte; _ID: Integer): Integer; overload; function jPaintShader_NewLinearGradient(env: PJNIEnv; _jpaintshader: JObject; _X0, _Y0, _X1, _Y1: Single; _Colors: TGradientColors; _Positions: TGradientPositions; _tMode: JByte; _ID: Integer): Integer; overload; function jPaintShader_NewLinearGradient(env: PJNIEnv; _jpaintshader: JObject; _X, _Y, _Wh, _Ht, _Rotate: Single; _Color0, _Color1: Integer; _tMode: JByte; _ID: Integer): Integer; overload; function jPaintShader_NewLinearGradient(env: PJNIEnv; _jpaintshader: JObject; _X, _Y, _Wh, _Ht, _Rotate: Single; _Colors: TGradientColors; _Positions: TGradientPositions; _tMode: JByte; _ID: Integer): Integer; overload; function jPaintShader_NewRadialGradient(env: PJNIEnv; _jpaintshader: JObject; _cX, _cY, _Radius: Single; _cColor, _eColor: Integer; _tMode: JByte; _ID: Integer): Integer; overload; function jPaintShader_NewRadialGradient(env: PJNIEnv; _jpaintshader: JObject; _cX, _cY, _Radius: Single; _Colors: TGradientColors; _Stops: TGradientPositions; _tMode: JByte; _ID: Integer): Integer; overload; function jPaintShader_NewSweepGradient (env: PJNIEnv; _jpaintshader: JObject; _cX, _cY: Single; _Color0, _Color1, _ID: Integer): Integer; overload; function jPaintShader_NewSweepGradient (env: PJNIEnv; _jpaintshader: JObject; _cX, _cY: Single; _Colors: TGradientColors; _Positions: TGradientPositions; _ID: Integer): Integer; overload; // transformation procedure jPaintShader_SetMatrix (env: PJNIEnv; _jpaintshader: JObject; _X, _Y, _scaleX, _scaleY, _Rotate: Single; _ID: Integer); procedure jPaintShader_SetRotate (env: PJNIEnv; _jpaintshader: JObject; _Degree: Single; _ID: Integer); overload; procedure jPaintShader_SetRotate (env: PJNIEnv; _jpaintshader: JObject; _Degree, _PointX, _PointY: Single; _ID: Integer); overload; procedure jPaintShader_SetScale (env: PJNIEnv; _jpaintshader: JObject; _X, _Y: Single; _ID: Integer); procedure jPaintShader_SetTranslate (env: PJNIEnv; _jpaintshader: JObject; _X, _Y: Single; _ID: Integer); const PorterDuff: record ADD, DARKEN, DST, DST_ATOP, DST_IN, DST_OUT, DST_OVER, LIGHTEN, MULTIPLY, OVERLAY, SCREEN, SRC, SRC_ATOP, SRC_IN, SRC_OUT, SRC_OVER, mXOR: TPorterDuff; end = ( ADD: pdADD; DARKEN: pdDARKEN; DST: pdDST; DST_ATOP: pdDST_ATOP; DST_IN: pdDST_IN; DST_OUT: pdDST_OUT; DST_OVER: pdDST_OVER; LIGHTEN: pdLIGHTEN; MULTIPLY: pdMULTIPLY; OVERLAY: pdOVERLAY; SCREEN: pdSCREEN; SRC: pdSRC; SRC_ATOP: pdSRC_ATOP; SRC_IN: pdSRC_IN; SRC_OUT: pdSRC_OUT; SRC_OVER: pdSRC_OVER; mXOR: pdXOR; ); implementation // ------------- jPaintShader -------------- // ------------------------------------------- constructor JPaintShader.Create(AOwner: TComponent); begin inherited Create(AOwner); FShaderCount := 6; end; destructor JPaintShader.Destroy; begin if not (csDesigning in ComponentState) then begin if FjObject <> nil then begin jni_free(gApp.jni.jEnv, FjObject); FjObject:= nil; end; end; // you others free code here...' inherited Destroy; end; procedure JPaintShader.Init(Paint: JObject); begin if FInitialized then Exit; inherited Init; //set default ViewParent/FjPRLayout as jForm.View! FjObject := jPaintShader_jCreate(gApp.jni.jEnv, Int64(Self), Paint, gApp.jni.jThis); //jSelf ! FInitialized := True; end; procedure JPaintShader.SetPaint(Value: JObject); begin if FInitialized then jPaintShader_SetPaint(gApp.jni.jEnv, FjObject, Value); end; procedure JPaintShader.SetCount(Value: Integer); begin if FInitialized then begin FShaderCount := Value; jni_proc_i(gApp.jni.jEnv, FjObject, 'SetCount', Value); end; end; procedure JPaintShader.SetIndex(Value: Integer); begin if FInitialized then jni_proc_i(gApp.jni.jEnv, FjObject, 'SetIndex', Value); end; function JPaintShader.GetColor(): Integer; begin if FInitialized then Result := jni_func_out_i(gApp.jni.jEnv, FjObject, 'GetColor'); end; procedure JPaintShader.Clear(); begin if FInitialized then // end; procedure JPaintShader.Combine(shdrA, shdrB: Integer; Mode: TPorterDuff; dstID: Integer); begin if FInitialized then jPaintShader_Combine(gApp.jni.jEnv, FjObject, shdrA, shdrB, Byte(Mode), dstID); end; procedure JPaintShader.Bind(const ID: Integer); begin if FInitialized then jni_proc_i(gApp.jni.jEnv, FjObject, 'Bind', ID); end; procedure jPaintShader.Disable(); begin Bind(-1); end; procedure JPaintShader.SetIdentity(ID: Integer); begin if FInitialized then jni_proc_i(gApp.jni.jEnv, FjObject, 'SetIdentity', ID); end; procedure JPaintShader.SetZeroCoords(ID: Integer); begin if FInitialized then jni_proc_i(gApp.jni.jEnv, FjObject, 'SetZeroCoords', ID); end; procedure JPaintShader.SetMatrix(X, Y, scaleX, scaleY, Rotate: Single; ID: Integer); begin if FInitialized then jPaintShader_SetMatrix(gApp.jni.jEnv, FjObject, X, Y, scaleX, scaleY, Rotate, ID); end; procedure JPaintShader.SetRotate(Degree: Single; ID: Integer); begin if FInitialized then jPaintShader_SetRotate(gApp.jni.jEnv, FjObject, Degree, ID); end; procedure JPaintShader.SetRotate(Degree, PointX, PointY: Single; ID: Integer); begin if FInitialized then jPaintShader_SetRotate(gApp.jni.jEnv, FjObject, Degree, PointX, PointY, ID); end; procedure JPaintShader.SetScale(X, Y: Single; ID: Integer); begin if FInitialized then jPaintShader_SetScale(gApp.jni.jEnv, FjObject, X, Y, ID); end; procedure JPaintShader.SetTranslate(X, Y: Single; ID: Integer); begin if FInitialized then jPaintShader_SetTranslate(gApp.jni.jEnv, FjObject, X, Y, ID); end; function JPaintShader.NewBitmapShader(Bitmap: JOBject; tileX, tileY: TTileMode; ID: Integer): Integer; begin if FInitialized then Result := jPaintShader_NewBitmapShader(gApp.jni.jEnv, FjObject, Bitmap, Byte(tileX), Byte(tileY), ID); end; function JPaintShader.NewBitmapShader(Bitmap: JOBject; tileX, tileY: TTileMode; scaleX, scaleY, Rotate: Single; ID: Integer): Integer; begin if FInitialized then Result := jPaintShader_NewBitmapShader(gApp.jni.jEnv, FjObject, Bitmap, Byte(tileX), Byte(tileY), scaleX, scaleY, Rotate, ID); end; function JPaintShader.NewLinearGradient(X0, Y0, X1, Y1: Single; Color0, Color1: TAlphaColor; tMode: TTileMode; ID: Integer): Integer; begin if FInitialized then Result := jPaintShader_NewLinearGradient(gApp.jni.jEnv, FjObject, X0, Y0, X1, Y1, Color0, Color1, Byte(tMode), ID); end; function JPaintShader.NewLinearGradient(X0, Y0, X1, Y1: Single; Colors: TGradientColors; Positions: TGradientPositions; tMode: TTileMode; ID: Integer=-1): Integer; begin if FInitialized then Result := jPaintShader_NewLinearGradient(gApp.jni.jEnv, FjObject, X0, Y0, X1, Y1, Colors, Positions, Byte(tMode), ID); end; function JPaintShader.NewLinearGradient(X, Y, Wh, Ht, Rotate: Single; Color0, Color1: TAlphaColor; tMode: TTileMode; ID: Integer): Integer; begin if FInitialized then Result := jPaintShader_NewLinearGradient(gApp.jni.jEnv, FjObject, X, Y, Wh, Ht, Rotate, Color0, Color1, Byte(tMode), ID); end; function JPaintShader.NewLinearGradient(X, Y, Wh, Ht, Rotate: Single; Colors: TGradientColors; Positions: TGradientPositions; tMode: TTileMode; ID: Integer): Integer; begin if FInitialized then Result := jPaintShader_NewLinearGradient(gApp.jni.jEnv, FjObject, X, Y, Wh, Ht, Rotate, Colors, Positions, Byte(tMode), ID); end; function JPaintShader.NewRadialGradient(cX, cY, Radius: Single; cColor, eColor: TAlphaColor; tMode: TTileMode; ID: Integer): Integer; begin if FInitialized then Result := jPaintShader_NewRadialGradient(gApp.jni.jEnv, FjObject, cX, cY, Radius, cColor, eColor, Byte(tMode), ID); end; function JPaintShader.NewRadialGradient(cX, cY, Radius: Single; Colors: TGradientColors; Stops: TGradientPositions; tMode: TTileMode; ID: Integer): Integer; begin if FInitialized then Result := jPaintShader_NewRadialGradient(gApp.jni.jEnv, FjObject, cX, cY, Radius, Colors, Stops, Byte(tMode), ID); end; function JPaintShader.NewSweepGradient(cX, cY: Single; Color0, Color1: TAlphaColor; ID: Integer): Integer; begin if FInitialized then Result := jPaintShader_NewSweepGradient(gApp.jni.jEnv, FjObject, cX, cY, Color0, Color1, ID); end; function JPaintShader.NewSweepGradient(cX, cY: Single; Colors: TGradientColors; Positions: TGradientPositions; ID: Integer): Integer; begin if FInitialized then Result := jPaintShader_NewSweepGradient(gApp.jni.jEnv, FjObject, cX, cY, Colors, Positions, ID); end; // -------- jPaintShader_JNI_Bridge ---------- // ------------------------------------------- function jPaintShader_jCreate(env: PJNIEnv; _Self: Int64; _Paint, this: JObject): jObject; var jParams: array[0..1] of JValue; jMethod: JMethodID = nil; jCls : JClass = nil; label _exceptionOcurred; begin result := nil; if (env = nil) or (this = nil) then exit; jCls := Get_gjClass(env); if jCls = nil then goto _exceptionOcurred; jMethod := env^.GetMethodID(env, jCls, 'jPaintShader_jCreate', '(JLjava/lang/Object;)Ljava/lang/Object;'); if jMethod = nil then goto _exceptionOcurred; jParams[0].j := _Self; jParams[1].l := _Paint; Result := env^.CallObjectMethodA(env, this, jMethod, @jParams); Result := env^.NewGlobalRef(env, Result); _exceptionOcurred: if jni_ExceptionOccurred(env) then result := nil; end; procedure jPaintShader_SetPaint(env: PJNIEnv; _jpaintshader, _Paint: JObject); var jParams: array[0..0] of JValue; jMethod: JMethodID = nil; jCls : JClass = nil; label _exceptionOcurred; begin if (env = nil) or (_jpaintshader = nil) or (_Paint = nil) then exit; jCls := env^.GetObjectClass(env, _jpaintshader); if jCls = nil then goto _exceptionOcurred; jMethod := env^.GetMethodID(env, jCls, 'SetPaint', '(Landroid/graphics/Paint;)V'); // '(Ljava/lang/Object;)V' if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].l := _Paint; env^.CallVoidMethodA(env, _jpaintshader, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jPaintShader_Combine(env: PJNIEnv; _jpaintshader: JObject; _shdrA, _shdrB: Integer; _Mode: JByte; _dstID: Integer); var jParams: array[0..3] of JValue; jMethod: JMethodID = nil; jCls : JClass = nil; label _exceptionOcurred; begin if (env = nil) or (_jpaintshader = nil) then exit; jCls := env^.GetObjectClass(env, _jpaintshader); if jCls = nil then goto _exceptionOcurred; jMethod := env^.GetMethodID(env, jCls, 'Combine', '(IIBI)V'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].i := _shdrA; jParams[1].i := _shdrB; jParams[2].b := _Mode; jParams[3].i := _dstID; env^.CallVoidMethodA(env, _jpaintshader, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; function jPaintShader_NewBitmapShader(env: PJNIEnv; _jpaintshader: JObject; _Bitmap: JOBject; _tileX, _tileY: JByte; _ID: Integer): Integer; var jParams: array[0..3] of JValue; jMethod: JMethodID = nil; jCls : JClass = nil; label _exceptionOcurred; begin if (env = nil) or (_jpaintshader = nil) then exit; jCls := env^.GetObjectClass(env, _jpaintshader); if jCls = nil then goto _exceptionOcurred; jMethod := env^.GetMethodID(env, jCls, 'NewBitmapShader', '(Landroid/graphics/Bitmap;BBI)I'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].l := _Bitmap; jParams[1].b := _tileX; jParams[2].b := _tileY; jParams[3].i := _ID; Result := env^.CallIntMethodA(env, _jpaintshader, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; function jPaintShader_NewBitmapShader(env: PJNIEnv; _jpaintshader: JObject; _Bitmap: JOBject; _tileX, _tileY: JByte; _scaleX, _scaleY, _Rotate: Single; _ID: Integer): Integer; var jParams: array[0..6] of JValue; jMethod: JMethodID = nil; jCls : JClass = nil; label _exceptionOcurred; begin if (env = nil) or (_jpaintshader = nil) then exit; jCls := env^.GetObjectClass(env, _jpaintshader); if jCls = nil then goto _exceptionOcurred; jMethod := env^.GetMethodID(env, jCls, 'NewBitmapShader', '(Landroid/graphics/Bitmap;BBFFFI)I'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].l := _Bitmap; jParams[1].b := _tileX; jParams[2].b := _tileY; jParams[3].f := _scaleX; jParams[4].f := _scaleY; jParams[5].f := _Rotate; jParams[6].i := _ID; Result := env^.CallIntMethodA(env, _jpaintshader, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; function jPaintShader_NewLinearGradient(env: PJNIEnv; _jpaintshader: JObject; _X0, _Y0, _X1, _Y1: Single; _Color0, _Color1: Integer; _tMode: JByte; _ID: Integer): Integer; var jParams: array[0..7] of JValue; jMethod: JMethodID = nil; jCls : JClass = nil; label _exceptionOcurred; begin if (env = nil) or (_jpaintshader = nil) then exit; jCls := env^.GetObjectClass(env, _jpaintshader); if jCls = nil then goto _exceptionOcurred; jMethod := env^.GetMethodID(env, jCls, 'NewLinearGradient', '(FFFFIIBI)I'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].f := _X0; jParams[1].f := _Y0; jParams[2].f := _X1; jParams[3].f := _Y1; jParams[4].i := _Color0; jParams[5].i := _Color1; jParams[6].b := _tMode; jParams[7].i := _ID; Result := env^.CallIntMethodA(env, _jpaintshader, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; function jPaintShader_NewLinearGradient(env: PJNIEnv; _jpaintshader: JObject; _X0, _Y0, _X1, _Y1: Single; _Colors: TGradientColors; _Positions: TGradientPositions; _tMode: JByte; _ID: Integer): Integer; var jParams : array[0..7] of JValue; jMethod : JMethodID = nil; jCls : JClass = nil; clrArray: JByteArray; posArray: JByteArray; label _exceptionOcurred; begin if (env = nil) or (_jpaintshader = nil) then exit; jCls := env^.GetObjectClass(env, _jpaintshader); if jCls = nil then goto _exceptionOcurred; jMethod := env^.GetMethodID(env, jCls, 'NewLinearGradient', '(FFFF[I[FBI)I'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; // gradient colors clrArray := env^.NewIntArray(env, Length(_Colors)); // allocate if clrArray = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; env^.SetIntArrayRegion(env, clrArray, 0, Length(_Colors), @_Colors[0]); // gradient positions posArray := env^.NewFloatArray(env, Length(_Positions)); // allocate if posArray = nil then begin env^.DeleteLocalRef(env, clrArray); env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; env^.SetFloatArrayRegion(env, posArray, 0, Length(_Positions), @_Positions[0]); jParams[0].f := _X0; jParams[1].f := _Y0; jParams[2].f := _X1; jParams[3].f := _Y1; jParams[4].l := clrArray; jParams[5].l := posArray; jParams[6].b := _tMode; jParams[7].i := _ID; Result := env^.CallIntMethodA(env, _jpaintshader, jMethod, @jParams); env^.DeleteLocalRef(env, jParams[4].l); env^.DeleteLocalRef(env, jParams[5].l); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; function jPaintShader_NewLinearGradient(env: PJNIEnv; _jpaintshader: JObject; _X, _Y, _Wh, _Ht, _Rotate: Single; _Color0, _Color1: Integer; _tMode: JByte; _ID: Integer): Integer; var jParams: array[0..8] of JValue; jMethod: JMethodID = nil; jCls : JClass = nil; label _exceptionOcurred; begin if (env = nil) or (_jpaintshader = nil) then exit; jCls := env^.GetObjectClass(env, _jpaintshader); if jCls = nil then goto _exceptionOcurred; jMethod := env^.GetMethodID(env, jCls, 'NewLinearGradient', '(FFFFFIIBI)I'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].f := _X; jParams[1].f := _Y; jParams[2].f := _Wh; jParams[3].f := _Ht; jParams[4].f := _Rotate; jParams[5].i := _Color0; jParams[6].i := _Color1; jParams[7].b := _tMode; jParams[8].i := _ID; Result := env^.CallIntMethodA(env, _jpaintshader, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; function jPaintShader_NewLinearGradient(env: PJNIEnv; _jpaintshader: JObject; _X, _Y, _Wh, _Ht, _Rotate: Single; _Colors: TGradientColors; _Positions: TGradientPositions; _tMode: JByte; _ID: Integer): Integer; var jParams : array[0..8] of JValue; jMethod : JMethodID = nil; jCls : JClass = nil; clrArray: JByteArray; posArray: JByteArray; label _exceptionOcurred; begin if (env = nil) or (_jpaintshader = nil) then exit; jCls := env^.GetObjectClass(env, _jpaintshader); if jCls = nil then goto _exceptionOcurred; jMethod := env^.GetMethodID(env, jCls, 'NewLinearGradient', '(FFFFF[I[FBI)I'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; // gradient colors clrArray := env^.NewIntArray(env, Length(_Colors)); // allocate if clrArray = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; env^.SetIntArrayRegion(env, clrArray, 0, Length(_Colors), @_Colors[0]); // gradient positions posArray := env^.NewFloatArray(env, Length(_Positions)); // allocate if posArray = nil then begin env^.DeleteLocalRef(env, clrArray); env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; env^.SetFloatArrayRegion(env, posArray, 0, Length(_Positions), @_Positions[0]); jParams[0].f := _X; jParams[1].f := _Y; jParams[2].f := _Wh; jParams[3].f := _Ht; jParams[4].f := _Rotate; jParams[5].l := clrArray; jParams[6].l := posArray; jParams[7].b := _tMode; jParams[8].i := _ID; Result := env^.CallIntMethodA(env, _jpaintshader, jMethod, @jParams); env^.DeleteLocalRef(env, jParams[5].l); env^.DeleteLocalRef(env, jParams[6].l); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; function jPaintShader_NewRadialGradient(env: PJNIEnv; _jpaintshader: JObject; _cX, _cY, _Radius: Single; _cColor, _eColor: Integer; _tMode: JByte; _ID: Integer): Integer; var jParams: array[0..6] of JValue; jMethod: JMethodID = nil; jCls : JClass = nil; label _exceptionOcurred; begin if (env = nil) or (_jpaintshader = nil) then exit; jCls := env^.GetObjectClass(env, _jpaintshader); if jCls = nil then goto _exceptionOcurred; jMethod := env^.GetMethodID(env, jCls, 'NewRadialGradient', '(FFFIIBI)I'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].f:= _cX; jParams[1].f:= _cY; jParams[2].f:= _Radius; jParams[3].i:= _cColor; jParams[4].i:= _eColor; jParams[5].b:= _tMode; jParams[6].i:= _ID; Result := env^.CallIntMethodA(env, _jpaintshader, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; function jPaintShader_NewRadialGradient(env: PJNIEnv; _jpaintshader: JObject; _cX, _cY, _Radius: Single; _Colors: TGradientColors; _Stops: TGradientPositions; _tMode: JByte; _ID: Integer): Integer; var jParams : array[0..6] of JValue; jMethod : JMethodID = nil; jCls : JClass = nil; clrArray: JByteArray; posArray: JByteArray; label _exceptionOcurred; begin if (env = nil) or (_jpaintshader = nil) then exit; jCls := env^.GetObjectClass(env, _jpaintshader); if jCls = nil then goto _exceptionOcurred; jMethod := env^.GetMethodID(env, jCls, 'NewRadialGradient', '(FFF[I[FBI)I'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; // gradient colors clrArray := env^.NewIntArray(env, Length(_Colors)); // allocate if clrArray = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; env^.SetIntArrayRegion(env, clrArray, 0, Length(_Colors), @_Colors[0]); // gradient positions posArray := env^.NewFloatArray(env, Length(_Stops)); // allocate if posArray = nil then begin env^.DeleteLocalRef(env, clrArray); env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; env^.SetFloatArrayRegion(env, posArray, 0, Length(_Stops), @_Stops[0]); jParams[0].f:= _cX; jParams[1].f:= _cY; jParams[2].f:= _Radius; jParams[3].l:= clrArray; jParams[4].l:= posArray; jParams[5].b:= _tMode; jParams[6].i:= _ID; Result := env^.CallIntMethodA(env, _jpaintshader, jMethod, @jParams); env^.DeleteLocalRef(env, jParams[3].l); env^.DeleteLocalRef(env, jParams[4].l); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; function jPaintShader_NewSweepGradient(env: PJNIEnv; _jpaintshader: JObject; _cX, _cY: Single; _Color0, _Color1, _ID: Integer): Integer; var jParams: array[0..4] of JValue; jMethod: JMethodID = nil; jCls : JClass = nil; label _exceptionOcurred; begin if (env = nil) or (_jpaintshader = nil) then exit; jCls := env^.GetObjectClass(env, _jpaintshader); if jCls = nil then goto _exceptionOcurred; jMethod := env^.GetMethodID(env, jCls, 'NewSweepGradient', '(FFIII)I'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].f := _cX; jParams[1].f := _cY; jParams[2].i := _Color0; jParams[3].i := _Color1; jParams[4].i := _ID; Result := env^.CallIntMethodA(env, _jpaintshader, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; function jPaintShader_NewSweepGradient(env: PJNIEnv; _jpaintshader: JObject; _cX, _cY: Single; _Colors: TGradientColors; _Positions: TGradientPositions; _ID: Integer): Integer; var jParams : array[0..4] of JValue; jMethod : JMethodID = nil; jCls : JClass = nil; clrArray: JByteArray; posArray: JByteArray; label _exceptionOcurred; begin if (env = nil) or (_jpaintshader = nil) then exit; jCls := env^.GetObjectClass(env, _jpaintshader); if jCls = nil then goto _exceptionOcurred; jMethod := env^.GetMethodID(env, jCls, 'NewSweepGradient', '(FF[I[FI)I'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; // gradient colors clrArray := env^.NewIntArray(env, Length(_Colors)); // allocate if clrArray = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; env^.SetIntArrayRegion(env, clrArray, 0, Length(_Colors), @_Colors[0]); // gradient positions posArray := env^.NewFloatArray(env, Length(_Positions)); // allocate if posArray = nil then begin env^.DeleteLocalRef(env, clrArray); env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; env^.SetFloatArrayRegion(env, posArray, 0, Length(_Positions), @_Positions[0]); jParams[0].f:= _cX; jParams[1].f:= _cY; jParams[2].l := clrArray; jParams[3].l := posArray; jParams[4].i := _ID; Result := env^.CallIntMethodA(env, _jpaintshader, jMethod, @jParams); env^.DeleteLocalRef(env, jParams[2].l); env^.DeleteLocalRef(env, jParams[3].l); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jPaintShader_SetMatrix(env: PJNIEnv; _jpaintshader: JObject; _X, _Y, _scaleX, _scaleY, _Rotate: Single; _ID: Integer); var jParams: array[0..5] of JValue; jMethod: JMethodID = nil; jCls : JClass = nil; label _exceptionOcurred; begin if (env = nil) or (_jpaintshader = nil) then exit; jCls := env^.GetObjectClass(env, _jpaintshader); if jCls = nil then goto _exceptionOcurred; jMethod := env^.GetMethodID(env, jCls, 'SetMatrix', '(FFFFFI)V'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].f := _X; jParams[0].f := _Y; jParams[0].f := _scaleX; jParams[0].f := _scaleY; jParams[0].f := _Rotate; jParams[0].i := _ID; env^.CallVoidMethodA(env, _jpaintshader, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jPaintShader_SetRotate(env: PJNIEnv; _jpaintshader: JObject; _Degree: Single; _ID: Integer); var jParams: array[0..1] of JValue; jMethod: JMethodID = nil; jCls : JClass = nil; label _exceptionOcurred; begin if (env = nil) or (_jpaintshader = nil) then exit; jCls := env^.GetObjectClass(env, _jpaintshader); if jCls = nil then goto _exceptionOcurred; jMethod := env^.GetMethodID(env, jCls, 'SetRotate', '(FI)V'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].f := _Degree; jParams[1].i := _ID; env^.CallVoidMethodA(env, _jpaintshader, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jPaintShader_SetRotate(env: PJNIEnv; _jpaintshader: JObject; _Degree, _PointX, _PointY: Single; _ID: Integer); var jParams: array[0..3] of JValue; jMethod: JMethodID = nil; jCls : JClass = nil; label _exceptionOcurred; begin if (env = nil) or (_jpaintshader = nil) then exit; jCls := env^.GetObjectClass(env, _jpaintshader); if jCls = nil then goto _exceptionOcurred; jMethod := env^.GetMethodID(env, jCls, 'SetRotate', '(FFFI)V'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].f := _Degree; jParams[1].f := _PointX; jParams[2].f := _PointY; jParams[3].i := _ID; env^.CallVoidMethodA(env, _jpaintshader, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jPaintShader_SetScale(env: PJNIEnv; _jpaintshader: JObject; _X, _Y: Single; _ID: Integer); var jParams: array[0..2] of JValue; jMethod: JMethodID = nil; jCls : JClass = nil; label _exceptionOcurred; begin if (env = nil) or (_jpaintshader = nil) then exit; jCls := env^.GetObjectClass(env, _jpaintshader); if jCls = nil then goto _exceptionOcurred; jMethod := env^.GetMethodID(env, jCls, 'SetScale', '(FFI)V'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].f := _X; jParams[1].f := _Y; jParams[2].i := _ID; env^.CallVoidMethodA(env, _jpaintshader, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jPaintShader_SetTranslate(env: PJNIEnv; _jpaintshader: JObject; _X, _Y: Single; _ID: Integer); var jParams: array[0..4] of JValue; jMethod: JMethodID = nil; jCls : JClass = nil; label _exceptionOcurred; begin if (env = nil) or (_jpaintshader = nil) then exit; jCls := env^.GetObjectClass(env, _jpaintshader); if jCls = nil then goto _exceptionOcurred; jMethod := env^.GetMethodID(env, jCls, 'SetTranslate', '(FFI)V'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].f := _X; jParams[1].f := _Y; jParams[2].i := _ID; env^.CallVoidMethodA(env, _jpaintshader, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; end.
unit frmEndMarker; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Spin, ExtCtrls; type TMarkerForm = class(TForm) Label1: TLabel; eValue: TSpinEdit; GroupBox1: TGroupBox; rbSelected: TRadioButton; rbAll: TRadioButton; btnOK: TButton; btnCancel: TButton; Label2: TLabel; pnlOK: TPanel; procedure eValueKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnOKClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var MarkerForm: TMarkerForm; implementation {$R *.DFM} procedure TMarkerForm.eValueKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if eValue.Value>eValue.MaxValue then eValue.Value:=eValue.MaxValue; if Key=VK_ESCAPE then btnCancelClick(self); if Key=VK_RETURN then btnOKClick(self); end; procedure TMarkerForm.btnOKClick(Sender: TObject); begin pnlOK.Caption:='OK'; Close; end; procedure TMarkerForm.btnCancelClick(Sender: TObject); begin pnlOK.Caption:='Cancel'; Close; end; end.
unit JSON.CustomerList; // ************************************************* // Generated By: JsonToDelphiClass - 0.65 // Project link: https://github.com/PKGeorgiev/Delphi-JsonToDelphiClass // Generated On: 2019-05-22 22:07:06 // ************************************************* // Created By : Petar Georgiev - 2014 // WebSite : http://pgeorgiev.com // ************************************************* interface uses Generics.Collections , Rest.Json , REST.JSON.Types ; type TPrimaryEmailAddrClass = class private FAddress: String; public property Address: String read FAddress write FAddress; function ToJsonString: string; class function FromJsonString(AJsonString: string): TPrimaryEmailAddrClass; end; TMetaDataClass = class private FCreateTime: String; FLastUpdatedTime: String; public property CreateTime: String read FCreateTime write FCreateTime; property LastUpdatedTime: String read FLastUpdatedTime write FLastUpdatedTime; function ToJsonString: string; class function FromJsonString(AJsonString: string): TMetaDataClass; end; TCurrencyRefClass = class private FName: String; FValue: String; public property name: String read FName write FName; property value: String read FValue write FValue; function ToJsonString: string; class function FromJsonString(AJsonString: string): TCurrencyRefClass; end; TCustomerClass = class private FActive: Boolean; FBalance: Extended; FBalanceWithJobs: Extended; FBillWithParent: Boolean; FCurrencyRef: TCurrencyRefClass; FDisplayName: String; FFullyQualifiedName: String; FId: String; FIsProject: Boolean; FJob: Boolean; FMetaData: TMetaDataClass; FPreferredDeliveryMethod: String; FPrimaryEmailAddr: TPrimaryEmailAddrClass; FPrintOnCheckName: String; FSyncToken: String; FTaxable: Boolean; FDomain: String; FSparse: Boolean; public property Active: Boolean read FActive write FActive; property Balance: Extended read FBalance write FBalance; property BalanceWithJobs: Extended read FBalanceWithJobs write FBalanceWithJobs; property BillWithParent: Boolean read FBillWithParent write FBillWithParent; property CurrencyRef: TCurrencyRefClass read FCurrencyRef write FCurrencyRef; property DisplayName: String read FDisplayName write FDisplayName; property FullyQualifiedName: String read FFullyQualifiedName write FFullyQualifiedName; property Id: String read FId write FId; property IsProject: Boolean read FIsProject write FIsProject; property Job: Boolean read FJob write FJob; property MetaData: TMetaDataClass read FMetaData write FMetaData; property PreferredDeliveryMethod: String read FPreferredDeliveryMethod write FPreferredDeliveryMethod; property PrimaryEmailAddr: TPrimaryEmailAddrClass read FPrimaryEmailAddr write FPrimaryEmailAddr; property PrintOnCheckName: String read FPrintOnCheckName write FPrintOnCheckName; property SyncToken: String read FSyncToken write FSyncToken; property Taxable: Boolean read FTaxable write FTaxable; property domain: String read FDomain write FDomain; property sparse: Boolean read FSparse write FSparse; constructor Create; destructor Destroy; override; function ToJsonString: string; class function FromJsonString(AJsonString: string): TCustomerClass; end; TQueryResponseClass = class private FCustomer: TArray<TCustomerClass>; FMaxResults: Extended; FStartPosition: Extended; public property Customer: TArray<TCustomerClass> read FCustomer write FCustomer; property maxResults: Extended read FMaxResults write FMaxResults; property startPosition: Extended read FStartPosition write FStartPosition; destructor Destroy; override; function ToJsonString: string; class function FromJsonString(AJsonString: string): TQueryResponseClass; end; TCustomerListClass = class private FQueryResponse: TQueryResponseClass; FTime: String; public property QueryResponse: TQueryResponseClass read FQueryResponse write FQueryResponse; property time: String read FTime write FTime; constructor Create; destructor Destroy; override; function ToJsonString: string; class function FromJsonString(AJsonString: string): TCustomerListClass; end; implementation {TPrimaryEmailAddrClass} function TPrimaryEmailAddrClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TPrimaryEmailAddrClass.FromJsonString(AJsonString: string): TPrimaryEmailAddrClass; begin result := TJson.JsonToObject<TPrimaryEmailAddrClass>(AJsonString) end; {TMetaDataClass} function TMetaDataClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TMetaDataClass.FromJsonString(AJsonString: string): TMetaDataClass; begin result := TJson.JsonToObject<TMetaDataClass>(AJsonString) end; {TCurrencyRefClass} function TCurrencyRefClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TCurrencyRefClass.FromJsonString(AJsonString: string): TCurrencyRefClass; begin result := TJson.JsonToObject<TCurrencyRefClass>(AJsonString) end; {TCustomerClass} constructor TCustomerClass.Create; begin inherited; FCurrencyRef := TCurrencyRefClass.Create(); FMetaData := TMetaDataClass.Create(); FPrimaryEmailAddr := TPrimaryEmailAddrClass.Create(); end; destructor TCustomerClass.Destroy; begin FCurrencyRef.free; FMetaData.free; FPrimaryEmailAddr.free; inherited; end; function TCustomerClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TCustomerClass.FromJsonString(AJsonString: string): TCustomerClass; begin result := TJson.JsonToObject<TCustomerClass>(AJsonString) end; {TQueryResponseClass} destructor TQueryResponseClass.Destroy; var LCustomerItem: TCustomerClass; begin for LCustomerItem in FCustomer do LCustomerItem.free; inherited; end; function TQueryResponseClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TQueryResponseClass.FromJsonString(AJsonString: string): TQueryResponseClass; begin result := TJson.JsonToObject<TQueryResponseClass>(AJsonString) end; {TRootClass} constructor TCustomerListClass.Create; begin inherited; FQueryResponse := TQueryResponseClass.Create(); end; destructor TCustomerListClass.Destroy; begin FQueryResponse.free; inherited; end; function TCustomerListClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TCustomerListClass.FromJsonString(AJsonString: string): TCustomerListClass; begin result := TJson.JsonToObject<TCustomerListClass>(AJsonString) end; end.
unit FilterStreams; interface uses SysUtils, Classes; const FilterBufferSize = 1024; type PByte = ^Byte; IStreamFilter = interface function Read(Stream : TStream; var Buffer; Count: Longint): Longint; function Write(Stream : TStream; const Buffer; Count: Longint): Longint; function Seek(Stream : TStream; Offset: Longint; Origin: Word): Longint; end; TFilterStream = class(TStream) private FOriginStream : TStream; FFilter : IStreamFilter; protected public constructor Create(AOriginStream : TStream; AFilter : IStreamFilter); destructor Destroy; override; function Read(var Buffer; Count: Longint): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; function Seek(Offset: Longint; Origin: Word): Longint; override; property OriginStream : TStream read FOriginStream; property Filter : IStreamFilter read FFilter; end; TXorFilter = class(TInterfacedObject, IStreamFilter) private FKey : string; FKeyLength : Integer; FKeyIndex : Integer; public constructor Create(const AKey : string); function Read(Stream : TStream; var Buffer; Count: Longint): Longint; function Write(Stream : TStream; const Buffer; Count: Longint): Longint; function Seek(Stream : TStream; Offset: Longint; Origin: Word): Longint; property Key : string read FKey; end; implementation { TFilterStream } constructor TFilterStream.Create(AOriginStream: TStream; AFilter : IStreamFilter); begin Assert((AOriginStream<>nil) and (AFilter<>nil)); FOriginStream := AOriginStream; FFilter := AFilter; end; destructor TFilterStream.Destroy; begin FFilter := nil; inherited; end; function TFilterStream.Read(var Buffer; Count: Integer): Longint; begin Result := Filter.Read(OriginStream,Buffer,Count); end; function TFilterStream.Seek(Offset: Integer; Origin: Word): Longint; begin Result := Filter.Seek(OriginStream,Offset,Origin); end; function TFilterStream.Write(const Buffer; Count: Integer): Longint; begin Result := Filter.Write(OriginStream,Buffer,Count); end; { TXorFilter } constructor TXorFilter.Create(const AKey: string); begin FKey := AKey; FKeyLength := Length(FKey); Assert(FKeyLength>0); FKeyIndex := 0; end; function TXorFilter.Read(Stream: TStream; var Buffer; Count: Integer): Longint; var I : Integer; P : PByte; begin Result := Stream.Read(Buffer,Count); P := @Buffer; for I:=0 to Result-1 do begin P^ := P^ xor Ord(Key[FKeyIndex+1]); FKeyIndex := (FKeyIndex+1) mod FKeyLength; Inc(P); end; end; function TXorFilter.Write(Stream: TStream; const Buffer; Count: Integer): Longint; var I : Integer; PBuffer, PFilterBuffer : PByte; FilterBuffer : array[0..FilterBufferSize-1] of Byte; BufferSize : Integer; WriteSize : Integer; begin Result := 0; PBuffer := @Buffer; while Count>0 do begin if Count>FilterBufferSize then BufferSize := FilterBufferSize else BufferSize := Count; Move(PBuffer^,FilterBuffer,BufferSize); Inc(PBuffer, BufferSize); Dec(Count, BufferSize); PFilterBuffer := @FilterBuffer; for I:=0 to BufferSize-1 do begin PFilterBuffer^ := PFilterBuffer^ xor Ord(Key[FKeyIndex+1]); FKeyIndex := (FKeyIndex+1) mod FKeyLength; Inc(PFilterBuffer); end; WriteSize := Stream.Write(FilterBuffer,BufferSize);; Inc(Result,WriteSize); if WriteSize<BufferSize then Break; end; end; function TXorFilter.Seek(Stream: TStream; Offset: Integer; Origin: Word): Longint; begin Result := Stream.Seek(Offset,Origin); FKeyIndex := Result mod FKeyLength; end; end.
unit Utls; interface uses Windows, Classes, SysUtils, clipbrd; procedure SaveClipboard(S: TStream); procedure LoadClipboard(S: TStream); procedure CtrlC; function GetStringFromClipboard: WideString; function DownCase(ds: char): char; function cltxt(ds:string): string; function clr(ds: string; fs: boolean): string; function SmallFonts : boolean; function IsCapsLockOn : boolean; function IsCBText:boolean; implementation function clr(ds: string; fs: boolean): string; var i : integer; begin Result := ''; for i := 1 to length(ds) do if fs then begin case ds[i] of 'a'..'z', 'A'..'Z', 'à'..'ÿ', 'À'..'ß', '¸', '¨': Result := Result + DownCase(ds[i]); end; end else Result := Result + DownCase(ds[i]); end; function cltxt(ds:string):string; var i : integer; begin Result := ''; for i := 1 to length(ds) do case ds[1] of 'a'..'z', 'A'..'Z', 'à'..'ÿ', 'À'..'ß', '¸', '¨': Result := Result + ds[i]; end; end; function DownCase(ds: char): char; begin case ds of 'A' : ds := 'a'; 'B' : ds := 'b'; 'C' : ds := 'c'; 'D' : ds := 'd'; 'E' : ds := 'e'; 'F' : ds := 'f'; 'G' : ds := 'g'; 'H' : ds := 'h'; 'I' : ds := 'i'; 'J' : ds := 'j'; 'K' : ds := 'k'; 'L' : ds := 'l'; 'M' : ds := 'm'; 'N' : ds := 'n'; 'O' : ds := 'o'; 'P' : ds := 'p'; 'Q' : ds := 'q'; 'R' : ds := 'r'; 'S' : ds := 's'; 'T' : ds := 't'; 'U' : ds := 'u'; 'V' : ds := 'v'; 'W' : ds := 'w'; 'X' : ds := 'x'; 'Y' : ds := 'y'; 'Z' : ds := 'z'; 'À' : ds := 'à'; 'Á' : ds := 'á'; 'Â' : ds := 'â'; 'Ã' : ds := 'ã'; 'Ä' : ds := 'ä'; 'Å' : ds := 'å'; '¨' : ds := '¸'; 'Æ' : ds := 'æ'; 'Ç' : ds := 'ç'; 'È' : ds := 'è'; 'É' : ds := 'é'; 'Ê' : ds := 'ê'; 'Ë' : ds := 'ë'; 'Ì' : ds := 'ì'; 'Í' : ds := 'í'; 'Î' : ds := 'î'; 'Ï' : ds := 'ï'; 'Ð' : ds := 'ð'; 'Ñ' : ds := 'ñ'; 'Ò' : ds := 'ò'; 'Ó' : ds := 'ó'; 'Ô' : ds := 'ô'; 'Õ' : ds := 'õ'; 'Ö' : ds := 'ö'; '×' : ds := '÷'; 'Ø' : ds := 'ø'; 'Ù' : ds := 'ù'; 'Ú' : ds := 'ú'; 'Û' : ds := 'û'; 'Ü' : ds := 'ü'; 'Ý' : ds := 'ý'; 'Þ' : ds := 'þ'; 'ß' : ds := 'ÿ'; end; Result := ds; end; function GetStringFromClipboard: WideString; var Data: THandle; begin if IsClipboardFormatAvailable(CF_UNICODETEXT) then begin Clipboard.Open; Data:= GetClipboardData(CF_UNICODETEXT); try if Data <> 0 then Result:= PWideChar(GlobalLock(Data)) else Result:= ''; finally if Data <> 0 then GlobalUnlock(Data); Clipboard.Close; end; end {begin} else Result:= Clipboard.AsText; end; procedure CopyStreamToClipboard(fmt: Cardinal; S: TStream); var hMem: THandle; pMem: Pointer; begin Assert(Assigned(S)); S.Position := 0; hMem := GlobalAlloc(GHND or GMEM_DDESHARE, S.Size); if hMem <> 0 then begin pMem := GlobalLock(hMem); if pMem <> nil then begin try S.Read(pMem^, S.Size); S.Position := 0; finally GlobalUnlock(hMem); end; Clipboard.Open; try Clipboard.SetAsHandle(fmt, hMem); finally Clipboard.Close; end; end { If } else begin GlobalFree(hMem); OutOfMemoryError; end; end { If } else OutOfMemoryError; end; { CopyStreamToClipboard } procedure CopyStreamFromClipboard(fmt: Cardinal; S: TStream); var hMem: THandle; pMem: Pointer; begin Assert(Assigned(S)); hMem := Clipboard.GetAsHandle(fmt); if hMem <> 0 then begin pMem := GlobalLock(hMem); if pMem <> nil then begin try S.Write(pMem^, GlobalSize(hMem)); S.Position := 0; finally GlobalUnlock(hMem); end; end { If } else exit; // raise Exception.Create('CopyStreamFromClipboard: could not lock global handle ' + // 'obtained from clipboard!'); end; { If } end; { CopyStreamFromClipboard } procedure SaveClipboardFormat(fmt: Word; writer: TWriter); var fmtname: array[0..128] of Char; ms: TMemoryStream; begin Assert(Assigned(writer)); if 0 = GetClipboardFormatName(fmt, fmtname, SizeOf(fmtname)) then fmtname[0] := #0; ms := TMemoryStream.Create; try CopyStreamFromClipboard(fmt, ms); if ms.Size > 0 then begin writer.WriteInteger(fmt); writer.WriteString(fmtname); writer.WriteInteger(ms.Size); writer.Write(ms.Memory^, ms.Size); end; { If } finally ms.Free end; { Finally } end; { SaveClipboardFormat } procedure LoadClipboardFormat(reader: TReader); var fmt: Integer; fmtname: string; Size: Integer; ms: TMemoryStream; begin Assert(Assigned(reader)); fmt := reader.ReadInteger; fmtname := reader.ReadString; Size := reader.ReadInteger; ms := TMemoryStream.Create; try ms.Size := Size; reader.Read(ms.memory^, Size); if Length(fmtname) > 0 then fmt := RegisterCLipboardFormat(PChar(fmtname)); if fmt <> 0 then CopyStreamToClipboard(fmt, ms); finally ms.Free; end; { Finally } end; { LoadClipboardFormat } procedure SaveClipboard(S: TStream); var writer: TWriter; i: Integer; begin Assert(Assigned(S)); writer := TWriter.Create(S, 4096); try Clipboard.Open; try writer.WriteListBegin; for i := 0 to Clipboard.formatcount - 1 do SaveClipboardFormat(Clipboard.Formats[i], writer); writer.WriteListEnd; finally Clipboard.Close; end; { Finally } finally writer.Free end; { Finally } end; { SaveClipboard } procedure LoadClipboard(S: TStream); var reader: TReader; begin Assert(Assigned(S)); reader := TReader.Create(S, 4096); try Clipboard.Open; try clipboard.Clear; reader.ReadListBegin; while not reader.EndOfList do LoadClipboardFormat(reader); reader.ReadListEnd; finally Clipboard.Close; end; { Finally } finally reader.Free end; { Finally } end; { LoadClipboard } function SmallFonts : BOOLEAN; var DC : HDC; begin DC := GetDC(0); Result := (GetDeviceCaps(DC, LOGPIXELSX) = 96); ReleaseDC(0, DC); END; function IsCapsLockOn : Boolean; begin Result := 0 <> (GetKeyState(VK_CAPITAL) and $01); end; procedure CtrlC; begin keybd_event(VK_CONTROL, MapVirtualKey(VK_CONTROL, 0), 0, 0); keybd_event(67, MapVirtualKey(67, 0), 0, 0); keybd_event(67, MapVirtualKey(67, 0), KEYEVENTF_KEYUP, 0); keybd_event(VK_CONTROL, MapVirtualKey(VK_CONTROL, 0), KEYEVENTF_KEYUP, 0) end; function IsCBText:boolean; begin Result:=false; if (Clipboard.HasFormat(CF_UNICODETEXT)) or (Clipboard.HasFormat(CF_OEMTEXT)) or (Clipboard.HasFormat(CF_DSPTEXT)) or (Clipboard.HasFormat(CF_TEXT)) then Result:= true; end; end.
unit CadastroAbastecimento; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Buttons, Vcl.ComCtrls; type TFormCadastroAbastecimento = class(TForm) LabelBomba: TLabel; EditBomba: TEdit; LabelTipo: TLabel; EditTipo: TEdit; Bevel01: TBevel; LabelMoeda01: TLabel; EditTotalPagar: TEdit; LabelTotalPagar: TLabel; LabelLitros: TLabel; EditLitros: TEdit; LabelMoeda02: TLabel; LabelPrecoLitro: TLabel; EditlPrecoLitro: TEdit; ComboBoxForma: TComboBox; Bevel1: TBevel; BitBtnNovoAbastecimento: TBitBtn; BitBtnIniciarAbastecimento: TBitBtn; StatusBar: TStatusBar; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormShow(Sender: TObject); procedure ComboBoxFormaChange(Sender: TObject); procedure BitBtnNovoAbastecimentoClick(Sender: TObject); procedure EditLitrosKeyPress(Sender: TObject; var Key: Char); procedure EditTotalPagarKeyPress(Sender: TObject; var Key: Char); procedure EditLitrosChange(Sender: TObject); procedure EditTotalPagarChange(Sender: TObject); procedure BitBtnIniciarAbastecimentoClick(Sender: TObject); private FBombaId: Integer; procedure SetBombaId(const Value: Integer); procedure CarregarInformacoesBomba; procedure Abastecer; function ValidarAbastecimento:Boolean; public property BombaId: Integer read FBombaId write SetBombaId; end; var FormCadastroAbastecimento: TFormCadastroAbastecimento; implementation {$R *.dfm} uses Util, BombaBO, Bomba, Tanque, ConfiguracaoBO, Configuracao, Abastecimento, AbastecimentoBO; procedure TFormCadastroAbastecimento.Abastecer; var BombaBO :TBombaBO; ConfiguracaoBO :TConfiguracaoBO; Configuracao :TConfiguracao; AbastecimentoBO :TAbastecimentoBO; Abastecimento :TAbastecimento; begin try BombaBO := TBombaBO.Create; ConfiguracaoBO := TConfiguracaoBO.Create; Configuracao := ConfiguracaoBO.ObterConfiguracao(); FreeAndNil(ConfiguracaoBO); Abastecimento := TAbastecimento.Create; Abastecimento.Data := Date; Abastecimento.Bomba := BombaBO.ObterBombaPorId(BombaId); Abastecimento.Litros := TUtil.StringEmCurrency(Trim(EditLitros.Text)); Abastecimento.Valor := TUtil.StringEmCurrency(Trim(EditTotalPagar.Text)); Abastecimento.Imposto := ((Configuracao.ValorImposto * Abastecimento.Valor) / 100); AbastecimentoBO := TAbastecimentoBO.Create; AbastecimentoBO.Salvar(Abastecimento); FreeAndNil(AbastecimentoBO); FreeAndNil(BombaBO); FreeAndNil(Abastecimento); except on E: Exception do begin TUtil.Mensagem(e.Message); end; end; end; procedure TFormCadastroAbastecimento.BitBtnIniciarAbastecimentoClick(Sender: TObject); begin try if not(ValidarAbastecimento()) then begin Exit; end; Abastecer(); TUtil.Mensagem('Abastecimento realizado com sucesso.'); if not(TUtil.Confirmacao('Deseja realizar outro abastecimento?')) then begin Close; end; BitBtnNovoAbastecimentoClick(Sender); except on E: Exception do begin TUtil.Mensagem(e.Message); end; end; end; procedure TFormCadastroAbastecimento.BitBtnNovoAbastecimentoClick(Sender: TObject); begin try if (Sender = BitBtnNovoAbastecimento) then begin if not(TUtil.Confirmacao('Confirmar início de um novo abastecimento?')) then begin Exit; end; end; ComboBoxForma.ItemIndex := 0; ComboBoxFormaChange(Sender); except on E: Exception do begin TUtil.Mensagem(e.Message); end; end; end; procedure TFormCadastroAbastecimento.CarregarInformacoesBomba; var BombaBO: TBombaBO; Bomba :TBomba; ConfiguracaoBO :TConfiguracaoBO; Configuracao :TConfiguracao; begin try BombaBO := TBombaBO.Create; Bomba := BombaBO.ObterBombaPorId(BombaId); FreeAndNil(BombaBO); ConfiguracaoBO := TConfiguracaoBO.Create; Configuracao := ConfiguracaoBO.ObterConfiguracao(); FreeAndNil(ConfiguracaoBO); EditBomba.Text := Trim(Bomba.Descricao); case (Bomba.Tanque.Tipo) of Gasolina : begin EditTipo.Text := 'Gasolina'; EditlPrecoLitro.Text := FormatFloat('#,##0.00',Configuracao.ValorLitroGasolina); end; OleoDiesel : begin EditTipo.Text := 'Óleo Diesel'; EditlPrecoLitro.Text := FormatFloat('#,##0.00',Configuracao.ValorLitroOleoDiesel); end; end; FreeAndNil(Bomba); FreeAndNil(Configuracao); ComboBoxForma.SetFocus; except on E: Exception do begin TUtil.Mensagem(e.Message); end; end; end; procedure TFormCadastroAbastecimento.ComboBoxFormaChange(Sender: TObject); begin try case (ComboBoxForma.ItemIndex) of 0 : begin EditTotalPagar.Enabled := False; EditTotalPagar.Color := clBtnFace; EditTotalPagar.Text := '0,00'; EditLitros.Enabled := False; EditLitros.Color := clBtnFace; EditLitros.Text := '0,00'; ComboBoxForma.SetFocus; end; 1 : begin EditTotalPagar.Enabled := False; EditTotalPagar.Color := clBtnFace; EditTotalPagar.Text := '0,00'; EditLitros.Enabled := True; EditLitros.Color := clWindow; EditLitros.Text := '0,00'; EditLitros.SetFocus(); end; 2 : begin EditTotalPagar.Enabled := True; EditTotalPagar.Color := clWindow; EditTotalPagar.Text := '0,00'; EditLitros.Enabled := False; EditLitros.Color := clBtnFace; EditLitros.Text := '0,00'; EditTotalPagar.SetFocus(); end; end; except on E: Exception do begin TUtil.Mensagem(e.Message); end; end; end; procedure TFormCadastroAbastecimento.EditLitrosChange(Sender: TObject); begin try if not(EditLitros.Enabled) then begin Exit; end; if (Trim(EditLitros.Text) = '') then begin EditLitros.Text := '0,00'; EditTotalPagar.Text := '0,00'; Exit; end; EditTotalPagar.Text := FormatFloat('#,##0.00', TUtil.StringEmCurrency(Trim(EditLitros.Text)) * TUtil.StringEmCurrency(Trim(EditlPrecoLitro.Text))); except on E: Exception do begin TUtil.Mensagem(e.Message); end; end; end; procedure TFormCadastroAbastecimento.EditLitrosKeyPress(Sender: TObject; var Key: Char); begin try if not(Key in ['0'..'9',Char(8),Char(44)]) then begin Key := #0; end; except on E: Exception do begin TUtil.Mensagem(e.Message); end; end; end; procedure TFormCadastroAbastecimento.EditTotalPagarChange(Sender: TObject); begin try if not(EditTotalPagar.Enabled) then begin Exit; end; if (Trim(EditTotalPagar.Text) = '') then begin EditLitros.Text := '0,00'; EditTotalPagar.Text := '0,00'; Exit end; EditLitros.Text := FormatFloat('#,##0.00', TUtil.StringEmCurrency(Trim(EditTotalPagar.Text)) / TUtil.StringEmCurrency(Trim(EditlPrecoLitro.Text))); except on E: Exception do begin TUtil.Mensagem(e.Message); end; end; end; procedure TFormCadastroAbastecimento.EditTotalPagarKeyPress(Sender: TObject; var Key: Char); begin try if not(Key in ['0'..'9',Char(8),Char(44)]) then begin Key := #0; end; except on E: Exception do begin TUtil.Mensagem(e.Message); end; end; end; procedure TFormCadastroAbastecimento.FormClose(Sender: TObject; var Action: TCloseAction); begin try Action := caFree; except on E: Exception do begin TUtil.Mensagem(e.Message); end; end; end; procedure TFormCadastroAbastecimento.FormDestroy(Sender: TObject); begin try FormCadastroAbastecimento := nil; except on E: Exception do begin TUtil.Mensagem(e.Message); end; end; end; procedure TFormCadastroAbastecimento.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin try case (Key) of VK_ESCAPE : Close; end; except on E: Exception do begin TUtil.Mensagem(e.Message); end; end; end; procedure TFormCadastroAbastecimento.FormShow(Sender: TObject); begin try CarregarInformacoesBomba(); except on E: Exception do begin TUtil.Mensagem(e.Message); end; end; end; procedure TFormCadastroAbastecimento.SetBombaId(const Value: Integer); begin FBombaId := Value; end; function TFormCadastroAbastecimento.ValidarAbastecimento: Boolean; begin try Result := False; if (ComboBoxForma.ItemIndex = 0) then begin TUtil.Mensagem('Selecione a forma do abastecimento.'); ComboBoxForma.SetFocus; Exit; end; case (ComboBoxForma.ItemIndex) of 1 : begin if (Trim(EditLitros.Text) = '0,00') then begin TUtil.Mensagem('Informe a quantidade de litros do abastecimento.'); EditLitros.SetFocus; Exit; end; end; 2 : begin if (Trim(EditTotalPagar.Text) = '0,00') then begin TUtil.Mensagem('Informe o valor a pagar do abastecimento.'); EditTotalPagar.SetFocus; Exit; end; end; end; Result := True; except on E: Exception do begin TUtil.Mensagem(e.Message); end; end; end; end.
(* 1. Input and Output 2. Data Types 3. Variables 4. Constants 5. Case Sensitivity 6. Comments 7. Arithmetic operators *) program firstTests; var x, y, z : integer; c : char; s : string; b : boolean; const ADD = 5; out = 'meow'; { 1. Input and Output } procedure inputOutput; var i : integer; begin writeln('Check Input and Output'); write('input an integer: '); readln(i); writeln('i: ', i); writeln; end; { 2. Data Types 3. Variables 5. Case Sensitivity } procedure dataTypes; begin writeln('Check Data Types, Vriables, and Case Sensitivity'); x := 5; y := -1; z := +7; c := 'p'; s := 'Will I pass CMPILER?'; b := true; writeln('x: ', X); writeln('y: ', y); writeln('z: ', Z); writeln('c: ', c); writeln('s: ', S); writeln('b: ', b); writeln; end; { 4. Constants Assignments } procedure constants; begin writeln('Check Constants'); x := ADD + 2; writeln('x: ', x); writeln; s := out; writeln('What is s? ', s); end; { 7. Arithmetic Operations ( ) Grouping * Multiplication, / Division, % Modulo + Addition, - Subtraction } procedure arithmetic; var i, j, k, l: integer; begin writeln('Check Arithmetic Operations'); x := 1; y := x + 1; {Answer: 2} z := x - 1; {Answer: 0} i := x * 2; {Answer: 2} j := 9 div 3; k := 5 mod 3; l := (1 - 2) div 3 - ((2*2) mod 2) + 4 * 2; writeln('y - addition: ', y); writeln('z - subtraction: ', z); writeln('i - multiplication: ', i); writeln('j - division: ', j); writeln('k - modulo: ', k); writeln('l: ', l); writeln; end; begin inputOutput; dataTypes; constants; arithmetic; end.
unit TJCDatabase; { TJCDb je databaze jizdnich cest. } interface uses TechnologieJC, TBlok, IniFiles, SysUtils, Windows, IdContext, Generics.Collections, Classes, IBUtils, TBloky; type EJCIdAlreadyExists = class(Exception); TJCDb = class private JCs:TObjectList<TJC>; ffilename:string; function GetCount():Word; function FindPlaceForNewJC(id:Integer):Integer; public constructor Create(); destructor Destroy(); override; function LoadData(const filename:string):Byte; function SaveData(const filename:string):Byte; procedure UpdateJCIndexes(); procedure Update(); procedure StavJC(StartBlk,EndBlk:TBlk; SenderPnl:TIdContext; SenderOR:TObject); function AddJC(JCdata:TJCprop):TJC; procedure RemoveJC(index:Integer); function GetJCByIndex(index:Integer):TJC; function GetJCIndex(id:Integer):Integer; function GetJCByID(id:integer):TJC; // najde JC, ktera je postavena, ci prave stavena ! function FindJC(NavestidloBlokID:Integer;Staveni:Boolean = false):Integer; function FindOnlyStaveniJC(NavestidloBlokID:Integer):Integer; function IsJC(id:Integer; ignore_index:Integer = -1):boolean; //pouzivano pri vypadku polohy vyhybky postavene jizdni cesty function FindPostavenaJCWithVyhybka(vyh_id:Integer):TArI; function FindPostavenaJCWithUsek(usek_id:Integer):Integer; function FindPostavenaJCWithPrisl(blk_id:Integer):TArI; function FindPostavenaJCWithPrj(blk_id:Integer):Integer; function FindPostavenaJCWithTrat(trat_id:Integer):Integer; function FindPostavenaJCWithZamek(zam_id:Integer):TArI; // jakmile dojde k postaveni cesty fJC, muze dojit k ovlivneni nejakeho navestidla pred ni // tato fce zajisti, ze k ovlivneni dojde procedure CheckNNavaznost(fJC:TJC); procedure RusAllJC(); procedure RusJC(Blk:TBlk); // rusi cestu, ve ktere je zadany blok // volano pri zmene ID JC na indexu \index // -> je potreba zmenit poradi JC procedure JCIDChanged(index:Integer); property Count:Word read GetCount; property filename:string read ffilename; end; var JCDb:TJcDb; implementation uses Logging, GetSystems, TBlokSCom, TBlokUsek, TOblRizeni, TCPServerOR, DataJC, Zasobnik, TOblsRizeni, TMultiJCDatabase, appEv, TBlokVyhybka; //////////////////////////////////////////////////////////////////////////////// // TRIDA TJCDb // databaze jizdnich cest //////////////////////////////////////////////////////////////////////////////// constructor TJCDb.Create(); begin inherited Create(); Self.JCs := TObjectList<TJC>.Create(); end;//ctor destructor TJCDb.Destroy(); begin Self.JCs.Free(); inherited Destroy(); end;//dtor //////////////////////////////////////////////////////////////////////////////// // load data from ini file function TJCDb.LoadData(const filename:string):Byte; var ini:TMemIniFile; i:Integer; sections:TStrings; JC:TJC; begin writelog('Načítám JC - '+filename, WR_DATA); Self.ffilename := filename; try ini := TMemIniFile.Create(filename, TEncoding.UTF8); except Exit(1); end; Self.JCs.Clear(); sections := TStringList.Create(); ini.ReadSections(sections); for i := 0 to sections.Count-1 do begin JC := TJC.Create(); try JC.index := i; JC.LoadData(ini, sections[i]); Self.JCs.Insert(Self.FindPlaceForNewJC(JC.id), JC); except on E:Exception do begin AppEvents.LogException(E, 'JC '+JC.nazev+' se nepodařilo načíst'); JC.Free(); end; end; end;//for i Self.UpdateJCIndexes(); ini.Free; sections.Free(); Result := 0; writelog('Načteno '+IntToStr(Self.JCs.Count)+' JC', WR_DATA); end;//function // save data to ini file: function TJCDb.SaveData(const filename:string):Byte; var ini:TMemIniFile; i:Integer; begin writelog('Ukládám JC - '+filename, WR_DATA); try DeleteFile(PChar(filename)); ini := TMemIniFile.Create(filename, TEncoding.UTF8); except Exit(1); end; for i := 0 to Self.JCs.Count-1 do Self.JCs[i].SaveData(ini, IntToStr(Self.JCs[i].id)); ini.UpdateFile(); ini.Free(); Result := 0; writelog('JC uloženy', WR_DATA); end;//function //////////////////////////////////////////////////////////////////////////////// procedure TJCDb.Update(); var i:Integer; begin if (not GetFunctions.GetSystemStart) then Exit; for i := 0 to Self.JCs.Count-1 do begin try if (Self.JCs[i].stav.RozpadBlok > -5) then Self.JCs[i].UsekyRusJC(); if (Self.JCs[i].stav.RozpadBlok = -6) then Self.JCs[i].UsekyRusNC(); if (Self.JCs[i].Staveni) then begin Self.JCs[i].UpdateStaveni(); Self.JCs[i].UpdateTimeOut(); end; except on E:Exception do begin if (not log_err_flag) then AppEvents.LogException(E, 'JC '+Self.JCs[i].nazev + ' update error'); if (Self.JCs[i].staveni) then Self.JCs[i].CancelStaveni('Vyjímka', true) else Self.JCs[i].RusJCWithoutBlk(); end; end;//except end;//for i end;//procedure //////////////////////////////////////////////////////////////////////////////// function TJCDb.GetJCByIndex(index:Integer):TJC; begin if ((index < 0) or (index >= Self.JCs.Count)) then begin Result := nil; Exit; end; Result := Self.JCs[index]; end;//function //////////////////////////////////////////////////////////////////////////////// //toto se vola zvnejsi, kdyz chceme postavit jakoukoliv JC procedure TJCDb.StavJC(StartBlk,EndBlk:TBlk; SenderPnl:TIdContext; SenderOR:TObject); var i, j:Integer; Blk:TBlk; begin for i := 0 to Self.JCs.Count-1 do begin Blky.GetBlkByID(Self.JCs[i].data.NavestidloBlok, Blk); if (Blk <> StartBlk) then continue; Blky.GetBlkByID(Self.JCs[i].data.Useky[Self.JCs[i].data.Useky.Count-1], Blk); if (Blk <> EndBlk) then continue; if ((Integer((StartBlk as TBlkSCom).ZacatekVolba) = Integer(Self.JCs[i].data.TypCesty)) or (((StartBlk as TBlkSCom).ZacatekVolba = TBLkSComVolba.NC) and (Self.JCs[i].data.TypCesty = TJCType.vlak)) or (((StartBlk as TBlkSCom).ZacatekVolba = TBLkSComVolba.PP) and (Self.JCs[i].data.TypCesty = TJCType.posun))) then begin // nasli jsme jizdni cestu, kterou hledame // jeste kontrola variantnich bodu: if (Self.JCs[i].data.vb.Count <> (SenderOR as TOR).vb.Count) then continue; for j := 0 to Self.JCs[i].data.vb.Count-1 do if (Self.JCs[i].data.vb[j] <> ((SenderOR as TOR).vb[j] as TBlk).id) then continue; // v pripade nouzove cesty klik na DK opet prevest na klienta if ((StartBlk as TBlkSCom).ZacatekVolba = TBLkSComVolba.NC) then for j:= 0 to (StartBlk as TBlkSCom).OblsRizeni.Cnt-1 do (StartBlk as TBlkSCom).OblsRizeni.ORs[j].ORDKClickClient(); if ((SenderOR as TOR).stack.volba = TORStackVolba.VZ) then begin (SenderOR as TOR).stack.AddJC(Self.JCs[i], SenderPnl, ((StartBlk as TBlkSCom).ZacatekVolba = TBLkSComVolba.NC) or ((StartBlk as TBlkSCom).ZacatekVolba = TBLkSComVolba.PP)); // zrusime zacatek, konec a variantni body (StartBlk as TBlkSCom).ZacatekVolba := TBlkSComVOlba.none; (EndBlk as TBlkUsek).KonecJC := TZaver.no; (SenderOR as TOR).ClearVb(); end else begin (SenderOR as TOR).vb.Clear(); // variantni body aktualne stavene JC jen smazeme z databaze (zrusime je na konci staveni JC) Self.JCs[i].StavJC(SenderPnl, SenderOR, nil, ((StartBlk as TBlkSCom).ZacatekVolba = TBLkSComVolba.NC) or ((StartBlk as TBlkSCom).ZacatekVolba = TBLkSComVolba.PP)); end; Exit; end; end;//for i // kontrola staveni slozene jizdni cesty if ((StartBlk as TBlkSCom).ZacatekVolba <> TBLkSComVolba.NC) then if (MultiJCDb.StavJC(StartBlk, EndBlk, SenderPnl, SenderOR)) then Exit(); (EndBlk as TBlkUsek).KonecJC := TZaver.no; ORTCPServer.SendInfoMsg(SenderPnl, 'Cesta nenalezena v závěrové tabulce'); writelog('Nelze postavit JC - nenalezena v zaverove tabulce',WR_VC); end;//procedure //////////////////////////////////////////////////////////////////////////////// function TJCDb.AddJC(JCdata:TJCprop):TJC; var JC:TJC; index:Integer; i:Integer; begin // kontrola existence JC stejneho ID if (Self.IsJC(JCData.id)) then raise EJCIdAlreadyExists.Create('ID jízdní cesty '+IntToStr(JCData.id)+' již použito'); index := Self.FindPlaceForNewJC(JCData.id); JC := TJC.Create(JCData); JC.index := index; Self.JCs.Insert(index, JC); // indexy prislusnych JC na konci seznamu posuneme o 1 nahoru for i := index+1 to Self.JCs.Count-1 do Self.JCs[i].index := Self.JCs[i].index + 1; JCTableData.AddJC(index); Result := JC; end;//function procedure TJCDb.RemoveJC(index:Integer); var i:Integer; OblR:TOR; begin if (index < 0) then raise Exception.Create('Index podtekl seznam JC'); if (index >= Self.JCs.Count) then raise Exception.Create('Index pretekl seznam JC'); if (Self.JCs[index].postaveno) then raise Exception.Create('JC postavena, nelze smazat'); for i := 0 to ORs.Count-1 do begin ORs.GetORByIndex(i, OblR); if (OblR.stack.IsJCInStack(Self.JCs[index])) then raise Exception.Create('JC v zasobniku OR '+OblR.id); end; Self.JCs.Delete(index); // aktulizujeme indexy JC (dekrementujeme) for i := index to Self.JCs.Count-1 do Self.JCs[i].index := Self.JCs[i].index - 1; JCTableData.RemoveJC(index); end;//function //////////////////////////////////////////////////////////////////////////////// procedure TJCDb.RusAllJC(); var i:Integer; begin for i := 0 to Self.JCs.Count-1 do if (Self.JCs[i].postaveno) then Self.JCs[i].RusJC(); end;//procedure //////////////////////////////////////////////////////////////////////////////// function TJCDb.FindJC(NavestidloBlokID:Integer; Staveni:Boolean = false):Integer; var i:Integer; begin for i := 0 to Self.JCs.Count-1 do if (((Self.JCs[i].postaveno) or ((Staveni) and (Self.JCs[i].staveni))) and (Self.JCs[i].data.NavestidloBlok = NavestidloBlokID)) then Exit(i); Exit(-1); end;//function function TJCDb.FindOnlyStaveniJC(NavestidloBlokID:Integer):Integer; var i:Integer; begin for i := 0 to Self.JCs.Count-1 do if ((Self.JCs[i].staveni) and (Self.JCs[i].data.NavestidloBlok = NavestidloBlokID)) then Exit(i); Exit(-1); end; //////////////////////////////////////////////////////////////////////////////// //vyuzivani pri vypadku polohy vyhybky ke zruseni jizdni cesty // muze vracet vic jizdnich cest - jeden odvrat muze byt u vic aktualne postavenych JC function TJCDB.FindPostavenaJCWithVyhybka(vyh_id:Integer):TArI; var i,j:Integer; refz:TJCRefZaver; blk:TBlk; vyh:TBlkVyhybka; begin Blky.GetBlkByID(vyh_id, blk); vyh := TBlkVyhybka(blk); SetLength(Result, 0); for i := 0 to Self.JCs.Count-1 do begin if (not Self.JCs[i].postaveno) then continue; // prime vyhybky for j := 0 to Self.JCs[i].data.Vyhybky.Count-1 do begin if (Self.JCs[i].data.Vyhybky[j].Blok = vyh_id) then begin SetLength(Result, Length(Result)+1); Result[Length(Result)-1] := i; end;//if (JC[cyklus2].VyhybkyZaver[cyklus3].Blok = Bloky.Data[cyklus].ID) end;//for j // odvraty for j := 0 to Self.JCs[i].data.Odvraty.Count-1 do begin if (Self.JCs[i].data.Odvraty[j].Blok = vyh_id) then begin SetLength(Result, Length(Result)+1); Result[Length(Result)-1] := i; end;//if (JC[cyklus2].VyhybkyZaver[cyklus3].Blok = Bloky.Data[cyklus].ID) end;//for j // zamky if ((vyh <> nil) and (vyh.zamek <> nil)) then begin for refz in Self.JCs[i].data.zamky do begin if (refz.Blok = vyh.zamek.id) then begin SetLength(Result, Length(Result)+1); Result[Length(Result)-1] := i; end; end; end; end;//for i end;//function //vyuzivani pri vypadku polohy vyhybky ke zruseni jizdni cesty function TJCDB.FindPostavenaJCWithUsek(usek_id:Integer):Integer; var i,j:Integer; begin Result := -1; for i := 0 to Self.JCs.Count-1 do begin if (not Self.JCs[i].postaveno) then continue; for j := 0 to Self.JCs[i].data.Useky.Count-1 do if (Self.JCs[i].data.Useky[j] = usek_id) then Exit(i); end;//for i end;//function function TJCDB.FindPostavenaJCWithPrisl(blk_id:Integer):TArI; var i,j:Integer; begin SetLength(Result, 0); for i := 0 to Self.JCs.Count-1 do begin if (not Self.JCs[i].postaveno) then continue; for j := 0 to Self.JCs[i].data.Prisl.Count-1 do begin if (Self.JCs[i].data.Prisl[j].Blok = blk_id) then begin SetLength(Result, Length(Result)+1); Result[Length(Result)-1] := i; end;//if (JC[cyklus2].VyhybkyZaver[cyklus3].Blok = Bloky.Data[cyklus].ID) end;//for j end;//for i end;//function function TJCDB.FindPostavenaJCWithTrat(trat_id:Integer):Integer; var i:Integer; begin for i := 0 to Self.JCs.Count-1 do begin if (not Self.JCs[i].postaveno) then continue; if (Self.JCs[i].data.Trat = trat_id) then Exit(i); end;//for i Exit(-1); end;//function function TJCDB.FindPostavenaJCWithPrj(blk_id:Integer):Integer; var i,j:Integer; begin for i := 0 to Self.JCs.Count-1 do begin if (not Self.JCs[i].postaveno) then continue; for j := 0 to Self.JCs[i].data.Prejezdy.Count-1 do if (Self.JCs[i].data.Prejezdy[j].Prejezd = blk_id) then Exit(i); end;//for i Exit(-1); end;//procedure function TJCDB.FindPostavenaJCWithZamek(zam_id:Integer):TArI; var i,j:Integer; begin SetLength(Result, 0); for i := 0 to Self.JCs.Count-1 do begin if (not Self.JCs[i].postaveno) then continue; // prime vyhybky for j := 0 to Self.JCs[i].data.zamky.Count-1 do begin if (Self.JCs[i].data.zamky[j].Blok = zam_id) then begin SetLength(Result, Length(Result)+1); Result[Length(Result)-1] := i; end;//if (JC[cyklus2].VyhybkyZaver[cyklus3].Blok = Bloky.Data[cyklus].ID) end;//for j end;//for i end;//function //////////////////////////////////////////////////////////////////////////////// //jakmile dojde k nastaveni navestidla na ceste JC, tady se zkontroluje, zda-li //se nahodou nema nejake navestidlo pred cestou JC rozsvitit jinak procedure TJCDb.CheckNNavaznost(fJC:TJC); var i:Integer; nav:TBlk; my_nav:TBlkSCom; begin if (fJC.data.TypCesty = TJCType.posun) then Exit; Blky.GetBlkByID(fJC.data.NavestidloBlok, nav); if (nav = nil) then Exit; my_nav := (nav as TBlkSCom); for i := 0 to Self.JCs.Count-1 do begin if ((Self.JCs[i].data.TypCesty = TJCType.posun) or (Self.JCs[i].data.DalsiNNavaznost <> fJC.data.NavestidloBlok)) then continue; Blky.GetBlkByID(Self.JCs[i].data.NavestidloBlok, nav); if (not (nav as TBlkSCom).IsPovolovaciNavest()) then continue; if (my_nav.IsPovolovaciNavest()) then begin if (Self.JCs[i].data.RychlostDalsiN = 4) then begin if ((my_nav.Navest = TBlkSCom._NAV_VYSTRAHA_40) or (my_nav.Navest = TBlkSCom._NAV_40_OCEK_40) or (my_nav.Navest = TBlkSCom._NAV_VOLNO_40)) then (nav as TBlkSCom).Navest := TBlkSCom._NAV_40_OCEK_40 else (nav as TBlkSCom).Navest := TBlkSCom._NAV_VOLNO_40; end else begin if ((my_nav.Navest = TBlkSCom._NAV_VYSTRAHA_40) or (my_nav.Navest = TBlkSCom._NAV_40_OCEK_40) or (my_nav.Navest = TBlkSCom._NAV_VOLNO_40)) then (nav as TBlkSCom).Navest := TBlkSCom._NAV_OCEK_40 else (nav as TBlkSCom).Navest := TBlkSCom._NAV_VOLNO; end; end else begin if (Self.JCs[i].data.RychlostNoDalsiN = 4) then (nav as TBlkSCom).Navest := TBlkSCom._NAV_VYSTRAHA_40 else (nav as TBlkSCom).Navest := TBlkSCom._NAV_VYSTRAHA; end; end;//for i end;//procedure //////////////////////////////////////////////////////////////////////////////// // rusi cestu, ve ktere je zadany blok procedure TJCDb.RusJC(Blk:TBlk); var tmpblk:TBlk; jcs:TArI; i, j:Integer; jc:TJC; begin case (Blk.typ) of _BLK_VYH : jcs := JCDb.FindPostavenaJCWithVyhybka(Blk.id); _BLK_PREJEZD : begin SetLength(jcs, 1); jcs[0] := JCDb.FindPostavenaJCWithPrj(Blk.id); end; _BLK_USEK, _BLK_TU: begin SetLength(jcs, 1); jcs[0] := JCDb.FindPostavenaJCWithUsek(Blk.id); end; _BLK_SCOM: begin SetLength(jcs, 1); jcs[0] := JCDb.FindJC(Blk.id); end; _BLK_TRAT: begin SetLength(jcs, 1); jcs[0] := JCDb.FindPostavenaJCWithTrat(Blk.id); end; _BLK_ZAMEK: jcs := JCDb.FindPostavenaJCWithZamek(Blk.id); end;//case if (Length(jcs) > 0) then begin for i := 0 to Length(jcs)-1 do begin if (jcs[i] < 0) then continue; // toto tady musi byt, protoze napr FindPostavenaJCWithTrat vraci -1, pokud trat nenajde jc := JCDb.GetJCByIndex(jcs[i]); Blky.GetBlkByID(JCDb.GetJCByIndex(jcs[i]).data.NavestidloBlok, tmpblk); if ((TBlkSCom(tmpblk).Navest > 0) and (TBlkSCom(tmpblk).DNjc = jc)) then begin JCDB.GetJCByIndex(jcs[i]).RusJCWithoutBlk(); for j := 0 to (tmpBlk as TBlkScom).OblsRizeni.Cnt-1 do (tmpBlk as TBlkScom).OblsRizeni.ORs[j].BlkWriteError(Self, 'Chyba povolovací návěsti '+tmpblk.name, 'TECHNOLOGIE'); end; end;//for i end;//if jcindex <> -1 end;//procedure //////////////////////////////////////////////////////////////////////////////// function TJCDb.GetCount():Word; begin Result := Self.JCs.Count; end;//function //////////////////////////////////////////////////////////////////////////////// // najde index pro novou jizdni cestu function TJCDb.FindPlaceForNewJC(id:Integer):Integer; var i:Integer; begin i := Self.JCs.Count-1; while ((i >= 0) and (Self.JCs[i].id > id)) do i := i - 1; Result := i+1; end;//function //////////////////////////////////////////////////////////////////////////////// function TJCDb.IsJC(id:Integer; ignore_index:Integer = -1):boolean; var index:Integer; begin index := Self.GetJCIndex(id); Result := ((index <> -1) and (index <> ignore_index)); end; //////////////////////////////////////////////////////////////////////////////// // Hledame JC se zadanym ID v seznamu bloku pomoci binarniho vyhledavani. function TJCDb.GetJCIndex(id:Integer):Integer; var left, right, mid:Integer; begin left := 0; right := Self.JCs.Count-1; while (left <= right) do begin mid := (left + right) div 2; if (Self.JCs[mid].id = id) then Exit(mid); if (Self.JCs[mid].id > id) then right := mid - 1 else left := mid + 1; end; Result := -1; end; //////////////////////////////////////////////////////////////////////////////// function TJCDb.GetJCByID(id:integer):TJC; var index:Integer; begin Result := nil; index := Self.GetJCIndex(id); if (index > -1) then Result := Self.JCs[index]; end; //////////////////////////////////////////////////////////////////////////////// procedure TJCDb.JCIDChanged(index:Integer); var new_index, min_index, i:Integer; tmp:TJC; begin tmp := Self.JCs[index]; Self.JCs.Delete(index); new_index := FindPlaceForNewJC(tmp.id); // provedeme prehozeni bloku na jinou pozici Self.JCs.Insert(new_index, tmp); if (index = new_index) then Exit(); // od nejmensiho prohazovaneho indexu aktualizujeme indexy // aktualizjeme dokud indexy nesedi min_index := Min(new_index, index); for i := min_index to Self.JCs.Count-1 do if (Self.JCs[i].index = i) then break else Self.JCs[i].index := i; JCTableData.MoveJC(index, new_index); end; //////////////////////////////////////////////////////////////////////////////// procedure TJCDb.UpdateJCIndexes(); var i:Integer; begin for i := 0 to Self.JCs.Count-1 do Self.JCs[i].index := i; end; //////////////////////////////////////////////////////////////////////////////// initialization JCDb := TJCDb.Create(); finalization FreeAndNil(JCDb); end.//unit
unit dmEstadistica; interface uses SysUtils, Classes, DB, IBCustomDataSet, IBQuery; type TDato = record Dinero: Currency; Papel: Currency; Zona: integer; Mas_0, Mas_1, Mas_2, Mas_3, Mas: Integer; Menos_0, Menos_1, Menos_2, Menos_3, Menos: Integer; end; TDatos = array of TDato; PDato = ^TDato; PDatos = ^TDatos; TEstadistica = class(TDataModule) qData: TIBQuery; qDataDINERO: TIBBCDField; qDataPAPEL: TIBBCDField; qDataZONA: TIBStringField; qDataVARIACION: TIBBCDField; qDataFLAGS: TIntegerField; procedure DataModuleCreate(Sender: TObject); private public Datos: TDatos; end; implementation uses dmBD, dmData, flags; {$R *.dfm} procedure TEstadistica.DataModuleCreate(Sender: TObject); var subida: Currency; dinero, papel: currency; zona: Byte; dato: PDato; num: integer; flags: TFlags; function get(const dinero, papel: Currency; const zona: integer): PDato; var i: integer; begin for i := Low(Datos) to High(Datos) do begin if (Datos[i].Dinero = dinero) and (Datos[i].Papel = papel) and (Datos[i].Zona = Zona) then begin result := @Datos[i]; exit; end; end; result := nil; end; begin flags := TFlags.Create; qData.Params[0].AsInteger := Data.OIDValor; qData.Open; qData.Last; subida := qDataVARIACION.Value; qData.Prior; while not qData.bof do begin if qDataDINERO.IsNull then begin flags.Free; exit; end; flags.Flags := qDataFLAGS.Value; if flags.Es(cInicioCiclo) or flags.Es(cInicioCicloVirtual) then begin dinero := qDataDINERO.Value; papel := qDataPAPEL.Value; zona := qDataZONA.AsInteger; dato := get(dinero, papel, zona); if dato = nil then begin num := Length(Datos); SetLength(Datos, num + 1); Datos[num].Dinero := dinero; Datos[num].Papel := papel; Datos[num].Zona := zona; Datos[num].Mas_0 := 0; Datos[num].Mas_1 := 0; Datos[num].Mas_2 := 0; Datos[num].Mas_3 := 0; Datos[num].Mas := 0; Datos[num].Menos_0 := 0; Datos[num].Menos_1 := 0; Datos[num].Menos_2 := 0; Datos[num].Menos_3 := 0; Datos[num].Menos := 0; dato := @Datos[num]; end; if subida > 0 then begin if subida < 1 then begin dato^.Mas_0 := dato^.Mas_0 + 1; end else begin if (subida >= 1) and (subida < 2) then begin dato^.Mas_1 := dato^.Mas_1 + 1; end else begin if (subida >= 2) and (subida < 3) then begin dato^.Mas_2 := dato^.Mas_2 + 1; end else begin if (subida >= 3) and (subida < 4) then begin dato^.Mas_3 := dato^.Mas_3 + 1; end else begin dato^.Mas := dato^.Mas + 1; end; end; end; end; end else begin if subida > -1 then begin dato^.Menos_0 := dato^.Menos_0 + 1; end else begin if (subida <= -1) and (subida > -2) then begin dato^.Menos_1 := dato^.Menos_1 + 1; end else begin if (subida <= -2) and (subida > -3) then begin dato^.Menos_2 := dato^.Menos_2 + 1; end else begin if (subida <= -3) and (subida > -4) then begin dato^.Menos_3 := dato^.Menos_3 + 1; end else begin dato^.Menos := dato^.Menos + 1; end; end; end; end; end; end; subida := qDataVARIACION.Value; qData.Prior; end; flags.Free; end; end.
{***************************************************************************} { } { DUnitX } { } { Copyright (C) 2015 Vincent Parrett & Contributors } { } { vincent@finalbuilder.com } { http://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DUnitX.Utils.XML; interface {$I DUnitX.inc} function IsValidXMLChar(const wc: WideChar): Boolean; function StripInvalidXML(const s: string): string; function EscapeForXML(const value: string; const isAttribute: boolean = True; const isCDATASection : Boolean = False): string; implementation uses {$IFDEF USE_NS} System.SysUtils; {$ELSE} SysUtils; {$ENDIF} function IsValidXMLChar(const wc: WideChar): Boolean; begin case Word(wc) of $0009, $000A, $000C, $000D, $0020..$D7FF, $E000..$FFFD, // Standard Unicode chars below $FFFF $D800..$DBFF, // High surrogate of Unicode character = $10000 - $10FFFF $DC00..$DFFF: // Low surrogate of Unicode character = $10000 - $10FFFF result := True; else result := False; end; end; function StripInvalidXML(const s: string): string; var i, count: Integer; begin {$IFNDEF NEXTGEN} count := Length(s); setLength(result, count); for i := 1 to Count do // Iterate begin if IsValidXMLChar(WideChar(s[i])) then result[i] := s[i] else result[i] := ' '; end; // for} {$ELSE} count := s.Length; SetLength(result, count); for i := 0 to count - 1 do // Iterate begin if IsValidXMLChar(s.Chars[i]) then begin result := result.Remove(i, 1); result := result.Insert(i, s.Chars[i]); end else begin result := result.Remove(i, 1); result := result.Insert(i, s.Chars[i]); end; end; // for} {$ENDIF} end; function EscapeForXML(const value: string; const isAttribute: boolean = True; const isCDATASection : Boolean = False): string; begin result := StripInvalidXML(value); {$IFNDEF NEXTGEN} if isCDATASection then begin Result := StringReplace(Result, ']]>', ']>',[rfReplaceAll]); exit; end; //note we are avoiding replacing &amp; with &amp;amp; !! Result := StringReplace(result, '&amp;', '[[-xy-amp--]]',[rfReplaceAll]); Result := StringReplace(result, '&', '&amp;',[rfReplaceAll]); Result := StringReplace(result, '[[-xy-amp--]]', '&amp;amp;',[rfReplaceAll]); Result := StringReplace(result, '<', '&lt;',[rfReplaceAll]); Result := StringReplace(result, '>', '&gt;',[rfReplaceAll]); if isAttribute then begin Result := StringReplace(result, '''', '&#39;',[rfReplaceAll]); Result := StringReplace(result, '"', '&quot;',[rfReplaceAll]); end; {$ELSE} if isCDATASection then begin Result := Result.Replace(']]>', ']>', [rfReplaceAll]); exit; end; //note we are avoiding replacing &amp; with &amp;amp; !! Result := Result.Replace('&amp;', '[[-xy-amp--]]',[rfReplaceAll]); Result := Result.Replace('&', '&amp;',[rfReplaceAll]); Result := Result.Replace('[[-xy-amp--]]', '&amp;amp;',[rfReplaceAll]); Result := Result.Replace('<', '&lt;',[rfReplaceAll]); Result := Result.Replace('>', '&gt;',[rfReplaceAll]); if isAttribute then begin Result := Result.Replace('''', '&#39;',[rfReplaceAll]); Result := Result.Replace('"', '&quot;',[rfReplaceAll]); end; {$ENDIF} end; end.
unit uPedidoCabModel; interface uses System.Generics.Collections, uPedidoItemModel, System.SysUtils, System.Math; type TPedidoCabModel = class private FIDPed: Integer; FDtEmissao: TDate; FNumero: Integer; FCliente: String; FListaItensPedido: TObjectList<TPedidoItemModel>; FValorTotalPedido: Double; procedure ReordenarSequenciaItens; procedure SetCliente(const Value: String); public constructor Create; destructor Destroy; override; function AdicionarItem(oPedidoItem: TPedidoItemModel) : Integer; function RemoverItem(iIdItem: Integer) : Integer; function BuscarItemNoPedido(iIdItem: Integer) : Integer; function AlterarItem(oPedidoItem: TPedidoItemModel) : Integer; function ValidarDados(out sMsg: String): Integer; procedure AtualizarValorTotalPedido; published property IDPed: Integer read FIDPed write FIDPed; property DtEmissao: TDate read FDtEmissao write FDtEmissao; property Numero: Integer read FNumero write FNumero; property Cliente: String read FCliente write SetCliente; property ListaItensPedido: TObjectList<TPedidoItemModel> read FListaItensPedido write FListaItensPedido; property ValorTotalPedido: double read FValorTotalPedido write FValorTotalPedido; end; implementation uses Winapi.Windows, Vcl.Dialogs; { TPedidoCabModel } function TPedidoCabModel.AdicionarItem(oPedidoItem: TPedidoItemModel): Integer; var iIndice: Integer; begin FListaItensPedido.Add(TPedidoItemModel.Create); iIndice := FListaItensPedido.Count - 1; FListaItensPedido[iIndice].IDPed := FIDPed; FListaItensPedido[iIndice].IDItemSeq := iIndice + 1; FListaItensPedido[iIndice].IDItem := oPedidoItem.IDItem; FListaItensPedido[iIndice].Descricao := oPedidoItem.Descricao; FListaItensPedido[iIndice].Quantidade := oPedidoItem.Quantidade; FListaItensPedido[iIndice].ValorUnitario := oPedidoItem.ValorUnitario; AtualizarValorTotalPedido(); Result := FListaItensPedido.Count; end; procedure TPedidoCabModel.ReordenarSequenciaItens; var iCont: Integer; begin for iCont := 0 to FListaItensPedido.Count - 1 do FListaItensPedido[iCont].IDItemSeq := iCont + 1; end; procedure TPedidoCabModel.SetCliente(const Value: String); begin if Length(Value) > 100 then begin raise EArgumentException.Create('A identificação do cliente deve ter no máximo 100 caracteres.'); end; FCliente := Value; end; function TPedidoCabModel.ValidarDados(out sMsg: String): Integer; begin if FNumero = 0 then begin sMsg := 'O número do pedido deve ser maior que zero!'; Result := -1; Exit; end; if FDtEmissao > Date() then begin sMsg := 'A data de emissão do pedido não pode ser maior que a data atual!'; Result := -1; Exit; end; if Length(FCliente) < 5 then begin sMsg := 'Digite um nome de cliente com pelo menos 5 caracteres!'; Result := -1; Exit; end; if Length(FCliente) > 100 then begin sMsg := 'A identificação do cliente deve ter no máximo 100 caracteres!'; Result := -1; Exit; end; if FListaItensPedido.Count = 0 then begin sMsg := 'O pedido não contém nenhum item!'; Result := -1; Exit; end; Result := 1; end; function TPedidoCabModel.AlterarItem(oPedidoItem: TPedidoItemModel): Integer; var iIndice: Integer; begin iIndice := BuscarItemNoPedido(oPedidoItem.IDItem); FListaItensPedido[iIndice].Quantidade := oPedidoItem.Quantidade; FListaItensPedido[iIndice].ValorUnitario := oPedidoItem.ValorUnitario; AtualizarValorTotalPedido(); Result := iIndice; end; procedure TPedidoCabModel.AtualizarValorTotalPedido; var iCont: Integer; dAuxiliar: Double; begin FValorTotalPedido := 0; for iCont := 0 to FListaItensPedido.Count - 1 do begin dAuxiliar := FListaItensPedido[iCont].Quantidade * FListaItensPedido[iCont].ValorUnitario; dAuxiliar := SimpleRoundTo(dAuxiliar, -2); FValorTotalPedido := FValorTotalPedido + dAuxiliar; end; end; function TPedidoCabModel.BuscarItemNoPedido(iIdItem: Integer): Integer; var iIndice: Integer; begin Result := -1; for iIndice := 0 to FListaItensPedido.Count -1 do begin if FListaItensPedido[iIndice].IDItem = iIdItem then begin Result := iIndice; Exit; end; end; end; constructor TPedidoCabModel.Create; begin FListaItensPedido := TObjectList<TPedidoItemModel>.Create; end; destructor TPedidoCabModel.Destroy; begin if Assigned(FListaItensPedido) then begin FreeAndNil(FListaItensPedido); end; inherited; end; function TPedidoCabModel.RemoverItem(iIdItem: Integer): Integer; begin Result := BuscarItemNoPedido(iIdItem); if Result >= 0 then begin ListaItensPedido.Delete(Result); ReordenarSequenciaItens; AtualizarValorTotalPedido(); end; end; end.
unit PDEInterface; interface uses Classes, Datenbank{, u_types_att}; type IPdeConnection = interface function Login(const user, passwd: string): boolean; function IsConnected(): boolean; function GetVersion(): string; function GetUserName(): string; function GetUserLevel(): integer; procedure SetMessageHandle(phandle: tfptr_debug); procedure SetConnectStr(connstr: string); procedure Logout(); property ConnectStr: string write SetConnectStr; property Connected: boolean read IsConnected; property UnitVersion: string read GetVersion; property UserName: string read GetUserName; property UserLevel: integer read GetUserLevel; end; TPdeConnection = class(TInterfacedObject, IPdeConnection) protected t_conn: t_db_connection; public constructor Create(const conn: t_db_connection); overload; destructor Destroy; override; function Login(const user, passwd: string): boolean; function IsConnected(): boolean; function GetVersion(): string; function GetUserName(): string; function GetUserLevel(): integer; procedure SetMessageHandle(phandle: tfptr_debug); procedure SetConnectStr(connstr: string); procedure Logout(); property ConnectStr: string write SetConnectStr; property Connected: boolean read IsConnected; property UnitVersion: string read GetVersion; property UserName: string read GetUserName; property UserLevel: integer read GetUserLevel; end; IPdeTestData = interface procedure SetProductID(const prodid: string); procedure SetTestStationID(const tsid: string); procedure SetContractNr(const cntrnr: string); procedure SetContractNrLen(const lmin, lmax: integer); procedure SetVersion(const evers: t_vers_enum; const verstr: string); procedure SetBoardNr(const boardnr: string); procedure SetSubBoardNr(const boardnr: string); procedure SetDeviceNr(const devnr: string); procedure SetTestBegin(startdt: TDateTime); procedure SetTestEnd(enddt: TDateTime); procedure SetTestMode(const tm: t_en_db_testmode); procedure SetResultOK(); procedure SetResultError(const stepnr: double; const func, actval, refval: string); procedure SetErrorCode(const errcode: string); procedure SetComment(const cmnt: string); procedure AddMeasValue(const stepnr, sval: string); procedure ClearAll(); procedure ClearResult(); procedure ClearComments(); procedure ClearMeasValues(); procedure ClearVersionInfo(); property ProductID: string write SetProductID; property TestStationID: string write SetTestStationID; property ContractNr: string write SetContractNr; property BoardNumber: string write SetBoardNr; property SubBoardNumber: string write SetSubBoardNr; property DeviceNumber: string write SetDeviceNr; property TestBegin: TDateTime write SetTestBegin; property TestEnd: TDateTime write SetTestEnd; property TestMode: t_en_db_testmode write SetTestMode; end; TPdeTestData = class(TInterfacedObject, IPdeTestData) protected t_conn: t_db_connection; t_tdata:t_db_infoblock; protected procedure ClearResultError(); public constructor Create(const tdata: t_db_infoblock; const conn: t_db_connection); overload; destructor Destroy; override; procedure SetProductID(const prodid: string); procedure SetTestStationID(const tsid: string); procedure SetContractNr(const cntrnr: string); procedure SetContractNrLen(const lmin, lmax: integer); procedure SetVersion(const evers: t_vers_enum; const verstr: string); procedure SetBoardNr(const boardnr: string); procedure SetSubBoardNr(const boardnr: string); procedure SetDeviceNr(const devnr: string); procedure SetTestBegin(startdt: TDateTime); procedure SetTestEnd(enddt: TDateTime); procedure SetTestMode(const tm: t_en_db_testmode); procedure SetResultOK(); procedure SetResultError(const stepnr: double; const func, actval, refval: string); procedure SetErrorCode(const errcode: string); procedure SetComment(const cmnt: string); procedure AddMeasValue(const stepnr, sval: string); procedure ClearAll(); procedure ClearResult(); procedure ClearComments(); procedure ClearMeasValues(); procedure ClearVersionInfo(); property ProductID: string write SetProductID; property TestStationID: string write SetTestStationID; property ContractNr: string write SetContractNr; property BoardNumber: string write SetBoardNr; property SubBoardNumber: string write SetSubBoardNr; property DeviceNumber: string write SetDeviceNr; property TestBegin: TDateTime write SetTestBegin; property TestEnd: TDateTime write SetTestEnd; property TestMode: t_en_db_testmode write SetTestMode; end; IPdeActor = interface function CheckContractNr(): boolean; function CheckConsistency(): boolean; function CheckBoardNr(): boolean; function AddComment(idx: integer): boolean; procedure WriteResult(); procedure SetMeasValueActive(const active: boolean); procedure SetVersInfoActive(const active: boolean); end; TPdeAdapter = class(TInterfacedObject, IPdeActor, IPdeConnection, IPdeTestData) protected t_infoblock:t_db_infoblock; t_dbconn: t_db_connection; t_connimpl: TPdeConnection; t_dataimpl: TPdeTestData; b_vers: boolean; b_meas: boolean; protected function IsConnected(): boolean; public constructor Create(); destructor Destroy(); override; property ConnectionService: TPdeConnection read t_connimpl implements IPdeConnection; property TestDataService: TPdeTestData read t_dataimpl implements IPdeTestData; function CheckContractNr(): boolean; function CheckConsistency(): boolean; function CheckBoardNr(): boolean; function AddComment(idx: integer): boolean; procedure WriteResult(); procedure SetMeasValueActive(const active: boolean); procedure SetVersInfoActive(const active: boolean); property VersInfoActived: boolean read b_vers write SetVersInfoActive; property MeasValueActived: boolean read b_meas write SetMeasValueActive; End; implementation uses SysUtils; constructor TPdeConnection.Create(const conn: t_db_connection); begin inherited Create(); t_conn := conn; end; destructor TPdeConnection.Destroy; begin inherited Destroy(); end; function TPdeConnection.Login(const user, passwd: string): boolean; begin if assigned(t_conn) then result := t_conn.login(user, passwd) else result := false; end; function TPdeConnection.IsConnected(): boolean; begin if assigned(t_conn) then result := t_conn.connected else result := false; end; function TPdeConnection.GetVersion(): string; begin if assigned(t_conn) then result := t_conn.version else result := ''; end; function TPdeConnection.GetUserName(): string; begin if assigned(t_conn) then result := t_conn.user_name else result := ''; end; function TPdeConnection.GetUserLevel(): integer; begin if assigned(t_conn) then result := t_conn.user_level else result := -1; end; procedure TPdeConnection.SetMessageHandle(phandle: tfptr_debug); begin if assigned(t_conn) then t_conn.fptr_debug := phandle; end; procedure TPdeConnection.SetConnectStr(connstr: string); begin if assigned(t_conn) then t_conn.ConnectString := connstr; end; procedure TPdeConnection.Logout(); begin if assigned(t_conn) then t_conn.logout(); end; function TPdeAdapter.IsConnected(): boolean; begin result := t_dbconn.connected; end; procedure TPdeTestData.ClearResultError(); begin if assigned(t_tdata) then begin t_tdata.my_error_info.f_pruefschritt := 0.0; t_tdata.my_error_info.s_function := ''; t_tdata.my_error_info.s_value_actual := ''; t_tdata.my_error_info.s_value_ref := ''; end; end; constructor TPdeTestData.Create(const tdata: t_db_infoblock; const conn: t_db_connection); begin inherited Create(); t_tdata := tdata; t_conn := conn; end; destructor TPdeTestData.Destroy; begin inherited Destroy(); end; procedure TPdeTestData.SetProductID(const prodid: string); begin if assigned(t_tdata) then t_tdata.sap_main := prodid; end; procedure TPdeTestData.SetTestStationID(const tsid: string); begin if assigned(t_tdata) then t_tdata.id_pruefplatz := tsid; end; procedure TPdeTestData.SetContractNr(const cntrnr: string); begin if assigned(t_tdata) then t_tdata.fa_nr := cntrnr; end; procedure TPdeTestData.SetContractNrLen(const lmin, lmax: integer); begin if assigned(t_conn) then begin t_conn.fa_min_len := lmin; t_conn.fa_max_len := lmax; end; end; procedure TPdeTestData.SetVersion(const evers: t_vers_enum; const verstr: string); begin if assigned(t_tdata) then begin case evers of vinfo_exe: t_tdata.my_versinfo.s_vers_exe := verstr; vinfo_ini: t_tdata.my_versinfo.s_vers_ini := verstr; vinfo_psl: t_tdata.my_versinfo.s_vers_psl := verstr; vinfo_bl1: t_tdata.my_versinfo.s_vers_bl1 := verstr; vinfo_fw1: t_tdata.my_versinfo.s_vers_fw1 := verstr; vinfo_hw1: t_tdata.my_versinfo.s_vers_hw1 := verstr; vinfo_bl2: t_tdata.my_versinfo.s_vers_bl2 := verstr; vinfo_fw2: t_tdata.my_versinfo.s_vers_fw2 := verstr; vinfo_hw2: t_tdata.my_versinfo.s_vers_hw2 := verstr; vinfo_bl_simple: ; vinfo_fw_simple: ; vinfo_hw_simple: ; end; end; end; procedure TPdeTestData.SetBoardNr(const boardnr: string); begin if assigned(t_tdata) then t_tdata.s_boardnumber := boardnr; end; procedure TPdeTestData.SetSubBoardNr(const boardnr: string); begin //todo:; end; procedure TPdeTestData.SetDeviceNr(const devnr: string); begin if assigned(t_tdata) then t_tdata.s_devicenumber := devnr; end; procedure TPdeTestData.SetTestBegin(startdt: TDateTime); begin if assigned(t_tdata) then t_tdata.s_starttime := FormatDateTime('yyyy-mm-dd hh:nn:ss', startdt); end; procedure TPdeTestData.SetTestEnd(enddt: TDateTime); begin if assigned(t_tdata) then t_tdata.s_endtime := FormatDateTime('yyyy-mm-dd hh:nn:ss', enddt); end; procedure TPdeTestData.SetTestMode(const tm: t_en_db_testmode); begin if assigned(t_tdata) then t_tdata.en_testmode := tm; end; procedure TPdeTestData.SetResultOK(); begin if assigned(t_tdata) then begin t_tdata.b_result := true; ClearResultError(); end; end; procedure TPdeTestData.SetResultError(const stepnr: double; const func, actval, refval: string); begin if assigned(t_tdata) then begin t_tdata.b_result := false; t_tdata.my_error_info.f_pruefschritt := stepnr; t_tdata.my_error_info.s_function := func; t_tdata.my_error_info.s_value_actual := actval; t_tdata.my_error_info.s_value_ref := refval; end; end; procedure TPdeTestData.SetErrorCode(const errcode: string); begin if assigned(t_tdata) then t_tdata.s_errcode := errcode; end; procedure TPdeTestData.SetComment(const cmnt: string); begin if assigned(t_tdata) then t_tdata.s_comment := cmnt; end; procedure TPdeTestData.AddMeasValue(const stepnr, sval: string); begin if assigned(t_tdata) then t_tdata.add_mess_value(stepnr, sval); end; procedure TPdeTestData.ClearAll(); begin if assigned(t_tdata) then t_tdata.clear(); end; procedure TPdeTestData.ClearResult(); begin ClearResultError(); if assigned(t_tdata) then begin t_tdata.s_starttime := ''; t_tdata.s_endtime := ''; t_tdata.s_boardnumber := ''; t_tdata.s_devicenumber := ''; t_tdata.s_errcode := ''; t_tdata.s_comment := ''; t_tdata.b_result := FALSE; end; end; procedure TPdeTestData.ClearComments(); begin //todo: discuss about DBInterface with aha end; procedure TPdeTestData.ClearMeasValues(); begin //todo: discuss about DBInterface with aha end; procedure TPdeTestData.ClearVersionInfo(); begin if assigned(t_tdata) then begin t_tdata.my_versinfo.s_vers_exe := ''; t_tdata.my_versinfo.s_vers_ini := ''; t_tdata.my_versinfo.s_vers_psl := ''; t_tdata.my_versinfo.s_vers_bl1 := ''; t_tdata.my_versinfo.s_vers_fw1 := ''; t_tdata.my_versinfo.s_vers_hw1 := ''; t_tdata.my_versinfo.s_vers_bl2 := ''; t_tdata.my_versinfo.s_vers_fw2 := ''; t_tdata.my_versinfo.s_vers_hw2 := ''; end; end; constructor TPdeAdapter.Create(); begin inherited Create(); t_infoblock := t_db_infoblock.Create(); t_dbconn := t_db_connection.Create(); t_connimpl := TPdeConnection.Create(t_dbconn); t_dataimpl := TPdeTestData.Create(t_infoblock, t_dbconn); end; destructor TPdeAdapter.Destroy(); begin t_dataimpl.Free(); t_connimpl.Free(); t_dbconn.Free(); t_infoblock.Free(); inherited Destroy(); end; function TPdeAdapter.CheckContractNr(): boolean; begin result := t_infoblock.check_consistency_fa(t_dbconn) end; function TPdeAdapter.CheckConsistency(): boolean; begin result := t_infoblock.check_consistency_variant(t_dbconn); end; function TPdeAdapter.CheckBoardNr(): boolean; begin result := t_dbconn.check_boardnumber(t_infoblock.s_boardnumber); end; function TPdeAdapter.AddComment(idx: integer): boolean; begin try t_infoblock.add_comment(idx); result := true; except result := false; end; end; procedure TPdeAdapter.WriteResult(); begin t_infoblock.write_test_result(t_dbconn); end; procedure TPdeAdapter.SetMeasValueActive(const active: boolean); begin b_meas := active; end; procedure TPdeAdapter.SetVersInfoActive(const active: boolean); begin b_vers := active; end; end.
unit U_calculadora; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TFormCalculadora = class(TForm) Edt_Resultado: TEdit; btn_7: TButton; btn_8: TButton; btn_9: TButton; btn_somar: TButton; btn_4: TButton; btn_5: TButton; btn_6: TButton; btn_subtrair: TButton; btn_3: TButton; btn_1: TButton; btn_2: TButton; btn_Multiplicar: TButton; btn_igual: TButton; btn_Limpar: TButton; btn_0: TButton; btn_dividir: TButton; Label1: TLabel; procedure btn_somarClick(Sender: TObject); procedure btn_subtrairClick(Sender: TObject); procedure btn_MultiplicarClick(Sender: TObject); procedure btn_dividirClick(Sender: TObject); procedure NumeroClick(Sender: TObject); procedure btn_igualClick(Sender: TObject); procedure btn_LimparClick(Sender: TObject); procedure FormClick(Sender: TObject); private { Private declarations } Foperacao : Char; Ftotal : Double; //guardar valor total da opreção (numero com virgula) FUltimoNumero : Double; Procedure Calcular; Procedure Limpar; public { Public declarations } end; var FormCalculadora: TFormCalculadora; implementation {$R *.dfm} procedure TFormCalculadora.NumeroClick(Sender: TObject); begin if FUltimoNumero = 0 then Edt_Resultado.Text := TButton (Sender).Caption Else Edt_Resultado.Text := edt_Resultado.Text + TButton(Sender).Caption; FUltimoNumero := StrToFloat (Edt_Resultado.Text); end; procedure TFormCalculadora.btn_dividirClick(Sender: TObject); begin FUltimoNumero := StrToFloat(Edt_Resultado.text); Foperacao := '/'; Calcular; end; procedure TFormCalculadora.btn_igualClick(Sender: TObject); begin Calcular; end; procedure TFormCalculadora.btn_LimparClick(Sender: TObject); begin Limpar; end; procedure TFormCalculadora.btn_MultiplicarClick(Sender: TObject); begin FUltimoNumero := StrToFloat(Edt_Resultado.text); Calcular; Foperacao := '*'; end; procedure TFormCalculadora.btn_somarClick(Sender: TObject); begin FUltimoNumero := StrToFloat(Edt_Resultado.text); Calcular; Foperacao := '+'; //Alimentar a variavel Operação com o valor + end; procedure TFormCalculadora.btn_subtrairClick(Sender: TObject); begin FUltimoNumero := StrToFloat(Edt_Resultado.text); Calcular; Foperacao := '-'; end; procedure TFormCalculadora.Calcular; begin case FOperacao of '+' : Ftotal := Ftotal + StrToFloat (Edt_Resultado.Text); //valor total receberá o valor que está la mais o que vai ser digitado. '-' : Ftotal := Ftotal - StrToFloat (Edt_Resultado.Text); '*' : Ftotal := Ftotal * StrToFloat (Edt_Resultado.Text); '/' : Ftotal := Ftotal / StrToFloat (Edt_Resultado.Text); end; Edt_Resultado.Text := FloatToStr (Ftotal); FUltimoNumero := 0; end; procedure TFormCalculadora.FormClick(Sender: TObject); begin Limpar; end; procedure TFormCalculadora.Limpar; begin FUltimoNumero :=0; Edt_Resultado.Text := '0'; FOperacao := '+'; FTotal := 0; end; end.
unit itdTabSheetBase; {$I twcomp.pas} interface uses Classes, ComCtrls, uIITDFormWrapper, Vcl.Graphics, Controls, CAS_TABLE_CONTROLS, Messages, uITDSubForm, uTWCAxForm, Forms; type TITDTabsheetInfo = class; TITDTabSheetBase = class(TITDSubForm) protected afterLoadRec, afterNewRec: boolean; fHideTabOnNew: boolean; ignoreafterLoadedinPageChange: boolean; tabSheet: TTabSheet; haschanged: boolean; initialized: boolean; ignorepageControlChange: boolean; doneOnce: boolean; function getOwnerCASComponentByName(name : string) : TCASTableDataField; function getPageIndex: Integer; virtual; procedure DoOnceSucc; virtual; function afterLoaded: boolean; procedure activeTabsheetChangedTo(aTabSheet: TTabSheet); protected class function getTabSheetCaptionFromCache: String; class function loadTabSheetOnDemand: boolean; override; class function getTabCaption: String; virtual; class function getTabVisibility( formWrapper: IITDFormWrapper; aTabSheet: TTabSheet ): Boolean; virtual; class function getTabSheetInfoCache: TStringList; class function getTabsheetInfoFromCache: TITDTabsheetInfo; public constructor Create; reintroduce; overload; constructor Create( formWrapper: IITDFormWrapper ); overload; override; procedure InitForm( AParentForm: TTWCAxForm ); override; class function getTabName: String; virtual; procedure DoOnce; procedure initializeTabsheet; virtual; procedure WM_INCOMINGMESSAGE(var Message: TMessage); virtual; function getPageControl: TPageControl; virtual; procedure PageControl0Change(Sender: TObject; aActiveTabSheet: TTabsheet); override; procedure AfterNewRecord; override; procedure AfterLoadRecord; override; procedure AfterSaveRecord; override; function GetTabSheet: TTabSheet; override; procedure SetTabSheet( aTabSheet: TTabSheet ); procedure BeforeSetTabVisibleByType(atabSheet: TTabSheet; var aTabVisible: boolean); override; procedure SetupPresentationService; override; class function getFieldNames: TStringList; override; end; TITDTabsheetInfo = class private Caption: String; FieldList: TStringList; procedure addFieldNames(control: TWinControl); public constructor Create(itdTabsheet: TITDTabSheetBase); destructor Destroy; override; end; type TITDTabSheetClass = class of TITDTabSheetBase; type TITDSubFormContainerSheet = class( TTabSheet ) private itdForm: IITDFormWrapper; tabSheetClass: TITDTabSheetClass; subForm: TITDTabSheetBase; function getPageIndex( itdForm: IITDFormWrapper; aParentControl: TWinControl ): Integer; procedure showTabSheet( Sender: TObject); public constructor Create( itdForm: IITDFormWrapper; tabSheetClass: TITDTabSheetClass; aParentControl: TWinControl); reintroduce; function getTabVisibility( itdForm: IITDFormWrapper): Boolean; function createSubForm(): TITDTabSheetBase; function doCreateOnNew(): TITDTabSheetBase; function isSubFormLoaded(): boolean; function isSubFormVisible: boolean; procedure setSubFormVisible; private fUsedFields: TStringList; procedure fillUsedFields(tabSheetClass: TITDTabSheetClass); public destructor Destroy; override; function getUsedFields: TStringList; end; implementation {$R *.dfm} uses SysUtils, Dialogs, uTWCAxSubForm, Windows, twTools, CAS_TABLE; var tabSheetInfoCache: TStringList; function TITDSubFormContainerSheet.isSubFormLoaded(): boolean; begin Result := assigned(subForm); end; function TITDSubFormContainerSheet.getPageIndex( itdForm: IITDFormWrapper; aParentControl: TWinControl ): Integer; begin if ( aParentControl is TTabSheet ) then Result := ( aParentControl as TTabSheet ).PageIndex + 1 else if assigned( itdForm.getForm() ) then Result := itdForm.getForm().TSAdditionalFields.PageIndex else Result := itdForm.getPageControl.PageCount - 1; end; procedure TITDSubFormContainerSheet.showTabSheet( Sender: TObject); begin createSubForm; end; function TITDSubFormContainerSheet.doCreateOnNew(): TITDTabSheetBase; begin if not Assigned( subForm ) then begin if tabSheetClass.createonNew(itdform) then createSubForm(); end; Result := subForm; end; function TITDSubFormContainerSheet.createSubForm: TITDTabSheetBase; begin if not Assigned( subForm ) then begin subForm := tabSheetClass.Create( itdForm ); subForm.setTabSheet( self ); subForm.Parent := Nil; subForm.Visible := false; itdForm.getForm.RegisterSubForm( subForm ); subForm.Parent := self; itdForm := Nil; end; Result := subForm; end; destructor TITDSubFormContainerSheet.Destroy; begin if assigned(fUsedFields) then FreeAndNil(fUsedFields); inherited; end; constructor TITDSubFormContainerSheet.Create( itdForm: IITDFormWrapper; tabSheetClass: TITDTabSheetClass; aParentControl: TWinControl ); begin inherited Create( itdForm.getForm ); self.itdForm := itdForm; self.tabSheetClass := tabSheetClass; if itdForm.getPageControl() = nil then Visible := false else begin Parent := itdForm.getPageControl(); PageControl := itdForm.getPageControl(); end; Name := tabSheetClass.getTabName; Caption := tabSheetClass.getTabCaption; PageIndex := getPageIndex( itdForm, aParentControl ); OnShow := showTabSheet; fillUsedFields(tabSheetClass); end; procedure TITDSubFormContainerSheet.fillUsedFields(tabSheetClass: TITDTabSheetClass); var lfieldNames: TStringList; begin lfieldNames := tabSheetClass.getFieldNames(); if assigned(lfieldNames) and (lfieldNames.Count > 0) then begin fUsedFields := TStringList.Create; fUsedFields.AddStrings(lfieldNames); end; end; function TITDSubFormContainerSheet.getTabVisibility( itdForm: IITDFormWrapper): Boolean; begin Result := tabSheetClass.getTabVisibility( itdForm, self ); end; function TITDSubFormContainerSheet.isSubFormVisible: boolean; begin if Assigned( subForm ) and subForm.Visible then Result := true else Result := false; end; procedure TITDSubFormContainerSheet.setSubFormVisible; begin subForm.Visible := true; end; class function TITDTabSheetBase.getTabSheetCaptionFromCache: String; var tabInfo: TITDTabsheetInfo; begin tabInfo := getTabsheetInfoFromCache(); if not Assigned(tabInfo) then Exit( '' ); Result := tabInfo.Caption; end; class function TITDTabSheetBase.getTabSheetInfoCache: TStringList; begin if not Assigned( tabSheetInfoCache ) then tabSheetInfoCache := TStringList.Create(true); Result := tabSheetInfoCache; end; class function TITDTabSheetBase.getTabsheetInfoFromCache: TITDTabsheetInfo; var idx: Integer; dummy: TITDTabSheetBase; begin idx := getTabSheetInfoCache().IndexOf(ClassName); if idx > -1 then Exit(getTabSheetInfoCache().Objects[idx] as TITDTabsheetInfo); dummy := Create; Result := TITDTabsheetInfo.Create(dummy); getTabSheetInfoCache().AddObject(ClassName, Result); dummy.Free; end; constructor TITDTabSheetBase.Create; begin inherited Create; end; constructor TITDTabSheetBase.Create( formWrapper: IITDFormWrapper ); begin inherited Create( formWrapper ); doneOnce := false; fHideTabOnNew := false; initialized := false; afterLoadRec := false; afterNewRec := false; ignoreafterLoadedinPageChange := false; ignorepageControlChange := false; end; procedure TITDTabSheetBase.InitForm( AParentForm: TTWCAxForm ); begin inherited InitForm( AParentForm ); if assigned( tabSheet ) then exit; tabSheet := TTabSheet.Create( self.Owner ); if getPageControl() = nil then tabSheet.Visible := false else begin tabSheet.Parent := getPageControl(); tabSheet.PageControl := getPageControl(); end; tabSheet.Name := getTabName; tabSheet.Caption := Caption; tabSheet.PageIndex := getPageIndex; Parent := tabSheet; ParentBackGround := true; end; class function TITDTabSheetBase.getFieldNames: TStringList; var tabInfo: TITDTabsheetInfo; begin tabInfo := getTabsheetInfoFromCache(); if not Assigned(tabInfo) then Exit(nil); Result := tabInfo.FieldList; end; function TITDTabSheetBase.getOwnerCASComponentByName(name : string) : TCASTableDataField; var i : integer; begin for i:=0 to Owner.ComponentCount-1 do begin if Sametext(Owner.Components[i].name, name) then begin Result := Owner.Components[i] as TCASTableDataField; exit; end; end; Result := nil; end; class function TITDTabSheetBase.getTabName: String; begin Result := ''; end; procedure TITDTabSheetBase.initializeTabsheet; begin initialized := true; DoOnce; end; procedure TITDTabSheetBase.WM_INCOMINGMESSAGE(var Message: TMessage); begin end; function TITDTabSheetBase.getPageIndex: Integer; begin if ( Parent is TTabSheet ) then Result := ( Parent as TTabSheet ).PageIndex + 1 else if assigned( itdForm.getForm() ) then Result := itdForm.getForm().TSAdditionalFields.PageIndex else Result := itdForm.getPageControl.PageCount - 1; end; function TITDTabSheetBase.getPageControl: TPageControl; begin Result := itdForm.getPageControl; end; procedure TITDTabSheetBase.PageControl0Change(Sender: TObject; aActiveTabSheet: TTabsheet); begin inherited; activeTabsheetChangedTo(aActiveTabSheet); end; procedure TITDTabSheetBase.AfterNewRecord; begin inherited; afterNewRec := true; end; procedure TITDTabSheetBase.AfterLoadRecord; begin inherited; afterLoadRec := true; end; procedure TITDTabSheetBase.AfterSaveRecord; begin inherited; afterLoadRec := false; afterNewRec := false; end; function TITDTabSheetBase.getTabsheet: TTabSheet; begin Result := tabSheet; end; procedure TITDTabSheetBase.DoOnce; begin if not doneOnce then begin doneOnce := true; DoOnceSucc; end; end; procedure TITDTabSheetBase.DoOnceSucc; begin end; function TITDTabSheetBase.afterLoaded: boolean; begin result := afterLoadRec or afterNewRec; end; procedure TITDTabSheetBase.BeforeSetTabVisibleByType(atabSheet: TTabSheet; var aTabVisible: boolean); begin inherited BeforeSetTabVisibleByType(atabSheet, aTabVisible); if fHideTabOnNew then if aTabVisible and assigned(tabSheet) and (atabSheet = tabSheet) then begin if (itdForm.getFMode = fmNew) or (itdForm.getFMode = fmDuplicate) then aTabVisible := false; end; end; procedure TITDTabSheetBase.SetTabSheet( aTabSheet: TTabSheet ); begin tabSheet := aTabSheet; end; procedure TITDTabSheetBase.SetupPresentationService; begin inherited; activeTabsheetChangedTo(FAxForm.ThePageControl.ActivePage); end; procedure TITDTabSheetBase.activeTabsheetChangedTo(aTabSheet: TTabSheet); begin if not assigned( tabSheet ) or ignorepageControlChange then exit; if (aTabSheet = tabSheet) and (ignoreafterLoadedinPageChange or afterLoaded) then //zum Schluss soll PageControl0Change nochmal kommen begin initializeTabSheet; if not Visible then begin Resize; Refresh; Application.ProcessMessages; Visible := true; end; end; end; class function TITDTabSheetBase.loadTabSheetOnDemand: boolean; begin Result := true; end; class function TITDTabSheetBase.getTabCaption: String; begin Result := getTabSheetCaptionFromCache; end; { TITDTabsheetInfo } procedure TITDTabsheetInfo.addFieldNames(control: TWinControl); var i: Integer; begin for i := 0 to control.ControlCount - 1 do begin if SameText(control.Controls[i].ClassName, 'TCASTABLEDATAFIELD') then begin if TCASTableDataField(control.Controls[i]).FieldName <> '' then FieldList.Add(TCASTableDataField(control.Controls[i]).FieldName); end else if control.Controls[i] is TWinControl then addFieldNames(control.Controls[i] as TWinControl); end; end; constructor TITDTabsheetInfo.Create(itdTabsheet: TITDTabSheetBase); begin if itdTabsheet.Caption <> '' then Caption := itdTabsheet.Caption else Caption := '~' + itdTabsheet.ClassName + '_' + itdTabsheet.UnitName; FieldList := TStringList.Create(); addFieldNames(itdTabsheet); end; class function TITDTabSheetBase.getTabVisibility( formWrapper: IITDFormWrapper; aTabSheet: TTabSheet ): Boolean; begin Result := true; end; destructor TITDTabsheetInfo.Destroy; begin FreeAndNilEx(FieldList); inherited; end; function TITDSubFormContainerSheet.getUsedFields: TStringList; begin Result := fUsedFields; end; end.
unit uPersistent; interface uses W3C.Console, SmartCL.System, System.Types; type EPersistent = Class(EW3Exception); IPersistent = Interface function objToString:String; procedure objFromString(const aData:String); procedure objReset; end; TPersistent = Class(TObject,IPersistent) private (* Implements:: IPersistent *) function objToString:String; Procedure objFromString(const aData:String); procedure objReset; protected Procedure AssignTo(const aTarget:TPersistent);virtual; public Procedure Assign(const aSource:TPersistent);virtual; End; TNamedValuePair = Record PropertyFieldName: String; PropertyFieldValue: Variant; GetterFieldValue: Variant; End; TNamedValuePairArray = Array of TNamedValuePair; TPersistentHelper = Class helper for TPersistent public class function getRTTIProperties(var aPairs:TNamedValuePairArray):Integer; class procedure setRTTIProperties(const aPairs:TNamedValuePairArray); end; implementation resourcestring CNT_ERR_TPERSISTENT_READ = 'Persistent read error [%s]'; CNT_ERR_TPERSISTENT_WRITE = 'Persistent write error [%s]'; //############################################################################# // TPersistentHelper //############################################################################# class procedure TPersistentHelper.setRTTIProperties (const aPairs:TNamedValuePairArray); var mRTTI: Array of TRTTIRawAttribute; mAttrib: TRTTIRawAttribute; mTypeId: TRTTITypeInfo; x,y: Integer; Begin if aPairs.length>0 then begin for y:=aPairs.low to aPairs.high do Begin mTypeId:=TypeOf(self.classtype); mRTTI:=RTTIRawAttributes; if mRtti.length>0 then Begin for x:=mRtti.low to mRtti.high do begin mAttrib:=mRtti[x]; //if (mAttrib.T = mTypeId) and (mAttrib.A is RTTIPropertyAttribute) then if (variant(mAttrib).T.ID = variant(mTypeId).ID) and (mAttrib.A is RTTIPropertyAttribute) then begin var prop := RTTIPropertyAttribute(mAttrib.A); if prop.name = aPairs[y].PropertyFieldName then prop.setter(variant(self),aPairs[y].PropertyFieldValue); //prop.setter(variant(self),aPairs[y].PropertyFieldValue); //prop.setter(variant(self),aPairs[y].PropertyFieldValue); end; end; end; end; end; end; class function TPersistentHelper.getRTTIProperties (var aPairs:TNamedValuePairArray):Integer; var mRTTI: Array of TRTTIRawAttribute; mAttrib: TRTTIRawAttribute; mTypeId: TRTTITypeInfo; x: Integer; mPair: TNamedValuePair; Begin aPairs.clear; result:=-1; mTypeId:=TypeOf(self.classtype); mRTTI:=RTTIRawAttributes; if mRtti.Length>0 then begin for x:=mRtti.Low to mRtti.High do begin mAttrib:=mRtti[x]; //if (mAttrib.T = mTypeId) and (mAttrib.A is RTTIPropertyAttribute) then if (variant(mAttrib).T.ID = variant(mTypeId).ID) and (mAttrib.A is RTTIPropertyAttribute) then begin var prop := RTTIPropertyAttribute(mAttrib.A); mPair.PropertyFieldName:=prop.name; mPair.PropertyFieldValue:=prop.Typ.Name; //Prop.Getter(Variant(self)); mPair.GetterFieldValue :=prop.Getter(Variant(Self)); aPairs.add(mPair); end; end; result:=aPairs.length; end; end; //############################################################################# // TPersistent //############################################################################# procedure TPersistent.objReset; var mData: TNamedValuePairArray; x: Integer; Begin if getRTTIProperties(mData)>0 then begin for x:=mData.low to mData.high do mData[x].PropertyFieldValue:=undefined; setRTTIProperties(mData); end; end; function TPersistent.objToString:String; var mData: TNamedValuePairArray; mCount: Integer; x: Integer; Begin mCount:=getRTTIProperties(mData); if mCount>0 then begin try asm @Result = JSON.stringify(@mData); console.log(@mData); end; finally mData.clear; end; end end; Procedure TPersistent.objFromString(const aData:String); var mData: TNamedValuePairArray; Begin if length(aData)>0 then Begin asm @mData = JSON.parse(@aData); console.log(@aData); end; if mData.length>0 then Begin setRTTIProperties(mData); mData.clear; end; end else objReset; end; Procedure TPersistent.Assign(const aSource:TPersistent); Begin if aSource<>NIL then Begin try objFromString(aSource.objToString); except on e: exception do Raise EPersistent.CreateFmt(CNT_ERR_TPERSISTENT_READ,[e.message]); end; end; end; procedure TPersistent.AssignTo(const aTarget: TPersistent); begin if aTarget<>NIL then begin try aTarget.objFromString(objToString); except on e: exception do Raise EPersistent.CreateFmt(CNT_ERR_TPERSISTENT_WRITE,[e.message]); end; end; end; end.
unit UtilWeb; interface uses UtilThread, WinInet, Classes, SysUtils; type EHTTP = class(Exception); ETimeOut = class(EHTTP); EHTTPNoHeaders = class(EHTTP); EHTTPInternetOpen = class(EHTTP); EHTTPInternetConnect = class(EHTTP); EHTTPOpenRequest = class(EHTTP); EHTTPSendRequest = class(EHTTP); EHTTPInternetReadFile = class(EHTTP); EHTTPSearchStatus = class(EHTTP); EHTTPClass = class of EHTTP; THTTP = class; THTTPThread = class (TProtectedThread) private FHttp: THTTP; FServer: string; FVerb: string; FURI: string; FParams: string; Port: Word; FHttpErrorCode: integer; FHttpErrorMsg: string; FHttpErrorClass: EHTTPClass; FHttpErrorInetMsg: string; FHttpError: boolean; FHttpStatus: integer; FHeaders: string; Buffer: TStream; constructor Create(const http: THTTP; const Server, Verb, URI, Params: string); procedure SearchHttpStatus(const hRequest: HINTERNET); procedure DownloadResponse(const hRequest: HINTERNET); procedure AcceptRequest(const hRequest: HINTERNET); procedure InformAcceptedRequest; procedure InformReceivedData; protected procedure InternalCancel; override; procedure InternalExecute; override; procedure FreeResources; override; procedure DoRequest; end; TOnAcceptedRequest = procedure (const headers: string) of object; THTTP = class private tiempoFinal: TDateTime; ThreadHandle: THandle; HTTPThread: THTTPThread; FHttpStatus: Integer; FHttpError: boolean; FHttpErrorCode: integer; FHttpErrorMsg: string; FCanceled: Boolean; FTimeOut: Cardinal; FOnAcceptedRequest: TOnAcceptedRequest; FOnHttpEnd: TNotifyEvent; FHttpErrorClass: EHTTPClass; FHttpErrorInetMsg: string; procedure AcceptedRequest(const headers: string); procedure ReceivedData; public constructor Create(const Server, Verb, URI, Params: string); overload; constructor Create(const Server, Verb, URI: string; const Params: TStringList); overload; constructor Create(const Server, Verb, URI: string); overload; destructor Destroy; override; procedure ExecuteSincrono(const Buffer: TStream; const TimeOut: Cardinal = 40000); procedure ExecuteAsincrono(const Buffer: TStream); // procedure WaitForThread; procedure Cancel; property Canceled: Boolean read FCanceled; property HttpErrorClass: EHTTPClass read FHttpErrorClass; property HttpErrorMsg: string read FHttpErrorMsg; property HttpErrorCode: integer read FHttpErrorCode; property HttpErrorInetMsg: string read FHttpErrorInetMsg; property HttpError: boolean read FHttpError; property HttpStatus: Integer read FHttpStatus; property OnAcceptedRequest: TOnAcceptedRequest read FOnAcceptedRequest write FOnAcceptedRequest; property OnHttpEnd: TNotifyEvent read FOnHttpEnd write FOnHttpEnd; end; THTTPPOST = class(THTTP) public constructor Create(const Server, URI, Params: string); reintroduce; overload; constructor Create(const Server, URI: string; const Params: TStringList); reintroduce; overload; constructor Create(const Server, URI: string); reintroduce; overload; end; implementation uses Windows, Forms, DateUtils; //http://stackoverflow.com/questions/1823542/how-to-send-a-http-post-request-in-delphi-using-wininet-api resourcestring S_EHTTP_GENERAL = 'No se ha podido establecer contacto con el servidor.' + sLineBreak + sLineBreak + 'Esto puede ser debido a varias causas: ' + sLineBreak + ' - No está conectado a Internet.' + sLineBreak + ' - El servidor no está disponible en estos momentos.' + sLineBreak + sLineBreak + 'Compruebe que su conexión a Internet funcione correctamente y si fuera así vuelva a intentarlo más tarde.'; S_EHTTP_READ = 'Se pudo conectar al servidor pero se ha perdido la conexión.'; S_TIMEOUT = 'Se ha superado el tiempo de espera máximo para que el servidor respondiera.' + sLineBreak + 'Compruebe que su conexión a Internet funcione correctamente y si fuera así vuelva a intentarlo más tarde.'; const // USER_AGENT = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3'; USER_AGENT = 'SymbolChart UtilWeb'; winetdll = 'wininet.dll'; function GetWinInetError(ErrorCode:Cardinal): string; var Len: Integer; Buffer: PChar; begin Len := FormatMessage( FORMAT_MESSAGE_FROM_HMODULE or FORMAT_MESSAGE_FROM_SYSTEM or FORMAT_MESSAGE_ALLOCATE_BUFFER or FORMAT_MESSAGE_IGNORE_INSERTS or FORMAT_MESSAGE_ARGUMENT_ARRAY, Pointer(GetModuleHandle(winetdll)), ErrorCode, 0, @Buffer, 0, nil); try while (Len > 0) and {$IFDEF UNICODE}(CharInSet(Buffer[Len - 1], [#0..#32, '.'])) {$ELSE}(Buffer[Len - 1] in [#0..#32, '.']) {$ENDIF} do Dec(Len); SetString(Result, Buffer, Len); finally LocalFree(HLOCAL(Buffer)); end; end; { THTTPThread } procedure THTTPThread.AcceptRequest(const hRequest: HINTERNET); const HEADER_BUFFER_SIZE = 4096; var dwBufLen, dwIndex: DWord; HeaderData: Array[0..HEADER_BUFFER_SIZE - 1] of Char; begin dwIndex := 0; dwBufLen := HEADER_BUFFER_SIZE; if HttpQueryInfo(hRequest, HTTP_QUERY_RAW_HEADERS_CRLF, @HeaderData, dwBufLen, dwIndex) then begin FHeaders := HeaderData; if not Canceled then Synchronize(InformAcceptedRequest); end else raise EHTTPNoHeaders.Create(S_EHTTP_GENERAL); end; constructor THTTPThread.Create(const http: THTTP; const Server, Verb, URI, Params: string); var i: integer; begin inherited Create(true); FHttp := http; FVerb := Verb; FURI := URI; FParams := Params; i := Pos(':', Server); if i > 0 then begin Port := StrToInt(Copy(Server, i + 1, length(Server))); FServer := Copy(Server, 1, i - 1); end else begin Port := INTERNET_DEFAULT_HTTP_PORT; FServer := Server; end; end; procedure THTTPThread.DoRequest; const // accept: packed array[0..1] of LPWSTR = (PChar('*/*'), nil); header: string = 'Content-Type: application/x-www-form-urlencoded'; var hSession, hConnect, hRequest: HINTERNET; AcceptTypes: Array[0..1] of PChar; Flags: Cardinal; begin if Canceled then raise ETerminateThread.Create; hSession := InternetOpen(PChar(USER_AGENT), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0); try if hSession = nil then raise EHTTPInternetOpen.Create(S_EHTTP_GENERAL); if Canceled then raise ETerminateThread.Create; hConnect := InternetConnect(hSession, PChar(FServer), Port, nil, nil, INTERNET_SERVICE_HTTP, 0, 0); try if hConnect = nil then raise EHTTPInternetConnect.Create(S_EHTTP_GENERAL); if Canceled then raise ETerminateThread.Create; // Preparing the request AcceptTypes[0] := PChar('*/*'); AcceptTypes[1] := nil; // Flags Flags := 0; Inc(Flags, INTERNET_FLAG_RELOAD); Inc(Flags, INTERNET_FLAG_HYPERLINK); Inc(Flags, INTERNET_FLAG_RESYNCHRONIZE); Inc(Flags, INTERNET_FLAG_PRAGMA_NOCACHE); Inc(Flags, INTERNET_FLAG_NO_CACHE_WRITE); hRequest := HttpOpenRequest(hConnect, PChar(FVerb), PChar(FURI), nil, nil, @AcceptTypes, Flags, 0); try if hRequest = nil then raise EHTTPOpenRequest.Create(S_EHTTP_GENERAL); if Canceled then raise ETerminateThread.Create; if not HttpSendRequest(hRequest, PChar(header), length(header), PChar(FParams), length(FParams)) then raise EHTTPSendRequest.Create(S_EHTTP_GENERAL); SearchHttpStatus(hRequest); AcceptRequest(hRequest); if Canceled then raise ETerminateThread.Create; DownloadResponse(hRequest); finally InternetCloseHandle(hRequest); end; finally InternetCloseHandle(hConnect); end; finally InternetCloseHandle(hSession); end; end; procedure THTTPThread.DownloadResponse(const hRequest: HINTERNET); var aBuffer: Array[0..4096] of Char; BytesRead: Cardinal; begin if Canceled then raise ETerminateThread.Create; if not InternetReadFile(hRequest, @aBuffer, SizeOf(aBuffer), BytesRead) then raise EHTTPInternetReadFile.Create(S_EHTTP_READ); while BytesRead > 0 do begin if Canceled then raise ETerminateThread.Create; Synchronize(Self, InformReceivedData); if Canceled then raise ETerminateThread.Create; Buffer.Write(aBuffer, BytesRead); if not InternetReadFile(hRequest, @aBuffer, SizeOf(aBuffer), BytesRead) then raise EHTTPInternetReadFile.Create(S_EHTTP_READ); end; end; procedure THTTPThread.FreeResources; begin inherited; if (FHttp <> nil) and (not Canceled) then begin FHttp.FHttpStatus := FHttpStatus; FHttp.FHttpError := FHttpError; FHttp.FHttpErrorCode := FHttpErrorCode; FHttp.FHttpErrorMsg := FHttpErrorMsg; FHttp.FHttpErrorClass := FHttpErrorClass; FHttp.FHttpErrorInetMsg := FHttpErrorInetMsg; end; end; procedure THTTPThread.InformAcceptedRequest; begin FHttp.AcceptedRequest(FHeaders); end; procedure THTTPThread.InformReceivedData; begin FHttp.ReceivedData; end; procedure THTTPThread.InternalCancel; begin inherited; FHttp.OnAcceptedRequest := nil; FHttp.OnHttpEnd := nil; end; procedure THTTPThread.InternalExecute; begin try DoRequest; except on e: EHTTP do begin FHttpError := true; FHttpErrorMsg := e.Message; FHttpErrorClass := EHTTPClass(e.ClassType); FHttpErrorInetMsg := GetWinInetError(GetLastError); end; end; end; procedure THTTPThread.SearchHttpStatus(const hRequest: HINTERNET); const HEADER_BUFFER_SIZE = 4096; var dwBufLen, dwIndex: DWord; HeaderData: Array[0..HEADER_BUFFER_SIZE - 1] of Char; begin dwIndex := 0; dwBufLen := HEADER_BUFFER_SIZE; if HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_CODE, @HeaderData, dwBufLen, dwIndex) then begin FHttpStatus := StrToIntDef(HeaderData, 0); end else raise EHTTPSearchStatus.Create(S_EHTTP_GENERAL); end; { THTTP } constructor THTTP.Create(const Server, Verb, URI, Params: string); begin inherited Create; HTTPThread := THTTPThread.Create(Self, Server, Verb, URI, Params); HTTPThread.SetNilOnFree(@HTTPThread); HTTPThread.FreeOnTerminate := true; end; procedure THTTP.AcceptedRequest(const headers: string); begin tiempoFinal := IncMilliSecond(Now, FTimeOut); if Assigned(FOnAcceptedRequest) then FOnAcceptedRequest(headers); end; procedure THTTP.Cancel; begin if HTTPThread <> nil then HTTPThread.Cancel; FCanceled := True; end; constructor THTTP.Create(const Server, Verb, URI: string); begin Create(Server, Verb, URI, ''); end; destructor THTTP.Destroy; var WaitResult: Cardinal; begin if HTTPThread <> nil then begin HTTPThread.Cancel; repeat WaitResult := MsgWaitForMultipleObjects(1, ThreadHandle, False, 4000, QS_ALLINPUT); if WaitResult = WAIT_TIMEOUT then begin HTTPThread.Free; end else Application.ProcessMessages; until (WaitResult <> WAIT_OBJECT_0 + 1) or Application.Terminated; repeat WaitResult := MsgWaitForMultipleObjects(1, ThreadHandle, False, 4000, QS_ALLINPUT); if WaitResult = WAIT_TIMEOUT then begin TerminateThread(ThreadHandle, 0); end else Application.ProcessMessages; until (WaitResult <> WAIT_OBJECT_0 + 1) or Application.Terminated; end; inherited; end; constructor THTTP.Create(const Server, Verb, URI: string; const Params: TStringList); var i, num: integer; cad: string; begin cad := ''; num := Params.Count - 1; if num >= 0 then begin cad := Params[num]; dec(num); for i := 0 to num do begin cad := cad + '&' + Params[i]; end; end; Create(Server, Verb, URI, cad); end; procedure THTTP.ExecuteAsincrono(const Buffer: TStream); begin FTimeOut := 0; HTTPThread.Buffer := Buffer; HTTPThread.SetNilOnFree(@HTTPThread); HTTPThread.Resume; end; procedure THTTP.ExecuteSincrono(const Buffer: TStream; const TimeOut: Cardinal); begin FTimeOut := TimeOut; HTTPThread.Buffer := Buffer; HTTPThread.SetNilOnFree(@HTTPThread); ThreadHandle := HTTPThread.Handle; HTTPThread.Resume; tiempoFinal := IncMilliSecond(Now, TimeOut); repeat Application.ProcessMessages; until (HTTPThread = nil) or (tiempoFinal < now); if HTTPThread <> nil then begin HTTPThread.Cancel; raise ETimeOut.Create(S_TIMEOUT); end; if Assigned(FOnHttpEnd) then FOnHttpEnd(Self); end; procedure THTTP.ReceivedData; begin tiempoFinal := IncMilliSecond(Now, FTimeOut); end; { procedure THTTP.WaitForThread; begin tiempoFinal := IncMilliSecond(Now, 3000); while (HTTPThread <> nil) and (tiempoFinal < now) do; end; } { THTTPPOST } constructor THTTPPOST.Create(const Server, URI, Params: string); begin inherited Create(Server, 'POST', URI, Params); end; constructor THTTPPOST.Create(const Server, URI: string; const Params: TStringList); begin inherited Create(Server, 'POST', URI, Params); end; constructor THTTPPOST.Create(const Server, URI: string); begin inherited Create(Server, 'POST', URI); end; end.
unit Vs.Pedido.Venda.Salvar; interface uses // Vs Vs.Pedido.Venda.Repositorio; type IPedidoVendaSalvar = interface ['{4C2732CB-EDEC-42B6-B525-FDA5696DCF10}'] function Executar(ACliente: string; AValor: Double): Integer; end; function PedidoVendaSalvar(APedidoVendaRepositorio: IPedidoVendaRepositorio): IPedidoVendaSalvar; implementation uses // Deb EventBus, // Vs Vs.Pedido.Venda.Entidade, Vs.Pedido.Venda.Salvar.Eventos; type TPedidoVendaSalvar = class(TInterfacedObject, IPedidoVendaSalvar) strict private FPedidoVendaRepositorio: IPedidoVendaRepositorio; public constructor Create(APedidoVendaRepositorio: IPedidoVendaRepositorio); destructor Destroy; override; class function Instancia(APedidoVendaRepositorio: IPedidoVendaRepositorio): IPedidoVendaSalvar; function Executar(ACliente: string; AValor: Double): Integer; end; function PedidoVendaSalvar(APedidoVendaRepositorio: IPedidoVendaRepositorio): IPedidoVendaSalvar; begin Result := TPedidoVendaSalvar.Instancia(APedidoVendaRepositorio); end; { TPedidoVendaSalvar } constructor TPedidoVendaSalvar.Create(APedidoVendaRepositorio: IPedidoVendaRepositorio); begin inherited Create; FPedidoVendaRepositorio := APedidoVendaRepositorio; end; destructor TPedidoVendaSalvar.Destroy; begin inherited; end; function TPedidoVendaSalvar.Executar(ACliente: string; AValor: Double): Integer; var LPedidoVenda: TPedidoVenda; begin LPedidoVenda := TPedidoVenda.Instancia(-1, ACliente, AValor); try Result := FPedidoVendaRepositorio.Salvar(LPedidoVenda); // Publica o evento de pedido de venda salvo GlobalEventBus.Post(EventoPedidoVendaSalvo(LPedidoVenda), ''); finally LPedidoVenda.Free; end; end; class function TPedidoVendaSalvar.Instancia(APedidoVendaRepositorio: IPedidoVendaRepositorio): IPedidoVendaSalvar; begin Result := Self.Create(APedidoVendaRepositorio); end; 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/ } { } { Software distributed under the License is distributed on an } { "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express } { or implied. See the License for the specific language } { governing rights and limitations under the License. } { } { Copyright Creative IT. } { Current maintainer: Eric Grange } { } {**********************************************************************} unit dwsWebServerHelpers; {$I dws.inc} interface uses Windows, Classes, SysUtils, Registry, dwsUtils, dwsXPlatform; type TDirectoryIndexInfo = class(TRefCountedObject) private FIndexFileName : String; public property IndexFileName : String read FIndexFileName write FIndexFileName; end; TDirectoryIndexCache = class private FLock : TFixedCriticalSection; FHash : TSimpleNameObjectHash<TDirectoryIndexInfo>; FIndexFileNames : TStrings; protected function CreateIndexInfo(const directory : String) : TDirectoryIndexInfo; public constructor Create; destructor Destroy; override; function IndexFileForDirectory(var path : String) : Boolean; procedure Flush; property IndexFileNames : TStrings read FIndexFileNames; end; TFileAccessInfo = class(TRefCountedObject) public CookedPathName : String; FileAttribs : Cardinal; DWScript : Boolean; end; // this class is not thread safe, use from a single thread TFileAccessInfoCache = class private FHash : TSimpleNameObjectHash<TFileAccessInfo>; FMaxSize, FSize : Integer; FCacheCounter : Cardinal; public constructor Create(const aMaxSize : Integer); destructor Destroy; override; function FileAccessInfo(const pathInfo : String) : TFileAccessInfo; inline; function CreateFileAccessInfo(const pathInfo : String) : TFileAccessInfo; procedure Flush; property CacheCounter : Cardinal read FCacheCounter write FCacheCounter; end; TMIMETypeInfo = class (TRefCountedObject) MIMEType : RawByteString; constructor CreateAuto(const ext : String); end; TMIMETypeInfos = TSimpleNameObjectHash<TMIMETypeInfo>; TMIMETypeCache = class private FList : TMIMETypeInfos; procedure Prime(const ext : String; const mimeType : RawByteString); public constructor Create; destructor Destroy; override; function MIMEType(const fileName : String) : RawByteString; end; // Decodes an http request URL and splits path & params // Skips initial '/' // Normalizes '/' to '\' for the pathInfo procedure HttpRequestUrlDecode(const s : RawByteString; var pathInfo, params : String); // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ procedure HttpRequestUrlDecode(const s : RawByteString; var pathInfo, params : String); var n, c : Integer; decodedBuffer : UTF8String; pIn : PAnsiChar; pOut : PAnsiChar; paramsOffset : PAnsiChar; begin n:=Length(s); if n=0 then begin pathInfo:=''; params:=''; Exit; end; SetLength(decodedBuffer, n); c:=0; // workaround for spurious compiler warning paramsOffset:=nil; pIn:=Pointer(s); if pIn^='/' then Inc(pIn); pOut:=Pointer(decodedBuffer); while True do begin case pIn^ of #0 : break; '%' : begin Inc(pIn); case pIn^ of '0'..'9' : c:=Ord(pIn^)-Ord('0'); 'a'..'f' : c:=Ord(pIn^)+(10-Ord('a')); 'A'..'F' : c:=Ord(pIn^)+(10-Ord('A')); else break; // invalid url end; Inc(pIn); case pIn^ of '0'..'9' : c:=(c shl 4)+Ord(pIn^)-Ord('0'); 'a'..'f' : c:=(c shl 4)+Ord(pIn^)+(10-Ord('a')); 'A'..'F' : c:=(c shl 4)+Ord(pIn^)+(10-Ord('A')); else break; // invalid url end; pOut^:=AnsiChar(c); end; '+' : pOut^:=' '; '?' : begin pOut^:='?'; if paramsOffset=nil then paramsOffset:=pOut; end; '/' : begin if paramsOffset=nil then pOut^:='\' else pOut^:='/'; end; else pOut^:=pIn^; end; Inc(pIn); Inc(pOut); end; if paramsOffset=nil then begin params:=''; n:=UInt64(pOut)-UInt64(Pointer(decodedBuffer)); SetLength(pathInfo, n); n:=MultiByteToWideChar(CP_UTF8, 0, Pointer(decodedBuffer), n, Pointer(pathInfo), n); SetLength(pathInfo, n); end else begin n:=UInt64(paramsOffset)-UInt64(Pointer(decodedBuffer)); SetLength(pathInfo, n); n:=MultiByteToWideChar(CP_UTF8, 0, Pointer(decodedBuffer), n, Pointer(pathInfo), n); SetLength(pathInfo, n); n:=UInt64(pOut)-UInt64(paramsOffset); SetLength(params, n); n:=MultiByteToWideChar(CP_UTF8, 0, Pointer(paramsOffset), n, Pointer(params), n); SetLength(params, n); end; end; // ------------------ // ------------------ TDirectoryIndexCache ------------------ // ------------------ // Create // constructor TDirectoryIndexCache.Create; begin inherited; FLock:=TFixedCriticalSection.Create; FHash:=TSimpleNameObjectHash<TDirectoryIndexInfo>.Create; FIndexFileNames:=TStringList.Create; end; // Destroy // destructor TDirectoryIndexCache.Destroy; begin inherited; FHash.Clean; FHash.Free; FLock.Free; FIndexFileNames.Free; end; // IndexFileForDirectory // function TDirectoryIndexCache.IndexFileForDirectory(var path : String) : Boolean; var indexInfo : TDirectoryIndexInfo; begin if not StrEndsWith(path, PathDelim) then path:=path+PathDelim; FLock.Enter; try indexInfo:=FHash.Objects[path]; if indexInfo=nil then begin indexInfo:=CreateIndexInfo(path); FHash.Objects[path]:=indexInfo; end; if indexInfo.IndexFileName<>'' then begin path:=indexInfo.IndexFileName; Result:=True; end else Result:=False; finally FLock.Leave; end; end; // Flush // procedure TDirectoryIndexCache.Flush; begin FLock.Enter; try FHash.Clean; FHash.Free; FHash:=TSimpleNameObjectHash<TDirectoryIndexInfo>.Create; finally FLock.Leave; end; end; // CreateIndexInfo // function TDirectoryIndexCache.CreateIndexInfo(const directory : String) : TDirectoryIndexInfo; var i : Integer; path, fileName : String; begin Result:=TDirectoryIndexInfo.Create; path:=IncludeTrailingPathDelimiter(directory); for i:=0 to IndexFileNames.Count-1 do begin fileName:=path+IndexFileNames[i]; if FileExists(fileName) then begin Result.IndexFileName:=fileName; Break; end; end; end; // ------------------ // ------------------ TFileAccessInfoCache ------------------ // ------------------ // Create // constructor TFileAccessInfoCache.Create(const aMaxSize : Integer); begin inherited Create; FHash:=TSimpleNameObjectHash<TFileAccessInfo>.Create; FMaxSize:=aMaxSize; end; // Destroy // destructor TFileAccessInfoCache.Destroy; begin FHash.Clean; FHash.Free; inherited; end; // FileAccessInfo // function TFileAccessInfoCache.FileAccessInfo(const pathInfo : String) : TFileAccessInfo; begin Result:=FHash.Objects[pathInfo]; end; // CreateFileAccessInfo // function TFileAccessInfoCache.CreateFileAccessInfo(const pathInfo : String) : TFileAccessInfo; begin if FSize=FMaxSize then Flush; Result:=TFileAccessInfo.Create; Result.CookedPathName:=pathInfo; FHash.AddObject(pathInfo, Result); Inc(FSize); end; // Flush // procedure TFileAccessInfoCache.Flush; begin FHash.Clean; FHash.Free; FHash:=TSimpleNameObjectHash<TFileAccessInfo>.Create; FSize:=0; end; // ------------------ // ------------------ TMIMETypeInfo ------------------ // ------------------ // CreateAuto // constructor TMIMETypeInfo.CreateAuto(const ext : String); var reg : TRegistry; begin reg:=TRegistry.Create; try reg.RootKey:=HKEY_CLASSES_ROOT; if reg.OpenKeyReadOnly(ext) and reg.ValueExists('Content Type') then MIMEType:=ScriptStringToRawByteString(reg.ReadString('Content Type')); if MIMEType='' then MIMEType:='application/unknown'; finally reg.Free; end; end; // ------------------ // ------------------ TMIMETypeCache ------------------ // ------------------ // Create // constructor TMIMETypeCache.Create; begin inherited; FList:=TMIMETypeInfos.Create; // prime the cache with common extensions Prime('.txt', 'text/plain'); Prime('.htm', 'text/html'); Prime('.html', 'text/html'); Prime('.js', 'text/javascript'); Prime('.css', 'text/css'); Prime('.png', 'image/png'); Prime('.jpg', 'image/jpeg'); Prime('.gif', 'image/gif'); end; // Destroy // destructor TMIMETypeCache.Destroy; begin inherited; FList.Clean; FList.Free; end; // MIMEType // function TMIMETypeCache.MIMEType(const fileName : String) : RawByteString; var ext : String; info : TMIMETypeInfo; begin ext:=ExtractFileExt(fileName); info:=FList.Objects[ext]; if info=nil then begin info:=TMIMETypeInfo.CreateAuto(ext); FList.Objects[ext]:=info; end; Result:=info.MIMEType; end; // Prime // procedure TMIMETypeCache.Prime(const ext : String; const mimeType : RawByteString); var info : TMIMETypeInfo; begin info:=TMIMETypeInfo.Create; info.MIMEType:=mimeType; FList.Objects[ext]:=info; end; end.
unit DiretorioBackup; interface uses Usuario; type TDiretorioBackup = class private FCodigo :Integer; FCaminho :String; FUsuario :TUsuario; FCodigoUsuario :Integer; procedure SetCaminho (const Value: String); procedure SetCodigo (const Value: Integer); procedure SetUsuario (const Value: TUsuario); procedure SetCodigoUsuario (const Value: Integer); public constructor Create; destructor Destroy; override; public property Codigo :Integer read FCodigo write SetCodigo; property Caminho :String read FCaminho write SetCaminho; property CodigoUsuario :Integer read FCodigoUsuario write SetCodigoUsuario; property Usuario :TUsuario read FUsuario write SetUsuario; end; implementation uses Repositorio, FabricaRepositorio, SysUtils; { TDiretorioBackup } constructor TDiretorioBackup.Create; begin self.FCodigo := 0; self.FCaminho := ''; self.FUsuario := nil; end; destructor TDiretorioBackup.Destroy; begin self.FUsuario := nil; inherited; end; procedure TDiretorioBackup.SetCaminho(const Value: String); begin FCaminho := Value; end; procedure TDiretorioBackup.SetCodigo(const Value: Integer); begin FCodigo := Value; end; procedure TDiretorioBackup.SetCodigoUsuario(const Value: Integer); begin FCodigoUsuario := Value; end; procedure TDiretorioBackup.SetUsuario(const Value: TUsuario); begin FUsuario := Value; if Assigned(self.FUsuario) then self.FCodigoUsuario := self.FUsuario.Codigo; end; end.
unit Multimeter; interface uses DeviceBase, IniFiles, Classes, RelayControl, TextMessage, ConfigBase; type ECurrentFlow = ( CF_DC, //direct current CF_AC //alternating current ); EContinueMode = ( CM_OFF, CM_ON ); EMeasureAction = ( MA_ANY, //undefinitive measurement MA_RES, //measure resistance MA_DCV, //measure direct voltage MA_ACV, //measure alternating voltage MA_DCI, //measure direct current MA_ACI, //measure alternating current MA_FREQ, //measure frequence MA_PERI, //measure period MA_TEMP //measure temperature ); IMultimeter = interface function MeasureR(var val: double): boolean; function MeasureDCV(var val: double): boolean; function MeasureACV(var val: double): boolean; function MeasureDCI(var val: double): boolean; function MeasureACI(var val: double): boolean; function MeasureF(var val: double): boolean; function MeasureP(var val: double): boolean; function MeasureT(var val: double): boolean; procedure SetMeasureRange(const meas:EMeasureAction; const range: double = 0.0); end; TMultimeter = class(TDeviceBase, IMultimeter) protected e_curma: EMeasureAction; //current setting for the measurement protected function InitFromFile(const sfile: string): boolean; virtual; function SwitchMeasurement(const meas: EMeasureAction): boolean; virtual; function ReadData(var val: double): boolean; virtual; procedure TriggerMesssure(); virtual; public constructor Create(owner: TComponent); override; destructor Destroy; override; function MeasureR(var val: double): boolean; virtual; function MeasureDCV(var val: double): boolean; virtual; function MeasureACV(var val: double): boolean; virtual; function MeasureDCI(var val: double): boolean; virtual; function MeasureACI(var val: double): boolean; virtual; function MeasureF(var val: double): boolean; virtual; function MeasureP(var val: double): boolean; virtual; function MeasureT(var val: double): boolean; virtual; procedure SetMeasureRange(const meas:EMeasureAction; const range: double); virtual; end; TMultimeterKeithley = class(TMultimeter, IRelayControl) protected e_cont : EContinueMode; //indicate if continue mode is shut on s_idn: string; t_relay: TRelayKeithley; protected function SwitchMeasurement(const meas: EMeasureAction): boolean; override; function ReadingValue(const elem: string): string; function ReadData(var val: double): boolean; override; //procedure TriggerMesssure(); virtual; public constructor Create(owner: TComponent); override; destructor Destroy(); override; property RelayControl: TRelayKeithley read t_relay implements IRelayControl; property ContinueMode : EContinueMode read e_cont write e_cont; function InitDevice(): boolean; override; function ReleaseDevice(): boolean; override; procedure SetMeasureRange(const meas:EMeasureAction; const range: double); override; end; implementation uses SysUtils, GenUtils, StrUtils, RS232; const // Keithley-Multimert 2700 C_KEITHLEY_BEEP_OFF = 'SYST:BEEP 0'; // Beep off C_KEITHLEY_CLEAR_ERROR = '*CLS'; // alle 'Event register' und 'error queue' loeschen C_KEITHLEY_SELF_TEST = '*TST?'; // Eigentest C_KEITHLEY_ID_QUERY = '*IDN?'; // string for querying identifer of the device C_KEITHLEY_RESET = '*RST'; // string for resetting the device C_KEITHLEY_FORMAT_ELEMENT = 'FORM:ELEM READ'; // Datenformat: element only read C_KEITHLEY_FORMAT_ASCII = 'FORM:DATA ASC'; // Datenformat: ASCII C_KEITHLEY_MEAS_ONE = 'INIT:CONT OFF'; // one-shot measurement mode C_KEITHLEY_MEAS_CONTINU = 'INIT:CONT ON'; // continuouse measurement mode C_KEITHLEY_MEAS_READ = 'READ?'; // Einzelmessung triggern C_KEITHLEY_DATA_ASK = 'DATA?'; // Daten lesen C_KEITHLEY_SET_FUNC = 'FUNC "%s"'; // set function to messure C_KEITHLEY_FUNC_ASK = 'FUNC?'; // ask for the current function of the messurement C_KEITHLEY_RANGE_SET = ':RANG %s'; // set range of the measurement, it must be used with measurement function together C_KEITHLEY_RANGE_AUTO_ON = ':RANG:AUTO ON'; // turn on automatical range C_KEITHLEY_RANGE_AUTO_OFF = ':RANG:AUTO OFF'; // trun off automatical range C_KEITHLEY_OVERFLOW = '+9.9E37'; // overflowing data C_KEITHLEY_FUNC: array[EMeasureAction] of string = ( 'ANY', 'RES', 'VOLT:DC', 'VOLT:AC', 'CURR:DC', 'CURR:AC', 'FREQ', 'PER', 'TEMP' ); C_KEITHLEY_UNITS: array[EMeasureAction] of string = ( 'ANY', 'OHM', 'VDC', 'VAC', 'ADC', 'AAC', 'HZ', 'SEC', '°C' ); C_KEITHLEY_RANGE: array[EMeasureAction] of single = ( 0.0, //not in use 120.0e6, 1010.0, 757.5, 3.0, 3.0, 0.0, //not in use 0.0, //not in use 0.0 //not in use ); function TMultimeter.InitFromFile(const sfile: string): boolean; begin result := false; t_msgrimpl.AddMessage(format('"%s.InitFromFile" must be reimplemented in its subclass.', [ClassName()]), ML_ERROR); end; function TMultimeter.SwitchMeasurement(const meas: EMeasureAction): boolean; begin result := (Ord(meas) > Ord(MA_ANY)) and (Ord(meas) <= Ord(MA_TEMP)); //t_msgrimpl.AddMessage(format('"%s.SwitchMeasurement" must be reimplemented in its subclass.', [ClassName()]), ML_ERROR); end; function TMultimeter.ReadData(var val: double): boolean; begin result := false; t_msgrimpl.AddMessage(format('"%s.ReadData" must be reimplemented in its subclass.', [ClassName()]), ML_ERROR); end; procedure TMultimeter.TriggerMesssure(); begin //todo: if it's neccessary end; constructor TMultimeter.Create(owner: TComponent); begin inherited Create(owner); e_curma := MA_ANY; end; destructor TMultimeter.Destroy; begin inherited Destroy; end; function TMultimeter.MeasureR(var val: double): boolean; begin val := 0.0; if SwitchMeasurement(MA_RES) then result := ReadData(val) else result := false; end; function TMultimeter.MeasureDCV(var val: double): boolean; begin val := 0.0; if SwitchMeasurement(MA_DCV) then result := ReadData(val) else result := false; end; function TMultimeter.MeasureACV(var val: double): boolean; begin val := 0.0; if SwitchMeasurement(MA_ACV) then result := ReadData(val) else result := false; end; function TMultimeter.MeasureDCI(var val: double): boolean; begin val := 0.0; if SwitchMeasurement(MA_DCI) then result := ReadData(val) else result := false; end; function TMultimeter.MeasureACI(var val: double): boolean; begin val := 0.0; if SwitchMeasurement(MA_ACI) then result := ReadData(val) else result := false; end; function TMultimeter.MeasureF(var val: double): boolean; begin val := 0.0; if SwitchMeasurement(MA_FREQ) then result := ReadData(val) else result := false; end; function TMultimeter.MeasureP(var val: double): boolean; begin val := 0.0; if SwitchMeasurement(MA_PERI) then result := ReadData(val) else result := false; end; function TMultimeter.MeasureT(var val: double): boolean; begin val := 0.0; if SwitchMeasurement(MA_TEMP) then result := ReadData(val) else result := false; end; procedure TMultimeter.SetMeasureRange(const meas:EMeasureAction; const range: double); begin t_msgrimpl.AddMessage(format('"%s.SetMeasurementRange" must be reimplemented in its subclass.', [ClassName()]), ML_WARNING); end; function TMultimeterKeithley.SwitchMeasurement(const meas: EMeasureAction): boolean; var s_sending, s_recv: string; begin result := inherited SwitchMeasurement(meas); if result then begin if (e_curma <> meas) then begin s_sending := format(C_KEITHLEY_SET_FUNC, [C_KEITHLEY_FUNC[meas]]) + Char(13); result := t_curconn.SendStr(s_sending); end; if result then begin result := t_curconn.SendStr(C_KEITHLEY_FUNC_ASK + Char(13)); if result then begin result := t_curconn.ExpectStr(s_recv, Char(13), false); s_recv := TGenUtils.ClearQuotationMarks(trim(s_recv)); if result then result := SameText(s_recv, C_KEITHLEY_FUNC[meas]); end; if result then e_curma := meas else e_curma := MA_ANY; end else result := false; end; if result then t_msgrimpl.AddMessage(format('Successful to switch to the measurement(%s).', [C_KEITHLEY_FUNC[meas]])) else t_msgrimpl.AddMessage(format('Failed to switch to the measurement(%s).', [C_KEITHLEY_FUNC[meas]]), ML_ERROR); end; //return the value string of keithley reading element //NOTE: the measurement data is composed of several elements, e.g. //+4.69781780E+00OHM,+8179.250SECS,+46802RDNG#,000,0000LIMITS //this function gives back the first value string without unit function TMultimeterKeithley.ReadingValue(const elem: string): string; var i_pos: integer; begin i_pos := AnsiPos(',', elem); if (i_pos > 0) then result := trim(AnsiLeftStr(elem, i_pos - 1)) else result := trim(elem); if EndsText(C_KEITHLEY_UNITS[e_curma], result) then result := AnsiLeftStr(result, length(result) - length(C_KEITHLEY_UNITS[e_curma])); //keithley multimeter sends data only with '.' as decimal separator //it has to be changed into the local format result := TGenUtils.ReplaceDecimalSeparator(result); end; function TMultimeterKeithley.ReadData(var val: double): boolean; var s_recv: string; begin result := t_curconn.SendStr(C_KEITHLEY_MEAS_READ + Char(13)); if result then begin result := t_curconn.ExpectStr(s_recv, Char(13), false); if result then begin if StartsText(C_KEITHLEY_OVERFLOW, s_recv) then t_msgrimpl.AddMessage(format('The measurement data(%s) is overflowed.', [C_KEITHLEY_OVERFLOW]), ML_ERROR) else begin s_recv := ReadingValue(s_recv); //trim(s_recv); result := TryStrToFloat(s_recv, val); if result then t_msgrimpl.AddMessage(format('Successful to convert data %0.5f %s.', [val, C_KEITHLEY_UNITS[e_curma]])) else t_msgrimpl.AddMessage(format('Failed to convert data %s', [s_recv])); end; end; end; end; constructor TMultimeterKeithley.Create(owner: TComponent); begin inherited Create(owner); t_relay := TRelayKeithley.Create(); end; destructor TMultimeterKeithley.Destroy(); begin t_relay.Free(); inherited Destroy(); end; function TMultimeterKeithley.InitDevice(): boolean; begin if (not assigned(t_curconn)) then begin t_curconn := TMtxRS232.Create(self); //test ITextMessengerImpl(t_curconn).Messenger := t_msgrimpl.Messenger; t_curconn.Config('Port:5|baudrate:9600'); //test end; e_curma := MA_ANY; s_idn := ''; result := t_curconn.Connect; t_relay.CurConnect := t_curconn; if result then begin //get identifer string from the device result := t_curconn.SendStr(C_KEITHLEY_ID_QUERY + Char(13)); if result then begin result := t_curconn.ExpectStr(s_idn, Char(13), false); if result then result := ContainsText(s_idn, 'KEITHLEY'); if result then begin s_idn := trim(s_idn); t_curconn.SendStr(C_KEITHLEY_RESET + Char(13)); t_curconn.SendStr(C_KEITHLEY_CLEAR_ERROR + Char(13)); t_curconn.SendStr(C_KEITHLEY_BEEP_OFF + Char(13)); t_curconn.SendStr(C_KEITHLEY_FORMAT_ELEMENT + Char(13)); t_curconn.SendStr(C_KEITHLEY_FORMAT_ASCII + Char(13)); t_curconn.SendStr(C_KEITHLEY_MEAS_ONE + Char(13)); end; end; end; if result then t_msgrimpl.AddMessage('Successful to initialize deviec.') else t_msgrimpl.AddMessage('Failed to initialize deviec.', ML_ERROR); end; function TMultimeterKeithley.ReleaseDevice(): boolean; begin if assigned(t_curconn) then FreeAndNil(t_curconn); result := inherited ReleaseDevice(); end; procedure TMultimeterKeithley.SetMeasureRange(const meas:EMeasureAction; const range: double); var s_range, s_sending: string; begin if (meas in [MA_RES, MA_DCV, MA_ACV, MA_DCI, MA_ACI]) then begin if (range > 0.0)then begin //set range if range > C_KEITHLEY_RANGE[meas] then s_range := FloatToStr(C_KEITHLEY_RANGE[meas]) else s_range := FloatToStr(range); //keithley multimeter accepts only '.'- decimal separator //the local format has to be changed into the keithley format //s_range := ReplaceStr(s_range, DecimalSeparator, '.'); s_range := TGenUtils.ReplaceDecimalSeparator(s_range); s_sending := Format(C_KEITHLEY_FUNC[meas] + C_KEITHLEY_RANGE_SET + AnsiChar(13), [s_range]); end else //auto range s_sending := C_KEITHLEY_FUNC[meas] + C_KEITHLEY_RANGE_AUTO_ON + AnsiChar(13); t_curconn.SendStr(s_sending); end; end; end.
unit Departments.ViewModel; interface uses Data.DB, Departments.Classes, Departments.Model; type TDepartmentsViewModel = class private FModel: TDepartmentModel; FDepartment: TDepartment; public constructor Create; //(AModel: TDepartmentModel); property Model: TDepartmentModel read FModel; property Department: TDepartment read FDepartment; function GetDataset: TDataSet; end; implementation { TDepartmentsViewModel } constructor TDepartmentsViewModel.Create; //(AModel: TDepartmentModel); begin inherited Create; FModel := TDepartmentModel.Create; FDepartment := FModel.Department; end; function TDepartmentsViewModel.GetDataset: TDataSet; begin Result := FModel.DataSet; end; end.
unit AqDrop.Core.Observer; interface uses System.Classes, System.Generics.Collections, System.SysUtils, AqDrop.Core.InterfacedObject, AqDrop.Core.Observer.Intf, AqDrop.Core.Collections; type TAqObserver = class(TAqInterfacedObject, IAqObserver) strict protected {$IFNDEF AUTOREFCOUNT} class function MustCountReferences: Boolean; override; {$ENDIF} public procedure Notify(const Sender: TObject); virtual; abstract; end; TAqObserverByMethod = class(TAqObserver) strict private FObserverMethod: TProc<TObject>; public constructor Create(const pMethod: TProc<TObject>); procedure Notify(const Sender: TObject); override; end; TAqObserverByEvent = class(TAqObserver) strict private FObserverEvent: TNotifyEvent; public constructor Create(const pEvent: TNotifyEvent); procedure Notify(const Sender: TObject); override; end; TAqObserversChannel = class strict private FObservers: TAqIDDictionary<IAqObserver>; public constructor Create; destructor Destroy; override; procedure Notify(Sender: TObject); function RegisterObserver(pObserver: IAqObserver): TAqID; procedure UnregisterObserver(const pObserverID: TAqID); end; resourcestring StrItWasNotPossibleToRemoveTheObserverFromTheChannelObserverNotFound = 'It was not possible to remove the observer from the channel (observer not found).'; implementation uses AqDrop.Core.Exceptions; { TAqObserverByMethod } constructor TAqObserverByMethod.Create(const pMethod: TProc<TObject>); begin inherited Create; FObserverMethod := pMethod; end; procedure TAqObserverByMethod.Notify(const Sender: TObject); begin FObserverMethod(Sender); end; { TAqObserverByEvent } constructor TAqObserverByEvent.Create(const pEvent: TNotifyEvent); begin inherited Create; FObserverEvent := pEvent; end; procedure TAqObserverByEvent.Notify(const Sender: TObject); begin FObserverEvent(Sender); end; { TAqObserversChannel } function TAqObserversChannel.RegisterObserver(pObserver: IAqObserver): TAqID; begin Result := FObservers.Add(pObserver); end; constructor TAqObserversChannel.Create; begin inherited; FObservers := TAqIDDictionary<IAqObserver>.Create(False); end; procedure TAqObserversChannel.UnregisterObserver(const pObserverID: TAqID); begin if not FObservers.ContainsKey(pObserverID) then begin raise EAqInternal.Create(StrItWasNotPossibleToRemoveTheObserverFromTheChannelObserverNotFound); end; FObservers.Remove(pObserverID); end; destructor TAqObserversChannel.Destroy; begin FObservers.Free; inherited; end; procedure TAqObserversChannel.Notify(Sender: TObject); var lObserver: IAqObserver; begin for lObserver in FObservers.Values do begin lObserver.Notify(Sender); end; end; { TAqNotificacao } {$IFNDEF AUTOREFCOUNT} class function TAqObserver.MustCountReferences: Boolean; begin Result := True; end; {$ENDIF} end.
unit fUserEdit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, User, ComCtrls; type TF_UserEdit = class(TForm) Label1: TLabel; E_UserName: TEdit; Label2: TLabel; E_FirstName: TEdit; Label3: TLabel; E_LastName: TEdit; GB_Password: TGroupBox; Label4: TLabel; E_Password1: TEdit; Label5: TLabel; E_Password2: TEdit; CHB_root: TCheckBox; B_Apply: TButton; B_Cancel: TButton; GroupBox1: TGroupBox; LV_ORs: TListView; CB_Rights: TComboBox; CHB_Ban: TCheckBox; CHB_Reg: TCheckBox; procedure B_CancelClick(Sender: TObject); procedure B_ApplyClick(Sender: TObject); procedure LV_ORsChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure CB_RightsChange(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure LV_ORsCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); private OpenUser:TUser; new:boolean; procedure FillORs(); public procedure OpenForm(User:TUser); procedure NewUser(); end; var F_UserEdit: TF_UserEdit; implementation {$R *.dfm} uses UserDb, DataUsers, TOblsRizeni, TOblRizeni, fMain; //////////////////////////////////////////////////////////////////////////////// procedure TF_UserEdit.B_CancelClick(Sender: TObject); begin Self.Close(); end; procedure TF_UserEdit.CB_RightsChange(Sender: TObject); var i:Integer; begin for i := 0 to Self.LV_ORs.Items.Count-1 do begin if (Self.LV_ORs.Items[i].Selected) then begin Self.OpenUser.SetRights(Self.LV_ORs.Items[i].Caption, TORControlRights(Self.CB_Rights.ItemIndex)); Self.LV_ORs.Items[i].SubItems.Strings[1] := TOR.ORRightsToString(TORControlRights(Self.CB_Rights.ItemIndex)); TORControlRights(Self.LV_ORs.Items[i].Data^) := TORControlRights(Self.CB_Rights.ItemIndex); end; end; Self.LV_ORs.Repaint(); end; procedure TF_UserEdit.FormClose(Sender: TObject; var Action: TCloseAction); var i:Integer; begin Self.new := false; for i := 0 to Self.LV_ORs.Items.Count-1 do FreeMem(Self.LV_ORs.Items.Item[i].Data); Self.LV_ORs.Clear(); end; procedure TF_UserEdit.LV_ORsChange(Sender: TObject; Item: TListItem; Change: TItemChange); var rights, rights2:TORControlRights; i:Integer; begin if (Self.LV_ORs.SelCount = 0) then begin // 0 vybranych polozek Self.CB_Rights.ItemIndex := -1; Self.CB_Rights.Enabled := false; end else begin Self.CB_Rights.Enabled := true; if (Self.LV_ORs.SelCount = 1) then begin // 1 vybrana polozka if (Self.OpenUser.OblR.TryGetValue(Self.LV_ORs.Selected.Caption, rights)) then Self.CB_Rights.ItemIndex := Integer(rights) else Self.CB_Rights.ItemIndex := -1; end else begin // vic vybranych polozek -> pokud jsou opravenni stejna, vyplnime, jinak -1 for i := 0 to Self.LV_ORs.Items.Count-1 do if (Self.LV_ORs.Items[i].Selected) then Self.OpenUser.OblR.TryGetValue(Self.LV_ORs.Items[i].Caption, rights); for i := 0 to Self.LV_ORs.Items.Count-1 do if (Self.LV_ORs.Items[i].Selected) then begin Self.OpenUser.OblR.TryGetValue(Self.LV_ORs.Items[i].Caption, rights2); if (rights2 <> rights) then begin Self.CB_Rights.ItemIndex := -1; Exit(); end; end; Self.CB_Rights.ItemHeight := Integer(rights); end;// else SelCount > 1 end;//else Selected = nil end; procedure TF_UserEdit.LV_ORsCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); begin case TORCOntrolRights(Item.Data^) of TORCOntrolRights.null : Self.LV_ORs.Canvas.Brush.Color := clWhite; TORCOntrolRights.read : Self.LV_ORs.Canvas.Brush.Color := $FFFFAA; TORCOntrolRights.write : Self.LV_ORs.Canvas.Brush.Color := $AAFFFF; TORCOntrolRights.superuser : Self.LV_ORs.Canvas.Brush.Color := $AAAAFF; end;//case end; /////////////////////////////////////////////////////////////////////////////// procedure TF_UserEdit.OpenForm(User:TUser); begin Self.OpenUser := User; Self.FillORs(); Self.E_UserName.Text := User.id; Self.E_FirstName.Text := User.firstname; Self.E_LastName.Text := User.lastname; Self.CHB_root.Checked := User.root; Self.CHB_Ban.Checked := User.ban; Self.CHB_Reg.Checked := User.regulator; Self.E_Password1.Text := 'heslo'; Self.E_Password2.Text := 'heslo'; Self.ActiveControl := Self.E_UserName; Self.Caption := 'Editovat uživatele '+User.id; Self.ShowModal(); end;//procedure procedure TF_UserEdit.NewUser(); begin Self.new := true; Self.OpenUser := TUser.Create(); Self.FillORs(); Self.E_UserName.Text := ''; Self.E_FirstName.Text := ''; Self.E_LastName.Text := ''; Self.CHB_root.Checked := false; Self.CHB_Ban.Checked := false; Self.CHB_Reg.Checked := true; Self.E_Password1.Text := ''; Self.E_Password2.Text := ''; Self.ActiveControl := Self.E_UserName; Self.Caption := 'Vytvořit nového uživatele'; Self.ShowModal(); end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TF_UserEdit.B_ApplyClick(Sender: TObject); var index:Integer; begin if (Length(Self.E_UserName.Text) < 3) then begin Application.MessageBox('Uživatelské jméno musí mít alespoň 3 znaky!', 'nelze uložit data', MB_OK OR MB_ICONWARNING); Exit(); end; if (Self.OpenUser <> nil) then begin if (Self.E_Password1.Text = '') then begin Application.MessageBox('Heslo nemůže být prázdné!', 'nelze uložit data', MB_OK OR MB_ICONWARNING); Exit(); end; end;//if Self.OpenUser <> nil if (Self.E_Password1.Text <> Self.E_Password2.Text) then begin Application.MessageBox('Zadaná hesla se neshodují!', 'nelze uložit data', MB_OK OR MB_ICONWARNING); Exit(); end; if (Length(Self.E_Password1.Text) < 3) then begin Application.MessageBox('Heslo musí mít alespoň 3 znaky!', 'nelze uložit data', MB_OK OR MB_ICONWARNING); Exit(); end; if (Self.new) then begin Self.OpenUser.password := Self.E_Password1.Text; Self.OpenUser.lastlogin := Now; end else begin if (Self.E_Password1.Text <> 'heslo') then Self.OpenUser.password := Self.E_Password1.Text; end; Self.OpenUser.id := Self.E_UserName.Text; Self.OpenUser.firstname := Self.E_FirstName.Text; Self.OpenUser.lastname := Self.E_LastName.Text; Self.OpenUser.root := Self.CHB_root.Checked; Self.OpenUser.ban := Self.CHB_Ban.Checked; Self.OpenUser.regulator := Self.CHB_Reg.Checked; if (new) then begin try UsrDB.AddUser(Self.OpenUser); except on e:Exception do begin Application.MessageBox(PChar(e.Message), 'Varování', MB_OK OR MB_ICONWARNING); Exit(); end; end; end else begin UsersTableData.UpdateTable(); end; index := UsrDB.IndexOf(Self.OpenUser.id); if (index > -1) then begin F_Main.LV_Users.Items[index].Selected := true; F_Main.LV_Users.Items[index].Focused := true; end; Self.Close(); end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TF_UserEdit.FillORs(); var LI:TListItem; i:Integer; rights:TORCOntrolRights; data:Pointer; begin Self.LV_ORs.Clear(); for i := 0 to ORs.Count-1 do begin LI := Self.LV_ORs.Items.Add; LI.Caption := ORs.GetORIdByIndex(i); LI.SubItems.Add(ORs.GetORNameByIndex(i)); if (not Self.OpenUser.OblR.TryGetValue(LI.Caption, rights)) then rights := TORCOntrolRights.null; LI.SubItems.Add(TOR.ORRightsToString(rights)); GetMem(data, 3); TORControlRights(data^) := rights; LI.Data := data; end; Self.CB_Rights.ItemIndex := -1; Self.CB_Rights.Enabled := false; Self.LV_ORs.Repaint(); end;//procedure //////////////////////////////////////////////////////////////////////////////// end.//unit
unit Console; {$A+,B-,F-,Q-,R-,S-,W-,X+} { Text Console component Version 2.0 for 16 bit and 32 bit Delphi. Copyright (c) 1995,96 by Danny Thorpe (dthorpe@subliminal.com) You are hereby granted a royalty-free unlimited distribution license to compile the components in this source file into your applications. This source file may be freely distributed through online networks so long as no modifications are made to this file and no fee is charged to obtain this file, other than normal online connection charges. These components may NOT be distributed as source code or compiled DCU on diskette, CDRom, or as part of a product without prior written consent of the author. All rights not explicitly granted here are reserved by the author. } interface uses WinTypes, WinProcs, Messages, Classes, Controls, Forms, Graphics, SysUtils, AnsiStrings; { TConsole TConsole implements a WinCRT-like control for routing text file I/O (readlns and writelns) to a scrollable window. A text cursor can be positioned using X,Y text coordinates. TConsole is not intended to be a text editor, merely a TTY text output device. TConsole does not store its text buffers when it is streamed. Max display text in 16 bit applications is 64k (rows * columns <= 64k); in 32 bit applications, the only capacity limit is system memory. You can set the TConsole font name, style or other properties, but only fixed-pitch fonts should be used. TConsole can be extended to support text color attributes and multiple fonts, and can support multiple terminal emulation command decoders (like ANSI-BBS or DEC VT-100). TConsole supports keyboard input via the Pascal standard input functions ReadKey, Keypressed, and Readln. Note that the modal nature of Readln (execution doesn't return until EOL is received) is problematic. Only one outstanding Console Readln operation is supported for the entire application. Calling readln while another readln is pending (eg Readln on a button click) will raise an exception. TConsole provides a performance option called toLazyWrite. With this option turned off, each write operation to the Console is immediately displayed on the screen. With toLazyWrite turned on, screen updating is delayed slightly so that multiple text changes can be displayed in one Paint operation. Despite the 'lazy' name, this consolidation results in dramatically better display performance - a factor of 10 to 100 times faster than writing each little piece of text immediately. toLazyWrite is enabled by default. The public ScrollTo and TrackCursor methods don't use toLazyWrite, nor do the ReadKey or ReadBuf routines. When these routines modify the display or text buffer, the Console is updated immediately. The coFixedPitchOnly option, True by default, determines whether the console component raises an exception when a font which is not marked as fixed pitch is assigned to the component. Many off-brand truetype fonts which have a uniform character width are incorrectly marked as proportional fonts. By setting coFixedPitchOnly to false, you can now use those fonts in the console components. Using proportional fonts in a console component is not advised; it's very ugly. TColorConsole TColorConsole implements support for multiple text color attributes. The Console's font properties determine the text color, background color, font, style, etc of the display text. Text foreground color is Console.Font.Color; text background is Console.Font.BkColor. Set the Console's font properties, then writeln to the Console's text file and that text will be displayed with those attributes. In 16 bit applications, TColorConsole has the following capacity limits: Max display text is 32k. (rows * cols <= 32k). Max unique text attribute sets: 16k. (unique = font+color+bkcolor) In 32 bit applications, the only limit is system memory. Memory consumption is roughly 5 bytes per display text character cell: an 80 x 25 color console will use 80 x 25 = 2000 bytes for the text buffer plus 80 x 25 x 4 = 8000 bytes for the cell attribute buffer. Each unique text attribute set uses 36 bytes of memory. Text attribute sets are maintained in a pool. Each attr set is released when the last char in the display buffer using that set is overwritten with different attributes. Multiple fonts are supported, but the cell height and width of the fonts must be the same. That is, you can output text in Courier New 10pt, Courier New 10pt Bold, and Lucida Sans Monospace 10pt Italic all on the same screen. If the Console's font size is changed, that size change is applied to all fonts used by the Console control and the control is repainted. Fonts of the same height often have different widths. When a wider font is selected into the Console control, the character cell dimensions for all the text is enlarged to accommodate the wider font. Characters of narrower fonts will be spaced further apart to maintain column alignment. This rarely looks appealing, so take it easy on the fonts. TrueType fonts (like Courier New) tend to work better than bitmap fonts (like Courier). TConsole's output routines Most of the time, you'll use a text file to write data to the Console window. To make the component intercept all output written to stdout (ie anything that calls write or writeln without a file handle), include the coStdOutput flag in the component's Options property. Only one component in the application can intercept stdout. coStdOutput is disabled by default. For more specialized work, such as extending these objects or adding terminal emulation processor methods, you can use some of TConsole's specialized output routines. WriteChar Calls WriteCodedBuf to output one character using the current font/color attributes. WriteString Calls WriteCodedBuf to output the characters in the string using the current font/color attributes. WriteCodedBuf Passes control to the ProcessControlCodes method pointer if it is assigned. If the pointer is not assigned, WriteBuf is called instead. WriteCodedBuf is called by the internal text file device driver (Write and Writeln), WriteChar, and WriteString. Your ProcessControlCodes routine should parse the buffer to find and execute complex display formatting control codes and command sequences embedded in the data stream (such as ANSI terminal codes). ProcessControlCodes is an event so that it can be reassigned dynamically at runtime - for example, to switch from ANSI emulation to Wyse terminal emulation. Control code processing methods have full responsibility for displaying the actual text - they should parse their control codes, set the cursor position or font/color attributes as needed, and then call WriteChar, WriteString, or WriteFill as necessary to display the actual text (without codes). If you determine that a text buffer contains no special codes for your ProcessControlCodes event to handle, you can pass the text buffer to DefaultProcessControlCodes to perform the normal WriteBuf text processing on the buffer. This will save you some work in your event handler. WriteFill Replicates a single character (or space) N times starting from text coordinate X,Y and flowing down the page. All the replicated chars are displayed with the currently selected font and color attributes. The copy count can be any length up to (rows * cols). TColorConsole overrides this method to add additional color support. WriteBuf This is an internal (protected) mid-level method to process simple text file formatting codes. It scans the data stream for special characters (Carriage return, Linefeed, Backspace, Bell), wraps text at the right margin, and calls WriteBlock or WriteFill for actual output. WriteBlock This is an internal (protected) low-level method to output a string of characters. WriteBlock assumes the string parameter has been stripped of all special characters and is guaranteed to contain no more than one line of text (length <= Cols - Cursor.X). All the characters in the string are displayed with the currently selected font and color attributes. TColorConsole overrides this method to add additional color support. } const CM_TrackCursor = wm_User + 100; CM_ScrollBy = wm_User + 101; type EInvalidFont = class(Exception); TCMScrollBy = record Msg: Cardinal; dx : Integer; dy : Longint; end; TConsole = class; { forward declaration } TFixedFont = class(TFont) private FBkColor: TColor; procedure SetBkColor(NewColor: TColor); public constructor Create; procedure Assign(Source: TPersistent); override; published property BkColor: TColor read FBkColor write SetBkColor default clWindow; end; TConsoleOption = (coAutoTracking, coCheckEOF, coCheckBreak, coFulltimeCursor, coLazyWrite, coStdInput, coStdOutput, coFixedPitchOnly); TConsoleOptions = set of TConsoleOption; { CR/LF translation. CRLF = no translation CR = on CR add LF LF = on LF add CR } TConsoleLineBreak = (CRLF, CR, LF); TProcessControlCodes = procedure (Sender: TConsole; Buffer: PAnsiChar; Count: Cardinal) of object; TConsole = class(TCustomControl) private FOptions: TConsoleOptions; FFocused: Boolean; FFont: TFixedFont; FCols: Integer; { Screen buffer dimensions } FRows: Integer; FProcessControlCodes: TProcessControlCodes; FLineBreak: TConsoleLineBreak; { CR/LF/CRLF translation } procedure InternalClrScr; procedure SetOptions(NewOptions: TConsoleOptions); procedure SetCols(N: Integer); procedure SetRows(N: Integer); procedure SetFont(F: TFixedFont); procedure DoScroll(Which, Action, Thumb: Integer); procedure CMTrackCursor(var M); message CM_TrackCursor; procedure CMScrollBy(var M: TCMScrollBy); message CM_ScrollBy; procedure WMCreate(var M); message wm_Create; procedure WMSize(var M: TWMSize); message wm_Size; procedure WMHScroll(var M: TWMHScroll); message wm_HScroll; procedure WMVScroll(var M: TWMVScroll); message wm_VScroll; procedure WMSetFocus(var M: TWMSetFocus); message wm_SetFocus; procedure WMKillFocus(var M: TWMKillFocus); message wm_KillFocus; procedure WMGetDlgCode(var M: TWMGetDlgCode); message wm_GetDlgCode; procedure WMEraseBkgnd(var M: TWMEraseBkgnd); message wm_EraseBkgnd; protected FReading: Boolean; { Reading from CRT window? } FOldFont: TFixedFont; FFirstLine: Integer; { First visible line in circular buffer } FKeyCount: Integer; { Count of keys in KeyBuffer } FBuffer: PAnsiChar; { Screen buffer pointer } FRange: TPoint; { Scroll bar ranges } FOrigin: TPoint; { Client/scroll origin } FClientSize: TPoint; { Number of visible whole cells } FCharSize: TPoint; { Character cell size } FCharAscent: Integer; { Baseline location (for caret) } FOverhang: Integer; { Extra space needed for chars } FKeyBuffer: array[0..63] of AnsiChar; { Keyboard type-ahead buffer } Cursor: TPoint; { Cursor location } procedure CreateParams(var P: TCreateParams); override; procedure FontChanged(Sender: TObject); procedure ResizeBuffer; dynamic; procedure SetName(const NewName: TComponentName); override; procedure SetMetrics(const Metrics: TTextMetric); virtual; procedure RecalibrateFont; procedure RecalcSizeAndRange; function ScreenPtr(X, Y: Integer): PAnsiChar; procedure ShowText(L, R: Integer); procedure WriteFill(X,Y: Integer; Ch: AnsiChar; Count: Cardinal); virtual; procedure WriteBlock(X,Y: Integer; Buffer: PAnsiChar; Count: Cardinal); virtual; procedure WriteBuf(Buffer: PAnsiChar; Count: Cardinal); procedure SetScrollbars; procedure Paint; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure DoCtrlBreak; dynamic; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure LazyTrackCursor; procedure LazyScrollBy(dx, dy: Integer); procedure Loaded; override; public constructor Create(AnOwner: TComponent); override; destructor Destroy; override; procedure DefaultProcessControlCodes(Buffer: PAnsiChar; Count: Cardinal); procedure WriteCodedBuf(Buffer: PAnsiChar; Count: Cardinal); procedure WriteChar(Ch: AnsiChar); procedure WriteString(const S: String); function KeyPressed: Boolean; function ReadKey: AnsiChar; function ReadBuf(Buffer: PAnsiChar; Count: Cardinal): Cardinal; procedure ClrScr; procedure ClrEol; procedure CursorTo(X, Y: Integer); procedure ScrollTo(X, Y: Integer); procedure TrackCursor; procedure AssignCrt(var F: Text); dynamic; procedure ShowCursor; virtual; procedure HideCursor; published property Align; property ParentColor; property Color; property Font: TFixedFont read FFont write SetFont; property Options: TConsoleOptions read FOptions write SetOptions default [coAutoTracking, coCheckBreak, coLazyWrite{, coFixedPitchOnly}]; property Cols: Integer read FCols write SetCols default 80; property Rows: Integer read FRows write SetRows default 25; property LineBreak: TConsoleLineBreak read FLineBreak write FLineBreak; property ProcessControlCodes: TProcessControlCodes read FProcessControlCodes write FProcessControlCodes; end; type PIntArray = ^TIntArray; TIntArray = array [0..0] of Integer; type TAttr = class(TFixedFont) protected RefCount: Cardinal; Overhang: ShortInt; Underhang: ShortInt; public constructor Create(F: TFixedFont); end; TAttrManager = class(TPersistent) private FList: TList; FCache: TAttr; FCacheIndex: Integer; FFreeList: Integer; function GetCount: Integer; protected function GetAttr(Index: Integer): TAttr; procedure SetAttr(Index: Integer; NewAttr: TAttr); function InFreeList(P: Pointer): Boolean; function FirstFreeIndex: Integer; function NextFreeIndex(P: Pointer): Integer; procedure SetFree(Index: Integer); function AllocIndex: Integer; public constructor Create; destructor Destroy; override; function Allocate(F: TFixedFont): Integer; procedure Clear; procedure Reference(Index: Integer; Delta: Integer); property Attr[Index: Integer]: TAttr read GetAttr write SetAttr; default; property Count: Integer read GetCount; end; TColorConsole = class(TConsole) private FIndexes: PIntArray; FAttrList: TAttrManager; FCellWidths: PIntArray; procedure FillAttr(X,Y: Integer; Count: Cardinal); protected function IndexPtr(X,Y: Integer): PInteger; procedure ResizeBuffer; override; procedure SetMetrics(const Metrics: TTextMetric); override; procedure WriteFill(X,Y: Integer; Ch: AnsiChar; Count: Cardinal); override; procedure WriteBlock(X,Y: Integer; Buffer: PAnsiChar; Count: Cardinal); override; procedure Paint; override; public constructor Create(Owner: TComponent); override; destructor Destroy; override; end; procedure Register; procedure Exchange(var X,Y: Pointer); procedure FillInt(var Buf; Count: Cardinal; Value: Integer); implementation { Scroll key definition record } type TScrollKey = record sKey: Byte; Ctrl: Boolean; SBar: Byte; Action: Byte; end; var ReadActive: Boolean = False; { Anybody in a Readln? } { Scroll keys table } const ScrollKeyCount = 12; ScrollKeys: array[1..ScrollKeyCount] of TScrollKey = ( (sKey: vk_Left; Ctrl: False; SBar: sb_Horz; Action: sb_LineUp), (sKey: vk_Right; Ctrl: False; SBar: sb_Horz; Action: sb_LineDown), (sKey: vk_Left; Ctrl: True; SBar: sb_Horz; Action: sb_PageUp), (sKey: vk_Right; Ctrl: True; SBar: sb_Horz; Action: sb_PageDown), (sKey: vk_Home; Ctrl: False; SBar: sb_Horz; Action: sb_Top), (sKey: vk_End; Ctrl: False; SBar: sb_Horz; Action: sb_Bottom), (sKey: vk_Up; Ctrl: False; SBar: sb_Vert; Action: sb_LineUp), (sKey: vk_Down; Ctrl: False; SBar: sb_Vert; Action: sb_LineDown), (sKey: vk_Prior; Ctrl: False; SBar: sb_Vert; Action: sb_PageUp), (sKey: vk_Next; Ctrl: False; SBar: sb_Vert; Action: sb_PageDown), (sKey: vk_Home; Ctrl: True; SBar: sb_Vert; Action: sb_Top), (sKey: vk_End; Ctrl: True; SBar: sb_Vert; Action: sb_Bottom)); { Return the smaller of two integer values } function Min(X, Y: Integer): Integer; begin if X < Y then Min := X else Min := Y; end; { Return the larger of two integer values } function Max(X, Y: Integer): Integer; begin if X > Y then Max := X else Max := Y; end; procedure Exchange(var X,Y: Pointer); var Temp: Pointer; begin Temp := X; X := Y; Y := Temp; end; procedure FillInt(var Buf; Count: Cardinal; Value: Integer); var X: Cardinal; begin for X := 0 to Count-1 do TIntArray(Buf)[X] := Value; end; constructor TFixedFont.Create; begin inherited Create; Name := 'Courier New'; FBkColor := clWindow; end; procedure TFixedFont.Assign(Source: TPersistent); var Temp: TColor; begin Temp := FBkColor; if Source is TFixedFont then FBkColor := TFixedFont(Source).BkColor; try inherited Assign(Source); { inherited will call Changed } except FBkColor := Temp; { Restore original if inherited fails } raise; end; end; procedure TFixedFont.SetBkColor(NewColor: TColor); begin FBkColor := NewColor; Changed; end; constructor TConsole.Create(AnOwner: TComponent); begin inherited Create(AnOwner); Width := 160; Height := 88; Options := [coAutoTracking, coCheckBreak, coLazyWrite{, coFixedPitchOnly}]; ControlStyle := ControlStyle + [csOpaque]; FRows := 25; FCols := 80; ParentColor := False; Color := clWindow; FOldFont := TFixedFont.Create; FOldFont.Handle := GetStockObject(Ansi_Fixed_Font); FFont := TFixedFont.Create; FFont.Name := 'Courier'; FFont.OnChange := FontChanged; ResizeBuffer; TabStop := True; Enabled := True; end; destructor TConsole.Destroy; begin Options := Options - [coStdInput, coStdOutput]; { close files } AnsiStrings.StrDispose(FBuffer); FOldFont.Free; FFont.Free; inherited Destroy; end; procedure TConsole.Loaded; begin inherited Loaded; ClrScr; end; procedure TConsole.CreateParams(var P: TCreateParams); begin inherited CreateParams(P); P.WindowClass.Style := P.WindowClass.Style and not (cs_HRedraw or cs_VRedraw); end; procedure TConsole.DefaultProcessControlCodes(Buffer: PAnsiChar; Count: Cardinal); begin WriteBuf(Buffer, Count); end; procedure TConsole.WMCreate(var M); begin inherited; RecalibrateFont; { don't ClrScr, because text may already be in buffer } end; procedure TConsole.ResizeBuffer; var Temp: PAnsiChar; begin Temp := AnsiStrings.AnsiStrAlloc(Cols * Rows); AnsiStrings.StrDispose(FBuffer); FBuffer := Temp; FillChar(FBuffer^,Cols * Rows,' '); end; procedure TConsole.SetCols(N: Integer); begin if FCols <> N then begin FCols := N; ResizeBuffer; end; end; procedure TConsole.SetRows(N: Integer); begin if FRows <> N then begin FRows := N; ResizeBuffer; end; end; procedure TConsole.SetFont(F: TFixedFont); begin FFont.Assign(F); end; procedure TConsole.FontChanged(Sender: TObject); var DC: HDC; Save: THandle; Metrics: TTextMetric; Temp: String; begin if Font.Handle <> FOldFont.Handle then begin DC := GetDC(0); Save := SelectObject(DC, Font.Handle); GetTextMetrics(DC, Metrics); SelectObject(DC, Save); ReleaseDC(0, DC); if (coFixedPitchOnly in Options) and not (((Metrics.tmPitchAndFamily and ff_Modern) <> 0) and ((Metrics.tmPitchAndFamily and $01) = 0)) then begin Temp := 'TConsole: ' + Font.Name + ' is not fixed-pitch'; Font.Name := FOldFont.Name; { Keep other attributes of font } raise EInvalidFont.Create(Temp); end; SetMetrics(Metrics); end; FOldFont.Assign(Font); if csDesigning in ComponentState then InternalClrScr; end; { If the character cell is different, accept changes and redraw } procedure TConsole.SetMetrics(const Metrics: TTextMetric); begin with Metrics do begin FCharSize.X := tmAveCharWidth; FCharSize.Y := tmHeight + tmExternalLeading; FCharAscent := tmAscent; FOverhang := Max(tmOverhang, tmMaxCharWidth - tmAveCharWidth); Invalidate; RecalcSizeAndRange; end; end; procedure TConsole.RecalcSizeAndRange; begin if HandleAllocated then begin FClientSize.X := ClientWidth div FCharSize.X; FClientSize.Y := ClientHeight div FCharSize.Y; FRange.X := Max(0, Cols - FClientSize.X); FRange.Y := Max(0, Rows - FClientSize.Y); ScrollTo(Min(FOrigin.X, FRange.X), Min(FOrigin.Y, FRange.Y)); SetScrollBars; end; end; procedure TConsole.SetName(const NewName: TComponentName); begin inherited SetName(NewName); if csDesigning in ComponentState then ClrScr; end; { Return pointer to text location in screen buffer } { Always call ScreenPtr to get the next line you want, since the circular text buffer may wrap around between lines N and N+1. For the same reason, do not do pointer arithmetic between rows. } function TConsole.ScreenPtr(X, Y: Integer): PAnsiChar; begin Inc(Y, FFirstLine); if Y >= Rows then Dec(Y, Rows); Result := @FBuffer[Y * Cols + X]; end; { Update text on cursor line } procedure TConsole.ShowText(L, R: Integer); var B: TRect; begin if HandleAllocated and (L < R) then begin B.Left := (L - FOrigin.X) * FCharSize.X; B.Top := (Cursor.Y - FOrigin.Y) * FCharSize.Y; B.Right:= (R - FOrigin.X) * FCharSize.X + FOverhang; B.Bottom := B.Top + FCharSize.Y; InvalidateRect(Handle, @B, False); if not (coLazyWrite in Options) then Update; end; end; { Show caret } procedure TConsole.ShowCursor; begin if not HandleAllocated then Exit; CreateCaret(Handle, 0, FCharSize.X, 2); SetCaretPos((Cursor.X - FOrigin.X) * FCharSize.X, (Cursor.Y - FOrigin.Y) * FCharSize.Y + FCharAscent); ShowCaret(Handle); end; { Hide caret } procedure TConsole.HideCursor; begin DestroyCaret; end; { Set cursor position } procedure TConsole.CursorTo(X, Y: Integer); begin Cursor.X := Max(0, Min(X, Cols - 1)); Cursor.Y := Max(0, Min(Y, Rows - 1)); if FFocused and (FReading or (coFullTimeCursor in Options)) then ShowCursor; end; { Request asynchronous (lazy) ScrollBy, or update pending request } procedure TConsole.LazyScrollBy(dx, dy: Integer); var Msg: TMsg; begin if (coLazyWrite in Options) and HandleAllocated then begin if PeekMessage(Msg, Handle, cm_ScrollBy, cm_ScrollBy, PM_NoYield or PM_Remove) then begin Inc(dx, Msg.WParam); Inc(dy, Msg.LParam); end; { Flush accumulated scroll when delta >= half a screen } if (Abs(dx) >= Min(FClientSize.X, Cols) div 2) or (Abs(dy) >= Min(FClientSize.Y, Rows) div 2) then Perform(CM_ScrollBy, dx, dy) else if (dx or dy) <> 0 then PostMessage(Handle, cm_ScrollBy, dx, dy); end else Perform(CM_ScrollBy, dx, dy); end; { Respond to asynchronous (lazy) ScrollBy request } procedure TConsole.CMScrollBy(var M: TCMScrollBy); begin ScrollTo(FOrigin.X + M.dx, FOrigin.Y + M.dy); end; { Scroll window to given origin } { If font has overlapping cells (ie, italic), additional work is done to remove the residual overlapped pixels from the leftmost column. Using the clip rect with ScrollWindowEx helps eliminate pixel flicker in the left column. } procedure TConsole.ScrollTo(X, Y: Integer); var R: TRect; OldOrigin: TPoint; begin X := Max(0, Min(X, FRange.X)); Y := Max(0, Min(Y, FRange.Y)); if (X <> FOrigin.X) or (Y <> FOrigin.Y) then begin OldOrigin := FOrigin; FOrigin.X := X; FOrigin.Y := Y; if HandleAllocated then begin R := ClientRect; if X > OldOrigin.X then Inc(R.Left, FOverhang); if Y > OldOrigin.Y then R.Bottom := FClientSize.Y * FCharSize.Y; ScrollWindowEx(Handle, (OldOrigin.X - X) * FCharSize.X, (OldOrigin.Y - Y) * FCharSize.Y, nil, @R, 0, @R, 0); if Y <> OldOrigin.Y then begin SetScrollPos(Handle, sb_Vert, Y, True); if Y > OldOrigin.Y then begin InvalidateRect(Handle, @R, False); Update; R.Top := R.Bottom; R.Bottom := ClientRect.Bottom; end; end; if X <> OldOrigin.X then begin SetScrollPos(Handle, sb_Horz, X, True); if (FOverhang > 0) then begin if (X < OldOrigin.X) then { Scroll right - left edge repaint } begin { Add overhang to invalidation rect to redraw leftmost char pair } R.Left := 0; R.Right := Max(R.Right, (OldOrigin.X - X) * FCharSize.X + FOverhang); end else { Scroll left - right edge repaint } begin { Redraw leftmost chars to remove prev chars' overhang } InvalidateRect(Handle, @R, False); Update; { Update right side, before invalidating left side } R.Left := 0; R.Top := 0; R.Right := FOverhang; R.Bottom := ClientHeight; end; end; end; InvalidateRect(Handle, @R, False); Update; end; end; end; { Request asynchronous (lazy) TrackCursor, if not already pending } procedure TConsole.LazyTrackCursor; var Msg: TMsg; begin if (coLazyWrite in Options) and HandleAllocated then begin { Only post msg if there is not one already in the queue } if not PeekMessage(Msg, Handle, cm_TrackCursor, cm_TrackCursor, PM_NoYield or PM_NoRemove) then PostMessage(Handle, cm_TrackCursor, 0, 0); end else TrackCursor; end; { Respond to asynchronous (lazy) TrackCursor request } procedure TConsole.CMTrackCursor(var M); begin TrackCursor; end; { Scroll to make cursor visible (synchronous - immediate update)} procedure TConsole.TrackCursor; begin ScrollTo(Max(Cursor.X - FClientSize.X + 1, Min(FOrigin.X, Cursor.X)), Max(Cursor.Y - FClientSize.Y + 1, Min(FOrigin.Y, Cursor.Y))); end; { Update scroll bars } procedure TConsole.SetScrollBars; begin if not HandleAllocated then Exit; SetScrollRange(Handle, sb_Horz, 0, Max(1, FRange.X), False); SetScrollPos(Handle, sb_Horz, FOrigin.X, True); SetScrollRange(Handle, sb_Vert, 0, Max(1, FRange.Y), False); SetScrollPos(Handle, sb_Vert, FOrigin.Y, True); end; { Clear screen } procedure TConsole.InternalClrScr; begin WriteFill(0,0,' ',Cols * Rows); FOrigin.X := 0; FOrigin.Y := 0; Cursor.X := 0; Cursor.Y := 0; if (csDesigning in ComponentState) then WriteString(Name); Invalidate; end; procedure TConsole.ClrScr; begin InternalClrScr; RecalibrateFont; end; procedure TConsole.RecalibrateFont; begin FCharSize.X := 0; FCharSize.Y := 0; FCharAscent := 0; FOverhang := 0; FOldFont.Handle := 0; FOldFont.Size := 0; FontChanged(FFont); { This will force a repaint and recalibrate } end; { Clear to end of line } procedure TConsole.ClrEol; begin WriteFill(Cursor.X, Cursor.Y, ' ', Cols - Cursor.X); ShowText(Cursor.X, Cols); end; procedure TConsole.WriteBlock(X,Y: Integer; Buffer: PAnsiChar; Count: Cardinal); begin Move(Buffer^, ScreenPtr(X,Y)^, Count); end; { Write text buffer to CRT window - Process any special characters in buffer - Insert line breaks } procedure TConsole.WriteBuf(Buffer: PAnsiChar; Count: Cardinal); var L, R: Integer; procedure Return; begin L := 0; R := 0; Cursor.X := 0; end; procedure LineFeed; // var // Rect: TRect; begin Inc(Cursor.Y); if Cursor.Y = Rows then begin Dec(Cursor.Y); Inc(FFirstLine); if FFirstLine = Rows then FFirstline := 0; WriteFill(0, Cursor.Y, ' ', Cols); Dec(FOrigin.Y, 1); LazyScrollBy(0, 1); end; end; var BlockEnd, BlockLen, BlockStart: Integer; P: PAnsiChar; begin L := Cursor.X; R := Cursor.X; while Count > 0 do begin BlockEnd := Min(Cols - Cursor.X, Count); P := Buffer; {$IFDEF WIN32} BlockStart := BlockEnd; while (BlockEnd > 0) and (Buffer^ in [#32..#255]) do begin Inc(Buffer); Dec(BlockEnd); end; BlockLen := BlockStart - BlockEnd; {$ELSE} asm PUSH DS PUSH SI LDS SI, Buffer MOV CX, BlockEnd MOV DX, CX CLD @@1: LODSB CMP AL,' ' JB @@2 LOOP @@1 INC SI @@2: DEC SI MOV Buffer.Word[0],SI MOV BlockEnd, CX SUB DX,CX MOV BlockLen, DX POP SI POP DS end; {$ENDIF} if BlockLen > 0 then begin Dec(Count, BlockLen); WriteBlock(Cursor.X, Cursor.Y, P, BlockLen); Inc(Cursor.X, BlockLen); if Cursor.X > R then R := Cursor.X; if (BlockEnd = 0) and (Cursor.X >= Cols) then begin ShowText(L,R); Return; LineFeed; Continue; end; end; if Count > 0 then begin case Buffer^ of #13: begin ShowText(L,R); Return; if LineBreak = CR then LineFeed; end; #10: begin ShowText(L,R); if LineBreak = LF then Return; LineFeed; end; #8: if Cursor.X > 0 then begin Dec(Cursor.X); WriteFill(Cursor.X, Cursor.Y, ' ', 1); if Cursor.X < L then L := Cursor.X; end; #7: MessageBeep(0); end; Inc(Buffer); Dec(Count); end; end; ShowText(L, R); if coAutoTracking in Options then LazyTrackCursor; if FFocused and (coFullTimeCursor in Options) then ShowCursor; end; procedure TConsole.WriteCodedBuf(Buffer: PAnsiChar; Count: Cardinal); begin if Assigned(FProcessControlCodes) then FProcessControlCodes(Self, Buffer, Count) else WriteBuf(Buffer, Count); end; { Write character to CRT window } procedure TConsole.WriteChar(Ch: AnsiChar); begin WriteCodedBuf(@Ch, 1); end; procedure TConsole.WriteString(const S: String); var S2: AnsiString; begin S2 := AnsiString(S); WriteCodedBuf(@S2[1], Length(S2)); end; procedure TConsole.WriteFill(X,Y: Integer; Ch: AnsiChar; Count: Cardinal); var I: Integer; begin if Count = 0 then Exit; if (Int64(X) + Int64(Count)) > Cols then begin FillChar(ScreenPtr(X,Y)^, Cols - X, Ch); Dec(Count, Cols - X); I := Cols; while Count > 0 do begin Inc(Y); FillChar(ScreenPtr(X,Y)^, I, Ch); Dec(Count, I); end; end else FillChar(ScreenPtr(X,Y)^, Count, Ch); end; { Return keyboard status } function TConsole.KeyPressed: Boolean; begin Result := FKeyCount > 0; if (not Result) then begin Application.ProcessMessages; Result := FKeyCount > 0; end; end; { Read key from CRT window } function TConsole.ReadKey: AnsiChar; begin TrackCursor; if not KeyPressed then begin SetFocus; if FReading or ReadActive then raise EInvalidOperation.Create('Read already active'); try FReading := True; ReadActive := True; if FFocused then ShowCursor; repeat Application.HandleMessage until Application.Terminated or (FKeyCount > 0); if Application.Terminated then raise Exception.Create('WM_Quit received during ReadKey'); finally if FFocused and not (coFullTimeCursor in Options) then HideCursor; FReading := False; ReadActive := False; end; end; ReadKey := FKeyBuffer[0]; Dec(FKeyCount); Move(FKeyBuffer[1], FKeyBuffer[0], FKeyCount); end; { Read text buffer from CRT window } function TConsole.ReadBuf(Buffer: PAnsiChar; Count: Cardinal): Cardinal; var Ch: AnsiChar; I: Cardinal; begin I := 0; repeat Ch := ReadKey; case Ch of #8: if I > 0 then begin Dec(I); WriteChar(#8); end; #32..#255: if I < Count - 2 then begin Buffer[I] := Ch; Inc(I); WriteChar(Ch); end; end; until (Ch in [#0,#13]) or ((coCheckEOF in Options) and (Ch = #26)); Buffer[I] := Ch; Inc(I); if Ch = #13 then begin Buffer[I] := #10; Inc(I); WriteBuf(#13#10,2); end; TrackCursor; ReadBuf := I; if FFocused and (coFullTimeCursor in Options) then ShowCursor; end; { Text file device driver output function } function CrtOutput(var F: TTextRec): Integer; far; begin if F.BufPos <> 0 then with TObject((@F.UserData)^) as TConsole do begin WriteCodedBuf(PAnsiChar(F.BufPtr), F.BufPos); F.BufPos := 0; end; CrtOutput := 0; end; { Text file device driver input function } function CrtInput(var F: TTextRec): Integer; far; begin with TObject((@F.UserData)^) as TConsole do F.BufEnd := ReadBuf(PAnsiChar(F.BufPtr), F.BufSize); F.BufPos := 0; CrtInput := 0; end; { Text file device driver close function } function CrtClose(var F: TTextRec): Integer; far; begin CrtClose := 0; end; { Text file device driver open function } function CrtOpen(var F: TTextRec): Integer; far; begin if F.Mode = fmInput then begin F.InOutFunc := @CrtInput; F.FlushFunc := nil; end else begin F.Mode := fmOutput; F.InOutFunc := @CrtOutput; F.FlushFunc := @CrtOutput; end; F.CloseFunc := @CrtClose; CrtOpen := 0; end; { Assign text file to CRT device } procedure TConsole.AssignCrt(var F: Text); begin with TTextRec(F) do begin Handle := -1; Mode := fmClosed; BufSize := SizeOf(Buffer); BufPtr := @Buffer; OpenFunc := @CrtOpen; Move(Self, UserData[1],Sizeof(Pointer)); Name[0] := #0; end; end; procedure TConsole.SetOptions(NewOptions: TConsoleOptions); begin if not (csDesigning in ComponentState) then { don't open files at design time } begin if (coStdInput in (NewOptions - Options)) then with TTextRec(Input) do begin if (Mode <> fmClosed) and (Mode <> 0) then raise Exception.Create('TConsole.SetOptions: Standard Input is already open'); AssignCrt(Input); Reset(Input); Include(FOptions, coStdInput); { in case opening output fails } end else if (coStdInput in (Options - NewOptions)) then System.Close(Input); if (coStdOutput in (NewOptions - Options)) then with TTextRec(Output) do begin if (Mode <> fmClosed) and (Mode <> 0) then raise Exception.Create('TConsole.SetOptions: Standard Output is already open'); AssignCrt(Output); Rewrite(Output); end else if (coStdOutput in (Options - NewOptions)) then System.Close(Output); end; FOptions := NewOptions; end; { wm_Paint message handler } procedure TConsole.Paint; var X1, X2, Y1, Y2, PX, PY: Integer; R: TRect; begin Canvas.Font := Font; Canvas.Brush.Color := Font.BkColor; SetViewportOrgEx(Canvas.Handle, -FOrigin.X * FCharSize.X, -FOrigin.Y * FCharSize.Y, nil); GetClipBox(Canvas.Handle, R); X1 := Max(FOrigin.X, (R.left - FOverhang) div FCharSize.X); X2 := Min(Cols, (R.right + FCharSize.X) div FCharSize.X); Y1 := Max(0, R.top div FCharSize.Y); Y2 := Min(Rows, (R.bottom + FCharSize.Y - 1) div FCharSize.Y); PX := X1 * FCharSize.X; PY := Y1 * FCharSize.Y; { Draw first line using ETO_Opaque and the entire clipping region. } ExtTextOutA(Canvas.Handle, PX, PY, ETO_Opaque, @R, ScreenPtr(X1, Y1), X2 - X1, nil); Inc(Y1); Inc(PY, FCharSize.Y); while Y1 < Y2 do begin { Draw subsequent lines without any background fill or clipping rect } ExtTextOutA(Canvas.Handle, PX, PY, 0, nil, ScreenPtr(X1, Y1), X2 - X1, nil); Inc(Y1); Inc(PY, FCharSize.Y); end; end; procedure TConsole.WMSize(var M: TWMSize); //var // W,H: Integer; begin if FFocused and (FReading or (coFullTimeCursor in Options)) then HideCursor; inherited; RecalcSizeAndRange; if FFocused and (FReading or (coFullTimeCursor in Options)) then ShowCursor; end; procedure TConsole.DoScroll(Which, Action, Thumb: Integer); var X, Y: Integer; function GetNewPos(Pos, Page, Range: Integer): Integer; begin case Action of sb_LineUp: GetNewPos := Pos - 1; sb_LineDown: GetNewPos := Pos + 1; sb_PageUp: GetNewPos := Pos - Page; sb_PageDown: GetNewPos := Pos + Page; sb_Top: GetNewPos := 0; sb_Bottom: GetNewPos := Range; sb_ThumbPosition, sb_ThumbTrack : GetNewPos := Thumb; else GetNewPos := Pos; end; end; begin X := FOrigin.X; Y := FOrigin.Y; case Which of sb_Horz: X := GetNewPos(X, FClientSize.X div 2, FRange.X); sb_Vert: Y := GetNewPos(Y, FClientSize.Y, FRange.Y); end; ScrollTo(X, Y); end; procedure TConsole.WMHScroll(var M: TWMHScroll); begin DoScroll(sb_Horz, M.ScrollCode, M.Pos); end; procedure TConsole.WMVScroll(var M: TWMVScroll); begin DoScroll(sb_Vert, M.ScrollCode, M.Pos); end; procedure TConsole.KeyPress(var Key: Char); begin inherited KeyPress(Key); if Key <> #0 then begin if (coCheckBreak in Options) and (Key = #3) then DoCtrlBreak; if FKeyCount < SizeOf(FKeyBuffer) then begin FKeyBuffer[FKeyCount] := AnsiChar(Key); Inc(FKeyCount); end; end; end; procedure TConsole.KeyDown(var Key: Word; Shift: TShiftState); var I: Integer; begin inherited KeyDown(Key, Shift); if Key = 0 then Exit; if (coCheckBreak in Options) and (Key = vk_Cancel) then DoCtrlBreak; for I := 1 to ScrollKeyCount do with ScrollKeys[I] do if (sKey = Key) and (Ctrl = (Shift = [ssCtrl])) then begin DoScroll(SBar, Action, 0); Exit; end; end; procedure TConsole.WMSetFocus(var M: TWMSetFocus); begin FFocused := True; if FReading or (coFullTimeCursor in Options) then ShowCursor; inherited; end; procedure TConsole.WMKillFocus(var M: TWMKillFocus); begin inherited; if FReading or (coFullTimeCursor in Options) then HideCursor; FFocused := False; end; procedure TConsole.WMGetDlgCode(var M: TWMGetDlgCode); begin M.Result := dlgc_WantArrows or dlgc_WantChars; end; procedure TConsole.WMEraseBkgnd(var M: TWMEraseBkgnd); begin M.Result := 1; end; procedure TConsole.DoCtrlBreak; begin end; procedure TConsole.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin SetFocus; inherited MouseDown(Button, Shift, X, Y); end; {**************** TAttrManager ****************} constructor TAttr.Create(F: TFixedFont); var DC: HDC; Save: THandle; TM: TTextMetric; begin inherited Create; Assign(F); BkColor := F.BkColor; DC := GetDC(0); Save := SelectObject(DC, F.Handle); GetTextMetrics(DC, TM); SelectObject(DC, Save); ReleaseDC(0,DC); Overhang := TM.tmOverhang; Underhang := MulDiv(TM.tmDescent, TM.tmOverhang, TM.tmAscent); end; {**************** TAttrManager ****************} { The list of free slots in the TAttrManager's FList is maintained in the unused pointer slots inside the FList. FFreeList is the index of the first free slot, or -1 if there are no free slots. The pointer FList[FFreeList] contains the negative of the integer index of the next free slot, and so on. In 16 bit, this code assumes $FFFF will never appear as a selector. In 32 bit, this code would assume FList indexes and pointers stored in the FList are positive (>=0) when evaluated as signed integers. } const EndOfList = -MaxInt; constructor TAttrManager.Create; begin inherited Create; FList := TList.Create; end; destructor TAttrManager.Destroy; begin Clear; FList.Free; inherited Destroy; end; function TAttrManager.GetCount; begin Result := FList.Count; end; function TAttrManager.InFreeList(P: Pointer): Boolean; begin Result := (EndOfList <= Longint(P)) and (Longint(P) < 0); end; function TAttrManager.FirstFreeIndex: Integer; begin Result := FFreeList; end; function TAttrManager.NextFreeIndex(P: Pointer): Integer; begin if (EndOfList < Longint(P)) and (Longint(P) < 0) then Result := -Longint(P) - 1 else Result := -1; end; procedure TAttrManager.SetFree(Index: Integer); begin if FFreeList < 0 then FList[Index] := Pointer(Longint(EndOfList)) else FList[Index] := Pointer(Longint(-FFreeList - 1)); FFreeList := Index; end; function TAttrManager.AllocIndex: Integer; begin if FFreeList >= 0 then begin Result := FFreeList; FFreeList := NextFreeIndex(FList[FFreeList]); end else Result := FList.Count; end; function TAttrManager.Allocate(F: TFixedFont): Integer; var P: ^Pointer; H: THandle; C,B: TColor; // N: Integer; begin Result := FCacheIndex; with F do begin C := Color; B := BkColor; H := Handle; end; if FCache <> nil then with FCache do if (Color = C) and (BkColor = B) and (Handle = H) then Exit; { Search for a match } Result := FList.Count; P := Pointer(FList.List); { Use pointer iterator instead of For loop } while (Result > 0) do begin if not InFreeList(P^) then with TAttr(P^) do if (Color = C) and (BkColor = B) and (Handle = H) then begin FCache := TAttr(P^); Result := FList.Count - Result; FCacheIndex := Result; Exit; end; Inc(P); Dec(Result); end; { No match found, so create a new TAttr in an empty slot } Result := AllocIndex; Attr[Result] := TAttr.Create(F); end; procedure TAttrManager.Clear; var I: Integer; begin for I := 0 to FList.Count - 1 do if not InFreeList(FList[I]) then TObject(FList[I]).Free; FList.Clear; FCacheIndex := 0; FCache := nil; FFreeList := -1; end; procedure TAttrManager.Reference(Index: Integer; Delta: Integer); begin with Attr[Index] do begin Inc(RefCount, Delta); if RefCount <= 0 then Attr[Index] := nil; end; end; function TAttrManager.GetAttr(Index: Integer): TAttr; begin Result := TAttr(FList[Index]); if InFreeList(Result) then Result := nil; end; procedure TAttrManager.SetAttr(Index: Integer; NewAttr: TAttr); //var // Temp: TAttr; begin if NewAttr = nil then begin TObject(FList[Index]).Free; SetFree(Index); end else if Index = FList.Count then FList.Expand.Add(NewAttr) else FList[Index] := NewAttr; FCacheIndex := Index; FCache := NewAttr; end; { ************* TColorConsole *************** } constructor TColorConsole.Create(Owner: TComponent); begin FAttrList := TAttrManager.Create; inherited Create(Owner); end; destructor TColorConsole.Destroy; begin inherited Destroy; AnsiStrings.StrDispose(PAnsiChar(FIndexes)); FAttrList.Free; AnsiStrings.StrDispose(PAnsiChar(FCellWidths)); end; function TColorConsole.IndexPtr(X,Y: Integer): PInteger; begin Result := @FIndexes^[Longint(ScreenPtr(X,Y)) - Longint(FBuffer)]; end; { ResizeBuffer - Called by constructor to init buffers, and called by SetCols/SetRows when Cols or Rows change. Cols and Rows will be set to their new values before ResizeBuffer is called. - StrAlloc will fail (raise xptn) if Cols * Rows is greater than 32k - 2 - No attempt is made to preserve the contents of the buffers. Resizing the buffers is equivallent to a ClrScr. } procedure TColorConsole.ResizeBuffer; var // I: Integer; A: Integer; P: PInteger; P2: Pointer; begin inherited ResizeBuffer; Pointer(P) := nil; P2 := nil; try Pointer(P) := StrAlloc(Longint(Cols) * Rows * Sizeof(Integer)); P2 := StrAlloc(Cols * SizeOf(Integer)); Exchange(Pointer(FIndexes), Pointer(P)); Exchange(Pointer(FCellWidths), P2); finally AnsiStrings.StrDispose(PAnsiChar(P)); AnsiStrings.StrDispose(PAnsiChar(P2)); end; FAttrList.Clear; A := FAttrList.Allocate(Font); FillInt(FIndexes^, Cols * Rows, A); FAttrList.Reference(A, Cols * Rows ); FillInt(FCellWidths^, Cols, FCharSize.X); end; { If the character cell is larger, expand settings and redraw } procedure TColorConsole.SetMetrics(const Metrics: TTextMetric); var Changed: Boolean; I: Integer; A: TAttr; function Check(A, B: Longint): Longint; begin Result := A; if A < B then begin Result := B; Changed := True; end; end; begin { Different fonts of the same point size have slightly different char cells. Keep the global char cell large enough for all. } if FOldFont.Size = Font.Size then with Metrics do begin Changed := False; { TT fonts don't report overhang } FOverhang := Check(FOverhang, Max(tmOverhang, tmMaxCharWidth - tmAveCharWidth)); FCharSize.X := Check(FCharSize.X, tmAveCharWidth); FCharSize.Y := Check(FCharSize.Y, tmHeight + tmExternalLeading); FCharAscent := Check(FCharAscent, tmAscent); if Changed then begin if FCellWidths <> nil then FillInt(FCellWidths^, Cols, FCharSize.X); RecalcSizeAndRange; Invalidate; end; end else begin { If font size changed, accept new cell verbatim. } { Update all cached fonts to new size } for I := 0 to FAttrList.Count - 1 do begin A:= FAttrList[I]; if A <> nil then A.Size := Font.Size; end; if FCellWidths <> nil then FillInt(FCellWidths^, Cols, Metrics.tmAveCharWidth); inherited SetMetrics(Metrics); end; end; procedure TColorConsole.WriteFill(X,Y: Integer; Ch: AnsiChar; Count: Cardinal); begin if Count = 0 then Exit; FillAttr(X,Y,Count); inherited WriteFill(X,Y,Ch,Count); { write ch to the char buffer } end; procedure TColorConsole.FillAttr(X,Y: Integer; Count: Cardinal); procedure ReplaceAttr(A: Integer; P: PInteger; Count: Cardinal); var RunCount: Integer; RunValue: Integer; begin while Count > 0 do begin RunValue := P^; RunCount := 0; repeat P^ := A; Inc(P); Inc(RunCount); until (Int64(RunCount) >= Int64(Count)) or (P^ <> RunValue); FAttrList.Reference(RunValue, -RunCount); Dec(Count, RunCount); end; end; var A: Integer; I: Integer; begin A := FAttrList.Allocate(Font); FAttrList.Reference(A, Count); if (Int64(X) + Int64(Count)) > Cols then begin ReplaceAttr(A, IndexPtr(X,Y), Cols - X); Dec(Count, Cols - X); I := Cols; while Count > 0 do begin Inc(Y); ReplaceAttr(A, IndexPtr(X,Y), I); Dec(Count, I); end; end else ReplaceAttr(A, IndexPtr(X,Y), Count); end; procedure TColorConsole.WriteBlock(X,Y: Integer; Buffer: PAnsiChar; Count: Cardinal); begin if Count = 0 then Exit; FillAttr(X,Y,Count); { fill range with current attr } inherited WriteBlock(X,Y,Buffer,Count); { copy chars to char buf } end; procedure TColorConsole.Paint; var X1, X2, Y1, Y2, RunValue, RunStart, RunEnd, Len, Count, Prev: Integer; R: TRect; P: PInteger; Buf: PAnsiChar; A: TAttr; C: TPoint; DC: HDC; L: Integer; begin C := FCharSize; SetViewportOrgEx(Canvas.Handle, -FOrigin.X * FCharSize.X, -FOrigin.Y * C.Y, nil); GetClipBox(Canvas.Handle, R); X1 := Max(FOrigin.X, (R.left - FOverhang) div C.X); X2 := Min(Cols, (R.right + C.X) div C.X); Y1 := Max(0, R.top div C.Y); Y2 := Min(Rows, (R.bottom + C.Y - 1) div C.Y); if ((Cols * C.X) < R.Right) then begin Canvas.Brush := Brush; Count := R.Left; R.Left := Cols * C.X; Canvas.FillRect(R); R.Right := R.Left; R.Left := Count; end; if (Rows * C.Y) < R.Bottom then begin Canvas.Brush := Brush; R.Top := Rows * C.Y; Canvas.FillRect(R); end; { In this tight display loop, we don't need all the automatic services provided by TCanvas. To optimize performance, we'll select the text font and colors into the DC 'manually'. } DC := Canvas.Handle; SetBkMode(DC, OPAQUE); SetTextAlign(DC, TA_BaseLine); R.Top := Y1 * C.Y; R.Bottom := R.Top + C.Y; Prev := -1; while Y1 < Y2 do begin Buf := ScreenPtr(X1,Y1); P := Pointer(IndexPtr(X1,Y1)); Count := X2 - X1; R.Left := X1 * C.X; RunEnd := Integer(P) + Count * sizeof(Integer); while Count > 0 do begin RunStart := Integer(P); RunValue := P^; while (Integer(P) < RunEnd) and (P^ = RunValue) do Inc(P); Len := (Integer(P) - RunStart) div sizeof(Integer); Dec(Count, Len); if RunValue <> Prev then { Only select objects when we have to } begin { (this helps at line breaks ) } A := FAttrList[RunValue]; SelectObject(DC, A.Handle); SetTextColor(DC, ColorToRGB(A.Color)); SetBkColor(DC, ColorToRGB(A.BkColor)); Prev := RunValue; end else begin A := nil; end; R.Right := R.Left + Len * C.X; if Assigned(A) then begin L := R.Left - A.Underhang; end else begin L := R.Left; end; ExtTextOutA(DC, L, R.Top + FCharAscent, ETO_Opaque or ETO_Clipped, @R, Buf, Len, Pointer(FCellWidths)); R.Left := R.Right; Inc(Buf, Len); end; Inc(Y1); Inc(R.Top, C.Y); Inc(R.Bottom, C.Y); end; { Since we've manipulated the DC directly, and the canvas may think its current objects are still selected, we should force the canvas to deselect all GDI objects } Canvas.Handle := 0; end; procedure Register; begin RegisterComponents('Additional', [TConsole, TColorConsole]); RegisterClasses([TFixedFont]); end; end.
unit FResolution; interface uses Windows, Forms; var Resolution : record Windowed : boolean; FullScreen : boolean; Width : integer; Height : integer; end; procedure ChangeResolution(); procedure InitResolution(); procedure ResetResolution(); implementation uses FLogs, sysutils, FGlWindow, FConfig; procedure ResetResolution(); begin if Resolution.FullScreen and not Resolution.Windowed then ChangeDisplaySettings(devmode(nil^), 0); end; procedure ChangeResolution(); var dmScreenSettings : DevMode; begin if Resolution.FullScreen then begin GlWindow.BorderStyle := bsNone; GlWindow.WindowState := wsMaximized; if not Resolution.Windowed then begin ZeroMemory(@dmScreenSettings, SizeOf(dmScreenSettings)); with dmScreenSettings do begin dmSize := SizeOf(dmScreenSettings); dmPelsWidth := Resolution.Width; dmPelsHeight := Resolution.Height; dmBitsPerPel := 32; dmFields := DM_PELSWIDTH or DM_PELSHEIGHT or DM_BITSPERPEL; end; ChangeDisplaySettings(dmScreenSettings, CDS_FULLSCREEN); end; end else begin GlWindow.BorderStyle := bsSizeable; GlWindow.WindowState := wsNormal; end; end; procedure InitResolution(); var cfg : TConfig; begin cfg := TConfig.create; if not FileExists('Fooo.cfg') then begin cfg.set_resolution(1024, 768); cfg.set_windowed(true); cfg.set_fullscreen(false); end; Resolution.Windowed := cfg.get_windowed; Resolution.FullScreen := cfg.get_fullscreen; Resolution.Width := cfg.get_Wresolution; Resolution.Height := cfg.get_Hresolution; end; end.
{***************************************************************} { Copyright (c) 2013 год . } { Тетенев Леонид Петрович, ltetenev@yandex.ru } { } {***************************************************************} unit SaveGridParam; interface uses winapi.Windows, winapi.Messages, System.SysUtils, System.Classes, vcl.Graphics, vcl.Controls, vcl.Forms, vcl.Dialogs, System.Variants, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, DBGridEh, Data.DB, System.Math, System.UITypes, ProcReg; // сохранить в реестр procedure DBGridToReg(Grid: TDBGridEh; Key, Param: String); // загрузить из реестра procedure RegToDBGrid(Grid: TDBGridEh; Key, Param: String; HeightDef, FrozenDef: Integer ); procedure DBGridToStreem(Grid: TDBGridEh; var ParValue: TStringStream; out RowHeight, Frozen: Integer ); procedure StreemToDBGrid(Grid: TDBGridEh; ParValue: TStringStream ); implementation function NormValueSize( Value: Integer ): Integer; var ScreenWidth: Integer; begin Result := Value; ScreenWidth := ( Screen.Width div 3 ) * 2; If ( Value > ScreenWidth ) then Result := ScreenWidth else If ( Value < 5 ) then Result := 5; end; function SaveColumnParamToStr( Grid: TDBGridEh; Ind: Integer ): String; var PList: TStringList; Al: TAlignment; FS : TFontStyles; PS: TFontPitch; StyleInt: Byte; begin If ( not Assigned( Grid )) or ( not Assigned( Grid.Columns[ Ind ] )) then Exit; PList := TStringList.Create; With Grid.Columns[ Ind ] do try PList.Clear; PList.Append( FieldName ); PList.Append( IntToStr( Index )); PList.Append( IntToStr( NormValueSize( Width ))); PList.Append( Font.Name ); PList.Append( IntToStr( Font.Charset )); PList.Append( IntToStr( Font.Size )); PList.Append( IntToStr( Font.Height )); PList.Append( IntToStr( Font.Color )); Al := Alignment; Move( Al, StyleInt, 1); PList.Append( IntToStr( StyleInt )); FS := Font.Style; Move( FS, StyleInt, 1); PList.Append( IntToStr( StyleInt )); PS := Font.Pitch; Move( PS, StyleInt, 1); PList.Append( IntToStr( StyleInt )); PList.Append( IntToStr( Integer( Visible ))); finally Result := PList.Text; PList.Free; end; end; function IntToSortString( Ind, CharCount: Integer ): String; begin Result := IntToStr( Ind ); If Length( Result ) < CharCount then Result := StringOfChar( '0', CharCount - Length( Result ) ) + Result; end; Procedure DBGridToReg(Grid: TDBGridEh; Key, Param: String); var N: Integer; KeyName, StrCol: String; begin If not Assigned( Grid ) then Exit; Grid.AutoFitColWidths := False; Application.ProcessMessages; KeyName := Key + '\' + Param; try RegDeleteKey( HKEY_CURRENT_USER, KeyName ); except raise; end; RegSetInteger( HKEY_CURRENT_USER, KeyName, 'RowHeight', Grid.RowHeight, True ); RegSetInteger( HKEY_CURRENT_USER, KeyName, 'Frozen', Grid.FrozenCols, True); For N := 0 to Grid.Columns.Count - 1 do begin StrCol := SaveColumnParamToStr( Grid, N ); RegSetString(HKEY_CURRENT_USER, KeyName, IntToSortString( N, 3 ), StrCol, True); end; end; procedure DBGridToStreem(Grid: TDBGridEh; var ParValue: TStringStream; out RowHeight, Frozen: Integer ); var N, L: Integer; StrCol: String; begin if not Assigned( ParValue ) then begin Exit; end; If not Assigned( Grid ) then Exit; Grid.AutoFitColWidths := False; Application.ProcessMessages; RowHeight := Grid.RowHeight; Frozen := Grid.FrozenCols; ParValue.Seek( 0, soBeginning ); For N := 0 to Grid.Columns.Count - 1 do begin StrCol := SaveColumnParamToStr( Grid, N ); L := length( StrCol ); ParValue.Write( L, SizeOf( Integer )); ParValue.WriteString( StrCol ); end; end; function LoadFieldNameFromStr( StrColumn: String ): String; var PList: TStringList; begin PList := TStringList.Create; PList.Clear; PList.Text := StrColumn; If PList.Count = 0 then begin Result := ''; Exit; end; try Result := PList.Strings[ 0 ]; finally PList.Free; end; end; procedure LoadColumnParamFromStr( Grid: TDBGridEh; ColName: String; StrColumn: String ); Function GetColumnName( F_Name: String ): Integer; var N: Integer; begin Result := -1; For N := 0 to Grid.Columns.Count - 1 do If AnsiSameText( F_Name, Grid.Columns.Items[ N ].FieldName ) then begin Result := N; Break; end; end; var PList: TStringList; Al: TAlignment; FS : TFontStyles; PS: TFontPitch; StyleInt: Byte; Ind: Integer; ColumnInd: Integer; begin If not Assigned( Grid ) then Exit; Ind := GetColumnName( ColName ); If ( Ind = -1 ) or ( not Assigned( Grid.Columns.Items[ Ind ] )) then Exit; PList := TStringList.Create; PList.Clear; PList.Text := StrColumn; With Grid.Columns.Items[ Ind ] do try If ( PList.Strings[ 0 ] = '' ) or ( not AnsiSameText( PList.Strings[ 0 ], ColName )) then Exit; ColumnInd := StrToIntDef( PList.Strings[ 1 ], 0); If ColumnInd >= Grid.Columns.Count then Index := Grid.Columns.Count - 1 else Index := ColumnInd; Width := NormValueSize(StrToIntDef( PList.Strings[ 2 ], 50)); Font.Name := PList.Strings[ 3 ]; Font.Charset := StrToIntDef( PList.Strings[ 4 ], 204); Font.Size := StrToIntDef( PList.Strings[ 5 ], 8); Font.Height := StrToIntDef( PList.Strings[ 6 ], -11); Font.Color := StrToIntDef( PList.Strings[ 7 ], 0); StyleInt := StrToIntDef( PList.Strings[ 8 ], 0 ); Move( StyleInt, Al, 1); Alignment := Al; StyleInt := StrToIntDef( PList.Strings[ 9 ], 0 ); Move( StyleInt, FS, 1); Font.Style := FS; StyleInt := StrToIntDef( PList.Strings[ 10 ], 0 ); Move( StyleInt, PS, 1); Font.Pitch := PS; If PList.Count > 11 then Visible := StrToIntDef( PList.Strings[ 11 ], 0 ) = 1; finally PList.Free; end; end; procedure RegToDBGrid(Grid: TDBGridEh; Key, Param: String; HeightDef, FrozenDef: Integer ); var N, Frozen: Integer; F_Name, KeyName, StrCol: String; begin KeyName := Key + '\' + Param; Grid.RowHeight := RegGetInteger( HKEY_CURRENT_USER, KeyName, 'RowHeight', HeightDef ); Frozen := RegGetInteger( HKEY_CURRENT_USER, KeyName, 'Frozen', FrozenDef ); If Frozen >= 6 then Frozen := FrozenDef; try If Frozen >= Grid.Columns.Count then Grid.FrozenCols := 0 else Grid.FrozenCols := Frozen; except Grid.FrozenCols := 0; end; N := 0; While RegParamExists( HKEY_CURRENT_USER, KeyName, IntToSortString( N, 3 ) ) do begin StrCol := RegGetString( HKEY_CURRENT_USER, KeyName, IntToSortString( N, 3 )); F_Name := LoadFieldNameFromStr( StrCol ); LoadColumnParamFromStr( Grid, F_Name, StrCol ); Inc( N ); end; end; procedure StreemToDBGrid(Grid: TDBGridEh; ParValue: TStringStream ); var L: Integer; F_Name, StrCol: String; begin if not Assigned( ParValue ) then Exit; ParValue.Seek( 0, soBeginning ); While ParValue.Position < ParValue.Size do begin ParValue.Read( L, SizeOf( Integer )); Setlength( StrCol, L ); StrCol := ParValue.ReadString( L ); F_Name := LoadFieldNameFromStr( StrCol ); LoadColumnParamFromStr( Grid, F_Name, StrCol ); end; end; end.
unit MainUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, System.Win.ComObj, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGridExportLink, cxGraphics, Math, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, System.RegularExpressions, dxSkinsDefaultPainters, dxSkinscxPCPainter, cxPCdxBarPopupMenu, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, Data.DB, cxDBData, cxContainer, Vcl.ComCtrls, dxCore, cxSpinEdit, Vcl.StdCtrls, System.Zip, cxLabel, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, Vcl.ExtCtrls, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid, cxPC, ZAbstractRODataset, ZAbstractDataset, ZDataset, ZAbstractConnection, ZConnection, IniFiles, IdMessage, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase, IdSMTP, Vcl.ActnList, IdText, IdSSLOpenSSL, IdGlobal, strUtils, IdAttachmentFile, IdFTP, cxCurrencyEdit, cxCheckBox, Vcl.Menus, DateUtils, cxButtonEdit, ZLibExGZ; type TMainForm = class(TForm) ZConnection1: TZConnection; Timer1: TTimer; qryUnit: TZQuery; dsUnit: TDataSource; Panel2: TPanel; btnSendFTP: TButton; btnExport: TButton; btnExecute: TButton; btnAll: TButton; grtvUnit: TcxGridDBTableView; grReportUnitLevel1: TcxGridLevel; grReportUnit: TcxGrid; qryReport_Upload: TZQuery; dsReport_Upload: TDataSource; cxGrid: TcxGrid; cxGridDBTableView: TcxGridDBTableView; UnitCode: TcxGridDBColumn; JuridicalName: TcxGridDBColumn; cxGridLevel: TcxGridLevel; btnAllUnit: TButton; Address: TcxGridDBColumn; UnitName: TcxGridDBColumn; JuridicalCode: TcxGridDBColumn; btnGoods: TButton; btnJuridical: TButton; IdFTP1: TIdFTP; procedure FormCreate(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure btnExportClick(Sender: TObject); procedure btnSendFTPClick(Sender: TObject); procedure btnAllClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnExecuteClick(Sender: TObject); procedure btnGoodsClick(Sender: TObject); procedure btnJuridicalClick(Sender: TObject); procedure btnAllUnitClick(Sender: TObject); private { Private declarations } FileName: String; SavePath: String; TypeData: Integer; glFTPHost, glFTPPath, glFTPUser, glFTPPassword: String; glFTPPort : Integer; public { Public declarations } procedure OpenAndFormatSQL; procedure Add_Log(AMessage:String); end; var MainForm: TMainForm; implementation {$R *.dfm} function GetThousandSeparator : string; begin if FormatSettings.ThousandSeparator = #160 then Result := ' ' else Result := FormatSettings.ThousandSeparator; end; procedure TMainForm.Add_Log(AMessage: String); var F: TextFile; begin try AssignFile(F,ChangeFileExt(Application.ExeName,'.log')); if not fileExists(ChangeFileExt(Application.ExeName,'.log')) then Rewrite(F) else Append(F); try Writeln(F,FormatDateTime('YYYY.MM.DD hh:mm:ss',now) + ' - ' + AMessage); finally CloseFile(F); end; except end; end; procedure TMainForm.OpenAndFormatSQL; var I, W : integer; begin qryReport_Upload.Close; qryReport_Upload.DisableControls; try try qryReport_Upload.Open; except on E:Exception do begin Add_Log(E.Message); Exit; end; end; if qryReport_Upload.IsEmpty then begin qryReport_Upload.Close; Exit; end; grtvUnit.ClearItems; for I := 0 to qryReport_Upload.FieldCount - 1 do with grtvUnit.CreateColumn do begin HeaderAlignmentHorz := TAlignment.taCenter; Options.Editing := False; DataBinding.FieldName := qryReport_Upload.Fields.Fields[I].FieldName; if qryReport_Upload.Fields.Fields[I].DataType in [ftString, ftWideString] then begin W := 10; qryReport_Upload.First; while not qryReport_Upload.Eof do begin W := Max(W, LengTh(qryReport_Upload.Fields.Fields[I].AsString)); if W > 70 then Break; qryReport_Upload.Next; end; qryReport_Upload.First; Width := 6 * Min(W, 70) + 2; end; end; finally qryReport_Upload.EnableControls; end; end; procedure TMainForm.btnAllClick(Sender: TObject); begin try qryUnit.First; while not qryUnit.Eof do begin Add_Log(''); Add_Log('-------------------'); Add_Log('Аптека : ' + qryUnit.FieldByName('ID').AsString); btnExecuteClick(Nil); btnExportClick(Nil); btnSendFTPClick(Nil); qryUnit.Next; Application.ProcessMessages; end; except on E: Exception do Add_Log(E.Message); end; qryUnit.Close; qryUnit.Open; end; procedure TMainForm.btnAllUnitClick(Sender: TObject); begin if not qryUnit.Active then Exit; qryReport_Upload.SQL.Text := 'SELECT * FROM gpSelect_Object_Unit_ExportPriceForHelsi (''3'')'; OpenAndFormatSQL; if qryReport_Upload.Active then TypeData := 2; end; procedure TMainForm.btnExecuteClick(Sender: TObject); begin if not qryUnit.Active then Exit; if qryUnit.IsEmpty then Exit; qryReport_Upload.SQL.Text := 'SELECT * FROM gpSelect_GoodsOnUnitRemains_ForForHelsi (' + qryUnit.FieldByName('Id').AsString + ', ''3'')'; OpenAndFormatSQL; if qryReport_Upload.Active then TypeData := 4; end; function StrToXML(AStr : string) : string; begin Result := StringReplace(AStr, '<', '&lt;', [rfReplaceAll, rfIgnoreCase]); Result := StringReplace(Result, '&', '&amp;', [rfReplaceAll, rfIgnoreCase]); Result := StringReplace(Result, '''', '&apos;', [rfReplaceAll, rfIgnoreCase]); Result := StringReplace(Result, '"', '&quot;', [rfReplaceAll, rfIgnoreCase]); end; function CurrToXML(ACurr : Currency) : String; begin Result := CurrToStr(ACurr); Result := StringReplace(Result, FormatSettings.DecimalSeparator, '.', [rfReplaceAll, rfIgnoreCase]); end; procedure TMainForm.btnExportClick(Sender: TObject); var sl : TStringList; begin if not qryReport_Upload.Active then Exit; if qryReport_Upload.IsEmpty then Exit; Add_Log('Начало выгрузки отчета'); if not ForceDirectories(SavePath) then Begin Add_Log('Не могу создать директорию выгрузки'); exit; end; FileName := ''; if TypeData = 1 then begin // Формирование отчет по юр. лицам sl := TStringList.Create; try sl.Add('<?xml version="1.0" encoding="utf-8"?>'); sl.Add('<Enterprises>'); qryReport_Upload.First; while not qryReport_Upload.Eof do begin sl.Add(' <Enterprise>'); sl.Add(' <EnterpriseID>' + qryReport_Upload.FieldByName('JuridicalCode').AsString + '</EnterpriseID>'); sl.Add(' <TradeMark>' + StrToXML(qryReport_Upload.FieldByName('JuridicalName').AsString) + '</TradeMark>'); sl.Add(' </Enterprise>'); qryReport_Upload.Next; end; sl.Add('</Enterprises>'); FileName := FormatDateTime('HHHHMMDDhhnnss', Now) + '_Enterprise'; sl.SaveToFile(SavePath + FileName + '.xml', TEncoding.UTF8) finally sl.Free; end; end; if TypeData = 2 then begin // Формирование отчет по аптекам sl := TStringList.Create; try sl.Add('<?xml version="1.0" encoding="utf-8"?>'); sl.Add('<Branches>'); qryReport_Upload.First; while not qryReport_Upload.Eof do begin sl.Add(' <Branch>'); sl.Add(' <BranchID>' + qryReport_Upload.FieldByName('UnitCode').AsString + '</BranchID>'); sl.Add(' <EnterpriseID>' + qryReport_Upload.FieldByName('JuridicalCode').AsString + '</EnterpriseID>'); sl.Add(' <TradeMark>' + StrToXML(qryReport_Upload.FieldByName('UnitName').AsString) + '</TradeMark>'); sl.Add(' <Address>'); if (qryReport_Upload.FieldByName('Latitude').AsString <> '') AND (qryReport_Upload.FieldByName('Longitude').AsString <> '') then begin sl.Add(' <Lat>' + StrToXML(qryReport_Upload.FieldByName('Latitude').AsString) + '</Lat>'); sl.Add(' <Lng>' + StrToXML(qryReport_Upload.FieldByName('Longitude').AsString) + '</Lng>'); end; sl.Add(' <Full>' + StrToXML(qryReport_Upload.FieldByName('Address').AsString) + '</Full>'); sl.Add(' </Address>'); sl.Add(' <Phones>'); sl.Add(' <Phone Value="' + StrToXML(qryReport_Upload.FieldByName('Phone').AsString) + '" />'); sl.Add(' </Phones>'); if not qryReport_Upload.FieldByName('MondayStart').IsNull AND not qryReport_Upload.FieldByName('MondayEnd').IsNull then begin sl.Add(' <Schedule>'); sl.Add(' <Day>'); sl.Add(' <Number>1</Number>'); if FormatDateTime('HH:NN', qryReport_Upload.FieldByName('MondayStart').AsDateTime) = FormatDateTime('HH:NN', qryReport_Upload.FieldByName('MondayEnd').AsDateTime) then sl.Add(' <WorkTime>00:00-24:00</WorkTime>') else sl.Add(' <WorkTime>' + FormatDateTime('HH:NN', qryReport_Upload.FieldByName('MondayStart').AsDateTime) + '-' + FormatDateTime('HH:NN', qryReport_Upload.FieldByName('MondayEnd').AsDateTime) + '</WorkTime>'); sl.Add(' </Day>'); sl.Add(' <Day>'); sl.Add(' <Number>2</Number>'); if FormatDateTime('HH:NN', qryReport_Upload.FieldByName('MondayStart').AsDateTime) = FormatDateTime('HH:NN', qryReport_Upload.FieldByName('MondayEnd').AsDateTime) then sl.Add(' <WorkTime>00:00-24:00</WorkTime>') else sl.Add(' <WorkTime>' + FormatDateTime('HH:NN', qryReport_Upload.FieldByName('MondayStart').AsDateTime) + '-' + FormatDateTime('HH:NN', qryReport_Upload.FieldByName('MondayEnd').AsDateTime) + '</WorkTime>'); sl.Add(' </Day>'); sl.Add(' <Day>'); sl.Add(' <Number>3</Number>'); if FormatDateTime('HH:NN', qryReport_Upload.FieldByName('MondayStart').AsDateTime) = FormatDateTime('HH:NN', qryReport_Upload.FieldByName('MondayEnd').AsDateTime) then sl.Add(' <WorkTime>00:00-24:00</WorkTime>') else sl.Add(' <WorkTime>' + FormatDateTime('HH:NN', qryReport_Upload.FieldByName('MondayStart').AsDateTime) + '-' + FormatDateTime('HH:NN', qryReport_Upload.FieldByName('MondayEnd').AsDateTime) + '</WorkTime>'); sl.Add(' </Day>'); sl.Add(' <Day>'); sl.Add(' <Number>4</Number>'); if FormatDateTime('HH:NN', qryReport_Upload.FieldByName('MondayStart').AsDateTime) = FormatDateTime('HH:NN', qryReport_Upload.FieldByName('MondayEnd').AsDateTime) then sl.Add(' <WorkTime>00:00-24:00</WorkTime>') else sl.Add(' <WorkTime>' + FormatDateTime('HH:NN', qryReport_Upload.FieldByName('MondayStart').AsDateTime) + '-' + FormatDateTime('HH:NN', qryReport_Upload.FieldByName('MondayEnd').AsDateTime) + '</WorkTime>'); sl.Add(' </Day>'); sl.Add(' <Day>'); sl.Add(' <Number>5</Number>'); if FormatDateTime('HH:NN', qryReport_Upload.FieldByName('MondayStart').AsDateTime) = FormatDateTime('HH:NN', qryReport_Upload.FieldByName('MondayEnd').AsDateTime) then sl.Add(' <WorkTime>00:00-24:00</WorkTime>') else sl.Add(' <WorkTime>' + FormatDateTime('HH:NN', qryReport_Upload.FieldByName('MondayStart').AsDateTime) + '-' + FormatDateTime('HH:NN', qryReport_Upload.FieldByName('MondayEnd').AsDateTime) + '</WorkTime>'); sl.Add(' </Day>'); if not qryReport_Upload.FieldByName('SaturdayStart').IsNull AND not qryReport_Upload.FieldByName('SaturdayEnd').IsNull then begin sl.Add(' <Day>'); sl.Add(' <Number>6</Number>'); if FormatDateTime('HH:NN', qryReport_Upload.FieldByName('SaturdayStart').AsDateTime) = FormatDateTime('HH:NN', qryReport_Upload.FieldByName('SaturdayEnd').AsDateTime) then sl.Add(' <WorkTime>00:00-24:00</WorkTime>') else sl.Add(' <WorkTime>' + FormatDateTime('HH:NN', qryReport_Upload.FieldByName('SaturdayStart').AsDateTime) + '-' + FormatDateTime('HH:NN', qryReport_Upload.FieldByName('SaturdayEnd').AsDateTime) + '</WorkTime>'); sl.Add(' </Day>'); end; if not qryReport_Upload.FieldByName('SundayStart').IsNull AND not qryReport_Upload.FieldByName('SundayEnd').IsNull then begin sl.Add(' <Day>'); sl.Add(' <Number>7</Number>'); if FormatDateTime('HH:NN', qryReport_Upload.FieldByName('SundayStart').AsDateTime) = FormatDateTime('HH:NN', qryReport_Upload.FieldByName('SundayEnd').AsDateTime) then sl.Add(' <WorkTime>00:00-24:00</WorkTime>') else sl.Add(' <WorkTime>' + FormatDateTime('HH:NN', qryReport_Upload.FieldByName('SundayStart').AsDateTime) + '-' + FormatDateTime('HH:NN', qryReport_Upload.FieldByName('SundayEnd').AsDateTime) + '</WorkTime>'); sl.Add(' </Day>'); end; sl.Add(' </Schedule>'); end; sl.Add(' </Branch>'); qryReport_Upload.Next; end; sl.Add('</Branches>'); FileName := FormatDateTime('HHHHMMDDhhnnss', Now) + '_apt'; sl.SaveToFile(SavePath + FileName + '.xml', TEncoding.UTF8) finally sl.Free; end; end; if TypeData = 3 then begin // Формирование отчет по медикаментам sl := TStringList.Create; try sl.Add('<?xml version="1.0" encoding="utf-8"?>'); sl.Add('<Goods>'); qryReport_Upload.First; while not qryReport_Upload.Eof do begin sl.Add(' <Offer' + ' Code="' + qryReport_Upload.FieldByName('Code').AsString + '"' + ' Name="' + StrToXML(qryReport_Upload.FieldByName('Name').AsString) + '"' + ' Producer="' + StrToXML(qryReport_Upload.FieldByName('Producer').AsString) + '"' + ' Code1="' + qryReport_Upload.FieldByName('Code1').AsString + '"/>'); qryReport_Upload.Next; end; sl.Add('</Goods>'); FileName := FormatDateTime('HHHHMMDDhhnnss', Now) + '_sku'; sl.SaveToFile(SavePath + FileName + '.xml', TEncoding.UTF8) finally sl.Free; end; end; if TypeData = 4 then begin // Формирование отчет по остаткам sl := TStringList.Create; try sl.Add('<?xml version="1.0" encoding="utf-8"?>'); sl.Add('<Data>'); sl.Add(' <Branches>'); sl.Add(' <Branch>'); sl.Add(' <BranchID>' + qryReport_Upload.FieldByName('UnitCode').AsString + '</BranchID>'); sl.Add(' <EnterpriseID>' + qryReport_Upload.FieldByName('JuridicalCode').AsString + '</EnterpriseID>'); sl.Add(' <RestDateTime>' + FormatDateTime('YYYYMMDDHHNNSS', Now()) + '</RestDateTime>'); sl.Add(' <Rests>'); qryReport_Upload.First; while not qryReport_Upload.Eof do begin sl.Add(' <Rest' + ' Code="' + qryReport_Upload.FieldByName('GoodsCode').AsString + '"' + ' Price="' + CurrToXML(qryReport_Upload.FieldByName('Price').AsCurrency) + '"' + ' PriceReserve="' + CurrToXML(qryReport_Upload.FieldByName('Price').AsCurrency) + '"' + ' Quantity="' + CurrToXML(qryReport_Upload.FieldByName('Amount').AsCurrency) + '"/>'); qryReport_Upload.Next; end; sl.Add(' </Rests>'); sl.Add(' </Branch>'); sl.Add(' </Branches>'); sl.Add('</Data>'); FileName := FormatDateTime('HHHHMMDDhhnnss', Now) + '_price'; sl.SaveToFile(SavePath + FileName + '.xml', TEncoding.UTF8) finally sl.Free; end; end; end; procedure TMainForm.btnGoodsClick(Sender: TObject); begin if not qryUnit.Active then Exit; qryReport_Upload.SQL.Text := 'SELECT * FROM gpSelect_Goods_ForForHelsi (''3'')'; OpenAndFormatSQL; if qryReport_Upload.Active then TypeData := 3; end; procedure TMainForm.btnJuridicalClick(Sender: TObject); begin if not qryUnit.Active then Exit; qryReport_Upload.SQL.Text := 'SELECT * FROM gpSelect_Object_Juridical_ExportPriceForHelsi (''3'')'; OpenAndFormatSQL; if qryReport_Upload.Active then TypeData := 1; end; procedure TMainForm.btnSendFTPClick(Sender: TObject); var ZipFile: TZipFile; begin if not FileExists(SavePath + FileName + '.xml') then Exit; try Add_Log('Начало архивирования файла: ' + SavePath + FileName); ZipFile := TZipFile.Create; try ZipFile.Open(SavePath + FileName + '.zip', zmWrite); ZipFile.Add(SavePath + FileName + '.xml'); ZipFile.Close; finally ZipFile.Free; end; except on E: Exception do begin Add_Log(E.Message); Exit; end; end; Add_Log('Начало отправки файла: ' + SavePath + FileName); try IdFTP1.Disconnect; if glFTPPort <> 0 then IdFTP1.Host := glFTPHost; IdFTP1.Port := glFTPPort; idFTP1.Username := glFTPUser; idFTP1.Password := glFTPPassword; try idFTP1.Connect; Except ON E: Exception DO Begin Add_Log(E.Message); exit; End; end; if glFTPPath <> '' then try idFTP1.ChangeDir(glFTPPath); except ON E: Exception DO begin Add_Log(E.Message); exit; end; end; try idFTP1.Put(SavePath + FileName + '.zip', FileName + '.zip'); DeleteFile(SavePath + FileName + '.zip'); except ON E: Exception DO Begin Add_Log(E.Message); exit; End; end; finally idFTP1.Disconnect; end; DeleteFile(SavePath + FileName + '.zip'); DeleteFile(SavePath + FileName + '.xml'); end; procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TMainForm.FormCreate(Sender: TObject); var Ini: TIniFile; begin TypeData := 0; FileName := ''; Ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'ExportForHelsi.ini'); try SavePath := Trim(Ini.ReadString('Options', 'Path', ExtractFilePath(Application.ExeName))); if SavePath[Length(SavePath)] <> '\' then SavePath := SavePath + '\'; Ini.WriteString('Options', 'Path', SavePath); ZConnection1.Database := Ini.ReadString('Connect', 'DataBase', 'farmacy'); Ini.WriteString('Connect', 'DataBase', ZConnection1.Database); ZConnection1.HostName := Ini.ReadString('Connect', 'HostName', '172.17.2.5'); Ini.WriteString('Connect', 'HostName', ZConnection1.HostName); ZConnection1.User := Ini.ReadString('Connect', 'User', 'postgres'); Ini.WriteString('Connect', 'User', ZConnection1.User); ZConnection1.Password := Ini.ReadString('Connect', 'Password', 'eej9oponahT4gah3'); Ini.WriteString('Connect', 'Password', ZConnection1.Password); glFTPHost := Ini.ReadString('FTP','Host',''); Ini.WriteString('FTP','Host',glFTPHost); glFTPPort := Ini.ReadInteger('FTP','Port',0); Ini.WriteInteger('FTP','Port',glFTPPort); glFTPPath := Ini.ReadString('FTP','Path',''); Ini.WriteString('FTP','Path',glFTPPath); glFTPUser := Ini.ReadString('FTP','User',''); Ini.WriteString('FTP','User',glFTPUser); glFTPPassword := Ini.ReadString('FTP','Password',''); Ini.WriteString('FTP','Password',glFTPPassword); finally Ini.free; end; ZConnection1.LibraryLocation := ExtractFilePath(Application.ExeName) + 'libpq.dll'; try ZConnection1.Connect; except on E:Exception do begin Add_Log(E.Message); Close; Exit; end; end; if ZConnection1.Connected then begin qryUnit.Close; try qryUnit.Open; except on E: Exception do begin Add_Log(E.Message); Close; Exit; end; end; if not ((ParamCount >= 1) and (CompareText(ParamStr(1), 'manual') = 0)) then begin btnAll.Enabled := false; btnAllUnit.Enabled := false; btnExecute.Enabled := false; btnExport.Enabled := false; btnSendFTP.Enabled := false; Timer1.Enabled := true; end; end; end; procedure TMainForm.Timer1Timer(Sender: TObject); begin try timer1.Enabled := False; btnAllClick(nil); finally Close; end; end; end.
{* ***************************************************************************** PROYECTO FACTURACION ELECTRONICA Copyright (C) 2010-2014 - Bambú Code SA de CV - Ing. Luis Carrasco Esta clase representa la estructura de un PAC Ejemplo para basarse en ella y poder implementar a un nuevo PAC. Se deben de implementar los 3 métodos definidos en la interfase IProveedorAutorizadoDeCertificacion Este archivo pertenece al proyecto de codigo abierto de Bambú Code: http://bambucode.com/codigoabierto La licencia de este código fuente se encuentra en: http://github.com/bambucode/tfacturaelectronica/blob/master/LICENCIA ***************************************************************************** *} unit PACEjemplo; interface uses Classes, SysUtils, FacturaTipos, ProveedorAutorizadoCertificacion, FeCFD; type TPACEjemplo = class(TProveedorAutorizadoCertificacion) {$IFDEF VERSION_DE_PRUEBA} public {$ELSE} private {$ENDIF} fCredenciales : TFEPACCredenciales; public procedure AfterConstruction; override; procedure AsignarCredenciales(const aCredenciales: TFEPACCredenciales); function CancelarDocumento(const aDocumento: TTipoComprobanteXML): Boolean; function TimbrarDocumento(const aDocumento: TTipoComprobanteXML): TFETimbre; end; implementation procedure TPACEjemplo.AfterConstruction; begin inherited; end; procedure TPACEjemplo.AsignarCredenciales(const aCredenciales: TFEPACCredenciales); begin fCredenciales := aCredenciales; end; function TPACEjemplo.CancelarDocumento(const aDocumento: TTipoComprobanteXML): Boolean; begin // TODO: Implementar la cancelacion del documento por medio del API del PAC end; function TPACEjemplo.TimbrarDocumento(const aDocumento: TTipoComprobanteXML): TFETimbre; begin // TODO: Aqui se debe de implementar el metodo que recibe el comprobante XML y lo manda // al PAC segun el API del mismo (SOAP, REST, etc) // NOTA: Debemos validar los posibles tipos de error que se pueden presentar: // EDocumentoTimbradoPreviamenteException // Posteriormente asignamos el resultado de esta funcion (tipo TFETimbre) y las propiedades // del mismo end; end.
unit DragonTrunk; {$mode objfpc}{$H+} interface uses Classes, SysUtils, VolumeInfo, DragonCargo, BaseModel; type IBaseDragonTrunk = interface(IBaseModel) ['{21E3DEBF-B906-435C-8764-1E40F1A26587}'] function GetDragonCargo: IDragonCargo; function GetTrunkVolume: IVolumeInfo; procedure SetDragonCargo(AValue: IDragonCargo); procedure SetTrunkVolume(AValue: IVolumeInfo); end; IDragonTrunk = interface(IBaseDragonTrunk) ['{BC9F51A3-D5F7-48D5-BF31-6965250D5BFE}'] property DragonCargo: IDragonCargo read GetDragonCargo write SetDragonCargo; property TrunkVolume: IVolumeInfo read GetTrunkVolume write SetTrunkVolume; end; function NewDragonTrunk: IDragonTrunk; implementation uses JSON_Helper; type { TDragonTrunk } TDragonTrunk = class(TBaseModel, IDragonTrunk) private FDragonCargo: IDragonCargo; FTrunkVolume: IVolumeInfo; function GetDragonCargo: IDragonCargo; function GetTrunkVolume: IVolumeInfo; procedure SetDragonCargo(AValue: IDragonCargo); procedure SetTrunkVolume(AValue: IVolumeInfo); public procedure BuildSubObjects(const JSONData: IJSONData); override; function ToString: string; override; end; function NewDragonTrunk: IDragonTrunk; begin Result := TDragonTrunk.Create; end; { TDragonTrunk } function TDragonTrunk.GetDragonCargo: IDragonCargo; begin Result := FDragonCargo; end; function TDragonTrunk.GetTrunkVolume: IVolumeInfo; begin Result := FTrunkVolume; end; procedure TDragonTrunk.SetDragonCargo(AValue: IDragonCargo); begin FDragonCargo := AValue; end; procedure TDragonTrunk.SetTrunkVolume(AValue: IVolumeInfo); begin FTrunkVolume := AValue; end; procedure TDragonTrunk.BuildSubObjects(const JSONData: IJSONData); var SubJSONData: IJSONData; DragonCargo: IDragonCargo; TrunkVolume: IVolumeInfo; begin inherited BuildSubObjects(JSONData); SubJSONData := JSONData.GetPath('cargo'); DragonCargo := NewDragonCargo; JSONToModel(SubJSONData.GetJSONData, DragonCargo); Self.FDragonCargo := DragonCargo; SubJSONData := JSONData.GetPath('trunk_volume'); TrunkVolume := NewVolumeInfo; JSONToModel(SubJSONData.GetJSONData, TrunkVolume); Self.FTrunkVolume := TrunkVolume; end; function TDragonTrunk.ToString: string; begin Result := Format('' + 'Dragon Cargo: [' + LineEnding + ' %s' + LineEnding + ' ]' + LineEnding + 'Trunk Volume: %s' , [ StringReplace( GetDragonCargo.ToString, LineEnding, LineEnding + ' ', [rfReplaceAll]), GetTrunkVolume.ToString ]); end; end.
unit modbus; {$mode delphi} interface uses Classes, SysUtils, And_jni, {And_jni_Bridge,} AndroidWidget; type {Draft Component code by "LAMW: Lazarus Android Module Wizard" [10/9/2021 0:22:46]} {https://github.com/jmpessoa/lazandroidmodulewizard} TOnModbusConnect=procedure(Sender:TObject;success:boolean;msg:string) of object; {jControl template} jModbus = class(jControl) private FOnConnect: TOnModbusConnect; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Init; override; function jCreate(): jObject; procedure jFree(); function msg_: string; procedure Connect(_hostIP: string; _portNumber: integer); function IsConnected(): boolean; procedure ReadCoil(_slaveId: integer; _start: integer; _len: integer); procedure ReadDiscreteInput(_slaveId: integer; _start: integer; _len: integer); procedure ReadHoldingRegisters(_slaveId: integer; _start: integer; _len: integer); procedure ReadInputRegisters(_slaveId: integer; _start: integer; _len: integer); procedure WriteCoil(_slaveId: integer; _offset: integer; _value: boolean); procedure WriteRegister(_slaveId: integer; _offset: integer; _value: integer); procedure WriteRegisters(_slaveId: integer; _start: integer; var _shortArrayValues: TDynArrayOfSmallint); procedure GenEvent_OnModbusConnect(Sender:TObject;success:boolean;msg:string); published property OnConnect: TOnModbusConnect read FOnConnect write FOnConnect; end; function jModbus_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; procedure jModbus_jFree(env: PJNIEnv; _jmodbus: JObject); function jModbus_msg_(env: PJNIEnv; _jmodbus: JObject): string; procedure jModbus_Connect(env: PJNIEnv; _jmodbus: JObject; _hostIP: string; _portNumber: integer); function jModbus_IsConnected(env: PJNIEnv; _jmodbus: JObject): boolean; procedure jModbus_ReadCoil(env: PJNIEnv; _jmodbus: JObject; _slaveId: integer; _start: integer; _len: integer); procedure jModbus_ReadDiscreteInput(env: PJNIEnv; _jmodbus: JObject; _slaveId: integer; _start: integer; _len: integer); procedure jModbus_ReadHoldingRegisters(env: PJNIEnv; _jmodbus: JObject; _slaveId: integer; _start: integer; _len: integer); procedure jModbus_ReadInputRegisters(env: PJNIEnv; _jmodbus: JObject; _slaveId: integer; _start: integer; _len: integer); procedure jModbus_WriteCoil(env: PJNIEnv; _jmodbus: JObject; _slaveId: integer; _offset: integer; _value: boolean); procedure jModbus_WriteRegister(env: PJNIEnv; _jmodbus: JObject; _slaveId: integer; _offset: integer; _value: integer); procedure jModbus_WriteRegisters(env: PJNIEnv; _jmodbus: JObject; _slaveId: integer; _start: integer; var _shortArrayValues: TDynArrayOfSmallint); implementation {--------- jModbus --------------} constructor jModbus.Create(AOwner: TComponent); begin inherited Create(AOwner); //your code here.... end; destructor jModbus.Destroy; begin if not (csDesigning in ComponentState) then begin if FjObject <> nil then begin jFree(); FjObject:= nil; end; end; //you others free code here...' inherited Destroy; end; procedure jModbus.Init; begin if FInitialized then Exit; inherited Init; //set default ViewParent/FjPRLayout as jForm.View! //your code here: set/initialize create params.... FjObject := jCreate(); //jSelf ! if FjObject = nil then exit; FInitialized:= True; end; function jModbus.jCreate(): jObject; begin Result:= jModbus_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis); end; procedure jModbus.jFree(); begin //in designing component state: set value here... if FInitialized then jModbus_jFree(gApp.jni.jEnv, FjObject); end; procedure jModbus.Connect(_hostIP: string; _portNumber: integer); begin //in designing component state: set value here... if FInitialized then jModbus_Connect(gApp.jni.jEnv, FjObject, _hostIP ,_portNumber); end; function jModbus.msg_(): string; begin //in designing component state: result value here... if FInitialized then Result:= jModbus_msg_(gApp.jni.jEnv, FjObject); end; function jModbus.IsConnected(): boolean; begin //in designing component state: result value here... if FInitialized then Result:= jModbus_IsConnected(gApp.jni.jEnv, FjObject); end; procedure jModbus.ReadCoil(_slaveId: integer; _start: integer; _len: integer); begin //in designing component state: set value here... if FInitialized then jModbus_ReadCoil(gApp.jni.jEnv, FjObject, _slaveId ,_start ,_len); end; procedure jModbus.ReadDiscreteInput(_slaveId: integer; _start: integer; _len: integer); begin //in designing component state: set value here... if FInitialized then jModbus_ReadDiscreteInput(gApp.jni.jEnv, FjObject, _slaveId ,_start ,_len); end; procedure jModbus.ReadHoldingRegisters(_slaveId: integer; _start: integer; _len: integer); begin //in designing component state: set value here... if FInitialized then jModbus_ReadHoldingRegisters(gApp.jni.jEnv, FjObject, _slaveId ,_start ,_len); end; procedure jModbus.ReadInputRegisters(_slaveId: integer; _start: integer; _len: integer); begin //in designing component state: set value here... if FInitialized then jModbus_ReadInputRegisters(gApp.jni.jEnv, FjObject, _slaveId ,_start ,_len); end; procedure jModbus.WriteCoil(_slaveId: integer; _offset: integer; _value: boolean); begin //in designing component state: set value here... if FInitialized then jModbus_WriteCoil(gApp.jni.jEnv, FjObject, _slaveId ,_offset ,_value); end; procedure jModbus.WriteRegister(_slaveId: integer; _offset: integer; _value: integer); begin //in designing component state: set value here... if FInitialized then jModbus_WriteRegister(gApp.jni.jEnv, FjObject, _slaveId ,_offset ,_value); end; procedure jModbus.WriteRegisters(_slaveId: integer; _start: integer; var _shortArrayValues: TDynArrayOfSmallint); begin //in designing component state: set value here... if FInitialized then jModbus_WriteRegisters(gApp.jni.jEnv, FjObject, _slaveId ,_start ,_shortArrayValues); end; procedure jModbus.GenEvent_OnModbusConnect(Sender:TObject;success:boolean;msg:string); begin if Assigned(FOnConnect) then FOnConnect(Sender,success,msg); end; {-------- jModbus_JNI_Bridge ----------} function jModbus_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin Result := nil; jCls:= Get_gjClass(env); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'jModbus_jCreate', '(J)Ljava/lang/Object;'); if jMethod = nil then goto _exceptionOcurred; jParams[0].j:= _Self; Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams); Result:= env^.NewGlobalRef(env, Result); _exceptionOcurred: if jni_ExceptionOccurred(env) then result := nil; end; procedure jModbus_jFree(env: PJNIEnv; _jmodbus: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin jCls:= env^.GetObjectClass(env, _jmodbus); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'jFree', '()V'); if jMethod = nil then goto _exceptionOcurred; env^.CallVoidMethod(env, _jmodbus, jMethod); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jModbus_ReadCoil(env: PJNIEnv; _jmodbus: JObject; _slaveId: integer; _start: integer; _len: integer); var jParams: array[0..2] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin jCls:= env^.GetObjectClass(env, _jmodbus); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'ReadCoil', '(III)V'); if jMethod = nil then goto _exceptionOcurred; jParams[0].i:= _slaveId; jParams[1].i:= _start; jParams[2].i:= _len; env^.CallVoidMethodA(env, _jmodbus, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jModbus_ReadDiscreteInput(env: PJNIEnv; _jmodbus: JObject; _slaveId: integer; _start: integer; _len: integer); var jParams: array[0..2] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin jCls:= env^.GetObjectClass(env, _jmodbus); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'ReadDiscreteInput', '(III)V'); if jMethod = nil then goto _exceptionOcurred; jParams[0].i:= _slaveId; jParams[1].i:= _start; jParams[2].i:= _len; env^.CallVoidMethodA(env, _jmodbus, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jModbus_ReadHoldingRegisters(env: PJNIEnv; _jmodbus: JObject; _slaveId: integer; _start: integer; _len: integer); var jParams: array[0..2] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin jCls:= env^.GetObjectClass(env, _jmodbus); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'ReadHoldingRegisters', '(III)V'); if jMethod = nil then goto _exceptionOcurred; jParams[0].i:= _slaveId; jParams[1].i:= _start; jParams[2].i:= _len; env^.CallVoidMethodA(env, _jmodbus, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jModbus_ReadInputRegisters(env: PJNIEnv; _jmodbus: JObject; _slaveId: integer; _start: integer; _len: integer); var jParams: array[0..2] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin jCls:= env^.GetObjectClass(env, _jmodbus); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'ReadInputRegisters', '(III)V'); if jMethod = nil then goto _exceptionOcurred; jParams[0].i:= _slaveId; jParams[1].i:= _start; jParams[2].i:= _len; env^.CallVoidMethodA(env, _jmodbus, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jModbus_WriteCoil(env: PJNIEnv; _jmodbus: JObject; _slaveId: integer; _offset: integer; _value: boolean); var jParams: array[0..2] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin jCls:= env^.GetObjectClass(env, _jmodbus); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'WriteCoil', '(IIZ)V'); if jMethod = nil then goto _exceptionOcurred; jParams[0].i:= _slaveId; jParams[1].i:= _offset; jParams[2].z:= JBool(_value); env^.CallVoidMethodA(env, _jmodbus, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jModbus_WriteRegister(env: PJNIEnv; _jmodbus: JObject; _slaveId: integer; _offset: integer; _value: integer); var jParams: array[0..2] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin jCls:= env^.GetObjectClass(env, _jmodbus); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'WriteRegister', '(III)V'); if jMethod = nil then goto _exceptionOcurred; jParams[0].i:= _slaveId; jParams[1].i:= _offset; jParams[2].i:= _value; env^.CallVoidMethodA(env, _jmodbus, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jModbus_WriteRegisters(env: PJNIEnv; _jmodbus: JObject; _slaveId: integer; _start: integer; var _shortArrayValues: TDynArrayOfSmallint); var jParams: array[0..2] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; newSize0: integer; jNewArray0: jObject=nil; label _exceptionOcurred; begin jCls:= env^.GetObjectClass(env, _jmodbus); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'WriteRegisters', '(II[S)V'); if jMethod = nil then goto _exceptionOcurred; jParams[0].i:= _slaveId; jParams[1].i:= _start; newSize0:= Length(_shortArrayValues); jNewArray0:= env^.NewShortArray(env, newSize0); // allocate env^.SetShortArrayRegion(env, jNewArray0, 0 , newSize0, @_shortArrayValues[0] {source}); jParams[2].l:= jNewArray0; env^.CallVoidMethodA(env, _jmodbus, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[2].l); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jModbus_Connect(env: PJNIEnv; _jmodbus: JObject; _hostIP: string; _portNumber: integer); var jParams: array[0..1] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin jCls:= env^.GetObjectClass(env, _jmodbus); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'Connect', '(Ljava/lang/String;I)V'); if jMethod = nil then goto _exceptionOcurred; jParams[0].l:= env^.NewStringUTF(env, PChar(_hostIP)); jParams[1].i:= _portNumber; env^.CallVoidMethodA(env, _jmodbus, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; function jModbus_msg_(env: PJNIEnv; _jmodbus: JObject): string; var jStr: JString; jBoo: JBoolean; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin if (env = nil) or (_jmodbus = nil) then exit; jCls:= env^.GetObjectClass(env, _jmodbus); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'msg_', '()Ljava/lang/String;'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jStr:= env^.CallObjectMethod(env, _jmodbus, jMethod); Result := GetPStringAndDeleteLocalRef(env, jStr); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; function jModbus_IsConnected(env: PJNIEnv; _jmodbus: JObject): boolean; var jBoo: JBoolean; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin jCls:= env^.GetObjectClass(env, _jmodbus); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'IsConnected', '()Z'); if jMethod = nil then goto _exceptionOcurred; jBoo:= env^.CallBooleanMethod(env, _jmodbus, jMethod); Result:= boolean(jBoo); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; end.
unit UPrefFToolBuiltIn; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2006 by Bradford Technologies, Inc. } { This is the Frame that contains the Tools > Built-In Preferences} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids_ts, TSGrid, StdCtrls, ExtCtrls, UContainer; type TPrefToolBuiltIn = class(TFrame) AppToolList: TtsGrid; Panel1: TPanel; Panel2: TPanel; StaticText1: TStaticText; rdoImportWizard: TRadioGroup; procedure ToolListsChanged(Sender: TObject; DataCol, DataRow: Integer; ByUser: Boolean); procedure AppToolListClickCell(Sender: TObject; DataColDown, DataRowDown, DataColUp, DataRowUp: Integer; DownPos, UpPos: TtsClickPosition); private FDoc: TContainer; FToolsChged: boolean; FLastToolDir: String; public constructor CreateFrame(AOwner: TComponent; ADoc: TContainer); procedure LoadPrefs; //loads in the prefs from the app procedure SavePrefs; //saves the changes end; implementation uses UGlobals, UStatus, UUtil1, UInit, UMain, IniFiles; {$R *.dfm} constructor TPrefToolBuiltIn.CreateFrame(AOwner: TComponent; ADoc: TContainer); begin inherited Create(AOwner); FDoc := ADoc; AppToolList.RowVisible[4] := False; //not IsStudentVersion; //hide ePad AppToolList.RowVisible[7] := False; //not IsStudentVersion; //hide AWC AppToolList.RowVisible[9] := True; //not IsStudentVersion; //hide CNP AppToolList.RowVisible[10] := False; //not IsStudentVersion; //hide GPS for now AppToolList.RowVisible[6] := True; //not IsStudentVersion; //hide reviewer LoadPrefs; end; procedure TPrefToolBuiltIn.LoadPrefs; var i, numItems: integer; PrefFile: TMemIniFile; IniFilePath : String; begin //load the Apps Built-in Tools preference numItems := length(appPref_AppsTools); AppToolList.Rows := numItems; for i := 0 to numItems-1 do begin AppToolList.Cell[2,i+1] := appPref_AppsTools[i].MenuName; {AppToolList.Cell[3,i+1] := appPref_AppsTools[i].AppPath; //set menu description} if appPref_AppsTools[i].MenuVisible then AppToolList.Cell[1,i+1] := cbChecked else AppToolList.Cell[1,i+1] := cbUnchecked; end; //init some vars FLastToolDir := ''; FToolsChged := False; //github 905: IniFilePath := IncludeTrailingPathDelimiter(appPref_DirPref) + cClickFormsINI; PrefFile := TMemIniFile.Create(IniFilePath); //create the INI reader try With PrefFile do begin appPref_ImportAutomatedDataMapping := ReadBool('Tools', 'ImportAutomatedDataMapping', True); //Ticket #1432 end; finally PrefFile.Free; end; if appPref_ImportAutomatedDataMapping then rdoImportWizard.ItemIndex := 1 else rdoImportWizard.ItemIndex := 0; end; procedure TPrefToolBuiltIn.SavePrefs; var i, numItems: integer; PrefFile: TMemIniFile; IniFilePath : String; begin //save preference for apps built-in tools numItems := Length(appPref_AppsTools); for i := 1 to numItems do begin appPref_AppsTools[i-1].MenuVisible := (AppToolList.Cell[1,i] = cbChecked); end; case rdoImportWizard.ItemIndex of 0: appPref_ImportAutomatedDataMapping := False else appPref_ImportAutomatedDataMapping := True; end; Main.FileImportWizard.Visible := not appPref_ImportAutomatedDataMapping; Main.FileImportMLS.Visible := appPref_ImportAutomatedDataMapping; Main.UpdateToolsMenu; IniFilePath := IncludeTrailingPathDelimiter(appPref_DirPref) + cClickFormsINI; PrefFile := TMemIniFile.Create(IniFilePath); //create the INI writer try With PrefFile do begin WriteBool('Tools', 'ImportAutomatedDataMapping', appPref_ImportAutomatedDataMapping); UpdateFile; end; finally PrefFile.Free; end; end; procedure TPrefToolBuiltIn.ToolListsChanged(Sender: TObject; DataCol, DataRow: Integer; ByUser: Boolean); begin FToolsChged := True; end; procedure TPrefToolBuiltIn.AppToolListClickCell(Sender: TObject; DataColDown, DataRowDown, DataColUp, DataRowUp: Integer; DownPos, UpPos: TtsClickPosition); begin // if (DataColDown=1) and (DataRowDown=4) then // begin // ShowNotice('You need an "ePad" Signature Tablet to use this signature function. A signature tablet is like the tablet you use to sign your name on for charges at Home Depot.'); // AppToolList.Cell[1,4] := cbUnchecked; // end; end; end.
unit AqDrop.Core.Helpers.TObject; {$I '..\Core\AqDrop.Core.Defines.Inc'} interface uses System.Rtti, System.SyncObjs, System.Generics.Collections, {$IF CompilerVersion >= 27} // DXE6+ System.JSON; {$ELSE} Data.DBXJSON; {$ENDIF} type TAqFieldMapping = class strict private FFieldFrom: TRttiField; FFieldTo: TRttiField; public constructor Create(const pFieldFrom, pFieldTo: TRttiField); property FieldFrom: TRttiField read FFieldFrom; property FieldTo: TRttiField read FFieldTo; end; TAqObjectMapping = class strict private FFrom: TRttiType; FTo: TRttiType; FFieldMappings: TObjectList<TAqFieldMapping>; class var FLocker: TCriticalSection; class var FMappings: TObjectDictionary<string, TAqObjectMapping>; private class procedure _Initialize; class procedure _Finalize; public constructor Create(const pFrom, pTo: TClass); destructor Destroy; override; procedure Execute(const pFrom, pTo: TObject); class procedure Clone(const pFrom, pTo: TObject); end; TAqObjectHelper = class helper for TObject public procedure CloneTo(const pObject: TObject); overload; function CloneTo<T: class, constructor>: T; overload; function ConvertToJSON(const pDestroySource: Boolean = False): TJSONValue; end; implementation uses Data.DBXJSONReflect; { TAqObjectHelper } procedure TAqObjectHelper.CloneTo(const pObject: TObject); begin TAqObjectMapping.Clone(Self, pObject); end; function TAqObjectHelper.CloneTo<T>: T; begin if Assigned(Self) then begin Result := T.Create; try Self.CloneTo(Result); except Result.Free; raise; end; end else begin Result := nil; end; end; function TAqObjectHelper.ConvertToJSON(const pDestroySource: Boolean): TJSONValue; var lMarshal: TJSONMarshal; begin if not Assigned(Self) then begin Result := TJSONNull.Create; end else begin try lMarshal := TJSONMarshal.Create; try Result := lMarshal.Marshal(Self); finally lMarshal.Free; end; finally {$IFNDEF AQMOBILE} if pDestroySource then begin Free; end; {$ENDIF} end; end; end; { TAqObjectMapping } class procedure TAqObjectMapping.Clone(const pFrom, pTo: TObject); var lMappingName: string; lMapping: TAqObjectMapping; begin lMappingName := pFrom.QualifiedClassName + ' X ' + pTo.QualifiedClassName; FLocker.Enter; try if not FMappings.TryGetValue(lMappingName, lMapping) then begin lMapping := TAqObjectMapping.Create(pFrom.ClassType, pTo.ClassType); FMappings.Add(lMappingName, lMapping); end; finally FLocker.Leave; end; lMapping.Execute(pFrom, pTo); end; constructor TAqObjectMapping.Create(const pFrom, pTo: TClass); var lContext: TRttiContext; lFieldFrom: TRttiField; lFieldTo: TRttiField; begin FFieldMappings := TObjectList<TAqFieldMapping>.Create; lContext := TRttiContext.Create; try FFrom := lContext.GetType(pFrom); FTo := lContext.GetType(pTo); for lFieldFrom in FFrom.GetFields do begin lFieldTo := FTo.GetField(lFieldFrom.Name); if Assigned(lFieldTo) then begin FFieldMappings.Add(TAqFieldMapping.Create(lFieldFrom, lFieldTo)); end; end; finally lContext.Free; end; end; destructor TAqObjectMapping.Destroy; begin FFieldMappings.Free; end; procedure TAqObjectMapping.Execute(const pFrom, pTo: TObject); var lFieldMapping: TAqFieldMapping; begin for lFieldMapping in FFieldMappings do begin lFieldMapping.FieldTo.SetValue(Pointer(pTo), lFieldMapping.FieldFrom.GetValue(pFrom)); end; end; class procedure TAqObjectMapping._Finalize; begin FMappings.Free; FLocker.Free; end; class procedure TAqObjectMapping._Initialize; begin FLocker := TCriticalSection.Create; FMappings := TObjectDictionary<string, TAqObjectMapping>.Create([doOwnsValues]); end; { TAqFieldMapping } constructor TAqFieldMapping.Create(const pFieldFrom, pFieldTo: TRttiField); begin FFieldFrom := pFieldFrom; FFieldTo := pFieldTo; end; initialization TAqObjectMapping._Initialize; finalization TAqObjectMapping._Finalize; end.
Program Carregador_Sintatico; Uses Crt; Const NUMERO = 13; Type Str2 = String[2]; RTABSINT = Record TIPO : Str2; NOMETS : Str2; NUMNO : Integer; ALTTS : Integer; SUCTS : Integer; End; RTABGRAFO = Record TER : Boolean; SIM : Integer; ALTTG : Integer; SUCTG : Integer; End; RTABT = Record NOMET : Str2; End; RTABNT = Record NOMENT : Str2; PRIM : Integer; End; Var TABSINT : Array [1..NUMERO] of RTABSINT; TABGRAFO : Array [1..NUMERO] of RTABGRAFO; TABT : Array [1..NUMERO] of RTABT; TABNT : Array [1..NUMERO] of RTABNT; MAXT, MAXNT, INDPRIM, NOMAX : Integer; INDTS, J, I, E : Integer; (**********Function Verifica se Esta na TABNT *******************) Function EncontraNaTABNT (NOME : Str2) : Boolean; Var AUX_INDNT : Integer; CHAVE : Boolean; Begin Chave := false; AUX_INDNT := 1; While TABNT[AUX_INDNT].NOMENT <> '' Do Begin If TABNT[AUX_INDNT].NOMENT = NOME Then Chave := True; Inc(AUX_INDNT); End; EncontraNaTABNT := Chave; End; (**********Function Verifica se Esta na TABT *******************) Function EncontraNaTABT (NOME : Str2) : Boolean; Var AUX_INDT : Integer; CHAVE : Boolean; Begin Chave := false; AUX_INDT := 1; While TABT[AUX_INDT].NOMET <> '' Do Begin If TABT[AUX_INDT].NOMET = NOME Then Chave := True; Inc(AUX_INDT); End; EncontraNaTABT := Chave; End; Begin (************ Dados da Matriz TABSINT **************************) TABSINT[1].TIPO := 'C'; TABSINT[1].NOMETS := 'S'; TABSINT[1].NUMNO := -1; TABSINT[1].ALTTS := -1; TABSINT[1].SUCTS := -1; TABSINT[2].TIPO := 'T'; TABSINT[2].NOMETS := 'a'; TABSINT[2].NUMNO := 1; TABSINT[2].ALTTS := 5; TABSINT[2].SUCTS := 2; TABSINT[3].TIPO := 'T'; TABSINT[3].NOMETS := 'b'; TABSINT[3].NUMNO := 2; TABSINT[3].ALTTS := 3; TABSINT[3].SUCTS := 0; TABSINT[4].TIPO := 'N'; TABSINT[4].NOMETS := 'S'; TABSINT[4].NUMNO := 3; TABSINT[4].ALTTS := 0; TABSINT[4].SUCTS := 4; TABSINT[5].TIPO := 'T'; TABSINT[5].NOMETS := 'c'; TABSINT[5].NUMNO := 4; TABSINT[5].ALTTS := 0; TABSINT[5].SUCTS := 0; TABSINT[6].TIPO := 'T'; TABSINT[6].NOMETS := 'd'; TABSINT[6].NUMNO := 5; TABSINT[6].ALTTS := 7; TABSINT[6].SUCTS := 6; TABSINT[7].TIPO := 'N'; TABSINT[7].NOMETS := 'M'; TABSINT[7].NUMNO := 6; TABSINT[7].ALTTS := 0; TABSINT[7].SUCTS := 0; TABSINT[8].TIPO := 'T'; TABSINT[8].NOMETS := 'e'; TABSINT[8].NUMNO := 7; TABSINT[8].ALTTS := 0; TABSINT[8].SUCTS := 0; TABSINT[9].TIPO := 'C'; TABSINT[9].NOMETS := 'M'; TABSINT[9].NUMNO := -1; TABSINT[9].ALTTS := -1; TABSINT[9].SUCTS := -1; TABSINT[10].TIPO := 'T'; TABSINT[10].NOMETS := 'f'; TABSINT[10].NUMNO := 1; TABSINT[10].ALTTS := 3; TABSINT[10].SUCTS := 2; TABSINT[11].TIPO := 'N'; TABSINT[11].NOMETS := 'S'; TABSINT[11].NUMNO := 2; TABSINT[11].ALTTS := 0; TABSINT[11].SUCTS := 1; TABSINT[12].TIPO := 'T'; TABSINT[12].NOMETS := ''; TABSINT[12].NUMNO := 3; TABSINT[12].ALTTS := 0; TABSINT[12].SUCTS := 0; TABSINT[13].TIPO := ''; TABSINT[13].NOMETS := ''; TABSINT[13].NUMNO := -1; TABSINT[13].ALTTS := -1; TABSINT[13].SUCTS := -1; (************* Inicializacao das Variaveis ********************) Clrscr; MAXT := 0; MAXNT := 0; INDPRIM := 1; NOMAX := 0; INDTS := 1; While TABSINT[INDTS].TIPO <> '' DO Begin{1} If TABSINT[INDTS].TIPO = 'C' Then Begin{2} INDPRIM := INDPRIM + NOMAX; NOMAX := 0; If EncontraNaTABNT(TABSINT[INDTS].NOMETS) = False Then Begin{3} MAXNT := MAXNT + 1; TABNT[MAXNT].NOMENT := TABSINT[INDTS].NOMETS; TABNT[MAXNT].PRIM := INDPRIM; End;{3} For J := 1 To MAXNT DO Begin{4} If ((TABNT[J].NOMENT = TABSINT[INDTS].NOMETS) And (TABNT[J].PRIM = 0)) Then Begin {5} TABNT[J].PRIM := INDPRIM; End{5} Else Begin{7} {Erro (dois cabecas para um mesmo terminal) } End;{7} End;{4} End{2} Else Begin{8} I := INDPRIM + TABSINT[INDTS].NUMNO - 1; If ((TABSINT[INDTS].TIPO = 'T') And (TABSINT[INDTS].NOMETS <> '')) Then Begin {9} If (EncontraNaTABT(TABSINT[INDTS].NOMETS) = False) Then Begin {10} MAXT := MAXT + 1; TABT[MAXT].NOMET := TABSINT[INDTS].NOMETS; End; {10} For J := 1 To MAXT DO Begin{11} If (TABT[J].NOMET = TABSINT[INDTS].NOMETS) Then Begin {12} TABGRAFO[I].TER := True; End{12} End;{11} End; {9} If (TABSINT[INDTS].TIPO = 'N') Then Begin{13} If (EncontraNaTABNT(TABSINT[INDTS].NOMETS) = False) Then Begin {14} MAXNT := MAXNT + 1; TABNT[MAXNT].NOMENT := TABSINT[INDTS].NOMETS; TABNT[MAXNT].PRIM := 0; End; {14} For J := 1 To MAXNT DO Begin{15} If (TABNT[J].NOMENT = TABSINT[INDTS].NOMETS) Then Begin {16} TABGRAFO[I].TER := False; E := J; J := MAXNT; End{16} End;{15} End;{13} IF (TABSINT[INDTS].NOMETS = '') Then Begin {17} TABGRAFO[I].TER := True; TABGRAFO[I].SIM := 0; End{17} Else Begin{18} TABGRAFO[I].SIM := E; End;{18} IF (TABSINT[INDTS].ALTTS <> 0) Then Begin {19} TABGRAFO[I].ALTTG := INDPRIM + TABSINT[INDTS].ALTTS - 1; End{19} Else Begin{20} TABGRAFO[I].ALTTG := 0; End;{20} IF (TABSINT[INDTS].SUCTS <> 0) Then Begin {21} TABGRAFO[I].SUCTG := INDPRIM + TABSINT[INDTS].SUCTS - 1; End{21} Else Begin{22} TABGRAFO[I].SUCTG := 0; End;{22} If (NOMAX < TABSINT[INDTS].NUMNO) Then Begin{23} NOMAX := TABSINT[INDTS].NUMNO; End;{23} End;{8} INC(INDTS); End;{1} Writeln('TABSINT'); For J := 1 to Numero do Begin WRITElN(TABSINT[J].TIPO,' - ',TABSINT[J].NOMETS,' - ', TABSINT[J].NUMNO,' - ',TABSINT[J].ALTTS,' - ',TABSINT[J].SUCTS); End; READLN; Writeln('TABGRAFO'); For J := 1 to Numero do Begin WRITElN(TABGRAFO[J].TER,' - ',TABGRAFO[J].SIM,' - ', TABGRAFO[J].ALTTG,' - ',TABGRAFO[J].SUCTG); End; READLN; Writeln('TABT'); For J := 1 to Numero do Begin WRITElN(TABT[J].NOMET); End; READLN; Writeln('TABNT'); For J := 1 to Numero do Begin WRITElN(TABNT[J].NOMENT,' - ',TABNT[J].PRIM); End; READLN; End.
unit UAutoUpdate; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. } { This unit checks for updates. It uses a thread } interface uses Classes, Contnrs, Controls, RzTray, UInterfaces, UProcessingForm, UStreams, UTaskThread, UVersion; type TAutoUpdateState = ( ausHaveNotChecked, ausChecking, ausMaintenanceExpired, ausNoUpdatesAvailable, ausUpdatesAvailable, ausDownloading, ausUpdatesDownloaded, ausError ); TStateChangeEvent = procedure(const State: TAutoUpdateState) of object; TDownloadProgressEvent = procedure(const Received: LongWord; const TotalReceived: Int64; const TotalDownload: Int64) of object; TEndProcessEvent = procedure(const ReturnValue: Integer; const Message: String) of object; TRelease = class private FFileName: String; FProductID: TProductID; FVersion: LongWord; FURL: String; private procedure SetURL(const Value: String); public property FileName: String read FFileName write FFileName; property ProductID: TProductID read FProductID write FProductID; property Version: LongWord read FVersion write FVersion; property URL: String read FURL write SetURL; end; TReleaseList = class(TObjectList) protected function Get(Index: Integer): TRelease; procedure Put(Index: Integer; Item: TRelease); public function Extract(Item: TRelease): TRelease; function First: TRelease; function Last: TRelease; property Items[Index: Integer]: TRelease read Get write Put; default; end; TAutoUpdate = class(TComponent, IAbortable) private FAborted: Boolean; FAuthorized: Boolean; FDownloadList: TReleaseList; FDownloadReceived: Int64; FDownloadSize: Int64; FFileStream: THttpFileStream; FInstallList: TReleaseList; FOnEndCheckForUpdates: TEndProcessEvent; FOnEndDownloadingUpdates: TEndProcessEvent; FOnDownloadProgress: TDownloadProgressEvent; FOnStateChange: TStateChangeEvent; FState: TAutoUpdateState; FThread: TTaskThread; private procedure DoStateChange; function GetDownloadedFile(Index: TProductID): String; procedure SetDownloadedFile(Index: TProductID; Value: String); function GetDownloadedVersion(Index: TProductID): LongWord; procedure SetDownloadedVersion(Index: TProductID; Value: LongWord); function GetInsallListItem(Index: Integer): TRelease; function GetInstallListCount: Integer; procedure OnDataReceived(const Stream: TStream; const Count: Longint); protected function GetAuthorization: Boolean; procedure GetAvailableUpdates(const CustomerID: String); procedure GetFile(const URL: String; const Stream: TStream); function GetFileSize(const URL: String): Int64; procedure DoDownloadProgress(const Received: LongWord; const TotalReceived: Int64; const TotalDownload: Int64); procedure DoEndCheckForUpdates(Sender: TObject); procedure DoEndDownloadingUpdates(Sender: TObject); procedure InternalCheckForUpdates(const Thread: TTaskThread; const Data: Pointer); procedure InternalDownloadUpdates(const Thread: TTaskThread; const Data: Pointer); procedure SetState(const State: TAutoUpdateState); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure BeginCheckForUpdates(const EndCheckForUpdates: TEndProcessEvent); procedure BeginDownloadUpdates(const EndDownloadingUpdates: TEndProcessEvent); property Authorized: Boolean read FAuthorized; property DownloadedFile[Index: TProductID]: String read GetDownloadedFile write SetDownloadedFile; property DownloadedVersion[Index: TProductID]: LongWord read GetDownloadedVersion write SetDownloadedVersion; property InstallList[Index: Integer]: TRelease read GetInsallListItem; property InstallListCount: Integer read GetInstallListCount; property State: TAutoUpdateState read FState; published property OnDownloadProgress: TDownloadProgressEvent read FOnDownloadProgress write FOnDownloadProgress; property OnStateChange: TStateChangeEvent read FOnStateChange write FOnStateChange; public // IAbortable procedure Abort; function GetAborted: Boolean; property Aborted: Boolean read GetAborted; end; implementation uses Windows, DateUtils, Dialogs, Forms, IdHTTP, Registry, ShellAPI, SysUtils, TypInfo, AWSI_Server_Clickforms, UCSVDataSet, UCustomerServices, UDebugTools, UGlobals, ULicUser, UPaths, UWebUtils, UWinUtils; const CRegDownloadedFile = 'DownloadedFile'; CRegDownloadedVersion = 'DownloadedVersion'; CTimeout = 30000; // 30 seconds // --- TRelease --------------------------------------------------------------- procedure TRelease.SetURL(const Value: String); const PathDelim = '/'; var I: Integer; begin FURL := Value; I := LastDelimiter(PathDelim + DriveDelim, Value); FFileName := IncludeTrailingPathDelimiter(ExtractFilePath(FFileName)) + Copy(Value, I + 1, MaxInt); end; // --- TReleaseList ----------------------------------------------------------- function TReleaseList.Get(Index: Integer): TRelease; begin Result := TObject(inherited Get(Index)) as TRelease; end; procedure TReleaseList.Put(Index: Integer; Item: TRelease); begin inherited Put(Index, Item); end; function TReleaseList.Extract(Item: TRelease): TRelease; begin Result := TObject(inherited Extract(Item)) as TRelease; end; function TReleaseList.First: TRelease; begin Result := TObject(inherited First) as TRelease; end; function TReleaseList.Last: TRelease; begin Result := TObject(inherited Last) as TRelease; end; // --- TAutoUpdate ------------------------------------------------------------ procedure TAutoUpdate.DoStateChange; begin if Assigned(FOnStateChange) then FOnStateChange(State); end; function TAutoUpdate.GetDownloadedFile(Index: TProductID): String; var Registry: TRegistry; begin Result := ''; Registry := TRegistry.Create(KEY_READ); try Registry.RootKey := HKEY_CURRENT_USER; if Registry.KeyExists(TRegPaths.Update + GuidToString(Index)) then begin Registry.OpenKeyReadOnly(TRegPaths.Update + GuidToString(Index)); if Registry.ValueExists(CRegDownloadedFile) then begin if FileExists(Registry.ReadString(CRegDownloadedFile)) then Result := Registry.ReadString(CRegDownloadedFile) else Result := ''; end; Registry.CloseKey; end; finally FreeAndNil(Registry); end; end; procedure TAutoUpdate.SetDownloadedFile(Index: TProductID; Value: String); var OldFile: String; Registry: TRegistry; begin if FileExists(Value) then begin OldFile := DownloadedFile[Index]; Registry := TRegistry.Create(KEY_WRITE); try Registry.RootKey := HKEY_CURRENT_USER; Registry.OpenKey(TRegPaths.Update + GuidToString(Index), True); Registry.WriteString(CRegDownloadedFile, Value); Registry.CloseKey; if (Value <> OldFile) and FileExists(OldFile) then DeleteFile(OldFile); finally FreeAndNil(Registry); end; end; end; function TAutoUpdate.GetDownloadedVersion(Index: TProductID): LongWord; var Registry: TRegistry; begin Result := 0; Registry := TRegistry.Create(KEY_READ); try Registry.RootKey := HKEY_CURRENT_USER; if Registry.KeyExists(TRegPaths.Update + GuidToString(Index)) then begin Registry.OpenKeyReadOnly(TRegPaths.Update + GuidToString(Index)); if Registry.ValueExists(CRegDownloadedVersion) then Result := Registry.ReadInteger(CRegDownloadedVersion); Registry.CloseKey; end; finally FreeAndNil(Registry); end; end; procedure TAutoUpdate.SetDownloadedVersion(Index: TProductID; Value: LongWord); var Registry: TRegistry; begin Registry := TRegistry.Create(KEY_WRITE); try Registry.RootKey := HKEY_CURRENT_USER; Registry.OpenKey(TRegPaths.Update + GuidToString(Index), True); Registry.WriteInteger(CRegDownloadedVersion, Value); Registry.CloseKey; finally FreeAndNil(Registry); end; end; function TAutoUpdate.GetInsallListItem(Index: Integer): TRelease; begin Result := FInstallList.Items[Index]; end; function TAutoUpdate.GetInstallListCount: Integer; begin Result := FInstallList.Count; end; procedure TAutoUpdate.OnDataReceived(const Stream: TStream; const Count: Longint); begin FDownloadReceived := FDownloadReceived + Count; DoDownloadProgress(Count, FDownloadReceived, FDownloadSize); end; function TAutoUpdate.GetAuthorization: Boolean; begin result := True; end; procedure TAutoUpdate.GetAvailableUpdates(const CustomerID: String); const CFieldProductID = 0; CFieldMajor = 1; CFieldMinor = 2; CFieldBuild = 3; CFieldDownloadURL = 4; CRequestParams = '?CustomerID=%s'; var DataSet: TCSVDataSet; Download: Boolean; Index: Integer; Install: Boolean; Product: TProductVersion; Protocol: TIDHTTP; Release: TRelease; Stream: TMemoryStream; Version: TVersion; begin DataSet := nil; Product := nil; Protocol := nil; Stream := nil; Version := nil; if IsConnectedToWeb and not Assigned(FFileStream) then try DataSet := TCSVDataSet.Create(nil); Product := TProductVersion.Create(nil); Protocol := TIDHTTP.Create; Stream := TMemoryStream.Create; Version := TVersion.Create(nil); FDownloadSize := 0; FDownloadList.Clear; FInstallList.Clear; Protocol.ReadTimeout := CTimeout; Protocol.Get(TWebPaths.ProductReleaseList + Format(CRequestParams, [CurrentUser.AWUserInfo.UserCustUID]), Stream); Stream.Position := 0; DataSet.CreateDataSetFromCSV(Stream); DataSet.First; for Index := 0 to DataSet.RecordCount - 1 do begin Product.ProductID := StringToGuid(DataSet.Fields[CFieldProductID].AsString); Version.Major := DataSet.Fields[CFieldMajor].AsInteger; Version.Minor := DataSet.Fields[CFieldMinor].AsInteger; Version.Build := DataSet.Fields[CFieldBuild].AsInteger; Install := Product.Installed; Install := Install and (Version.Value > Product.Value); Download := Install and (Version.Value > DownloadedVersion[Product.ProductID]); Download := Download or (Version.Value = DownloadedVersion[Product.ProductID]) and not FileExists(DownloadedFile[Product.ProductID]); if Install then begin Release := TRelease.Create; Release.ProductID := StringToGuid(DataSet.Fields[CFieldProductID].AsString); Release.Version := Version.Value; Release.URL := DataSet.Fields[CFieldDownloadURL].AsString; Release.FileName := TCFFilePaths.Update + ExtractFileName(Release.FileName); FInstallList.Add(Release); if Download then begin FDownloadSize := FDownloadSize + GetFileSize(Release.URL); FDownloadList.Add(Release); end; end; if not DataSet.Eof then DataSet.Next; end; finally FreeAndNil(Version); FreeAndNil(Stream); FreeAndNil(Protocol); FreeAndNil(Product); FreeAndNil(DataSet); end; end; procedure TAutoUpdate.GetFile(const URL: String; const Stream: TStream); var Protocol: TIdHTTP; begin Protocol := TIdHTTP.Create; try Protocol.ReadTimeout := CTimeout; Protocol.Get(URL, Stream); finally FreeAndNil(Protocol); end; end; function TAutoUpdate.GetFileSize(const URL: String): Int64; var Protocol: TIdHTTP; begin Result := 0; Protocol := TIdHTTP.Create; try Protocol.ReadTimeout := CTimeout; Protocol.Head(URL); if Assigned(Protocol.Response) and Protocol.Response.HasContentLength then Result := Protocol.Response.ContentLength; finally FreeAndNil(Protocol); end; end; procedure TAutoUpdate.DoDownloadProgress(const Received: LongWord; const TotalReceived: Int64; const TotalDownload: Int64); begin if Assigned(FOnDownloadProgress) then FOnDownloadProgress(Received, TotalReceived, TotalDownload); end; procedure TAutoUpdate.DoEndCheckForUpdates(Sender: TObject); begin if Assigned(FOnEndCheckForUpdates) then FOnEndCheckForUpdates(FThread.ReturnValue, FThread.ExceptionMessage); end; procedure TAutoUpdate.DoEndDownloadingUpdates(Sender: TObject); begin if Assigned(FOnEndDownloadingUpdates) then FOnEndDownloadingUpdates(FThread.ReturnValue, FThread.ExceptionMessage); end; procedure TAutoUpdate.InternalCheckForUpdates(const Thread: TTaskThread; const Data: Pointer); begin FAborted := False; SetState(ausChecking); FAuthorized := GetAuthorization; GetAvailableUpdates(CurrentUser.AWUserInfo.UserCustUID); if (FInstallList.Count = 0) then SetState(ausNoUpdatesAvailable) else if (FDownloadList.Count = 0) then SetState(ausUpdatesDownloaded) else if not FAuthorized then SetState(ausMaintenanceExpired) else SetState(ausUpdatesAvailable); end; procedure TAutoUpdate.InternalDownloadUpdates(const Thread: TTaskThread; const Data: Pointer); var Index: Integer; begin FAborted := False; FDownloadReceived := 0; SetState(ausDownloading); if not Assigned(FFileStream) then begin for Index := 0 to FDownloadList.Count - 1 do begin FFileStream := THttpFileStream.Create(FDownloadList.Items[Index].FileName, fmCreate); try try FFileStream.OnDataReceived := OnDataReceived; GetFile(FDownloadList.Items[Index].URL, FFileStream); DownloadedVersion[FDownloadList.Items[Index].ProductID] := FDownloadList.Items[Index].Version; DownloadedFile[FDownloadList.Items[Index].ProductID] := FDownloadList.Items[Index].FileName; except on E: Exception do begin SetState(ausError); raise; end; end; finally FreeAndNil(FFileStream); end; end; SetState(ausUpdatesDownloaded); end; end; procedure TAutoUpdate.SetState(const State: TAutoUpdateState); begin FState := State; TDebugTools.WriteLine(ClassName + ': ' + GetEnumName(TypeInfo(TAutoUpdateState), Integer(State))); FThread.Synchronize(FThread, DoStateChange); end; constructor TAutoUpdate.Create(AOwner: TComponent); begin inherited; FInstallList := TReleaseList.Create(True); FDownloadList := TReleaseList.Create(False); FState := ausHaveNotChecked; end; destructor TAutoUpdate.Destroy; begin Abort; FreeAndNil(FThread); FreeAndNil(FDownloadList); FreeAndNil(FInstallList); inherited; end; procedure TAutoUpdate.BeginCheckForUpdates(const EndCheckForUpdates: TEndProcessEvent); begin if Assigned(FThread) and FThread.Terminated then FreeAndNil(FThread); if not Assigned(FThread) and IsConnectedToWeb then begin FThread := TTaskThread.Create(InternalCheckForUpdates, nil); try FOnEndCheckForUpdates := EndCheckForUpdates; FThread.OnTerminate := DoEndCheckForUpdates; FThread.Priority := tpLowest; FThread.Resume; except FreeAndNil(FThread); raise; end; end; end; procedure TAutoUpdate.BeginDownloadUpdates(const EndDownloadingUpdates: TEndProcessEvent); begin if Assigned(FThread) and FThread.Terminated then FreeAndNil(FThread); if not Assigned(FThread) and IsConnectedToWeb then begin FThread := TTaskThread.Create(InternalDownloadUpdates, nil); try FOnEndDownloadingUpdates := EndDownloadingUpdates; FThread.OnTerminate := DoEndDownloadingUpdates; FThread.Priority := tpLowest; FThread.Resume; except FreeAndNil(FThread); raise; end; end; end; procedure TAutoUpdate.Abort; begin if Assigned(FThread) and not FAborted then begin if not FThread.Terminated then try FThread.Suspend; if Assigned(FFileStream) then FFileStream.Abort; finally FThread.Resume; end; FAborted := True; while not FThread.Terminated do begin Application.HandleMessage; if Application.Terminated then begin TerminateThread(FThread.Handle, Cardinal(S_FALSE)); break; end; end; FThread.WaitFor; SetState(ausError); end; end; function TAutoUpdate.GetAborted: Boolean; begin Result := FAborted; end; end.
unit PlotOptions; { SimThyr Project } { A numerical simulator of thyrotropic feedback control } { Version 4.0.3 (Merlion) } { (c) J. W. Dietrich, 1994 - 2020 } { (c) Ludwig Maximilian University of Munich 1995 - 2002 } { (c) Ruhr University of Bochum 2005 - 2020 } { This unit implements a dialog box for plot options } { Source code released under the BSD License } { See http://simthyr.sourceforge.net for details } {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, SimThyrTypes, SimThyrServices, EnvironmentInfo; type { TPlotOptionsForm } TPlotOptionsForm = class(TForm) FontsCombobox: TComboBox; TitleLabel: TLabel; OKButton: TButton; ColorButton1: TColorButton; TitleEdit: TEdit; procedure FormPaint(Sender: TObject); procedure FormShow(Sender: TObject); procedure OKButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { private declarations } public { public declarations } function GetPlotOptions: TPlotOptions; end; var PlotOptionsForm: TPlotOptionsForm; implementation {$R *.lfm} { TPlotOptionsForm } procedure TPlotOptionsForm.FormCreate(Sender: TObject); begin if YosemiteORNewer then begin OKButton.Height := 22; end; if DarkTheme then begin ColorButton1.ButtonColor := clWhite; end else begin ColorButton1.ButtonColor := clBlack; end end; function TPlotOptionsForm.GetPlotOptions: TPlotOptions; begin ShowModal; GetPlotOptions.titleString := AnsiString(TitleEdit.Text); GetPlotOptions.titleColor := ColorButton1.ButtonColor; if FontsCombobox.ItemIndex < 1 then GetPlotOptions.fontname := 'default' else GetPlotOptions.fontname := FontsCombobox.Items[FontsCombobox.ItemIndex]; end; procedure TPlotOptionsForm.OKButtonClick(Sender: TObject); begin Close; end; procedure TPlotOptionsForm.FormShow(Sender: TObject); begin FormPaint(Sender); FontsCombobox.Items.Assign(Screen.Fonts); ShowOnTop; SetFocus; end; procedure TPlotOptionsForm.FormPaint(Sender: TObject); begin if DarkTheme then begin Color := BACKCOLOUR; end else begin Color := clWhite; end end; end.
unit LAPI_Element; { Sandcat UI Element LUA Object Copyright (c) 2011-2014, Syhunt Informatica License: 3-clause BSD license See https://github.com/felipedaragon/sandcat/ for details. } interface uses Classes, Forms, SysUtils, Graphics, Dialogs, Lua, LuaObject, Variants; type TSCBUIElementObject = class(TLuaObject) private public Engine: string; Selector: string; EngineID: integer; procedure SetEngine(Name: string); procedure EnableElement(Enable: Boolean = true); function GetElementValue(Selector: string): Variant; procedure SetElementValue(Selector, NewValue: Variant); function GetElementAttribute(Selector, Name: string): Variant; procedure SetElementAttribute(Selector, Name: string; NewValue: Variant); constructor Create(LuaState: PLua_State; AParent: TLuaObject = nil); overload; override; function GetPropValue(propName: String): Variant; override; function SetPropValue(propName: String; const AValue: Variant) : Boolean; override; destructor Destroy; override; end; type TSCBUIEngineObject = class(TLuaObject) private function GetUIXTable: string; public Engine: string; EngineID: integer; procedure SetEngine(Name: string); constructor Create(LuaState: PLua_State; AParent: TLuaObject = nil); overload; override; function GetPropValue(propName: String): Variant; override; function SetPropValue(propName: String; const AValue: Variant) : Boolean; override; destructor Destroy; override; end; procedure RegisterSCBUIElement_Sandcat(L: PLua_State); procedure RegisterSCBUIEngine_Sandcat(L: PLua_State); function ElemValueToText(value: string): string; implementation uses uMain, plua, uUIComponents, uMisc, CatStrings, CatHTTP, uZones, uTab, uConst; function ElemValueToText(value: string): string; begin result := htmlunescape(value); result := replacestr(result, '<br/>', crlf); result := striphtml(result); result := trim(result); end; function GetSciterObject(L: PLua_State): TSandUIEngine; begin result := GetZoneByID(TSCBUIElementObject(LuaToTLuaObject(L, 1)).EngineID); end; function GetEngine(L: PLua_State): TSandUIEngine; begin result := GetZoneByID(TSCBUIEngineObject(LuaToTLuaObject(L, 1)).EngineID); end; function method_select(L: PLua_State): integer; cdecl; var o: TSCBUIElementObject; begin o := TSCBUIElementObject(LuaToTLuaObject(L, 1)); o.Selector := lua_tostring(L, 2); if lua_tostring(L, 3) <> emptystr then o.SetEngine(lua_tostring(L, 3)); result := 1; end; function method_getval(L: PLua_State): integer; cdecl; var v: Variant; o: TSCBUIElementObject; begin o := TSCBUIElementObject(LuaToTLuaObject(L, 1)); v := o.GetElementValue(o.Selector); plua_pushvariant(L, v); result := 1; end; function method_setval(L: PLua_State): integer; cdecl; var nv: Variant; o: TSCBUIElementObject; begin o := TSCBUIElementObject(LuaToTLuaObject(L, 1)); nv := plua_tovariant(L, 3); o.SetElementValue(o.Selector, nv); result := 1; end; function method_setattrib(L: PLua_State): integer; cdecl; var newval: Variant; o: TSCBUIElementObject; begin o := TSCBUIElementObject(LuaToTLuaObject(L, 1)); newval := plua_tovariant(L, 3); o.SetElementAttribute(o.Selector, lua_tostring(L, 2), newval); result := 1; end; function method_getattrib(L: PLua_State): integer; cdecl; var v: Variant; o: TSCBUIElementObject; begin o := TSCBUIElementObject(LuaToTLuaObject(L, 1)); v := o.GetElementAttribute(o.Selector, lua_tostring(L, 2)); plua_pushvariant(L, v); result := 1; end; function method_setstyleattrib(L: PLua_State): integer; cdecl; var nv: Variant; o: TSCBUIElementObject; e: ISandUIElement; begin o := TSCBUIElementObject(LuaToTLuaObject(L, 1)); nv := plua_tovariant(L, 3); e := GetZoneByID(o.EngineID).root.Select(o.Selector); if e <> nil then e.styleattr[lua_tostring(L, 2)] := nv; result := 1; end; function method_getstyleattrib(L: PLua_State): integer; cdecl; var v: Variant; o: TSCBUIElementObject; e: ISandUIElement; begin o := TSCBUIElementObject(LuaToTLuaObject(L, 1)); e := GetZoneByID(o.EngineID).root.Select(o.Selector); if e <> nil then v := e.styleattr[lua_tostring(L, 2)] else v := null; plua_pushvariant(L, v); result := 1; end; function method_engine_eval(L: PLua_State): integer; cdecl; var s: TSandUIEngine; str: widestring; res: string; begin s := GetEngine(L); str := lua_tostring(L, 2); if s <> nil then begin res := s.eval(str); lua_pushstring(L, res); end; result := 1; end; function method_engine_hide(L: PLua_State): integer; cdecl; var s: TSandUIEngine; begin s := GetEngine(L); if s <> nil then s.Height := 0; result := 1; end; function method_engine_load(L: PLua_State): integer; cdecl; var s, tablename: string; var o: TSCBUIEngineObject; const cContent = '{$Content}'; begin o := TSCBUIEngineObject(LuaToTLuaObject(L, 1)); s := lua_tostring(L, 2); tablename := htmlescape(lua_tostring(L, 3)); if s = emptystr then s := cBlank_Htm; if tablename <> emptystr then s := '<meta name="SandcatUIX" content="' + tablename + '">' + crlf + s; case o.EngineID of ENGINE_EXTENSIONPAGE: bottombar.LoadPage(s); ENGINE_CUSTOMTAB: tabmanager.ActiveTab.LoadExtensionPage(s); else s := replacestr(GetPakResourceAsString('tab_custom.html'), cContent, s); GetEngine(L).loadhtml(s, pluginsdir); end; result := 1; end; // Standard loading function method_engine_loadstd(L: PLua_State): integer; cdecl; var s: string; var o: TSCBUIEngineObject; begin o := TSCBUIEngineObject(LuaToTLuaObject(L, 1)); s := lua_tostring(L, 2); if s = emptystr then s := cBlank_Htm; case o.EngineID of ENGINE_EXTENSIONPAGE: BottomBar.ExtensionPage.loadhtml(s, pluginsdir); ENGINE_CUSTOMTAB: tabmanager.ActiveTab.LoadExtensionPage(s); else GetEngine(L).loadhtml(s, pluginsdir); end; result := 1; end; function method_engine_loadurl(L: PLua_State): integer; cdecl; var s: string; // o: TSCBUIEngineObject; begin // o := TSCBUIEngineObject(LuaToTLuaObject(L, 1)); s := lua_tostring(L, 2); GetEngine(L).loadurl(s); result := 1; end; // Element Object ************************************************************** procedure TSCBUIElementObject.SetEngine(Name: string); begin if name = emptystr then exit; EngineID := GetZoneID(Name); Engine := name; end; function TSCBUIElementObject.GetElementValue(Selector: string): Variant; var e: ISandUIElement; begin e := GetZoneByID(EngineID).root.Select(Selector); if e <> nil then result := e.Value else result := null; end; procedure TSCBUIElementObject.SetElementValue(Selector, NewValue: Variant); var e: ISandUIElement; begin e := GetZoneByID(EngineID).root.Select(Selector); if e <> nil then e.Value := NewValue; end; function TSCBUIElementObject.GetElementAttribute(Selector, Name: string): Variant; var e: ISandUIElement; begin e := GetZoneByID(EngineID).root.Select(Selector); if e <> nil then result := e.attr[Name] else result := null; end; procedure TSCBUIElementObject.SetElementAttribute(Selector, Name: string; NewValue: Variant); var e: ISandUIElement; begin e := GetZoneByID(EngineID).root.Select(Selector); if e <> nil then e.attr[Name] := NewValue; end; procedure TSCBUIElementObject.EnableElement(Enable: Boolean = true); begin if Enable then SetElementAttribute(Selector, 'disabled', emptystr) // enabled else SetElementAttribute(Selector, 'disabled', 'True'); end; function TSCBUIElementObject.GetPropValue(propName: String): Variant; begin if CompareText(propName, 'engine') = 0 then result := Engine else if CompareText(propName, 'selector') = 0 then result := Selector else if CompareText(propName, 'valueastext') = 0 then result := ElemValueToText(GetElementValue(Selector)) else if CompareText(propName, 'value') = 0 then result := GetElementValue(Selector) else result := inherited GetPropValue(propName); end; function TSCBUIElementObject.SetPropValue(propName: String; const AValue: Variant): Boolean; begin result := true; if CompareText(propName, 'enabled') = 0 then EnableElement(AValue) else if CompareText(propName, 'engine') = 0 then SetEngine(String(AValue)) else if CompareText(propName, 'selector') = 0 then Selector := String(AValue) else if CompareText(propName, 'value') = 0 then SetElementValue(Selector, AValue) else result := inherited SetPropValue(propName, AValue); end; constructor TSCBUIElementObject.Create(LuaState: PLua_State; AParent: TLuaObject); begin inherited Create(LuaState, AParent); end; destructor TSCBUIElementObject.Destroy; begin inherited Destroy; end; // ***************************************************************************** // Engine Object *************************************************************** function TSCBUIEngineObject.GetUIXTable: string; var e: ISandUIElement; begin result := emptystr; e := GetZoneByID(EngineID).root.Select('meta[name=''SandcatUIX'']'); if e <> nil then result := e.attr['content']; end; procedure TSCBUIEngineObject.SetEngine(Name: string); begin if name = emptystr then exit; EngineID := GetZoneID(Name); Engine := name; end; function TSCBUIEngineObject.GetPropValue(propName: String): Variant; begin if CompareText(propName, 'name') = 0 then result := Engine else if CompareText(propName, 'uix') = 0 then result := GetUIXTable() else result := inherited GetPropValue(propName); end; function TSCBUIEngineObject.SetPropValue(propName: String; const AValue: Variant): Boolean; begin result := true; if CompareText(propName, 'name') = 0 then SetEngine(String(AValue)) else result := inherited SetPropValue(propName, AValue); end; constructor TSCBUIEngineObject.Create(LuaState: PLua_State; AParent: TLuaObject); begin inherited Create(LuaState, AParent); end; destructor TSCBUIEngineObject.Destroy; begin inherited Destroy; end; // ***************************************************************************** procedure register_methods_element(L: PLua_State; classTable: integer); begin RegisterMethod(L, 'select', @method_select, classTable); // RegisterMethod(L,'getvalue', @method_getval, classTable); // RegisterMethod(L,'setvalue', @method_setval, classTable); RegisterMethod(L, 'getattrib', @method_getattrib, classTable); RegisterMethod(L, 'setattrib', @method_setattrib, classTable); RegisterMethod(L, 'getstyle', @method_getstyleattrib, classTable); RegisterMethod(L, 'setstyle', @method_setstyleattrib, classTable); end; const AClassNameElement = 'SandcatUIElement'; function newcallback_element(L: PLua_State; AParent: TLuaObject = nil) : TLuaObject; begin result := TSCBUIElementObject.Create(L, AParent); end; function Create_Element(L: PLua_State): integer; cdecl; var p: TLuaObjectNewCallback; begin p := @newcallback_element; result := new_LuaObject(L, AClassNameElement, p); end; procedure RegisterSCBUIElement_Sandcat(L: PLua_State); begin RegisterTLuaObject(L, AClassNameElement, @Create_Element, @register_methods_element); end; function lua_zone_addtis(L: PLua_State): integer; cdecl; var o: TSCBUIEngineObject; begin o := TSCBUIEngineObject(LuaToTLuaObject(L, 1)); uix.AddTIS(lua_tostring(L, 2), o.Engine); result := 1; end; function lua_zone_addhtml(L: PLua_State): integer; cdecl; var o: TSCBUIEngineObject; begin o := TSCBUIEngineObject(LuaToTLuaObject(L, 1)); uix.AddHTML(o.Engine, lua_tostring(L, 2), lua_tostring(L, 3)); result := 1; end; function lua_zone_addhtmlfile(L: PLua_State): integer; cdecl; var o: TSCBUIEngineObject; begin o := TSCBUIEngineObject(LuaToTLuaObject(L, 1)); uix.AddHTMLFile(o.Engine, lua_tostring(L, 2), lua_tostring(L, 3)); result := 1; end; function lua_zone_inserthtml(L: PLua_State): integer; cdecl; var idx: string; o: TSCBUIEngineObject; begin o := TSCBUIEngineObject(LuaToTLuaObject(L, 1)); case lua_type(L, 2) of LUA_TNUMBER: idx := inttostr(lua_tointeger(L, 2)); LUA_TSTRING: idx := '$("' + lua_tostring(L, 2) + '").index+1'; end; uix.InsertHTML(o.Engine, idx, lua_tostring(L, 3), lua_tostring(L, 4)); result := 1; end; function lua_zone_inserthtmlfile(L: PLua_State): integer; cdecl; var idx: string; o: TSCBUIEngineObject; begin o := TSCBUIEngineObject(LuaToTLuaObject(L, 1)); case lua_type(L, 2) of LUA_TNUMBER: idx := inttostr(lua_tointeger(L, 2)); LUA_TSTRING: idx := '$("' + lua_tostring(L, 2) + '").index'; end; uix.InsertHTMLFile(o.Engine, idx, lua_tostring(L, 3), lua_tostring(L, 4)); result := 1; end; procedure register_methods(L: PLua_State; classTable: integer); begin RegisterMethod(L, 'addhtml', @lua_zone_addhtml, classTable); RegisterMethod(L, 'addhtmlfile', @lua_zone_addhtmlfile, classTable); RegisterMethod(L, 'addtiscript', @lua_zone_addtis, classTable); RegisterMethod(L, 'inserthtml', @lua_zone_inserthtml, classTable); RegisterMethod(L, 'inserthtmlfile', @lua_zone_inserthtmlfile, classTable); RegisterMethod(L, 'hide', @method_engine_hide, classTable); RegisterMethod(L, 'eval', @method_engine_eval, classTable); RegisterMethod(L, 'loadx', @method_engine_load, classTable); RegisterMethod(L, 'loadx_std', @method_engine_loadstd, classTable); RegisterMethod(L, 'loadx_url', @method_engine_loadurl, classTable); end; const AClassName = 'SandcatUIZone'; function newcallback(L: PLua_State; AParent: TLuaObject = nil): TLuaObject; begin result := TSCBUIEngineObject.Create(L, AParent); end; function Create(L: PLua_State): integer; cdecl; var p: TLuaObjectNewCallback; begin p := @newcallback; result := new_LuaObject(L, AClassName, p); end; procedure RegisterSCBUIEngine_Sandcat(L: PLua_State); begin RegisterTLuaObject(L, AClassName, @Create, @register_methods); end; end.
unit CustomMarshallerTestU; interface uses TestFramework, CustomConverter, MyObjects; type TCustomMarshallerTest = class(TTestCase) published procedure TestSimpleObject; procedure TestSimpleObjectWithISODate; procedure TestComplexObject; procedure TestComplexObjectWithNestedObject; end; implementation uses DBXJSON, DBXJSONReflect, Classes, SysUtils; { TCustomMarshallerTest } procedure TCustomMarshallerTest.TestComplexObject; var Marshaller: TJSONMarshal; UnMarshaller: TJSONUnMarshal; Teenager: TTeenager; Value, JSONTeenager: TJSONObject; begin Marshaller := TJSONMarshal.Create(TJSONConverter.Create); try Marshaller.RegisterConverter(TTeenager, 'BornDate', ISODateTimeConverter); Marshaller.RegisterConverter(TStringList, StringListConverter); Teenager := TTeenager.CreateAndInitialize; try Value := Marshaller.Marshal(Teenager) as TJSONObject; finally Teenager.Free; end; // UnMarshalling Teenager UnMarshaller := TJSONUnMarshal.Create; try UnMarshaller.RegisterReverter(TTeenager, 'BornDate', ISODateTimeReverter); UnMarshaller.RegisterReverter(TStringList, StringListReverter); Teenager := UnMarshaller.Unmarshal(Value) as TTeenager; try CheckEquals('Daniele', Teenager.FirstName); CheckEquals('Teti', Teenager.LastName); CheckEquals(29, Teenager.Age); CheckEquals(EncodeDate(1979, 11, 4), Teenager.BornDate); CheckEquals(3, Teenager.Phones.Count); CheckEquals('NUMBER01', Teenager.Phones[0]); CheckEquals('NUMBER02', Teenager.Phones[1]); CheckEquals('NUMBER03', Teenager.Phones[2]); finally Teenager.Free; end; finally UnMarshaller.Free; end; finally Marshaller.Free; end; end; procedure TCustomMarshallerTest.TestComplexObjectWithNestedObject; var Marshaller: TJSONMarshal; UnMarshaller: TJSONUnMarshal; Programmer: TProgrammer; Value, JSONProgrammer: TJSONObject; begin Marshaller := TJSONMarshal.Create(TJSONConverter.Create); try Marshaller.RegisterConverter(TProgrammer, 'BornDate', ISODateTimeConverter); Marshaller.RegisterConverter(TStringList, StringListConverter); Marshaller.RegisterConverter(TProgrammer, 'Laptops', LaptopListConverter); Programmer := TProgrammer.CreateAndInitialize; try Value := Marshaller.Marshal(Programmer) as TJSONObject; finally Programmer.Free; end; // UnMarshalling Programmer UnMarshaller := TJSONUnMarshal.Create; try UnMarshaller.RegisterReverter(TProgrammer, 'BornDate', ISODateTimeReverter); UnMarshaller.RegisterReverter(TStringList, StringListReverter); UnMarshaller.RegisterReverter(TProgrammer, 'Laptops', LaptopListReverter); Programmer := UnMarshaller.Unmarshal(Value) as TProgrammer; try CheckEquals('Daniele', Programmer.FirstName); CheckEquals('Teti', Programmer.LastName); CheckEquals(29, Programmer.Age); CheckEquals(EncodeDate(1979, 11, 4), Programmer.BornDate); CheckEquals(3, Programmer.Phones.Count); CheckEquals('NUMBER01', Programmer.Phones[0]); CheckEquals('NUMBER02', Programmer.Phones[1]); CheckEquals('NUMBER03', Programmer.Phones[2]); CheckEquals('HP Presario C700',Programmer.Laptops[0].Model); CheckEquals(1000,Programmer.Laptops[0].Price); CheckEquals('Toshiba Satellite Pro',Programmer.Laptops[1].Model); CheckEquals(800,Programmer.Laptops[1].Price); CheckEquals('IBM Travelmate 500',Programmer.Laptops[2].Model); CheckEquals(1300,Programmer.Laptops[2].Price); finally Programmer.Free; end; finally UnMarshaller.Free; end; finally Marshaller.Free; end; end; procedure TCustomMarshallerTest.TestSimpleObject; var Marshaller: TJSONMarshal; UnMarshaller: TJSONUnMarshal; Kid: TKid; Value, JSONKid: TJSONObject; begin Marshaller := TJSONMarshal.Create(TJSONConverter.Create); try Kid := TKid.CreateAndInitialize; try Value := Marshaller.Marshal(Kid) as TJSONObject; // Full qualified class name CheckEquals('MyObjects.TKid', Value.Get(0).JsonValue.Value); // Object ID CheckEquals('1', Value.Get(1).JsonValue.Value); // Reference to the object fields JSONKid := Value.Get(2).JsonValue as TJSONObject; CheckEquals('FirstName', JSONKid.Get(0).JsonString.Value); CheckEquals('Daniele', JSONKid.Get(0).JsonValue.Value); CheckEquals('LastName', JSONKid.Get(1).JsonString.Value); CheckEquals('Teti', JSONKid.Get(1).JsonValue.Value); CheckEquals('Age', JSONKid.Get(2).JsonString.Value); CheckEquals('29', JSONKid.Get(2).JsonValue.Value); CheckEquals('BornDate', JSONKid.Get(3).JsonString.Value); CheckEquals(FloatToStr(EncodeDate(1979, 11, 4)), JSONKid.Get(3).JsonValue.Value); finally Kid.Free; end; // UnMarshalling Kid UnMarshaller := TJSONUnMarshal.Create; try Kid := UnMarshaller.Unmarshal(Value) as TKid; try CheckEquals('Daniele', Kid.FirstName); CheckEquals('Teti', Kid.LastName); CheckEquals(29, Kid.Age); CheckEquals(EncodeDate(1979, 11, 4), Kid.BornDate); finally Kid.Free; end; finally UnMarshaller.Free; end; finally Marshaller.Free; end; end; procedure TCustomMarshallerTest.TestSimpleObjectWithISODate; var Marshaller: TJSONMarshal; UnMarshaller: TJSONUnMarshal; Kid: TKid; Value, JSONKid: TJSONObject; begin Marshaller := TJSONMarshal.Create(TJSONConverter.Create); try Marshaller.RegisterConverter(TKid, 'BornDate', ISODateTimeConverter); Kid := TKid.CreateAndInitialize; try Value := Marshaller.Marshal(Kid) as TJSONObject; // Full qualified class name CheckEquals('MyObjects.TKid', Value.Get(0).JsonValue.Value); // Object ID CheckEquals('1', Value.Get(1).JsonValue.Value); // Reference to the object fields JSONKid := Value.Get(2).JsonValue as TJSONObject; CheckEquals('FirstName', JSONKid.Get(0).JsonString.Value); CheckEquals('Daniele', JSONKid.Get(0).JsonValue.Value); CheckEquals('LastName', JSONKid.Get(1).JsonString.Value); CheckEquals('Teti', JSONKid.Get(1).JsonValue.Value); CheckEquals('Age', JSONKid.Get(2).JsonString.Value); CheckEquals('29', JSONKid.Get(2).JsonValue.Value); CheckEquals('BornDate', JSONKid.Get(3).JsonString.Value); CheckEquals('1979-11-04 00:00:00', JSONKid.Get(3).JsonValue.Value); finally Kid.Free; end; // UnMarshalling Kid UnMarshaller := TJSONUnMarshal.Create; try UnMarshaller.RegisterReverter(TKid, 'BornDate', ISODateTimeReverter); Kid := UnMarshaller.Unmarshal(Value) as TKid; try CheckEquals('Daniele', Kid.FirstName); CheckEquals('Teti', Kid.LastName); CheckEquals(29, Kid.Age); CheckEquals(EncodeDate(1979, 11, 4), Kid.BornDate); finally Kid.Free; end; finally UnMarshaller.Free; end; finally Marshaller.Free; end; end; initialization RegisterTest(TCustomMarshallerTest.Suite); end.
unit Alcinoe.iOSApi.AdSupport; interface uses Macapi.ObjectiveC, iOSapi.Foundation; {$M+} type {******************************} ASIdentifierManager = interface; {*****************************************} //@interface ASIdentifierManager : NSObject ASIdentifierManagerClass = interface(NSObjectClass) ['{B646F491-264C-4DBD-8DE6-8C2CC09322E4}'] //+ (ASIdentifierManager * _Nonnull)sharedManager; {class} function sharedManager : ASIdentifierManager; cdecl; end; ASIdentifierManager = interface(NSObject) ['{FCE2CAED-3712-485A-8CDA-FEDE193E0E2C}'] //- (void)clearAdvertisingIdentifier API_UNAVAILABLE(ios, tvos); procedure clearAdvertisingIdentifier; cdecl; //@property (nonnull, nonatomic, readonly) NSUUID *advertisingIdentifier; function advertisingIdentifier : NSUUID; cdecl; //@property (nonatomic, readonly, getter=isAdvertisingTrackingEnabled) BOOL advertisingTrackingEnabled; function isAdvertisingTrackingEnabled : Boolean; cdecl; end; TASIdentifierManager = class(TOCGenericImport<ASIdentifierManagerClass, ASIdentifierManager>) end; PASIdentifierManager = Pointer; const libAdSupport = '/System/Library/Frameworks/AdSupport.framework/AdSupport'; implementation {****************************************************************************************} procedure StubProc1; cdecl; external libAdSupport name 'OBJC_CLASS_$_ASIdentifierManager'; end.
unit UForms; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. } { Purpose: Augments the standard VCL form classes with enhancements and bug fixes. } { Use: UForm classes are intended to replace TForm as the default forms ancester class.} {$IFDEF VISTA} {$MESSAGE WARN 'VISTA FEATURES ENABLED'} {$ENDIF} interface uses Classes, Controls, Forms, Graphics, Messages; type { a feature rich custom form that persists its properties from session to session } TAdvancedForm = class(TForm) private FGradientStartColor: TColor; FGradientEndColor: TColor; FSettingsName: String; FOffscreen: Boolean; private procedure DrawGradientBackground; procedure EnsureOnScreen; function GetFormSettingsRegistryKey: string; procedure RepaintBuggedControls(Ctrl: TControl); procedure RestoreINIWindowPlacement; protected procedure CMMouseWheel(var Message: TCMMouseWheel); message CM_MOUSEWHEEL; procedure WMPaint(var Message: TWMPaint); message WM_PAINT; procedure WMHScroll(var Message: TWMHScroll); message WM_HSCROLL; procedure WMVScroll(var Message: TWMVScroll); message WM_VSCROLL; procedure WMUpdateUIState(var Message: TWMUIState); message WM_UPDATEUISTATE; procedure Paint; override; procedure SetColor(Value: TColor); procedure SetGradientEndColor(const Value: TColor); procedure SetGradientStartColor(const Value: TColor); procedure CreateParams(var Params: TCreateParams); override; procedure DoHide; override; procedure DoShow; override; procedure RestoreWindowPlacement; virtual; procedure SaveWindowPlacement; virtual; property FormSettingsRegistryKey: string read GetFormSettingsRegistryKey; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure BeforeDestruction; override; procedure Resize; override; function ShowModal: Integer; override; published property IsOffscreen: Boolean read FOffScreen write FOffscreen; property DoubleBuffered; property GradientEndColor: TColor read FGradientEndColor write SetGradientEndColor; property GradientStartColor: TColor read FGradientStartColor write SetGradientStartColor; property SettingsName: String read FSettingsName write FSettingsName; end; /// summary: A form enabling Windows Vista user interface fonts. TVistaAdvancedForm = class(TAdvancedForm) protected procedure DoShow; override; end; { an application main form } TMainAdvancedForm = class(TAdvancedForm) private FTopMostLevel: Integer; FTopMostList: TList; procedure OnApplicationModalBegin(Sender: TObject); procedure OnApplicationModalEnd(Sender: TObject); protected procedure CreateParams(var Params: TCreateParams); override; procedure DoNormalizeTopMosts(IncludeMain: Boolean); procedure WMActivateApp(var Message: TWMActivateApp); message WM_ACTIVATEAPP; procedure WMSysCommand(var Message: TWMSysCommand); message WM_SYSCOMMAND; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Minimize; procedure NormalizeTopMosts; procedure NormalizeAllTopMosts; procedure RestoreTopMosts; procedure Restore; end; implementation uses Windows, Buttons, INIFiles, Math, Registry, StdCtrls, SysUtils, UDebugTools, UFonts, UGlobals, UPaths; const CRegistryValueWindowPlacement = 'Placement'; // --- Unit ------------------------------------------------------------------- type /// summary: The mixture of alpha, red, green, and blue required to produce a color. TARGBColor = record case LongWord of 1: (ARGB: LongWord); 2: (B: Byte; G: Byte; R: Byte; A: Byte); end; PTopMostEnumInfo = ^TTopMostEnumInfo; TTopMostEnumInfo = record TopWindow: HWND; IncludeMain: Boolean; end; procedure CheckApplicationHooks; const CAssertOnModalBegin = 'TMainAdvancedForm must be hooked into Application.OnModalBegin for modal forms to function properly.'; CAssertOnModalEnd = 'TMainAdvancedForm must be hooked into Application.OnModalEnd for modal forms to function properly.'; begin Assert(TMethod(Application.OnModalBegin).Code = @TMainAdvancedForm.OnApplicationModalBegin, CAssertOnModalBegin); Assert(TMethod(Application.OnModalEnd).Code = @TMainAdvancedForm.OnApplicationModalEnd, CAssertOnModalEnd); end; function GetTopMostWindows(Handle: HWND; Info: Pointer): BOOL; stdcall; begin Result := True; if GetWindow(Handle, GW_OWNER) = Application.MainForm.Handle then if (GetWindowLong(Handle, GWL_EXSTYLE) and WS_EX_TOPMOST <> 0) and ((Application.MainForm = nil) or PTopMostEnumInfo(Info)^.IncludeMain or (Handle <> Application.MainForm.Handle)) then (Application.MainForm as TMainAdvancedForm).FTopMostList.Add(Pointer(Handle)) else begin PTopMostEnumInfo(Info)^.TopWindow := Handle; Result := False; end; end; { --- TAdvancedForm ----------------------------------------------------------} constructor TAdvancedForm.Create(AOwner: TComponent); begin inherited; FOffscreen := False; TDebugTools.WriteLine('Form ' + Name + ' created.'); end; destructor TAdvancedForm.Destroy; begin TDebugTools.WriteLine('Form ' + Name + ' destroyed.'); inherited; end; /// summary: Draws a gradient background for the form. procedure TAdvancedForm.DrawGradientBackground; var ClientSize: TSize; DeltaA: Integer; DeltaR: Integer; DeltaG: Integer; DeltaB: Integer; EndColor: TARGBColor; ScanLine: Integer; ScanLineColor: TARGBColor; StartColor: TARGBColor; Percent: Double; begin // calculate the delta between the start and ending colors. StartColor.ARGB := ColorToRGB(FGradientStartColor); EndColor.ARGB := ColorToRGB(FGradientEndColor); DeltaA := EndColor.A - StartColor.A; DeltaR := EndColor.R - StartColor.R; DeltaG := EndColor.G - StartColor.G; DeltaB := EndColor.B - StartColor.B; // set up the canvas Canvas.Pen.Style := psSolid; Canvas.Pen.Width := 1; // draw gradient ClientSize.cx := ClientWidth; ClientSize.cy := ClientHeight; ScanLine := 0; repeat Percent := ScanLine / ClientSize.cy; ScanLineColor.A := Trunc(StartColor.A + DeltaA * Percent); ScanLineColor.R := Trunc(StartColor.R + DeltaR * Percent); ScanLineColor.G := Trunc(StartColor.G + DeltaG * Percent); ScanLineColor.B := Trunc(StartColor.B + DeltaB * Percent); Canvas.Pen.Color := TColor(ScanLineColor.ARGB); Canvas.MoveTo(0, ScanLine); Canvas.LineTo(ClientSize.cx, ScanLine); ScanLine := ScanLine + 1; until (ScanLine > ClientSize.cy); end; { ensures the window title bar is on the screen } procedure TAdvancedForm.EnsureOnScreen; var TitleBar: TRect; VisibleTitleBar: TRect; begin // ensure the window title bar is visible if (BorderStyle <> bsNone) and not FOffScreen then begin TitleBar.Left := Left; TitleBar.Top := Top; TitleBar.Right := Left + Width; TitleBar.Bottom := Top + (Height - ClientHeight - BorderWidth); IntersectRect(VisibleTitleBar, TitleBar, Screen.DesktopRect); // reposition if IsRectEmpty(VisibleTitleBar) then begin Width := Min(Width, Screen.Width); Height := Min(Height, Screen.Height); Top := (Screen.Height div 2) - (Height div 2); Left := (Screen.Width div 2) - (Width div 2); end; end; end; { returns the form settings registry key } function TAdvancedForm.GetFormSettingsRegistryKey: string; begin if (FSettingsName <> '') then Result := TRegPaths.Forms + FSettingsName else Result := ''; end; { TButton, TStaticText, TCheckBox, and TRadioButton are bugged in the VCL. They do not repaint after processing a WM_UPDATEUISTATE event. } procedure TAdvancedForm.RepaintBuggedControls(Ctrl: TControl); var Index: Integer; WinCtrl: TWinControl; begin if (Ctrl is TWinControl) then begin WinCtrl := Ctrl as TWinControl; if ((WinCtrl is TButtonControl) and not (WinCtrl is TBitBtn)) or (WinCtrl is TStaticText) then WinCtrl.Repaint; // paint child controls for Index := 0 to WinCtrl.ControlCount - 1 do RepaintBuggedControls(WinCtrl.Controls[Index]); end; end; { migrates window placement data from the ClickFORMS ini file } procedure TAdvancedForm.RestoreINIWindowPlacement; var INIFile: TINIFile; Region: TRect; begin INIFile := TINIFile.Create(IncludeTrailingPathDelimiter(appPref_DirPref) + cClickFormsINI); try Region.Top := INIFile.ReadInteger('Location', FSettingsName + 'Top', 0); Region.Left := INIFile.ReadInteger('Location', FSettingsName + 'Left', 0); Region.Right := INIFile.ReadInteger('Location', FSettingsName + 'Right', Region.Left + Width); Region.Bottom := INIFile.ReadInteger('Location', FSettingsName + 'Bot', Region.Top + Height); // special preference settings if SameText(FSettingsName, 'PrinterLoc') and INIFile.ValueExists('Location', 'PrinterHeight') then Region.Bottom := INIFile.ReadInteger('Location', 'PrinterHeight', Region.Bottom - Region.Top) + Region.Top else if SameText(FSettingsName, 'PhotoSheet') and INIFile.ValueExists('Location', 'PhotoSheetLength') then Region.Bottom := INIFile.ReadInteger('Location', 'PhotoSheetLength', Region.Bottom - Region.Top) + Region.Top; // validate and migrate if ((Region.Top <> 0) or (Region.Left <> 0)) and (Region.Bottom > Region.Top) and (Region.Right > Region.Left) then begin Top := Region.Top; Left := Region.Left; Width := Region.Right - Region.Left; Height := Region.Bottom - Region.Top; end; finally FreeAndNil(INIFile); end; end; procedure TAdvancedForm.CMMouseWheel(var Message: TCMMouseWheel); begin if (Message.WheelDelta < 0) then Perform(WM_VSCROLL, SB_LINEDOWN, 0) else if (Message.WheelDelta > 0) then Perform(WM_VSCROLL, SB_LINEUP, 0); inherited; end; /// summary: Uses double buffering to paint the form. /// remarks: Copied verbatim from TWinControl. procedure TAdvancedForm.WMPaint(var Message: TWMPaint); var DC, MemDC: HDC; MemBitmap, OldBitmap: HBITMAP; PS: TPaintStruct; begin if not FDoubleBuffered or (Message.DC <> 0) then begin if not (csCustomPaint in ControlState) and (ControlCount = 0) then inherited else PaintHandler(Message); end else begin DC := GetDC(0); MemBitmap := CreateCompatibleBitmap(DC, ClientRect.Right, ClientRect.Bottom); ReleaseDC(0, DC); MemDC := CreateCompatibleDC(0); OldBitmap := SelectObject(MemDC, MemBitmap); try DC := BeginPaint(Handle, PS); Perform(WM_ERASEBKGND, MemDC, MemDC); Message.DC := MemDC; WMPaint(Message); Message.DC := 0; BitBlt(DC, 0, 0, ClientRect.Right, ClientRect.Bottom, MemDC, 0, 0, SRCCOPY); EndPaint(Handle, PS); finally SelectObject(MemDC, OldBitmap); DeleteDC(MemDC); DeleteObject(MemBitmap); end; end; end; /// summary: Invalidates the window after scrolling when using a gradient background. procedure TAdvancedForm.WMHScroll(var Message: TWMHScroll); begin inherited; if (FGradientStartColor <> FGradientEndColor) then Invalidate; end; /// summary: Invalidates the window after scrolling when using a gradient background. procedure TAdvancedForm.WMVScroll(var Message: TWMVScroll); begin inherited; if (FGradientStartColor <> FGradientEndColor) then Invalidate; end; procedure TAdvancedForm.WMUpdateUIState(var Message: TWMUIState); begin inherited; RepaintBuggedControls(Self); end; /// summary: paints the form. procedure TAdvancedForm.Paint; begin if (FGradientStartColor <> FGradientEndColor) then DrawGradientBackground else inherited; end; /// summary: Sets the background color of the control to a solid color. procedure TAdvancedForm.SetColor(Value: TColor); begin inherited; GradientStartColor := Value; GradientEndColor := Value; end; /// summary: Sets the background gradient end color. procedure TAdvancedForm.SetGradientEndColor(const Value: TColor); begin if (Value <> FGradientEndColor) then begin FGradientEndColor := Value; Invalidate; end; end; /// summary: Sets the background gradient start color. procedure TAdvancedForm.SetGradientStartColor(const Value: TColor); begin if (Value <> FGradientStartColor) then begin inherited Color := Value; FGradientStartColor := Value; Invalidate; end; end; procedure TAdvancedForm.CreateParams(var Params: TCreateParams); begin inherited; // maintain window ordering when TMainAdvancedForm minimizes if (Params.WndParent = Application.Handle) and Assigned(Application.MainForm) then Params.WndParent := Application.MainForm.Handle; end; procedure TAdvancedForm.DoHide; begin SaveWindowPlacement; inherited; end; procedure TAdvancedForm.DoShow; var hWndOwner: THandle; begin // for modal form handling if Assigned(Application.MainForm) and (Application.MainForm <> Self) and (Application.MainForm is TMainAdvancedForm) then begin hWndOwner := GetWindow(Handle, GW_OWNER); if (hWndOwner = Application.Handle) and (FormStyle <> fsMDIChild) then SetWindowLong(Handle, GWL_HWNDPARENT, Application.MainForm.Handle); end; RestoreWindowPlacement; EnsureOnScreen; {$IFDEF VISTA} TAdvancedFont.UIFont.AssignToControls(Self, False); {$ENDIF} inherited; end; { reads window placement data from the registry } procedure TAdvancedForm.RestoreWindowPlacement; var placement: TWindowPlacement; registry: TRegistry; begin if (FormSettingsRegistryKey <> '') then begin registry := TRegistry.Create(KEY_ALL_ACCESS); try FillChar(placement, sizeof(placement), #0); placement.length := sizeof(placement); registry.RootKey := HKEY_CURRENT_USER; registry.OpenKeyReadOnly(FormSettingsRegistryKey); if registry.ValueExists(CRegistryValueWindowPlacement) then begin registry.ReadBinaryData(CRegistryValueWindowPlacement, placement, sizeof(placement)); SetWindowPlacement(Handle, @placement); if (WindowState = wsMinimized) then WindowState := wsNormal; end else RestoreINIWindowPlacement; except end; FreeAndNil(registry); end; end; { writes current window placement data to the registry } procedure TAdvancedForm.SaveWindowPlacement; var placement: TWindowPlacement; registry: TRegistry; begin if (FormSettingsRegistryKey <> '') then begin registry := TRegistry.Create(KEY_ALL_ACCESS); try FillChar(placement, sizeof(placement), #0); placement.length := sizeof(placement); GetWindowPlacement(Handle, @placement); registry.RootKey := HKEY_CURRENT_USER; registry.OpenKey(FormSettingsRegistryKey, True); registry.WriteBinaryData(CRegistryValueWindowPlacement, placement, sizeof(placement)); except end; FreeAndNil(registry); end; end; procedure TAdvancedForm.BeforeDestruction; begin if Visible then // FormClose events never fire when the application is exiting SaveWindowPlacement; inherited; end; procedure TAdvancedForm.Resize; begin inherited; if (FGradientStartColor <> FGradientEndColor) then Invalidate; end; function TAdvancedForm.ShowModal: Integer; begin if (Application.MainForm is TMainAdvancedForm) then CheckApplicationHooks; Result := inherited ShowModal; end; { --- TVistaAdvancedForm -----------------------------------------------------} /// summary: Sets the form font to the Windows user interface font /// when the form is shown. procedure TVistaAdvancedForm.DoShow; begin TAdvancedFont.UIFont.AssignToControls(Self, False); inherited; end; { --- TMainAdvancedForm ------------------------------------------------------} constructor TMainAdvancedForm.Create; var style: Integer; begin FTopMostList := TList.Create; inherited; // modal form handling Application.OnModalBegin := OnApplicationModalBegin; Application.OnModalEnd := OnApplicationModalEnd; // remove the TApplication "hidden" window from the taskbar style := GetWindowLong(Application.Handle, GWL_EXSTYLE); style := (style and not WS_EX_APPWINDOW) or WS_EX_TOOLWINDOW; //Ticket #1283: if user has multiple monitors and bring CF to show in between of the 2 monitors bring up multiple reports and close one //got the pop up dialog disappear and user has to end task. ///PAM: I have to roll it back so when we first bring up clickFORMS, if full max is set should bring up FULL screen. /// position := poScreenCenter; //Ticket #1283: originally was set to poMainFormCenter. /// DefaultMonitor := dmPrimary; //Ticket #1283: originally was set to dmActive ShowWindow(Application.Handle, SW_HIDE); SetWindowLong(Application.Handle, GWL_EXSTYLE, style); ShowWindow(Application.Handle, SW_SHOW); end; destructor TMainAdvancedForm.Destroy; begin // modal form handling CheckApplicationHooks; Application.OnModalBegin := nil; Application.OnModalEnd := nil; inherited; FreeAndNil(FTopMostList); end; procedure TMainAdvancedForm.OnApplicationModalBegin(Sender: TObject); begin (Application.MainForm as TMainAdvancedForm).NormalizeTopMosts; end; procedure TMainAdvancedForm.OnApplicationModalEnd(Sender: TObject); begin (Application.MainForm as TMainAdvancedForm).RestoreTopMosts; end; procedure TMainAdvancedForm.CreateParams(var Params: TCreateParams); begin inherited; // add window to the taskbar Params.ExStyle := (Params.ExStyle and not WS_EX_TOOLWINDOW) or WS_EX_APPWINDOW; end; procedure TMainAdvancedForm.DoNormalizeTopMosts(IncludeMain: Boolean); var I: Integer; Info: TTopMostEnumInfo; begin if (Application.Handle <> 0) then begin if FTopMostLevel = 0 then begin Info.TopWindow := Handle; Info.IncludeMain := IncludeMain; EnumWindows(@GetTopMostWindows, Longint(@Info)); if FTopMostList.Count <> 0 then begin Info.TopWindow := GetWindow(Info.TopWindow, GW_HWNDPREV); if GetWindowLong(Info.TopWindow, GWL_EXSTYLE) and WS_EX_TOPMOST <> 0 then Info.TopWindow := HWND_NOTOPMOST; for I := FTopMostList.Count - 1 downto 0 do SetWindowPos(HWND(FTopMostList[I]), Info.TopWindow, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE or SWP_NOOWNERZORDER); end; end; Inc(FTopMostLevel); end; end; procedure TMainAdvancedForm.WMActivateApp(var Message: TWMActivateApp); begin if Message.Active then begin RestoreTopMosts; PostMessage(Application.Handle, CM_ACTIVATE, 0, 0) end else begin NormalizeTopMosts; PostMessage(Application.Handle, CM_DEACTIVATE, 0, 0); end; end; procedure TMainAdvancedForm.WMSysCommand(var Message: TWMSysCommand); begin case (Message.CmdType and $FFF0) of SC_MINIMIZE: begin NormalizeTopMosts; ShowWindow(Handle, SW_MINIMIZE); Message.Result := 0; end; SC_RESTORE: begin ShowWindow(Handle, SW_RESTORE); RestoreTopMosts; Message.Result := 0; end; else inherited; end; end; procedure TMainAdvancedForm.Minimize; begin SendMessage(Handle, WM_SYSCOMMAND, SC_MINIMIZE, 0); end; procedure TMainAdvancedForm.NormalizeTopMosts; begin DoNormalizeTopMosts(False); end; procedure TMainAdvancedForm.NormalizeAllTopMosts; begin DoNormalizeTopMosts(True); end; procedure TMainAdvancedForm.RestoreTopMosts; var I: Integer; begin if (Application.Handle <> 0) and (FTopMostLevel > 0) then begin Dec(FTopMostLevel); if FTopMostLevel = 0 then begin for I := FTopMostList.Count - 1 downto 0 do SetWindowPos(HWND(FTopMostList[I]), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE or SWP_NOOWNERZORDER); FTopMostList.Clear; end; end; end; procedure TMainAdvancedForm.Restore; begin SendMessage(Handle, WM_SYSCOMMAND, SC_MAXIMIZE, 0); end; end.
unit MainUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, System.Win.ComObj, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGridExportLink, cxGraphics, Math, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, System.RegularExpressions, dxSkinsDefaultPainters, dxSkinscxPCPainter, cxPCdxBarPopupMenu, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, Data.DB, cxDBData, cxContainer, Vcl.ComCtrls, dxCore, cxSpinEdit, Vcl.StdCtrls, cxLabel, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, Vcl.ExtCtrls, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid, cxPC, ZAbstractRODataset, ZAbstractDataset, ZDataset, ZAbstractConnection, ZConnection, IniFiles, IdMessage, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase, IdSMTP, Vcl.ActnList, IdText, IdSSLOpenSSL, IdGlobal, strUtils, IdAttachmentFile, IdFTP, cxCurrencyEdit, cxCheckBox, Vcl.Menus, DateUtils, cxButtonEdit, ZLibExGZ, IdHTTP, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL; type TMainForm = class(TForm) ZConnection1: TZConnection; Timer1: TTimer; qryUnit: TZQuery; dsUnit: TDataSource; Panel2: TPanel; btnSendHTTPS: TButton; btnExport: TButton; btnExecute: TButton; btnAll: TButton; grtvUnit: TcxGridDBTableView; grReportUnitLevel1: TcxGridLevel; grReportUnit: TcxGrid; qryReport_Upload: TZQuery; dsReport_Upload: TDataSource; cxGrid: TcxGrid; cxGridDBTableView: TcxGridDBTableView; UnitCode: TcxGridDBColumn; Head: TcxGridDBColumn; cxGridLevel: TcxGridLevel; btnAllUnit: TButton; Address: TcxGridDBColumn; Code: TcxGridDBColumn; GoodsCode: TcxGridDBColumn; GoodsName: TcxGridDBColumn; Price: TcxGridDBColumn; Quant: TcxGridDBColumn; UnitName: TcxGridDBColumn; IdHTTP: TIdHTTP; IdSSLIOHandlerSocketOpenSSL1: TIdSSLIOHandlerSocketOpenSSL; procedure FormCreate(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure btnExportClick(Sender: TObject); procedure btnSendHTTPSClick(Sender: TObject); procedure btnAllClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnAllUnitClick(Sender: TObject); procedure btnExecuteClick(Sender: TObject); private { Private declarations } UnitFile: String; SavePath: String; Subject: String; FURL : String; FAccessKey : String; public { Public declarations } procedure Add_Log(AMessage:String); procedure AllUnit; end; var MainForm: TMainForm; implementation {$R *.dfm} function GetThousandSeparator : string; begin if FormatSettings.ThousandSeparator = #160 then Result := ' ' else Result := FormatSettings.ThousandSeparator; end; procedure TMainForm.Add_Log(AMessage: String); var F: TextFile; begin try AssignFile(F,ChangeFileExt(Application.ExeName,'.log')); if not fileExists(ChangeFileExt(Application.ExeName,'.log')) then Rewrite(F) else Append(F); try Writeln(F,FormatDateTime('YYYY.MM.DD hh:mm:ss',now) + ' - ' + AMessage); finally CloseFile(F); end; except end; end; procedure TMainForm.AllUnit; begin try Add_Log(''); Add_Log('-------------------'); Add_Log('Аптека : ' + qryUnit.FieldByName('ID').AsString); btnExecuteClick(Nil); btnExportClick(Nil); btnSendHTTPSClick(Nil); except on E: Exception do Add_Log(E.Message); end; end; procedure TMainForm.btnAllClick(Sender: TObject); begin try qryUnit.First; while not qryUnit.Eof do begin AllUnit; qryUnit.Next; Application.ProcessMessages; end; except on E: Exception do Add_Log(E.Message); end; qryUnit.Close; qryUnit.Open; end; procedure TMainForm.btnAllUnitClick(Sender: TObject); begin AllUnit; qryUnit.Close; qryUnit.Open; end; procedure TMainForm.btnExecuteClick(Sender: TObject); begin if not qryUnit.Active then Exit; qryReport_Upload.Close; qryReport_Upload.DisableControls; try try Subject := 'Данные по подразделению: ' + qryUnit.FieldByName('Address').AsString; qryReport_Upload.Params.ParamByName('UnitID').AsInteger := qryUnit.FieldByName('ID').AsInteger; qryReport_Upload.Open; except on E:Exception do begin Add_Log(E.Message); Exit; end; end; finally qryReport_Upload.EnableControls; end; end; function StrToJSON(AStr : string) : string; begin Result := StringReplace(AStr, '\', '\\', [rfReplaceAll, rfIgnoreCase]); Result := StringReplace(Result, '"', '\"', [rfReplaceAll, rfIgnoreCase]); end; function CurrToJSON(ACurr : currency) : string; begin Result := CurrToStr(ACurr); Result := StringReplace(Result, FormatSettings.DecimalSeparator, '.', [rfReplaceAll, rfIgnoreCase]); end; procedure TMainForm.btnExportClick(Sender: TObject); var sl : TStringList; begin if not qryReport_Upload.Active then Exit; if qryReport_Upload.IsEmpty then Exit; Add_Log('Начало выгрузки отчета'); if not ForceDirectories(SavePath) then Begin Add_Log('Не могу создать директорию выгрузки'); exit; end; // Формирование отчет sl := TStringList.Create; try sl.Add('{'); sl.Add(' "Meta": {'); sl.Add(' "id": "' + qryUnit.FieldByName('UnitCode').AsString + '",'); sl.Add(' "head": "' + StrToJSON(qryUnit.FieldByName('Head').AsString) + '",'); sl.Add(' "name": "' + StrToJSON(qryUnit.FieldByName('UnitName').AsString) + '",'); sl.Add(' "addr": "' + StrToJSON(qryUnit.FieldByName('Address').AsString) + '",'); sl.Add(' "code": "' + qryUnit.FieldByName('Code').AsString + '"'); sl.Add(' },'); sl.Add(' "Data": ['); qryReport_Upload.First; while not qryReport_Upload.Eof do begin sl.Add(' {'); sl.Add(' "id": "' + qryReport_Upload.FieldByName('GoodsCode').AsString + '",'); sl.Add(' "name": "' + StrToJSON(qryReport_Upload.FieldByName('GoodsName').AsString) + '",'); sl.Add(' "quant": ' + CurrToJSON(qryReport_Upload.FieldByName('Quant').AsCurrency) + ','); sl.Add(' "price": ' + CurrToJSON(qryReport_Upload.FieldByName('Price').AsCurrency) + ''); qryReport_Upload.Next; if qryReport_Upload.Eof then sl.Add(' }') else sl.Add(' },'); end; sl.Add(' ]'); sl.Add('}'); sl.SaveToFile(UnitFile, TEncoding.UTF8) finally sl.Free; end; end; procedure TMainForm.btnSendHTTPSClick(Sender: TObject); var sResponse : string; begin if not FileExists(UnitFile) then Exit; Add_Log('Начало отправки прайса: ' + UnitFile); begin try IdHTTP.Request.ContentType := 'application/json'; IdHTTP.Request.CustomHeaders.Clear; IdHTTP.Request.CustomHeaders.FoldLines := False; IdHTTP.Request.CustomHeaders.Values['X-Morion-Skynet-Tag'] := 'data.geoapt.ua'; IdHTTP.Request.CustomHeaders.Values['X-Morion-Skynet-Key'] := FAccessKey; try sResponse := IdHTTP.Post(FURL, UnitFile); except ON E: Exception DO Begin Add_Log(E.Message); exit; End; end; if IdHTTP.ResponseCode <> 200 then begin Add_Log(IntToStr(IdHTTP.ResponseCode) + ' ' + IdHTTP.ResponseText + '. ' + sResponse); end; DeleteFile(UnitFile); except on E: Exception do begin Add_Log(E.Message); end; end; end; end; procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TMainForm.FormCreate(Sender: TObject); var Ini: TIniFile; begin Ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'ExportForGeoApteka.ini'); try SavePath := Trim(Ini.ReadString('Options', 'Path', ExtractFilePath(Application.ExeName))); if SavePath[Length(SavePath)] <> '\' then SavePath := SavePath + '\'; Ini.WriteString('Options', 'Path', SavePath); ZConnection1.Database := Ini.ReadString('Connect', 'DataBase', 'farmacy'); Ini.WriteString('Connect', 'DataBase', ZConnection1.Database); ZConnection1.HostName := Ini.ReadString('Connect', 'HostName', '172.17.2.5'); Ini.WriteString('Connect', 'HostName', ZConnection1.HostName); ZConnection1.User := Ini.ReadString('Connect', 'User', 'postgres'); Ini.WriteString('Connect', 'User', ZConnection1.User); ZConnection1.Password := Ini.ReadString('Connect', 'Password', 'eej9oponahT4gah3'); Ini.WriteString('Connect', 'Password', ZConnection1.Password); UnitFile := SavePath + 'data.json'; FURL := Ini.ReadString('HTTP','URL', 'https://skynet.morion.ua/data/add'); Ini.WriteString('HTTP','URL',FURL); FAccessKey := Ini.ReadString('HTTP','AccessKey','90de624965f010447e663517922a42bed1446a99'); Ini.WriteString('HTTP','AccessKey',FAccessKey); finally Ini.free; end; ZConnection1.LibraryLocation := ExtractFilePath(Application.ExeName) + 'libpq.dll'; try ZConnection1.Connect; except on E:Exception do begin Add_Log(E.Message); Close; Exit; end; end; if ZConnection1.Connected then begin qryUnit.Close; try qryUnit.Open; except on E: Exception do begin Add_Log(E.Message); Close; Exit; end; end; if not (((ParamCount >= 1) and (CompareText(ParamStr(1), 'manual') = 0)) or (Pos('Farmacy.exe', Application.ExeName) <> 0)) then begin btnAll.Enabled := false; btnAllUnit.Enabled := false; btnExecute.Enabled := false; btnExport.Enabled := false; btnSendHTTPS.Enabled := false; Timer1.Enabled := true; end; end; end; procedure TMainForm.Timer1Timer(Sender: TObject); begin try timer1.Enabled := False; btnAllClick(nil); finally Close; end; end; end.
{Simulation des Wrfelspiels Craps in Pascal} PROGRAM CRAPS; USES crt; CONST Startzeile_Menu = 1; {Men startet bei dieser Zeile} Startzeile_Spiel = Startzeile_Menu+5; {erste Zeile fr Ausgabe bei Spiel} ErsteSpalte = 3; {erste Spalte bei Anzeige} Verzoegerung_Eingabe = 1000; {Verz”gerung nach Eingabe eines Zeichens (readKey)} Verzoegerung_Wuerfeln = 1000; {Verz”gerung vor Ausgabe des Wrfelergebnisses} Obergrenze_Kapital = 10000; {maximal m”gliches Kapital} VAR Kapital : INTEGER; {aktuelles Kapital} Einsatz : INTEGER; {aktueller Einsatz} Wuerfelsumme : BYTE; {Augensumme der beiden Wrfel} Menu_Auswahl : CHAR; {ausgew„hlter Menpunkt} Zaehler : INTEGER; {Z„hler fr aktuelle Zeilenverschiebung} Procedure UEBERSCHRIFT; {Darstellung der šberschrift} Begin {of UEBERSCHRIFT} gotoxy(ErsteSpalte,Startzeile_Menu); {Cursor zur Position bewegen} write('CRAPS'); {šberschrift} gotoxy(ErsteSpalte,Startzeile_Menu+1); write('====='); {Unterstreichung} End; {of UEBERSCHRIFT} Procedure MENU; {Anzeigen des Mens} Begin {of MENU} clrscr; {Bildschirm leeren} UEBERSCHRIFT; {Prozedur aufrufen} {Menpunkt 1} gotoxy(ErsteSpalte,Startzeile_Menu+3); write('(1) Neues Spiel beginnen'); {Menpunkt 2} gotoxy(ErsteSpalte,Startzeile_Menu+5); write('(2) Spielregeln anzeigen'); {Menpunkt 3} gotoxy(ErsteSpalte,Startzeile_Menu+9); write('(X) Spiel beenden'); {Menpunkt ausw„hlen} gotoxy(ErsteSpalte,Startzeile_Menu+17); write('Option w„hlen: '); {im Folgenden wird geprft, ob der ausgew„hlte Menpunkt vorhanden ist} REPEAT gotoxy(ErsteSpalte+15,Startzeile_Menu+17); write(' '); {vorhandene Zeichen l”schen} gotoxy(ErsteSpalte+15,Startzeile_Menu+17); {zur Eingabeposition wechseln} Menu_Auswahl := upCase(readKey); {Groábuchstaben einlesen} write(Menu_Auswahl); {Groábuchstaben anzeigen} DELAY(Verzoegerung_Eingabe); {mit weiterem Vorgehen warten} UNTIL (Menu_Auswahl='1') OR {bis ausgew„hlter Menpunkt vorhanden} (Menu_Auswahl='2') OR (Menu_Auswahl='X'); End; {of MENU} Function GANZZAHL (Eingabe : STRING) : BOOLEAN; {Prfung auf gltige Zahl} VAR Fehler : INTEGER; Eingabe1 : REAL; Begin {of GANZZAHL} GANZZAHL := false; {Startwert festlegen} VAL(Eingabe,Eingabe1,Fehler); {Prfung auf gltige Zahl in Eingabe} {falls der Fehlercode 0 auftaucht, ist es keine (gltige) Zahl} {wenn der gerundete Werte gleich der Eingabe ist, handelt es sich um eine Ganzzahl} IF Fehler=0 THEN Begin {gltiger Zahlenwert} IF Eingabe1=ROUND(Eingabe1) THEN GANZZAHL := true; {gltige Eingabe} End; {of IF Fehler=0} {im Falle einer Gleitkommazahl erscheint eine entsprechende Meldung} IF GANZZAHL=false THEN Begin gotoxy(ErsteSpalte,Startzeile_Menu+2); write('Der eingegebene Betrag muss ganzzahlig sein.'); End; {of IF GANZZAHL=false} End; {of GANZZAHL} Procedure EINGABE_KAPITAL; {Eingabe des Kapitals} VAR Kapital_Eingabe : STRING; {eingegebenes Kapital als Zeichenkette} f : BYTE; {Fehlercode} Kapital_neu : REAL; {Kapital als Gleitkommazahl} Begin {of EINGABE_KAPITAL} {im Folgenden wird geprft, ob ein gltiger Wert eingegeben wurde} REPEAT gotoxy(ErsteSpalte,Startzeile_Menu+3); write('Startkapital (in Euro): '); readln(Kapital_Eingabe); {Eingabe einlesen} VAL(Kapital_Eingabe,Kapital_neu,f); {wenn es sich um eine ungltige Zahl oder ein zu groáes Kapital handelt, wird diese Eingabe wieder gel”scht} IF (GANZZAHL(Kapital_Eingabe)=false) OR (Kapital_neu>Obergrenze_Kapital+1) THEN Begin gotoxy(ErsteSpalte+24,Startzeile_Menu+3); write(' '); {Eingabe l”schen} End; {of IF GANZZAHL(Kapital_Eingabe)=false} {Fehlermeldung bei zu groáem eingegebenen Kapital} IF (Kapital_neu>Obergrenze_Kapital+1) THEN Begin gotoxy(ErsteSpalte,Startzeile_Menu+2); write('Der eingegebene Betrag ist zu groá (gr”áer als ', Obergrenze_Kapital, ' Euro).'); End; {of IF GANZZAHL=false} UNTIL (Kapital_neu > 0) AND {bis gltiges Kapital} (GANZZAHL(Kapital_Eingabe)=true) AND (Kapital_neu <= Obergrenze_Kapital); Kapital := ROUND(Kapital_neu); {REAL zu INTEGER} End; {of EINGABE_KAPITAL} Procedure EINGABE_EINSATZ; {Eingabe des Einsatzes} VAR Einsatz_Eingabe : STRING; {eingegebener Einsatz als Zeichenkette} f : BYTE; {Fehlercode} Einsatz_neu : REAL; {Einsatz als Gleitkommazahl} Begin {of EINGABE_EINSATZ} clrscr; {Bildschirm leeren} UEBERSCHRIFT; {Prozedur aufrufen} Zaehler:=0; {Startwert setzen} {Anzeige des Kapitals} gotoxy(ErsteSpalte,Startzeile_Menu+2); write('Kapital: ', Kapital:5, ' Euro'); {im Folgenden wird geprft, ob ein gltiger Wert eingegeben wurde} REPEAT gotoxy(ErsteSpalte,Startzeile_Menu+3); write('Einsatz (in Euro): '); readln(Einsatz_Eingabe); {Eingabe einlesen} {bei einer Fehleingabe} VAL(Einsatz_Eingabe,Einsatz_neu,f); IF (GANZZAHL(Einsatz_Eingabe)=false) OR (Einsatz_neu <= 0) OR (Einsatz_neu > Kapital) THEN Begin gotoxy(ErsteSpalte+18,Startzeile_Menu+3); write(' '); {Eingabe l”schen} End; {of 'Fehleingabe'} {Meldung bei Fehleingabe} IF (Einsatz_neu > Kapital) THEN Begin gotoxy(ErsteSpalte,Startzeile_Menu+2); write('Ihr Einsatz darf nicht gr”áer als Ihr Kapital sein.'); End; {of 'Meldung'} UNTIL (Einsatz_neu > 0) AND {bis gltiger Einsatz} (Einsatz_neu < Kapital+1) AND (GANZZAHL(Einsatz_Eingabe)=true); Einsatz := ROUND(Einsatz_neu); {REAL zu INTEGER} {jetzt wird noch eine eventuelle Fehlermeldung durch die Anzeige des Kapitals ersetzt} gotoxy(ErsteSpalte,Startzeile_Menu+2); write('Kapital: ', Kapital:5, ' Euro '); End; {of EINGABE_EINSATZ} Procedure WUERFELN; {Simulation des Wrfelns} VAR Zahl1 : BYTE; {1. gewrfelte Zahl} Zahl2 : BYTE; {2. gewrfelte Zahl} Begin {of WUERFELN} RANDOMIZE; {Zufallsgenerator intialisieren} {Ausreiáen der Formatierung durch zu viele Zeilen verhindern, indem der erste Teil gel”scht wird} IF (Zaehler+Startzeile_Spiel+11)>25 THEN Begin clrscr; {Bildschirm leeren} UEBERSCHRIFT; {Prozedur aufrufen} {Kapital und Einsatz anzeigen} gotoxy(ErsteSpalte,Startzeile_Menu+2); write('Kapital: ', Kapital:5, ' Euro'); gotoxy(ErsteSpalte,Startzeile_Menu+3); write('Einsatz: ', Einsatz:5, ' Euro'); gotoxy(ErsteSpalte,Startzeile_Spiel); write('[...]'); Zaehler:=1; {erst eine Zeile sp„ter beginnen, da zuvor noch [...]} End; {of IF (Zaehler+Startzeile_Spiel+11)>25} {eigentliches Wrfeln} gotoxy(ErsteSpalte,Startzeile_Spiel+Zaehler); write('Es wird gewrfelt ...'); INC(Zaehler); {zur n„chsten Zeile wechseln} DELAY(Verzoegerung_Wuerfeln); Zahl1 := 1 + RANDOM(6); {1. Wrfel} Zahl2 := 1 + RANDOM(6); {2. Wrfel} Wuerfelsumme := Zahl1 + Zahl2; {Augensumme bilden} gotoxy(ErsteSpalte,Startzeile_Spiel+Zaehler); write('Die gewrfelte Summe ist ', Zahl1:2, ' + ', Zahl2:2, ' = ', Wuerfelsumme:2); INC(Zaehler); End; {of WUERFELN} Procedure SPIEL; {eigentlicher Ablauf des Spiels} VAR Runde1 : BOOLEAN; {1. Runde?} gewonnen : BOOLEAN; {gewonnen?} Ende : BOOLEAN; {beendet?} Wuerfelsumme1 : BYTE; {Augensumme des 1. Wurfes} weiter_Eingabe : CHAR; {Eingabe zu weiterem Vorgehen} weitere_Runde : BOOLEAN; {weiteres Mal spielen?} Begin {of SPIEL} {es wird so lange gespielt, bis der Nutzer es nicht mehr wnscht oder das Kapital 0 Euro betr„gt} REPEAT Runde1 := true; {1. Runde} EINGABE_EINSATZ; {Prozedur aufrufen} {bis Runde beendet} REPEAT WUERFELN; {Prozedur aufrufen} {wenn nicht mehr 1. Runde} IF Runde1=false THEN Begin IF Wuerfelsumme=7 THEN Begin {7 gewrfelt} gewonnen := false; {verloren} Ende := true; {beendet} End {of '7 gewrfelt'} ELSE Begin IF Wuerfelsumme=Wuerfelsumme1 THEN Begin {gleich wie erster Wurf} gewonnen := true; {gewonnen} Ende := true; {beendet} End {of 'gleich wie erster Wurf'} ELSE Ende := false; {noch nicht beendet} End; {of ELSE} End; {of IF Runde1=false} {wenn 1. Runde} IF Runde1=true THEN Begin CASE Wuerfelsumme OF {Augensumme von} 7,11 : Begin {of 7,11} gewonnen := true; {gewonnen} Ende := true; {beendet} End; {of 7,11} 2,3,12 : Begin {of 2,3,12} gewonnen := false; {verloren} Ende := true; {beendet} End; {of 2,3,12} ELSE Begin {of ELSE} Runde1 := false; {noch einmal wrfeln} Wuerfelsumme1 := Wuerfelsumme; {Augensumme speichern} Ende := false; {noch nicht beendet} End; {of ELSE} End; {of CASE Wuerfelsumme OF} End; {of IF Runde1=true} UNTIL Ende=true; {bis Runde beendet} {jetzt wird das Ergebnis der aktuellen Runde (gewonnen/verloren) angezeigt} gotoxy(ErsteSpalte,Startzeile_Spiel+Zaehler); INC(Zaehler); {gewonnen} IF gewonnen=true THEN Begin Kapital := Kapital + Einsatz; {Kapital um Einsatz erh”hen} write('Sie haben diese Runde gewonnen.'); End; {of 'gewonnen'} {verloren} IF gewonnen=false THEN Begin Kapital := Kapital - Einsatz; {Kapital um Einsatz vermindern} write('Sie haben diese Runde verloren.'); End; {of 'verloren'} {nun wird das aktuelle Kapital angezeigt und im Header aktualisiert} gotoxy(ErsteSpalte,Startzeile_Spiel+Zaehler); write('Ihr Kapital betr„gt jetzt ', Kapital, ' Euro.'); gotoxy(ErsteSpalte,Startzeile_Menu+2); write('Kapital: ', Kapital:5, ' Euro'); {Aktualisierung des Headers} INC(Zaehler); INC(Zaehler); {wenn das Kapital noch nicht verbraucht ist} IF Kapital>0 THEN Begin {Frage nach weiterer Runde} gotoxy(ErsteSpalte,Startzeile_Spiel+Zaehler); write('Weitere Runde spielen? (J/N) '); {auf gltige Eingabe warten} REPEAT gotoxy(ErsteSpalte+29,Startzeile_Spiel+Zaehler); write(' '); {Eingabefeld leeren} gotoxy(ErsteSpalte+29,Startzeile_Spiel+Zaehler); weiter_Eingabe := upCase(readKey); {eingegebenes Zeichen lesen} write(weiter_Eingabe); {eingegebenes Zeichen als Groábuchstaben ausgeben} DELAY(Verzoegerung_Eingabe); {warten} UNTIL (weiter_Eingabe='J') OR {auf gltige Eingabe warten} (weiter_Eingabe='N'); INC(Zaehler); {eingegebene Buchstaben in Wahrheitswerte bersetzen} CASE weiter_Eingabe OF {wenn Eingabe von} 'J': weitere_Runde := true; {weitere Runde} 'N': weitere_Runde := false; {keine weitere Runde} End; {of CASE weiter_Eingabe OF} End; {of IF Kapital>0} UNTIL (weitere_Runde=false) OR {bis keine weitere Runde gewnscht} (Kapital=0); {oder Kapital von 0 Euro} INC(Zaehler); {Ausgabe des Endkapitals} gotoxy(ErsteSpalte,Startzeile_Spiel+Zaehler); write('*** Sie haben das Spiel mit einem Kapital von ', Kapital, ' Euro beendet. ***'); {Rckkehr zum Men anbieten} gotoxy(ErsteSpalte,Startzeile_Spiel+Zaehler+3); write('(M) Zurck zum Men wechseln '); {auf gltige Eingabe warten} REPEAT Menu_Auswahl := upCase(readKey); {eingegebenes Zeichen lesen} UNTIL Menu_Auswahl='M'; {nur m/M akzeptiert} End; {of SPIEL} Procedure SPIELREGELN; {Anzeige der Spielregeln} Begin {of SPIELREGELN} {es wird immer erst die entsprechende Position "angefahren" und dann der Text angezeigt} gotoxy(ErsteSpalte,Startzeile_Menu+3); write('Es wird mit zwei Wrfeln gewrfelt und immer nur die Augensumme betrachtet.'); gotoxy(ErsteSpalte,Startzeile_Menu+4); write('Erreichen Sie beim ersten Wurf eine 7 oder 11, so haben Sie gewonnen.'); gotoxy(ErsteSpalte,Startzeile_Menu+5); write('Wrfeln Sie dagegen beim ersten Mal eine 2, 3 oder 12, so haben Sie verloren.'); gotoxy(ErsteSpalte,Startzeile_Menu+6); write('Bei jeder anderen Augensumme ist das das Spiel noch offen und es wird weiter'); gotoxy(ErsteSpalte,Startzeile_Menu+7); write('gewrfelt, bis Sie entweder eine 7 erzielen (dann haben Sie verloren) oder die'); gotoxy(ErsteSpalte,Startzeile_Menu+8); write('im ersten Wurf erreichte Augensumme in zweites Mal wrfeln (gewonnen).'); gotoxy(ErsteSpalte,Startzeile_Menu+10); write('Es werden nur ganzzahlige Betr„ge fr das Kapital und den Einsatz akzeptiert.'); gotoxy(ErsteSpalte,Startzeile_Menu+11); write('Das Spiel endet, wenn Sie das wnschen oder wenn Sie Ihr ganzes Kapital'); gotoxy(ErsteSpalte,Startzeile_Menu+12); write('verloren haben.'); {Rckkehr zum Men anbieten} gotoxy(ErsteSpalte,Startzeile_Menu+16); write('(M) Zurck zum Men wechseln '); {auf gltige Eingabe warten} REPEAT Menu_Auswahl := upCase(readKey); {eingegebenes Zeichen lesen} UNTIL Menu_Auswahl='M'; {nur m/M akzeptiert} End; {of SPIELREGELN} Procedure MENU_VERARBEITUNG; {Verarbeitung der Meneingaben} Begin {of MENU_VERARBEITUNG} CASE Menu_Auswahl OF {wenn Menpunkt} '1': Begin {1} clrscr; {Bildschirm leeren} UEBERSCHRIFT; {Prozedur aufrufen} EINGABE_KAPITAL; {Prozedur aufrufen} SPIEL; {Prozedur aufrufen} End; {1} '2': Begin {2} clrscr; {Bildschirm leeren} UEBERSCHRIFT; {Prozedur aufrufen} {im Folgenden wird die šberschrift erg„nzt} gotoxy(ErsteSpalte+5,Startzeile_Menu); write(' - Spielregeln'); gotoxy(ErsteSpalte+4,Startzeile_Menu+1); write('==============='); SPIELREGELN; {Prozedur aufrufen} End; {2} 'X': EXIT; {bei X Programm/Kommandozeile verlassen} End; {of CASE Menu_Auswahl OF} End; {of MENU_VERARBEITUNG} Begin {of Hauptprogramm} {Men und Verarbeitung der Eingaben wird st„ndig wiederholt} REPEAT MENU; {Prozedur aufrufen} MENU_VERARBEITUNG; {Prozedur aufrufen} UNTIL Menu_Auswahl='X'; {theoretisch unendliche Schleife, da X zum Beenden des Programmes fhrt} End . {of Hauptprogramm}
unit menu; {$mode delphi} interface uses Classes, SysUtils, And_jni, {And_jni_Bridge,} AndroidWidget; type {Draft Component code by "Lazarus Android Module Wizard" [5/5/2014 1:07:26]} {https://github.com/jmpessoa/lazandroidmodulewizard} {jControl template} { jMenu } jMenu = class(jControl) private FOptions: TStrings; FIcons: TStrings; procedure SetOptions(Value: TStrings); procedure SetIcons(Value: TStrings); protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Init; override; function jCreate(): jObject; procedure jFree(); procedure Add(_menu: jObject; _itemID: integer; _caption: string); procedure AddCheckable(_menu: jObject; _itemID: integer; _caption: string); procedure AddDrawable(_menu: jObject; _itemID: integer; _caption: string); procedure CheckItemCommute(_item: jObject); procedure CheckItem(_item: jObject); procedure UnCheckItem(_item: jObject); procedure AddSubMenu(_menu: jObject; _startItemID: integer; var _captions: TDynArrayOfString); overload; procedure AddCheckableSubMenu(_menu: jObject; _startItemID: integer; var _captions: TDynArrayOfString); function Size(): integer; function FindMenuItemByID(_itemID: integer): jObject; function GetMenuItemByIndex(_index: integer): jObject; procedure UnCheckAllMenuItem(); function CountSubMenus(): integer; procedure UnCheckAllSubMenuItemByIndex(_subMenuIndex: integer); procedure RegisterForContextMenu(_view: jObject); procedure UnRegisterForContextMenu(_View: JObject); procedure AddItem(_menu: jObject; _itemID: integer; _caption: string; _iconIdentifier: string; _itemType: TMenuItemType; _showAsAction: TMenuItemShowAsAction); overload; procedure AddItem(_subMenu: jObject; _itemID: integer; _caption: string; _itemType: TMenuItemType); overload; function AddSubMenu(_menu: jObject; _title: string; _headerIconIdentifier: string): jObject; overload; procedure InvalidateOptionsMenu(); //force call to OnPrepareOptionsMenu and PrepareOptionsMenuItem events procedure SetItemVisible(_item: jObject; _value: boolean); overload; procedure SetItemVisible(_menu: jObject; _index: integer; _value: boolean); overload; procedure Clear(_menu: jObject); overload; procedure Clear(); overload; procedure SetItemTitle(_item: jObject; _title: string); overload; procedure SetItemTitle(_menu: jObject; _index: integer; _title: string); overload; procedure SetItemIcon(_item: jObject; _iconIdentifier: integer); overload; procedure SetItemIcon(_menu: jObject; _index: integer; _iconIdentifier: integer); overload; procedure SetItemChecked(_item: jObject; _value: boolean); procedure SetItemCheckable(_item: jObject; _value: boolean); function GetItemIdByIndex(_menu: jObject; _index: integer): integer; function GetItemIndexById(_menu: jObject; _id: integer): integer; procedure RemoveItemById(_menu: jObject; _id: integer); procedure RemoveItemByIndex(_menu: jObject; _index: integer); procedure AddDropDownItem(_menu: jObject; _view: jObject); procedure ShowOptions(_menu: jObject); overload; procedure ShowOptions(_menu: jObject; _itemShowAsAction: TMenuItemShowAsAction); overload; published property Options: TStrings read FOptions write SetOptions; property IconIdentifiers: TStrings read FIcons write SetIcons; end; function jMenu_jCreate(env: PJNIEnv; this: JObject;_Self: int64): jObject; procedure jMenu_AddItem(env: PJNIEnv; _jmenu: JObject; _menu: jObject; _itemID: integer; _caption: string; _iconIdentifier: string; _itemType: integer; _showAsAction: integer); overload; procedure jMenu_AddItem(env: PJNIEnv; _jmenu: JObject; _subMenu: jObject; _itemID: integer; _caption: string; _itemType: integer); overload; function jMenu_AddSubMenu(env: PJNIEnv; _jmenu: JObject; _menu: jObject; _title: string; _headerIconIdentifier: string): jObject; overload; procedure jMenu_SetItemVisible(env: PJNIEnv; _jmenu: JObject; _item: jObject; _value: boolean); overload; procedure jMenu_SetItemVisible(env: PJNIEnv; _jmenu: JObject; _menu: jObject; _index: integer; _value: boolean); overload; procedure jMenu_Clear(env: PJNIEnv; _jmenu: JObject; _menu: jObject); overload; procedure jMenu_SetItemTitle(env: PJNIEnv; _jmenu: JObject; _item: jObject; _title: string); overload; procedure jMenu_SetItemIcon(env: PJNIEnv; _jmenu: JObject; _item: jObject; _iconIdentifier: integer); overload; procedure jMenu_SetItemIcon(env: PJNIEnv; _jmenu: JObject; _menu: jObject; _index: integer; _iconIdentifier: integer); overload; procedure jMenu_AddDropDownItem(env: PJNIEnv; _jmenu: JObject; _menu: jObject; _view: jObject); implementation {--------- jMenu --------------} constructor jMenu.Create(AOwner: TComponent); begin inherited Create(AOwner); //your code here.... FIcons:= TStringList.Create; FOptions:= TStringList.Create; end; destructor jMenu.Destroy; begin if not (csDesigning in ComponentState) then begin if FjObject <> nil then begin jFree(); FjObject:= nil; end; end; //you others free code here... FOptions.Free; FIcons.Free; inherited Destroy; end; procedure jMenu.Init; begin if FInitialized then Exit; inherited Init; //your code here: set/initialize create params.... FjObject := jCreate(); if FjObject = nil then exit; FInitialized:= True; end; function jMenu.jCreate(): jObject; begin Result:= jMenu_jCreate(gApp.jni.jEnv, gApp.jni.jThis , int64(Self)); end; procedure jMenu.jFree(); begin //in designing component state: set value here... if FInitialized then jni_proc(gApp.jni.jEnv, FjObject, 'jFree'); end; procedure jMenu.Add(_menu: jObject; _itemID: integer; _caption: string); begin //in designing component state: set value here... if FInitialized then jni_proc_men_it(gApp.jni.jEnv, FjObject, 'Add', _menu ,_itemID ,_caption); end; procedure jMenu.AddCheckable(_menu: jObject; _itemID: integer; _caption: string); begin //in designing component state: set value here... if FInitialized then jni_proc_men_it(gApp.jni.jEnv, FjObject, 'AddCheckable', _menu ,_itemID ,_caption); end; procedure jMenu.AddDrawable(_menu: jObject; _itemID: integer; _caption: string); begin //in designing component state: set value here... if FInitialized then jni_proc_men_it(gApp.jni.jEnv, FjObject, 'AddDrawable', _menu ,_itemID ,_caption); end; procedure jMenu.SetOptions(Value: TStrings); begin FOptions.Assign(Value); end; procedure jMenu.SetIcons(Value: TStrings); begin FIcons.Assign(Value); end; procedure jMenu.CheckItemCommute(_item: jObject); begin //in designing component state: set value here... if FInitialized then jni_proc_mei(gApp.jni.jEnv, FjObject, 'CheckItemCommute', _item); end; procedure jMenu.CheckItem(_item: jObject); begin //in designing component state: set value here... if FInitialized then jni_proc_mei(gApp.jni.jEnv, FjObject, 'CheckItem', _item); end; procedure jMenu.UnCheckItem(_item: jObject); begin //in designing component state: set value here... if FInitialized then jni_proc_mei(gApp.jni.jEnv, FjObject, 'UnCheckItem', _item); end; procedure jMenu.AddSubMenu(_menu: jObject; _startItemID: integer; var _captions: TDynArrayOfString); begin //in designing component state: set value here... if FInitialized then jni_proc_men_i_das(gApp.jni.jEnv, FjObject, 'AddSubMenu', _menu ,_startItemID ,_captions); end; procedure jMenu.AddCheckableSubMenu(_menu: jObject; _startItemID: integer; var _captions: TDynArrayOfString); begin //in designing component state: set value here... if FInitialized then jni_proc_men_i_das(gApp.jni.jEnv, FjObject, 'AddCheckableSubMenu', _menu ,_startItemID ,_captions); end; function jMenu.Size(): integer; begin Result := 0; //in designing component state: result value here... if FInitialized then Result:= jni_func_out_i(gApp.jni.jEnv, FjObject, 'Size'); end; function jMenu.FindMenuItemByID(_itemID: integer): jObject; begin Result := nil; //in designing component state: result value here... if FInitialized then Result:= jni_func_i_out_mei(gApp.jni.jEnv, FjObject, 'FindMenuItemByID', _itemID); end; function jMenu.GetMenuItemByIndex(_index: integer): jObject; begin Result := nil; //in designing component state: result value here... if FInitialized then Result:= jni_func_i_out_mei(gApp.jni.jEnv, FjObject, 'GetMenuItemByIndex', _index); end; procedure jMenu.UnCheckAllMenuItem(); begin //in designing component state: set value here... if FInitialized then jni_proc(gApp.jni.jEnv, FjObject, 'UnCheckAllMenuItem'); end; function jMenu.CountSubMenus(): integer; begin Result := 0; //in designing component state: result value here... if FInitialized then Result:= jni_func_out_i(gApp.jni.jEnv, FjObject, 'CountSubMenus'); end; procedure jMenu.UnCheckAllSubMenuItemByIndex(_subMenuIndex: integer); begin //in designing component state: set value here... if FInitialized then jni_proc_i(gApp.jni.jEnv, FjObject, 'UnCheckAllSubMenuItemByIndex', _subMenuIndex); end; procedure jMenu.RegisterForContextMenu(_view: jObject); begin //in designing component state: set value here... if FInitialized then jni_proc_viw(gApp.jni.jEnv, FjObject, 'RegisterForContextMenu', _view); end; procedure jMenu.UnRegisterForContextMenu(_View: JObject); begin if(FInitialized) then jni_proc_viw(gApp.jni.jEnv, FjObject, 'UnRegisterForContextMenu', _View); end; procedure jMenu.AddItem(_menu: jObject; _itemID: integer; _caption: string; _iconIdentifier: string; _itemType: TMenuItemType; _showAsAction: TMenuItemShowAsAction); begin //in designing component state: set value here... if FInitialized then jMenu_AddItem(gApp.jni.jEnv, FjObject, _menu ,_itemID ,_caption ,_iconIdentifier ,Ord(_itemType),Ord(_showAsAction)); end; procedure jMenu.AddItem(_subMenu: jObject; _itemID: integer; _caption: string; _itemType: TMenuItemType); begin //in designing component state: set value here... if FInitialized then jMenu_AddItem(gApp.jni.jEnv, FjObject, _subMenu ,_itemID ,_caption ,Ord(_itemType)); end; function jMenu.AddSubMenu(_menu: jObject; _title: string; _headerIconIdentifier: string): jObject; begin //in designing component state: result value here... if FInitialized then Result:= jMenu_AddSubMenu(gApp.jni.jEnv, FjObject, _menu ,_title ,_headerIconIdentifier); end; procedure jMenu.InvalidateOptionsMenu(); begin //in designing component state: set value here... if FInitialized then jni_proc(gApp.jni.jEnv, FjObject, 'InvalidateOptionsMenu'); end; procedure jMenu.SetItemVisible(_item: jObject; _value: boolean); begin //in designing component state: set value here... if FInitialized then jMenu_SetItemVisible(gApp.jni.jEnv, FjObject, _item ,_value); end; procedure jMenu.SetItemVisible(_menu: jObject; _index: integer; _value: boolean); begin //in designing component state: set value here... if FInitialized then jMenu_SetItemVisible(gApp.jni.jEnv, FjObject, _menu ,_index ,_value); end; procedure jMenu.Clear(_menu: jObject); begin //in designing component state: set value here... if FInitialized then jMenu_Clear(gApp.jni.jEnv, FjObject, _menu); end; procedure jMenu.Clear(); begin //in designing component state: set value here... if FInitialized then jni_proc(gApp.jni.jEnv, FjObject, 'Clear'); end; procedure jMenu.SetItemTitle(_item: jObject; _title: string); begin //in designing component state: set value here... if FInitialized then jMenu_SetItemTitle(gApp.jni.jEnv, FjObject, _item ,_title); end; procedure jMenu.SetItemTitle(_menu: jObject; _index: integer; _title: string); begin //in designing component state: set value here... if FInitialized then jni_proc_men_it(gApp.jni.jEnv, FjObject, 'SetItemTitle', _menu ,_index ,_title); end; procedure jMenu.SetItemIcon(_item: jObject; _iconIdentifier: integer); begin //in designing component state: set value here... if FInitialized then jMenu_SetItemIcon(gApp.jni.jEnv, FjObject, _item ,_iconIdentifier); end; procedure jMenu.SetItemIcon(_menu: jObject; _index: integer; _iconIdentifier: integer); begin //in designing component state: set value here... if FInitialized then jMenu_SetItemIcon(gApp.jni.jEnv, FjObject, _menu ,_index ,_iconIdentifier); end; procedure jMenu.SetItemChecked(_item: jObject; _value: boolean); begin //in designing component state: set value here... if FInitialized then jni_proc_mei_z(gApp.jni.jEnv, FjObject, 'SetItemChecked', _item ,_value); end; procedure jMenu.SetItemCheckable(_item: jObject; _value: boolean); begin //in designing component state: set value here... if FInitialized then jni_proc_mei_z(gApp.jni.jEnv, FjObject, 'SetItemCheckable', _item ,_value); end; function jMenu.GetItemIdByIndex(_menu: jObject; _index: integer): integer; begin Result := -1; //in designing component state: result value here... if FInitialized then Result:= jni_func_men_i_out_i(gApp.jni.jEnv, FjObject, 'GetItemIdByIndex', _menu ,_index); end; function jMenu.GetItemIndexById(_menu: jObject; _id: integer): integer; begin Result := -1; //in designing component state: result value here... if FInitialized then Result:= jni_func_men_i_out_i(gApp.jni.jEnv, FjObject, 'GetItemIndexById', _menu ,_id); end; procedure jMenu.RemoveItemById(_menu: jObject; _id: integer); begin //in designing component state: set value here... if FInitialized then jni_proc_men_i(gApp.jni.jEnv, FjObject, 'RemoveItemById', _menu ,_id); end; procedure jMenu.RemoveItemByIndex(_menu: jObject; _index: integer); begin //in designing component state: set value here... if FInitialized then jni_proc_men_i(gApp.jni.jEnv, FjObject, 'RemoveItemByIndex', _menu ,_index); end; procedure jMenu.AddDropDownItem(_menu: jObject; _view: jObject); begin //in designing component state: set value here... if FInitialized then jMenu_AddDropDownItem(gApp.jni.jEnv, FjObject, _menu ,_view); end; procedure jMenu.ShowOptions(_menu: jObject); var i, idItem: integer; begin if FOptions.Count > 0 then begin idItem:= 1; for i:= 0 to FOptions.Count-1 do begin if FOptions.Strings[i] <> '' then begin AddItem(_menu, idItem , FOptions.Strings[i], '' , mitDefault, misNever); inc(idItem); end; end; end; end; procedure jMenu.ShowOptions(_menu: jObject; _itemShowAsAction: TMenuItemShowAsAction); var i, idItem: integer; begin if FOptions.Count > 0 then begin idItem:= 1; for i:= 0 to FOptions.Count-1 do begin if FOptions.Strings[i] <> '' then begin if i < FIcons.Count then begin AddItem(_menu, idItem , FOptions.Strings[i], FIcons.Strings[i] , mitDefault, _itemShowAsAction); inc(idItem); end else begin AddItem(_menu, idItem , FOptions.Strings[i], '' , mitDefault, misNever); inc(idItem); end; end; end; end; end; {-------- jMenu_JNI_Bridge ----------} function jMenu_jCreate(env: PJNIEnv; this: JObject;_Self: int64): jObject; var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].j:= _Self; if (env = nil) or (this = nil) then exit; jCls:= Get_gjClass(env); jMethod:= env^.GetMethodID(env, jCls, 'jMenu_jCreate', '(J)Ljava/lang/Object;'); Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams); Result:= env^.NewGlobalRef(env, Result); end; (* //Please, you need insert: public java.lang.Object jMenu_jCreate(long _Self) { return (java.lang.Object)(new jMenu(this,_Self)); } //to end of "public class Controls" in "Controls.java" *) procedure jMenu_AddItem(env: PJNIEnv; _jmenu: JObject; _menu: jObject; _itemID: integer; _caption: string; _iconIdentifier: string; _itemType: integer; _showAsAction: integer); var jParams: array[0..5] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin if (env = nil) or (_jmenu = nil) then exit; jCls:= env^.GetObjectClass(env, _jmenu); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'AddItem', '(Landroid/view/Menu;ILjava/lang/String;Ljava/lang/String;II)V'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].l:= _menu; jParams[1].i:= _itemID; jParams[2].l:= env^.NewStringUTF(env, PChar(_caption)); jParams[3].l:= env^.NewStringUTF(env, PChar(_iconIdentifier)); jParams[4].i:= _itemType; jParams[5].i:= _showAsAction; if jParams[2].l = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; if jParams[3].l = nil then begin env^.DeleteLocalRef(env, jParams[2].l); env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; env^.CallVoidMethodA(env, _jmenu, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[2].l); env^.DeleteLocalRef(env,jParams[3].l); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jMenu_AddItem(env: PJNIEnv; _jmenu: JObject; _subMenu: jObject; _itemID: integer; _caption: string; _itemType: integer); var jParams: array[0..3] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin if (env = nil) or (_jmenu = nil) then exit; jCls:= env^.GetObjectClass(env, _jmenu); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'AddItem', '(Landroid/view/SubMenu;ILjava/lang/String;I)V'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].l:= _subMenu; jParams[1].i:= _itemID; jParams[2].l:= env^.NewStringUTF(env, PChar(_caption)); jParams[3].i:= _itemType; if jParams[2].l = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; env^.CallVoidMethodA(env, _jmenu, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[2].l); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; function jMenu_AddSubMenu(env: PJNIEnv; _jmenu: JObject; _menu: jObject; _title: string; _headerIconIdentifier: string): jObject; var jParams: array[0..2] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin if (env = nil) or (_jmenu = nil) then exit; jCls:= env^.GetObjectClass(env, _jmenu); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'AddSubMenu', '(Landroid/view/Menu;Ljava/lang/String;Ljava/lang/String;)Landroid/view/SubMenu;'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].l:= _menu; jParams[1].l:= env^.NewStringUTF(env, PChar(_title)); jParams[2].l:= env^.NewStringUTF(env, PChar(_headerIconIdentifier)); if jParams[1].l = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; if jParams[2].l = nil then begin env^.DeleteLocalRef(env, jParams[1].l); env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; Result:= env^.CallObjectMethodA(env, _jmenu, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[1].l); env^.DeleteLocalRef(env,jParams[2].l); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jMenu_SetItemVisible(env: PJNIEnv; _jmenu: JObject; _item: jObject; _value: boolean); var jParams: array[0..1] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin if (env = nil) or (_jmenu = nil) then exit; jCls:= env^.GetObjectClass(env, _jmenu); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'SetItemVisible', '(Landroid/view/MenuItem;Z)V'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].l:= _item; jParams[1].z:= JBool(_value); env^.CallVoidMethodA(env, _jmenu, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jMenu_SetItemVisible(env: PJNIEnv; _jmenu: JObject; _menu: jObject; _index: integer; _value: boolean); var jParams: array[0..2] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin if (env = nil) or (_jmenu = nil) then exit; jCls:= env^.GetObjectClass(env, _jmenu); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'SetItemVisible', '(Landroid/view/Menu;IZ)V'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].l:= _menu; jParams[1].i:= _index; jParams[2].z:= JBool(_value); env^.CallVoidMethodA(env, _jmenu, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jMenu_Clear(env: PJNIEnv; _jmenu: JObject; _menu: jObject); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin if (env = nil) or (_jmenu = nil) then exit; jCls:= env^.GetObjectClass(env, _jmenu); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'Clear', '(Landroid/view/Menu;)V'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].l:= _menu; env^.CallVoidMethodA(env, _jmenu, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jMenu_SetItemTitle(env: PJNIEnv; _jmenu: JObject; _item: jObject; _title: string); var jParams: array[0..1] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin if (env = nil) or (_jmenu = nil) then exit; jCls:= env^.GetObjectClass(env, _jmenu); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'SetItemTitle', '(Landroid/view/MenuItem;Ljava/lang/String;)V'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].l:= _item; jParams[1].l:= env^.NewStringUTF(env, PChar(_title)); if jParams[1].l = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; env^.CallVoidMethodA(env, _jmenu, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[1].l); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jMenu_SetItemIcon(env: PJNIEnv; _jmenu: JObject; _item: jObject; _iconIdentifier: integer); var jParams: array[0..1] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin if (env = nil) or (_jmenu = nil) then exit; jCls:= env^.GetObjectClass(env, _jmenu); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'SetItemIcon', '(Landroid/view/MenuItem;I)V'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].l:= _item; jParams[1].i:= _iconIdentifier; env^.CallVoidMethodA(env, _jmenu, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jMenu_SetItemIcon(env: PJNIEnv; _jmenu: JObject; _menu: jObject; _index: integer; _iconIdentifier: integer); var jParams: array[0..2] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin if (env = nil) or (_jmenu = nil) then exit; jCls:= env^.GetObjectClass(env, _jmenu); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'SetItemIcon', '(Landroid/view/Menu;II)V'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].l:= _menu; jParams[1].i:= _index; jParams[2].i:= _iconIdentifier; env^.CallVoidMethodA(env, _jmenu, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; procedure jMenu_AddDropDownItem(env: PJNIEnv; _jmenu: JObject; _menu: jObject; _view: jObject); var jParams: array[0..1] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin if (env = nil) or (_jmenu = nil) then exit; jCls:= env^.GetObjectClass(env, _jmenu); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'AddDropDownItem', '(Landroid/view/Menu;Landroid/view/View;)V'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].l:= _menu; jParams[1].l:= _view; env^.CallVoidMethodA(env, _jmenu, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; end.
unit DIOTA.Model.Signature; interface uses System.Classes; type TSignature = class private FSignatureFragments: TStrings; FAddress: String; public constructor Create; virtual; destructor Destroy; override; property Address: String read FAddress write FAddress; property SignatureFragments: TStrings read FSignatureFragments write FSignatureFragments; end; implementation { TSignature } constructor TSignature.Create; begin FSignatureFragments := TStringList.Create; end; destructor TSignature.Destroy; begin FSignatureFragments.Free; inherited; end; end.
unit EspecificacaoDependenciaEstoqueProduto; interface uses Especificacao; type TEspecificacaoDependenciaEstoqueProduto = class(TEspecificacao) private Fcodigo_produto :Integer; public constructor Create(codigo_produto :Integer); public function SatisfeitoPor(ProdutoDependenciaEst :TObject) :Boolean; override; end; implementation uses ProdutoDependenciaEst, SysUtils; { TEspecificacaoDependenciaEstoqueProduto } constructor TEspecificacaoDependenciaEstoqueProduto.Create(codigo_produto: Integer); begin self.Fcodigo_produto := codigo_produto; end; function TEspecificacaoDependenciaEstoqueProduto.SatisfeitoPor(ProdutoDependenciaEst: TObject): Boolean; begin result := TProdutoDependenciaEst( ProdutoDependenciaEst ).codigo_produto = self.Fcodigo_produto; end; end.
{***************************************************************************} { } { DUnitX } { } { Copyright (C) 2015 Vincent Parrett & Contributors } { } { vincent@finalbuilder.com } { http://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DUnitX.Expert.CodeGen.NewTestProject; interface {$I DUnitX.inc} uses ToolsAPI, DUnitX.Expert.CodeGen.NewProject; type TReportLeakOptions = (rloNone, rloFastMM4, rloFastMM5); TTestProjectFile = class({$IFNDEF DELPHIX_SEATTLE_UP}TNewProject{$ELSE}TNewProjectEx{$ENDIF}) private FReportLeakOptions: TReportLeakOptions; protected function NewProjectSource(const ProjectName: string): IOTAFile; override; public constructor Create(const ReportLeakOptions: TReportLeakOptions); overload; constructor Create(const APersonality: String; const ReportLeakOptions: TReportLeakOptions); overload; end; implementation uses DUnitX.Expert.CodeGen.SourceFile, DunitX.Expert.CodeGen.Templates, {$IFDEF USE_NS} System.SysUtils; {$ELSE} SysUtils; {$ENDIF} const REPORT_LEAK_DECLARATION: array[TReportLeakOptions] of String = ('', ' FastMM4,'#13#10' DUnitX.MemoryLeakMonitor.FastMM4,'#13#10, ' FastMM5,'#13#10' DUnitX.MemoryLeakMonitor.FastMM5,'#13#10); { TProjectFile } constructor TTestProjectFile.Create(const ReportLeakOptions: TReportLeakOptions); begin //TODO: Figure out how to make this be TestProjectX where X is the next available. //Return Blank and the project will be 'ProjectX.dpr' where X is the next available number FFileName := ''; FReportLeakOptions := ReportLeakOptions; end; constructor TTestProjectFile.Create(const APersonality: String; const ReportLeakOptions: TReportLeakOptions); begin Create(ReportLeakOptions); {$IFDEF DELPHIX_SEATTLE_UP} Personality := APersonality; {$ENDIF} end; function TTestProjectFile.NewProjectSource(const ProjectName: string): IOTAFile; {$IFDEF DELPHIX_SEATTLE_UP} var TestProjectCode: string; {$ENDIF} begin {$IFNDEF DELPHIX_SEATTLE_UP} result := TSourceFile.Create(STestDPR,[ProjectName, REPORT_LEAK_DECLARATION[FReportLeakOptions]]); {$ELSE} if Personality.isEmpty or SameText(Personality, sDelphiPersonality) then TestProjectCode := STestDPR else if SameText(Personality, sCBuilderPersonality) then TestProjectCode := STestCBPROJ; result := TSourceFile.Create(TestProjectCode, [ProjectName, REPORT_LEAK_DECLARATION[FReportLeakOptions]]); {$ENDIF} end; end.
unit FastBlend; // FastDIB: sourceforge.net/projects/tfastdib interface // Sapersky: per-pixel alpha, add with koeff, transparent color (Draw* procs) // x64 compability (except 16 bpp blending) {$R-} uses Windows, FastDIB; {$I platform.inc} procedure AvgBlend(Dst,Src1,Src2:TFastDIB); // Dst = (Src1 + Src2) / 2 procedure DifBlend(Dst,Src1,Src2:TFastDIB); // Dst = Sat(Src1 - Src2) + Sat(Src2 - Src1), Sat = force range 0..255 procedure SubBlend(Dst,Src1,Src2:TFastDIB); // Dst = Src1 - Src2 procedure AddBlend(Dst,Src1,Src2:TFastDIB); // Dst = Src1 + Src2 procedure MulBlend(Dst,Src1,Src2:TFastDIB); // Dst = Src1 * Src2 procedure AlphaBlend(Dst,Src1,Src2:TFastDIB;Alpha:Integer); // Dst = Src1 * Alpha + Src2 * (1 - Alpha) function DrawAlpha(Src, Dst : TFastDIB; AlphaConst : Integer = 255; dx : Integer = 0; dy : Integer = 0; Alpha : TFastDIB = nil): Boolean; // Dst = Src * Src.Alpha * AlphaConst + Dst * (1 - Src.Alpha * AlphaConst) function DrawAdd(Src, Dst : TFastDIB; K : Integer = 256; dx : Integer = 0; dy : Integer = 0): Boolean; // Dst = Src * K + Dst procedure DrawTrans(Src, Dst : TFastDIB; dx : Integer = 0; dy : Integer = 0; TransColor : DWord = 0); // if Src <> TransColor then Dst = Src implementation // ********************************* common ************************************ type TBlend8Proc = procedure(Dst, Src1, Src2 : PLine8; Size : Integer); TBlend8ProcP = procedure(Dst, Src1, Src2 : PLine32; Size, Param : Integer); TBppSet = set of 1..32; procedure xAnyBlend(Dst, Src1, Src2 : TFastDIB; Blend8, Blend8MMX : TBlend8Proc); var y: Integer; begin If (Src1.Bpp <> Dst.Bpp) or (Src2.Bpp <> Dst.Bpp) or (Src1.Bpp <> Src2.Bpp) then Exit; If Dst.Bpp in [8, 24, 32] then begin if cfMMX in CPUInfo.Features then Blend8 := Blend8MMX; for y:=0 to Dst.AbsHeight-1 do Blend8(Dst.Scanlines[y], Src1.Scanlines[y], Src2.Scanlines[y], Dst.BWidth - Dst.Gap); end; end; procedure xAnyBlendT(Dst, Src1, Src2 : TFastDIB; MainShift : Integer; Blend8, Blend8MMX, TailProc : TBlend8Proc); var y, w, ws, wTail: Integer; begin If (Src1.Bpp <> Dst.Bpp) or (Src2.Bpp <> Dst.Bpp) or (Src1.Bpp <> Src2.Bpp) then Exit; If Dst.Bpp in [8, 24, 32] then begin if cfMMX in CPUInfo.Features then Blend8 := Blend8MMX; w := Dst.BWidth - Dst.Gap; If (MainShift > 0) and (Assigned(TailProc)) then begin ws := w shr MainShift; wTail := w - (ws shl MainShift); for y:=0 to Dst.AbsHeight-1 do begin Blend8(Dst.Scanlines[y], Src1.Scanlines[y], Src2.Scanlines[y], ws shl MainShift); If wTail > 0 then TailProc(Dst.Scanlines[y], Src1.Scanlines[y], Src2.Scanlines[y], wTail); end; end else for y:=0 to Dst.AbsHeight-1 do Blend8(Dst.Scanlines[y], Src1.Scanlines[y], Src2.Scanlines[y], w); end; end; procedure xAnyBlendP(Dst, Src1, Src2 : TFastDIB; Blend8, Blend8MMX : TBlend8ProcP; Param : Integer; ValidBpps : TBppSet); var y: Integer; begin If (Src1.Bpp <> Dst.Bpp) or (Src2.Bpp <> Dst.Bpp) or (Src1.Bpp <> Src2.Bpp) then Exit; If Dst.Bpp in ValidBpps then begin if cfMMX in CPUInfo.Features then Blend8 := Blend8MMX; for y:=0 to Dst.AbsHeight-1 do Blend8(Dst.Scanlines[y], Src1.Scanlines[y], Src2.Scanlines[y], Dst.BWidth - Dst.Gap, Param); end; end; // ********************************* AvgBlend ********************************** {$IFDEF CPUX86} // no-MMX proc had a little advantage over PAS version (10%) - removed // 2 times faster than PAS version procedure xAvgMemMMX(Dst,Src1,Src2:PLine32;Size,Mask:Integer); // Dst = eax // Src1 = edx // Src2 = ecx // Size = [ebp + 12] // Mask = [ebp + 8] // a:b = [ebp - 8] var a,b: Integer; asm push edi push esi mov a,0 mov b,0 mov edi,edx mov esi,ecx mov ecx,[ebp+12] db $0F,$6E,$5D,$08 /// movd mm3,[ebp+8] db $0F,$6F,$E3 /// movq mm4,mm3 db $0F,$73,$F4,$20 /// psllq mm4,32 db $0F,$EB,$DC /// por mm3,mm4 shr ecx,3 jz @skip @quads: db $0F,$6F,$07 /// movq mm0,[edi] db $0F,$6F,$0E /// movq mm1,[esi] db $0F,$6F,$D0 /// movq mm2,mm0 db $0F,$DB,$C1 /// pand mm0,mm1 db $0F,$EF,$CA /// pxor mm1,mm2 db $0F,$73,$D1,$01 /// psrlq mm1,1 db $0F,$DB,$CB /// pand mm1,mm3 db $0F,$FE,$C8 /// paddd mm1,mm0 db $0F,$7F,$08 /// movq [eax],mm1 add edi,8 add esi,8 add eax,8 dec ecx jnz @quads @skip: mov ecx,[ebp+12] and ecx,111b jz @exit mov edx,ecx push edi lea edi,[ebp-8] rep movsb db $0F,$6F,$8D,$F8,$FF,$FF,$FF /// movq mm1,[ebp-8] mov ecx,edx pop esi lea edi,[ebp-8] rep movsb db $0F,$6F,$85,$F8,$FF,$FF,$FF /// movq mm0,[ebp-8] db $0F,$6F,$D0 /// movq mm2,mm0 db $0F,$DB,$C1 /// pand mm0,mm1 db $0F,$EF,$CA /// pxor mm1,mm2 db $0F,$73,$D1,$01 /// psrlq mm1,1 db $0F,$DB,$CB /// pand mm1,mm3 db $0F,$FE,$C8 /// paddd mm1,mm0 db $0F,$7F,$8D,$F8,$FF,$FF,$FF /// movq [ebp-8],mm1 mov ecx,edx lea esi,[ebp-8] mov edi,eax rep movsb @exit: db $0F,$77 // emms pop esi pop edi end; {$ENDIF} procedure xLine_AvgSameBpp(Dst, Src1, Src2 : PLine32; Size, Mask : Integer); Var x, i : Integer; begin For x:=0 to (Size shr 4)-1 do begin // (A+B)/2 = (A and B)+((A xor B)/2) : Paul Hsieh // (can be done at dword without overflow) Dst[0].i := (Src1[0].i and Src2[0].i) + ((Src1[0].i xor Src2[0].i) shr 1) and Mask; Dst[1].i := (Src1[1].i and Src2[1].i) + ((Src1[1].i xor Src2[1].i) shr 1) and Mask; Dst[2].i := (Src1[2].i and Src2[2].i) + ((Src1[2].i xor Src2[2].i) shr 1) and Mask; Dst[3].i := (Src1[3].i and Src2[3].i) + ((Src1[3].i xor Src2[3].i) shr 1) and Mask; Inc(PByte(Dst), 16); Inc(PByte(Src1), 16); Inc(PByte(Src2), 16); end; For x:=0 to ((Size and 15) shr 2)-1 do begin Dst[0].i := (Src1[0].i and Src2[0].i) + ((Src1[0].i xor Src2[0].i) shr 1) and Mask; Inc(PByte(Dst), 4); Inc(PByte(Src1), 4); Inc(PByte(Src2), 4); end; i := 0; For x:=0 to (Size and 3)-1 do begin Dst[0].b := (Src1[0].b and Src2[0].b) + ((Src1[0].b xor Src2[0].b) shr 1) and //Mask; PLine8(@Mask)[i]; Inc(i); If i > 3 then i := 0; Inc(PByte(Dst)); Inc(PByte(Src1)); Inc(PByte(Src2)); end; end; procedure AvgBlend(Dst,Src1,Src2:TFastDIB); Var Mask : Integer; begin If Dst.Bpp in [16, 32] then begin Mask := ( (Dst.RMask+(1 shl Dst.RShl)) or (Dst.GMask+(1 shl Dst.GShl)) or (Dst.BMask+1) ) shr 1; if Dst.Bpp=16 then Mask:=(Mask shl 16 or Mask)xor -1 else Mask:=Mask xor -1; end else Mask:=$7F7F7F7F; {$IFDEF CPUX86} xAnyBlendP(Dst, Src1, Src2, xLine_AvgSameBpp, xAvgMemMMX, Mask, [8, 16, 24, 32]); {$ELSE} xAnyBlendP(Dst, Src1, Src2, xLine_AvgSameBpp, xLine_AvgSameBpp, Mask, [8, 16, 24, 32]); {$ENDIF} end; // ********************************* DifBlend ********************************** {$IFDEF CPUX86} { procedure DifMem16(Dst,Src1,Src2:Pointer;Size:Integer); // Dst = eax // Src1 = edx // Src2 = ecx // Size = [ebp + 8] // a = [ebp - 4] // b = [ebp - 8] // c = [ebp - 12] var a,b,c: Integer; asm push ebx push edi push esi mov edi,edx mov esi,ecx mov ecx,[ebp+8] push ecx and ecx,$FFFFFFFC jz @skip add ecx,eax mov [ebp+8],ecx @dwords: mov ecx,[edi] mov ebx,[esi] and ecx,$001F001F and ebx,$001F001F or ecx,$00200020 sub ecx,ebx mov ebx,ecx and ebx,$00200020 shr ebx,5 imul ebx,$1F xor ecx,ebx mov edx,[edi] mov ebx,[esi] and edx,$07E007E0 and ebx,$07E007E0 shr edx,5 shr ebx,5 or edx,$00400040 sub edx,ebx mov ebx,edx and ebx,$00400040 shr ebx,6 imul ebx,$3F xor edx,ebx shl edx,5 or ecx,edx mov edx,[edi] mov ebx,[esi] and edx,$F800F800 and ebx,$F800F800 shr edx,11 shr ebx,11 or edx,$00200020 sub edx,ebx mov ebx,edx and ebx,$00200020 shr ebx,5 imul ebx,$1F xor edx,ebx shl edx,11 or ecx,edx xor ecx,-1 mov [eax],ecx add edi,4 add esi,4 add eax,4 cmp eax,[ebp+8] jne @dwords cmp edi,ebp je @last @skip: pop ecx and ecx,11b shr ecx,1 jz @exit mov cx,[edi] mov bx,[esi] mov a,ecx mov b,ebx lea edi,a lea esi,b push eax lea eax,c lea ebx,[eax+4] mov [ebp+8],ebx jmp @dwords @last: pop eax mov ebx,[ebp-12] mov [eax],bx @exit: pop esi pop edi pop ebx end; procedure DifMem16MMX(Dst,Src1,Src2:Pointer;Size:Integer); // Dst = eax // Src1 = edx // Src2 = ecx // Size = [ebp + 8] // B1:B2 = [ebp - 8] // G1:G2 = [ebp - 16] // M1:M2 = [ebp - 24] var B1,B2,G1,G2,M1,M2: Integer; asm push ebx push edi push esi mov B1,$001F001F mov B2,$001F001F mov G1,$07E007E0 mov G2,$07E007E0 mov M2,0 mov M1,0 pcmpeqd mm7,mm7 psrlw mm7,11 psllw mm7,11 mov edi,edx mov esi,ecx mov ecx,[ebp+8] push ecx shr ecx,3 jz @skip @quads: movq mm0,[edi] movq mm1,[esi] @cleanup: movq mm2,mm0 movq mm3,mm1 movq mm4,mm0 movq mm5,mm1 pand mm0,[ebp-8] pand mm1,[ebp-8] movq mm6,mm0 psubusw mm0,mm1 psubusw mm1,mm6 paddusw mm0,mm1 pand mm2,[ebp-16] pand mm3,[ebp-16] psrlw mm2,5 psrlw mm3,5 movq mm6,mm2 psubusw mm2,mm3 psubusw mm3,mm6 paddusw mm2,mm3 psllw mm2,5 por mm0,mm2 pand mm4,mm7 pand mm5,mm7 psrlw mm4,11 psrlw mm5,11 movq mm6,mm4 psubusw mm4,mm5 psubusw mm5,mm6 paddusw mm4,mm5 psllw mm4,11 por mm0,mm4 movq [eax],mm0 add edi,8 add esi,8 add eax,8 dec ecx jnz @quads cmp edi,0 je @last @skip: pop ecx and ecx,111b shr ecx,1 jz @exit mov edx,ecx push edi lea edi,M1 rep movsw movq mm1,[ebp-24] pop esi mov ecx,edx lea edi,M1 rep movsw movq mm0,[ebp-24] push eax lea eax,M1 mov edi,-8 mov ecx,1 jmp @cleanup @last: pop edi lea esi,M1 mov ecx,edx rep movsw @exit: emms pop esi pop edi pop ebx end; } procedure xDifBlend16(Dst,Src1,Src2:TFastDIB); type TDifMem16REG = array[0..256]of Byte; PDifMem16REG =^TDifMem16REG; TDifMem16MMX = array[0..299]of Byte; PDifMem16MMX =^TDifMem16MMX; TDifMem16Proc = procedure(Dst,Src1,Src2:Pointer;Size:Integer); const DifMem16REG: TDifMem16REG = ($55,$8B,$EC,$83,$C4,$F4,$53,$57,$56,$89,$D7,$89,$CE,$8B,$4D,$08,$51,$83,$E1, $FC,$0F,$84,$AE,$00,$00,$00,$01,$C1,$89,$4D,$08,$8B,$0F,$8B,$1E,$81,$E1,$1F, $00,$1F,$00,$81,$E3,$1F,$00,$1F,$00,$81,$C9,$20,$00,$20,$00,$29,$D9,$89,$CB, $81,$E3,$20,$00,$20,$00,$C1,$EB,$05,$6B,$DB,$1F,$31,$D9,$8B,$17,$8B,$1E,$81, $E2,$E0,$07,$E0,$07,$81,$E3,$E0,$07,$E0,$07,$C1,$EA,$05,$C1,$EB,$05,$81,$CA, $40,$00,$40,$00,$29,$DA,$89,$D3,$81,$E3,$40,$00,$40,$00,$C1,$EB,$06,$6B,$DB, $3F,$31,$DA,$C1,$E2,$05,$09,$D1,$8B,$17,$8B,$1E,$81,$E2,$00,$F8,$00,$F8,$81, $E3,$00,$F8,$00,$F8,$C1,$EA,$0B,$C1,$EB,$0B,$81,$CA,$20,$00,$20,$00,$29,$DA, $89,$D3,$81,$E3,$20,$00,$20,$00,$C1,$EB,$05,$6B,$DB,$1F,$31,$DA,$C1,$E2,$0B, $09,$D1,$83,$F1,$FF,$89,$08,$83,$C7,$04,$83,$C6,$04,$83,$C0,$04,$3B,$45,$08, $0F,$85,$5B,$FF,$FF,$FF,$39,$EF,$74,$29,$59,$83,$E1,$03,$D1,$E9,$74,$28,$66, $8B,$0F,$66,$8B,$1E,$89,$4D,$FC,$89,$5D,$F8,$8D,$7D,$FC,$8D,$75,$F8,$50,$8D, $45,$F4,$8D,$58,$04,$89,$5D,$08,$E9,$2E,$FF,$FF,$FF,$58,$8B,$5D,$F4,$66,$89, $18,$5E,$5F,$5B,$8B,$E5,$5D,$C2,$04,$00); DifMem16MMX: TDifMem16MMX = ($55,$8B,$EC,$83,$C4,$E8,$53,$57,$56,$C7,$45,$FC,$1F,$00,$1F,$00,$C7,$45,$F8, $1F,$00,$1F,$00,$C7,$45,$F4,$E0,$07,$E0,$07,$C7,$45,$F0,$E0,$07,$E0,$07,$C7, $45,$EC,$00,$00,$00,$00,$C7,$45,$E8,$00,$00,$00,$00,$0F,$76,$FF,$0F,$71,$D7, $0B,$0F,$71,$F7,$0B,$89,$D7,$89,$CE,$8B,$4D,$08,$51,$C1,$E9,$03,$0F,$84,$8E, $00,$00,$00,$0F,$6F,$07,$0F,$6F,$0E,$0F,$6F,$D0,$0F,$6F,$D9,$0F,$6F,$E0,$0F, $6F,$E9,$0F,$DB,$85,$F8,$FF,$FF,$FF,$0F,$DB,$8D,$F8,$FF,$FF,$FF,$0F,$6F,$F0, $0F,$D9,$C1,$0F,$D9,$CE,$0F,$DD,$C1,$0F,$DB,$95,$F0,$FF,$FF,$FF,$0F,$DB,$9D, $F0,$FF,$FF,$FF,$0F,$71,$D2,$05,$0F,$71,$D3,$05,$0F,$6F,$F2,$0F,$D9,$D3,$0F, $D9,$DE,$0F,$DD,$D3,$0F,$71,$F2,$05,$0F,$EB,$C2,$0F,$DB,$E7,$0F,$DB,$EF,$0F, $71,$D4,$0B,$0F,$71,$D5,$0B,$0F,$6F,$F4,$0F,$D9,$E5,$0F,$D9,$EE,$0F,$DD,$E5, $0F,$71,$F4,$0B,$0F,$EB,$C4,$0F,$7F,$00,$83,$C7,$08,$83,$C6,$08,$83,$C0,$08, $49,$0F,$85,$77,$FF,$FF,$FF,$83,$FF,$00,$74,$3B,$59,$83,$E1,$07,$D1,$E9,$74, $3C,$89,$CA,$57,$8D,$7D,$E8,$66,$F3,$A5,$0F,$6F,$8D,$E8,$FF,$FF,$FF,$5E,$89, $D1,$8D,$7D,$E8,$66,$F3,$A5,$0F,$6F,$85,$E8,$FF,$FF,$FF,$50,$8D,$45,$E8,$BF, $F8,$FF,$FF,$FF,$B9,$01,$00,$00,$00,$E9,$3D,$FF,$FF,$FF,$5F,$8D,$75,$E8,$89, $D1,$66,$F3,$A5,$0F,$77,$5E,$5F,$5B,$8B,$E5,$5D,$C2,$04,$00); var i: Integer; Code: PLine8; begin if cfMMX in CPUInfo.Features then begin GetMem(Code,SizeOf(TDifMem16MMX)); PDifMem16MMX(Code)^:=DifMem16MMX; i:=Dst.BMask shl 16 or Dst.BMask; PDWord(@Code[12])^:=i; PDWord(@Code[19])^:=i; i:=Dst.GMask shl 16 or Dst.GMask; PDWord(@Code[26])^:=i; PDWord(@Code[33])^:=i; Code[57]:=16-Dst.Bpr; Code[61]:=Dst.RShl; Code[140]:=Dst.GShl; Code[144]:=Dst.GShl; Code[160]:=Dst.GShl; Code[173]:=Dst.RShl; Code[177]:=Dst.RShl; Code[193]:=Dst.RShl; end else begin GetMem(Code,SizeOf(TDifMem16REG)); PDifMem16REG(Code)^:=DifMem16REG; i:=Dst.BMask shl 16 or Dst.BMask; PDWord(@Code[37])^:=i; PDWord(@Code[43])^:=i; i:=(i+i)and(not i); PDWord(@Code[49])^:=i; PDWord(@Code[59])^:=i; i:=Dst.GMask shl 16 or Dst.GMask; PDWord(@Code[77])^:=i; PDWord(@Code[83])^:=i; i:=i shr Dst.GShl; i:=(i+i)and(not i); PDWord(@Code[95])^:=i; PDWord(@Code[105])^:=i; i:=Dst.RMask shl 16 or Dst.RMask; PDWord(@Code[128])^:=i; PDWord(@Code[134])^:=i; i:=i shr Dst.RShl; i:=(i+i)and(not i); PDWord(@Code[146])^:=i; PDWord(@Code[156])^:=i; Code[65]:=Dst.Bpb; Code[68]:=(1 shl Dst.Bpb)-1; Code[89]:=Dst.GShl; Code[92]:=Dst.GShl; Code[111]:=Dst.Bpg; Code[114]:=(1 shl Dst.Bpg)-1; Code[119]:=Dst.GShl; Code[140]:=Dst.RShl; Code[143]:=Dst.RShl; Code[162]:=Dst.Bpr; Code[165]:=(1 shl Dst.Bpr)-1; Code[170]:=Dst.RShl; end; for i:=0 to Dst.AbsHeight-1 do TDifMem16Proc(Code)(Dst.Scanlines[i],Src1.Scanlines[i],Src2.Scanlines[i],Dst.BWidth-Dst.Gap); FreeMem(Code); end; procedure xDifMem8(Dst,Src1,Src2:PLine8;Size:Integer); // Dst = eax // Src1 = edx // Src2 = ecx // Size = [ebp + 8] // s = [ebp - 4] var s: Integer; asm push ebx push edi push esi mov edi,edx mov esi,ecx mov ecx,[ebp+8] push ecx mov s,esp mov esp,eax and ecx,$FFFFFFFC jz @skip add ecx,eax mov [ebp+8],ecx @dwords: mov ecx,[edi] mov ebx,[esi] mov eax,ecx mov edx,ebx and ecx,$00FF00FF and ebx,$00FF00FF or ecx,$01000100 sub ecx,ebx mov ebx,ecx and ebx,$01000100 imul ebx,$FF shr ebx,8 xor ecx,ebx and eax,$FF00FF00 and edx,$FF00FF00 shr eax,8 shr edx,8 or eax,$01000100 sub eax,edx mov edx,eax and edx,$01000100 imul edx,$FF shr edx,8 xor eax,edx shl eax,8 or ecx,eax xor ecx,-1 mov [esp],ecx add edi,4 add esi,4 add esp,4 cmp esp,[ebp+8] jne @dwords @skip: mov eax,esp mov esp,s pop ecx and ecx,11b jz @exit @bytes: movzx ebx,Byte([edi]) movzx edx,Byte([esi]) sub ebx,edx mov edx,ebx shr edx,8 xor ebx,edx mov [eax],bl inc edi inc esi inc eax dec ecx jnz @bytes @exit: pop esi pop edi pop ebx end; // 7 times faster than no-MMX version procedure xDifMem8MMX(Dst,Src1,Src2:PLine8;Size:Integer); // Dst = eax // Src1 = edx // Src2 = ecx // Size = [ebp + 8] asm push ebx push edi push esi mov edi,edx mov esi,ecx mov ecx,[ebp+8] push ecx shr ecx,3 jz @skip @quads: db $0F,$6F,$07 /// movq mm0,[edi] db $0F,$6F,$0E /// movq mm1,[esi] db $0F,$6F,$D0 /// movq mm2,mm0 db $0F,$D8,$C1 /// psubusb mm0,mm1 db $0F,$D8,$CA /// psubusb mm1,mm2 db $0F,$DC,$C1 /// paddusb mm0,mm1 db $0F,$7F,$00 /// movq [eax],mm0 add edi,8 add esi,8 add eax,8 dec ecx jnz @quads db $0F,$77 // emms @skip: pop ecx and ecx,111b jz @exit @bytes: movzx ebx,Byte([edi]) movzx edx,Byte([esi]) sub ebx,edx mov edx,ebx shr edx,8 xor ebx,edx mov [eax],bl inc edi inc esi inc eax dec ecx jnz @bytes @exit: pop esi pop edi pop ebx end; {$ENDIF} {$IFDEF CPUX64} // Dst = rcx, Src1 = rdx, Src2 = r8, Size = r9 procedure xDifMem8MMX(Dst,Src1,Src2:PLine8;Size:Integer); asm mov rax, r9 shr rax, 3 jz @skip @quads: movq mm0,[rdx] movq mm1,[r8] movq mm2,mm0 psubusb mm0,mm1 psubusb mm1,mm2 paddusb mm0,mm1 movq [rcx],mm0 add rdx,8 add r8,8 add rcx,8 dec rax jnz @quads emms @skip: mov rax, r9 and r9,111b jz @exit @bytes: movzx r10, byte ptr [rdx] movzx rax, byte ptr [r8] sub r10,rax mov rax,r10 shr rax,8 xor rax, r10 mov [rcx],al inc rdx inc r8 inc rcx dec r9 jnz @bytes @exit: end; {$ENDIF} procedure DifBlend(Dst,Src1,Src2:TFastDIB); begin {$IFDEF CPUX86} If (Src1.Bpp = 16) and (Src2.Bpp = 16) and (Dst.Bpp = 16) then xDifBlend16(Dst, Src1, Src2) else xAnyBlend(Dst, Src1, Src2, xDifMem8, xDifMem8MMX); {$ELSE} xAnyBlend(Dst, Src1, Src2, xDifMem8MMX, xDifMem8MMX); {$ENDIF} end; // ********************************* SubBlend ********************************** {$IFDEF CPUX86} { procedure SubMem16(Dst,Src1,Src2:Pointer;Size:Integer); // Dst = eax // Src1 = edx // Src2 = ecx // Size = [ebp + 8] // a = [ebp - 4] // b = [ebp - 8] // c = [ebp - 12] var a,b,c: Integer; asm push ebx push edi push esi mov edi,edx mov esi,ecx mov ecx,[ebp+8] push ecx and ecx,$FFFFFFFC jz @skip add ecx,eax mov [ebp+8],ecx @dwords: mov ecx,[edi] mov ebx,[esi] and ecx,$001F001F and ebx,$001F001F or ecx,$00200020 sub ecx,ebx mov ebx,ecx and ebx,$00200020 shr ebx,5 imul ebx,$1F and ecx,ebx mov edx,[edi] mov ebx,[esi] and edx,$07E007E0 and ebx,$07E007E0 shr edx,5 shr ebx,5 or edx,$00400040 sub edx,ebx mov ebx,edx and ebx,$00400040 shr ebx,6 imul ebx,$3F and edx,ebx shl edx,5 or ecx,edx mov edx,[edi] mov ebx,[esi] and edx,$F800F800 and ebx,$F800F800 shr edx,11 shr ebx,11 or edx,$00200020 sub edx,ebx mov ebx,edx and ebx,$00200020 shr ebx,5 imul ebx,$1F and edx,ebx shl edx,11 or ecx,edx mov [eax],ecx add edi,4 add esi,4 add eax,4 cmp eax,[ebp+8] jne @dwords cmp edi,ebp je @last @skip: pop ecx and ecx,11b shr ecx,1 jz @exit mov cx,[edi] mov bx,[esi] mov a,ecx mov b,ebx lea edi,a lea esi,b push eax lea eax,c lea ebx,[eax+4] mov [ebp+8],ebx jmp @dwords @last: pop eax mov ebx,[ebp-12] mov [eax],bx @exit: pop esi pop edi pop ebx end; procedure SubMem16MMX(Dst,Src1,Src2:Pointer;Size:Integer); // Dst = eax // Src1 = edx // Src2 = ecx // Size = [ebp + 8] // B1:B2 = [ebp - 8] // M1:M2 = [ebp - 16] var B1,B2,M1,M2: Integer; asm push ebx push edi push esi mov B1,$001F001F mov B2,$001F001F mov M2,0 mov M1,0 pcmpeqd mm6,mm6 psrlw mm6,10 psllw mm6,5 pcmpeqd mm7,mm7 psrlw mm7,11 psllw mm7,11 mov edi,edx mov esi,ecx mov ecx,[ebp+8] push ecx shr ecx,3 jz @skip @quads: movq mm0,[edi] movq mm1,[esi] @cleanup: movq mm2,mm0 movq mm3,mm1 movq mm4,mm0 movq mm5,mm1 pand mm0,[ebp-8] pand mm1,[ebp-8] psubusw mm0,mm1 pand mm2,mm6 pand mm3,mm6 psrlw mm2,5 psrlw mm3,5 psubusw mm2,mm3 psllw mm2,5 por mm0,mm2 pand mm4,mm7 pand mm5,mm7 psrlw mm4,11 psrlw mm5,11 psubusw mm4,mm5 psllw mm4,11 por mm0,mm4 movq [eax],mm0 add edi,8 add esi,8 add eax,8 dec ecx jnz @quads cmp edi,0 je @last @skip: pop ecx and ecx,111b shr ecx,1 jz @exit mov edx,ecx push edi lea edi,M1 rep movsw movq mm1,[ebp-16] pop esi mov ecx,edx lea edi,M1 rep movsw movq mm0,[ebp-16] push eax lea eax,M1 mov edi,-8 mov ecx,1 jmp @cleanup @last: pop edi lea esi,M1 mov ecx,edx rep movsw @exit: emms pop esi pop edi pop ebx end; } procedure xSubBlend16(Dst,Src1,Src2:TFastDIB); type TSubMem16REG = array[0..253]of Byte; PSubMem16REG =^TSubMem16REG; TSubMem16MMX = array[0..253]of Byte; PSubMem16MMX =^TSubMem16MMX; TSubMem16Proc = procedure(Dst,Src1,Src2:Pointer;Size:Integer); const SubMem16REG: TSubMem16REG = ($55,$8B,$EC,$83,$C4,$F4,$53,$57,$56,$89,$D7,$89,$CE,$8B,$4D,$08,$51,$83,$E1, $FC,$0F,$84,$AB,$00,$00,$00,$01,$C1,$89,$4D,$08,$8B,$0F,$8B,$1E,$81,$E1,$1F, $00,$1F,$00,$81,$E3,$1F,$00,$1F,$00,$81,$C9,$20,$00,$20,$00,$29,$D9,$89,$CB, $81,$E3,$20,$00,$20,$00,$C1,$EB,$05,$6B,$DB,$1F,$21,$D9,$8B,$17,$8B,$1E,$81, $E2,$E0,$07,$E0,$07,$81,$E3,$E0,$07,$E0,$07,$C1,$EA,$05,$C1,$EB,$05,$81,$CA, $40,$00,$40,$00,$29,$DA,$89,$D3,$81,$E3,$40,$00,$40,$00,$C1,$EB,$06,$6B,$DB, $3F,$21,$DA,$C1,$E2,$05,$09,$D1,$8B,$17,$8B,$1E,$81,$E2,$00,$F8,$00,$F8,$81, $E3,$00,$F8,$00,$F8,$C1,$EA,$0B,$C1,$EB,$0B,$81,$CA,$20,$00,$20,$00,$29,$DA, $89,$D3,$81,$E3,$20,$00,$20,$00,$C1,$EB,$05,$6B,$DB,$1F,$21,$DA,$C1,$E2,$0B, $09,$D1,$89,$08,$83,$C7,$04,$83,$C6,$04,$83,$C0,$04,$3B,$45,$08,$0F,$85,$5E, $FF,$FF,$FF,$39,$EF,$74,$29,$59,$83,$E1,$03,$D1,$E9,$74,$28,$66,$8B,$0F,$66, $8B,$1E,$89,$4D,$FC,$89,$5D,$F8,$8D,$7D,$FC,$8D,$75,$F8,$50,$8D,$45,$F4,$8D, $58,$04,$89,$5D,$08,$E9,$31,$FF,$FF,$FF,$58,$8B,$5D,$F4,$66,$89,$18,$5E,$5F, $5B,$8B,$E5,$5D,$C2,$04,$00); SubMem16MMX: TSubMem16MMX = ($55,$8B,$EC,$83,$C4,$F0,$53,$57,$56,$C7,$45,$FC,$1F,$00,$1F,$00,$C7,$45,$F8, $1F,$00,$1F,$00,$C7,$45,$F4,$00,$00,$00,$00,$C7,$45,$F0,$00,$00,$00,$00,$0F, $76,$F6,$0F,$71,$D6,$0A,$0F,$71,$F6,$05,$0F,$76,$FF,$0F,$71,$D7,$0B,$0F,$71, $F7,$0B,$89,$D7,$89,$CE,$8B,$4D,$08,$51,$C1,$E9,$03,$74,$67,$0F,$6F,$07,$0F, $6F,$0E,$0F,$6F,$D0,$0F,$6F,$D9,$0F,$6F,$E0,$0F,$6F,$E9,$0F,$DB,$85,$F8,$FF, $FF,$FF,$0F,$DB,$8D,$F8,$FF,$FF,$FF,$0F,$D9,$C1,$0F,$DB,$D6,$0F,$DB,$DE,$0F, $71,$D2,$05,$0F,$71,$D3,$05,$0F,$D9,$D3,$0F,$71,$F2,$05,$0F,$EB,$C2,$0F,$DB, $E7,$0F,$DB,$EF,$0F,$71,$D4,$0B,$0F,$71,$D5,$0B,$0F,$D9,$E5,$0F,$71,$F4,$0B, $0F,$EB,$C4,$0F,$7F,$00,$83,$C7,$08,$83,$C6,$08,$83,$C0,$08,$49,$75,$9E,$83, $FF,$00,$74,$3B,$59,$83,$E1,$07,$D1,$E9,$74,$3C,$89,$CA,$57,$8D,$7D,$F0,$66, $F3,$A5,$0F,$6F,$8D,$F0,$FF,$FF,$FF,$5E,$89,$D1,$8D,$7D,$F0,$66,$F3,$A5,$0F, $6F,$85,$F0,$FF,$FF,$FF,$50,$8D,$45,$F0,$BF,$F8,$FF,$FF,$FF,$B9,$01,$00,$00, $00,$E9,$64,$FF,$FF,$FF,$5F,$8D,$75,$F0,$89,$D1,$66,$F3,$A5,$0F,$77,$5E,$5F, $5B,$8B,$E5,$5D,$C2,$04,$00); var i: Integer; Code: PLine8; begin if cfMMX in CPUInfo.Features then begin GetMem(Code,SizeOf(TSubMem16MMX)); PSubMem16MMX(Code)^:=SubMem16MMX; i:=Dst.BMask shl 16 or Dst.BMask; PDWord(@Code[12])^:=i; PDWord(@Code[19])^:=i; Code[43]:=16-Dst.Bpg; Code[47]:=Dst.GShl; Code[54]:=16-Dst.Bpr; Code[58]:=Dst.RShl; Code[116]:=Dst.GShl; Code[120]:=Dst.GShl; Code[127]:=Dst.GShl; Code[140]:=Dst.RShl; Code[144]:=Dst.RShl; Code[151]:=Dst.RShl; end else begin GetMem(Code,SizeOf(TSubMem16REG)); PSubMem16REG(Code)^:=SubMem16REG; i:=Dst.BMask shl 16 or Dst.BMask; PDWord(@Code[37])^:=i; PDWord(@Code[43])^:=i; i:=(i+i)and(not i); PDWord(@Code[49])^:=i; PDWord(@Code[59])^:=i; i:=Dst.GMask shl 16 or Dst.GMask; PDWord(@Code[77])^:=i; PDWord(@Code[83])^:=i; i:=i shr Dst.GShl; i:=(i+i)and(not i); PDWord(@Code[95])^:=i; PDWord(@Code[105])^:=i; i:=Dst.RMask shl 16 or Dst.RMask; PDWord(@Code[128])^:=i; PDWord(@Code[134])^:=i; i:=i shr Dst.RShl; i:=(i+i)and(not i); PDWord(@Code[146])^:=i; PDWord(@Code[156])^:=i; Code[65]:=Dst.Bpb; Code[68]:=(1 shl Dst.Bpb)-1; Code[89]:=Dst.GShl; Code[92]:=Dst.GShl; Code[111]:=Dst.Bpg; Code[114]:=(1 shl Dst.Bpg)-1; Code[119]:=Dst.GShl; Code[140]:=Dst.RShl; Code[143]:=Dst.RShl; Code[162]:=Dst.Bpr; Code[165]:=(1 shl Dst.Bpr)-1; Code[170]:=Dst.RShl; end; for i:=0 to Dst.AbsHeight-1 do TSubMem16Proc(Code)(Dst.Scanlines[i],Src1.Scanlines[i],Src2.Scanlines[i],Dst.BWidth-Dst.Gap); FreeMem(Code); end; // no-MMX proc had no advantage over PAS version - removed // 6.6 times faster than PAS version procedure xSubMem8MMX(Dst,Src1,Src2:PLine8;Size:Integer); // Dst = eax // Src1 = edx // Src2 = ecx // Size = [ebp + 8] asm push ebx push edi push esi mov edi,edx mov esi,ecx mov ecx,[ebp+8] push ecx shr ecx,3 jz @skip @quads: db $0F,$6F,$07 /// movq mm0,[edi] db $0F,$6F,$0E /// movq mm1,[esi] db $0F,$D8,$C1 /// psubusb mm0,mm1 db $0F,$7F,$00 /// movq [eax],mm0 add edi,8 add esi,8 add eax,8 dec ecx jnz @quads db $0F,$77 // emms @skip: pop ecx and ecx,111b jz @exit @bytes: movzx ebx,Byte([edi]) movzx edx,Byte([esi]) sub ebx,edx mov edx,ebx shr edx,8 xor edx,-1 and ebx,edx mov [eax],bl inc edi inc esi inc eax dec ecx jnz @bytes @exit: pop esi pop edi pop ebx end; {$ENDIF} {$IFDEF CPUX64} // Dst = rcx, Src1 = rdx, Src2 = r8, Size = r9 procedure xSubMem8MMX(Dst,Src1,Src2:PLine8;Size:Integer); asm mov rax, r9 shr rax, 3 jz @skip @quads: movq mm0,[rdx] movq mm1,[r8] psubusb mm0,mm1 movq [rcx],mm0 add rdx,8 add r8,8 add rcx,8 dec rax jnz @quads emms @skip: and r9,111b jz @exit @bytes: movzx r10, byte ptr [rdx] movzx rax, byte ptr [r8] sub r10,rax mov rax,r10 shr rax,8 xor rax,-1 and rax, rbx mov [rcx],al inc rdx inc r8 inc rcx dec r9 jnz @bytes @exit: end; {$ENDIF} procedure xLine_SubSameBpp(Dst, Src1, Src2 : PLine8; Size : Integer); Var x, i : Integer; begin For x:=0 to (Size shr 2)-1 do begin // sort of loop unrolling... i := (Src1[0] - Src2[0]); If i < 0 then Dst[0] := 0 else Dst[0] := i; i := (Src1[1] - Src2[1]); If i < 0 then Dst[1] := 0 else Dst[1] := i; i := (Src1[2] - Src2[2]); If i < 0 then Dst[2] := 0 else Dst[2] := i; i := (Src1[3] - Src2[3]); If i < 0 then Dst[3] := 0 else Dst[3] := i; Inc(PByte(Dst), 4); Inc(PByte(Src1), 4); Inc(PByte(Src2), 4); end; For x:=0 to (Size and 3)-1 do begin i := (Src1[0] - Src2[0]); If i < 0 then Dst[0] := 0 else Dst[0] := i; Inc(PByte(Dst)); Inc(PByte(Src1)); Inc(PByte(Src2)); end; end; procedure SubBlend(Dst,Src1,Src2:TFastDIB); begin {$IFDEF CPUX86} If (Src1.Bpp = 16) and (Src2.Bpp = 16) and (Dst.Bpp = 16) then xSubBlend16(Dst, Src1, Src2) else xAnyBlend(Dst, Src1, Src2, xLine_SubSameBpp, xSubMem8MMX); // xAnyBlendT(Dst, Src1, Src2, 3, xLine_SubSameBpp, xSubMem8MMX, xLine_SubSameBpp); {$ELSE} xAnyBlend(Dst, Src1, Src2, xSubMem8MMX, xSubMem8MMX); {$ENDIF} end; // ********************************* AddBlend ********************************** {$IFDEF CPUX86} { procedure AddMem16(Dst,Src1,Src2:Pointer;Size:Integer); // Dst = eax // Src1 = edx // Src2 = ecx // Size = [ebp + 8] // a = [ebp - 4] // b = [ebp - 8] // c = [ebp - 12] var a,b,c: Integer; asm push ebx push edi push esi mov edi,edx mov esi,ecx mov ecx,[ebp+8] push ecx and ecx,$FFFFFFFC jz @skip add ecx,eax mov [ebp+8],ecx @dwords: mov ecx,[edi] mov ebx,[esi] and ecx,$001F001F and ebx,$001F001F add ecx,ebx mov ebx,ecx and ebx,$00200020 shr ebx,5 imul ebx,$1F or ecx,ebx mov edx,[edi] mov ebx,[esi] and edx,$07E007E0 and ebx,$07E007E0 shr edx,5 shr ebx,5 add edx,ebx mov ebx,edx and ebx,$00400040 shr ebx,6 imul ebx,$3F or edx,ebx shl edx,5 or ecx,edx mov edx,[edi] mov ebx,[esi] and edx,$F800F800 and ebx,$F800F800 shr edx,11 shr ebx,11 add edx,ebx mov ebx,edx and ebx,$00200020 shr ebx,5 imul ebx,$1F or edx,ebx shl edx,11 or ecx,edx mov [eax],ecx add edi,4 add esi,4 add eax,4 cmp eax,[ebp+8] jne @dwords cmp edi,ebp je @last @skip: pop ecx and ecx,11b shr ecx,1 jz @exit mov cx,[edi] mov bx,[esi] mov a,ecx mov b,ebx lea edi,a lea esi,b push eax lea eax,c lea ebx,[eax+4] mov [ebp+8],ebx jmp @dwords @last: pop eax mov ebx,[ebp-12] mov [eax],bx @exit: pop esi pop edi pop ebx end; procedure AddMem16MMX(Dst,Src1,Src2:Pointer;Size:Integer); // Dst = eax // Src1 = edx // Src2 = ecx // Size = [ebp + 8] // B1:B2 = [ebp - 8] // G1:G2 = [ebp - 16] // R1:R2 = [ebp - 24] // M1:M2 = [ebp - 32] var B1,B2,G1,G2,R1,R2,M1,M2: Integer; asm push edi push esi mov B1,$001F001F mov B2,$001F001F mov G1,$07E007E0 mov G2,$07E007E0 mov R1,$F800F800 mov R2,$F800F800 mov M2,0 mov M1,0 movq mm6,[ebp-16] psrlw mm6,5 movq mm7,[ebp-24] psrlw mm7,11 mov edi,edx mov esi,ecx mov ecx,[ebp+8] push ecx shr ecx,3 jz @skip @quads: movq mm0,[edi] movq mm1,[esi] @cleanup: movq mm2,mm0 movq mm3,mm1 movq mm4,mm0 movq mm5,mm1 pand mm0,[ebp-8] pand mm1,[ebp-8] paddusw mm0,mm1 movq mm1,mm0 pcmpgtw mm1,[ebp-8] psrlw mm1,11 por mm0,mm1 pand mm2,[ebp-16] pand mm3,[ebp-16] psrlw mm2,5 psrlw mm3,5 paddusw mm2,mm3 movq mm3,mm2 pcmpgtw mm3,mm6 psrlw mm3,10 por mm2,mm3 psllw mm2,5 por mm0,mm2 pand mm4,[ebp-24] pand mm5,[ebp-24] psrlw mm4,11 psrlw mm5,11 paddusw mm4,mm5 movq mm5,mm4 pcmpgtw mm5,mm7 psrlw mm5,11 por mm4,mm5 psllw mm4,11 por mm0,mm4 movq [eax],mm0 add edi,8 add esi,8 add eax,8 dec ecx jnz @quads cmp edi,0 je @last @skip: pop ecx and ecx,111b shr ecx,1 jz @exit mov edx,ecx push edi lea edi,M1 rep movsw movq mm1,[ebp-32] pop esi mov ecx,edx lea edi,M1 rep movsw movq mm0,[ebp-32] push eax lea eax,M1 mov edi,-8 mov ecx,1 jmp @cleanup @last: pop edi lea esi,M1 mov ecx,edx rep movsw @exit: emms pop esi pop edi end; } procedure xAddBlend16(Dst,Src1,Src2:TFastDIB); type TAddMem16REG = array[0..235]of Byte; PAddMem16REG =^TAddMem16REG; TAddMem16MMX = array[0..346]of Byte; PAddMem16MMX =^TAddMem16MMX; TAddMemProc = procedure(Dst,Src1,Src2:Pointer;Size:Integer); const AddMem16REG: TAddMem16REG = ($55,$8B,$EC,$83,$C4,$F4,$53,$57,$56,$89,$D7,$89,$CE,$8B,$4D,$08,$51,$83,$E1, $FC,$0F,$84,$99,$00,$00,$00,$01,$C1,$89,$4D,$08,$8B,$0F,$8B,$1E,$81,$E1,$1F, $00,$1F,$00,$81,$E3,$1F,$00,$1F,$00,$01,$D9,$89,$CB,$81,$E3,$20,$00,$20,$00, $C1,$EB,$05,$6B,$DB,$1F,$09,$D9,$8B,$17,$8B,$1E,$81,$E2,$E0,$07,$E0,$07,$81, $E3,$E0,$07,$E0,$07,$C1,$EA,$05,$C1,$EB,$05,$01,$DA,$89,$D3,$81,$E3,$40,$00, $40,$00,$C1,$EB,$06,$6B,$DB,$3F,$09,$DA,$C1,$E2,$05,$09,$D1,$8B,$17,$8B,$1E, $81,$E2,$00,$F8,$00,$F8,$81,$E3,$00,$F8,$00,$F8,$C1,$EA,$0B,$C1,$EB,$0B,$01, $DA,$89,$D3,$81,$E3,$20,$00,$20,$00,$C1,$EB,$05,$6B,$DB,$1F,$09,$DA,$C1,$E2, $0B,$09,$D1,$89,$08,$83,$C7,$04,$83,$C6,$04,$83,$C0,$04,$3B,$45,$08,$0F,$85, $70,$FF,$FF,$FF,$39,$EF,$74,$29,$59,$83,$E1,$03,$D1,$E9,$74,$28,$66,$8B,$0F, $66,$8B,$1E,$89,$4D,$FC,$89,$5D,$F8,$8D,$7D,$FC,$8D,$75,$F8,$50,$8D,$45,$F4, $8D,$58,$04,$89,$5D,$08,$E9,$43,$FF,$FF,$FF,$58,$8B,$5D,$F4,$66,$89,$18,$5E, $5F,$5B,$8B,$E5,$5D,$C2,$04,$00); AddMem16MMX: TAddMem16MMX = ($55,$8B,$EC,$83,$C4,$E0,$57,$56,$C7,$45,$FC,$1F,$00,$1F,$00,$C7,$45,$F8,$1F, $00,$1F,$00,$C7,$45,$F4,$E0,$07,$E0,$07,$C7,$45,$F0,$E0,$07,$E0,$07,$C7,$45, $EC,$00,$F8,$00,$F8,$C7,$45,$E8,$00,$F8,$00,$F8,$C7,$45,$E4,$00,$00,$00,$00, $C7,$45,$E0,$00,$00,$00,$00,$0F,$6F,$B5,$F0,$FF,$FF,$FF,$0F,$71,$D6,$05,$0F, $6F,$BD,$E8,$FF,$FF,$FF,$0F,$71,$D7,$0B,$89,$D7,$89,$CE,$8B,$4D,$08,$51,$C1, $E9,$03,$0F,$84,$A6,$00,$00,$00,$0F,$6F,$07,$0F,$6F,$0E,$0F,$6F,$D0,$0F,$6F, $D9,$0F,$6F,$E0,$0F,$6F,$E9,$0F,$DB,$85,$F8,$FF,$FF,$FF,$0F,$DB,$8D,$F8,$FF, $FF,$FF,$0F,$DD,$C1,$0F,$6F,$C8,$0F,$65,$8D,$F8,$FF,$FF,$FF,$0F,$71,$D1,$0B, $0F,$EB,$C1,$0F,$DB,$95,$F0,$FF,$FF,$FF,$0F,$DB,$9D,$F0,$FF,$FF,$FF,$0F,$71, $D2,$05,$0F,$71,$D3,$05,$0F,$DD,$D3,$0F,$6F,$DA,$0F,$65,$DE,$0F,$71,$D3,$0A, $0F,$EB,$D3,$0F,$71,$F2,$05,$0F,$EB,$C2,$0F,$DB,$A5,$E8,$FF,$FF,$FF,$0F,$DB, $AD,$E8,$FF,$FF,$FF,$0F,$71,$D4,$0B,$0F,$71,$D5,$0B,$0F,$DD,$E5,$0F,$6F,$EC, $0F,$65,$EF,$0F,$71,$D5,$0B,$0F,$EB,$E5,$0F,$71,$F4,$0B,$0F,$EB,$C4,$0F,$7F, $00,$83,$C7,$08,$83,$C6,$08,$83,$C0,$08,$49,$0F,$85,$5F,$FF,$FF,$FF,$83,$FF, $00,$74,$3B,$59,$83,$E1,$07,$D1,$E9,$74,$3C,$89,$CA,$57,$8D,$7D,$E0,$66,$F3, $A5,$0F,$6F,$8D,$E0,$FF,$FF,$FF,$5E,$89,$D1,$8D,$7D,$E0,$66,$F3,$A5,$0F,$6F, $85,$E0,$FF,$FF,$FF,$50,$8D,$45,$E0,$BF,$F8,$FF,$FF,$FF,$B9,$01,$00,$00,$00, $E9,$25,$FF,$FF,$FF,$5F,$8D,$75,$E0,$89,$D1,$66,$F3,$A5,$0F,$77,$5E,$5F,$8B, $E5,$5D,$C2,$04,$00); var i: Integer; Code: PLine8; begin if cfMMX in CPUInfo.Features then begin GetMem(Code,SizeOf(TAddMem16MMX)); PAddMem16MMX(Code)^:=AddMem16MMX; i:=Dst.BMask shl 16 or Dst.BMask; PDWord(@Code[11])^:=i; PDWord(@Code[18])^:=i; i:=Dst.GMask shl 16 or Dst.GMask; PDWord(@Code[25])^:=i; PDWord(@Code[32])^:=i; i:=Dst.RMask shl 16 or Dst.RMask; PDWord(@Code[39])^:=i; PDWord(@Code[46])^:=i; Code[74]:=Dst.GShl; Code[85]:=Dst.RShl; Code[151]:=16-Dst.Bpb; Code[172]:=Dst.GShl; Code[176]:=Dst.GShl; Code[189]:=16-Dst.Bpg; Code[196]:=Dst.GShl; Code[217]:=Dst.RShl; Code[221]:=Dst.RShl; Code[234]:=16-Dst.Bpr; Code[241]:=Dst.RShl; end else begin GetMem(Code,SizeOf(TAddMem16REG)); PAddMem16REG(Code)^:=AddMem16REG; i:=Dst.BMask shl 16 or Dst.BMask; PDWord(@Code[37])^:=i; PDWord(@Code[43])^:=i; PDWord(@Code[53])^:=(i+i)and(not i); i:=Dst.GMask shl 16 or Dst.GMask; PDWord(@Code[71])^:=i; PDWord(@Code[77])^:=i; i:=i shr Dst.GShl; PDWord(@Code[93])^:=(i+i)and(not i); i:=Dst.RMask shl 16 or Dst.RMask; PDWord(@Code[116])^:=i; PDWord(@Code[122])^:=i; i:=i shr Dst.RShl; PDWord(@Code[138])^:=(i+i)and(not i); Code[59]:=Dst.Bpb; Code[62]:=(1 shl Dst.Bpb)-1; Code[83]:=Dst.GShl; Code[86]:=Dst.GShl; Code[99]:=Dst.Bpg; Code[102]:=(1 shl Dst.Bpg)-1; Code[107]:=Dst.GShl; Code[128]:=Dst.RShl; Code[131]:=Dst.RShl; Code[144]:=Dst.Bpr; Code[147]:=(1 shl Dst.Bpr)-1; Code[152]:=Dst.RShl; end; for i:=0 to Dst.AbsHeight-1 do TAddMemProc(Code)(Dst.Scanlines[i],Src1.Scanlines[i],Src2.Scanlines[i],Dst.BWidth-Dst.Gap); FreeMem(Code); end; // 25% faster than PAS version procedure xAddMem8(Dst,Src1,Src2:PLine8;Size:Integer); // Dst = eax // Src1 = edx // Src2 = ecx // Size = [ebp + 8] var s: Integer; asm push ebx push edi push esi mov edi,edx mov esi,ecx mov ecx,[ebp+8] push ecx mov s,esp mov esp,eax and ecx,$FFFFFFFC jz @skip add ecx,eax mov [ebp+8],ecx @dwords: mov eax,[edi] mov ebx,[esi] mov ecx,eax mov edx,ebx and eax,$00FF00FF and ebx,$00FF00FF add eax,ebx mov ebx,eax and ebx,$01000100 shr ebx,8 imul ebx,$FF or eax,ebx and ecx,$FF00FF00 and edx,$FF00FF00 shr ecx,8 shr edx,8 add ecx,edx mov edx,ecx and edx,$01000100 shr edx,8 imul edx,$FF or ecx,edx shl ecx,8 or eax,ecx mov [esp],eax add edi,4 add esi,4 add esp,4 cmp esp,[ebp+8] jne @dwords @skip: mov eax,esp mov esp,s pop ecx and ecx,11b jz @exit @bytes: movzx ebx,Byte([esi]) movzx edx,Byte([edi]) add ebx,edx mov edx,ebx and edx,$0100 sub edx,$0100 xor edx,-1 shr edx,8 or ebx,edx mov [eax],bl inc esi inc edi inc eax dec ecx jnz @bytes @exit: pop esi pop edi pop ebx end; // 8 times faster than PAS version procedure xAddMem8MMX(Dst,Src1,Src2:PLine8;Size:Integer); // Dst = eax // Src1 = edx // Src2 = ecx // Size = [ebp + 8] asm push ebx push edi push esi mov edi,edx mov esi,ecx mov ecx,[ebp+8] push ecx shr ecx,3 jz @skip @quads: db $0F,$6F,$07 /// movq mm0,[edi] db $0F,$6F,$0E /// movq mm1,[esi] db $0F,$DC,$C1 /// paddusb mm0,mm1 db $0F,$7F,$00 /// movq [eax],mm0 add edi,8 add esi,8 add eax,8 dec ecx jnz @quads db $0F,$77 // emms @skip: pop ecx and ecx,111b jz @exit @bytes: movzx ebx,Byte([esi]) movzx edx,Byte([edi]) add ebx,edx mov edx,ebx and edx,$0100 sub edx,$0100 xor edx,-1 shr edx,8 or ebx,edx mov [eax],bl inc edi inc esi inc eax dec ecx jnz @bytes @exit: pop esi pop edi pop ebx end; {$ENDIF} {$IFDEF CPUX64} // Dst = rcx, Src1 = rdx, Src2 = r8, Size = r9 procedure xAddMem8MMX(Dst,Src1,Src2:PLine8;Size:Integer); asm mov rax, r9 shr rax, 3 jz @skip @quads: movq mm0,[rdx] movq mm1,[r8] paddusb mm0,mm1 movq [rcx],mm0 add rdx,8 add r8,8 add rcx,8 dec rax jnz @quads emms @skip: and r9,111b jz @exit @bytes: movzx r10, byte ptr [rdx] movzx rax, byte ptr [r8] add r10,rax mov rax,r10 and rax,$0100 sub rax,$0100 xor rax,-1 shr rax,8 or rax,r10 mov [rcx],al inc rdx inc r8 inc rcx dec r9 jnz @bytes @exit: end; {$ENDIF} procedure xLine_AddSameBpp(Dst, Src1, Src2 : PLine8; Size : Integer); Var x, i : Integer; begin For x:=0 to (Size shr 2)-1 do begin // sort of loop unrolling... i := Src1[0] + Src2[0]; If i > 255 then Dst[0] := 255 else Dst[0] := i; i := Src1[1] + Src2[1]; If i > 255 then Dst[1] := 255 else Dst[1] := i; i := Src1[2] + Src2[2]; If i > 255 then Dst[2] := 255 else Dst[2] := i; i := Src1[3] + Src2[3]; If i > 255 then Dst[3] := 255 else Dst[3] := i; Inc(PByte(Dst), 4); Inc(PByte(Src1), 4); Inc(PByte(Src2), 4); end; For x:=0 to (Size and 3)-1 do begin i := Src1[0] + Src2[0]; If i > 255 then Dst[0] := 255 else Dst[0] := i; Inc(PByte(Dst)); Inc(PByte(Src1)); Inc(PByte(Src2)); end; end; procedure AddBlend(Dst,Src1,Src2:TFastDIB); begin {$IFDEF CPUX86} If (Src1.Bpp = 16) and (Src2.Bpp = 16) and (Dst.Bpp = 16) then xAddBlend16(Dst, Src1, Src2) else xAnyBlend(Dst, Src1, Src2, xAddMem8, xAddMem8MMX); {$ELSE} //xAnyBlend(Dst, Src1, Src2, xLine_AddSameBpp, xLine_AddSameBpp); xAnyBlend(Dst, Src1, Src2, xAddMem8MMX, xAddMem8MMX); {$ENDIF} end; // ********************************* MulBlend ********************************** {$IFDEF CPUX86} { procedure MulMem16(Dst,Src1,Src2:Pointer;Size:Integer); // Dst = eax // Src1 = edx // Src2 = ecx // Size = [ebp + 8] // a = [ebp - 4] // b = [ebp - 8] var a,b,s: Integer; asm push ebx push edi push esi mov s,esp mov edi,edx mov esi,ecx mov esp,eax mov ecx,[ebp+8] shr ecx,1 jz @exit @words: movzx ebx,Word([edi]) movzx edx,Word([esi]) mov a,ebx mov b,edx and ebx,$0000001F and edx,$0000001F imul ebx,edx shr ebx,5 mov eax,a mov edx,b and eax,$000007E0 and edx,$000007E0 shr eax,5 shr edx,5 imul eax,edx shr eax,6 shl eax,5 or ebx,eax mov eax,a mov edx,b and eax,$0000F800 and edx,$0000F800 shr eax,11 shr edx,11 imul eax,edx shr eax,5 shl eax,11 or ebx,eax mov [esp],bx add edi,2 add esi,2 add esp,2 dec ecx jnz @words @exit: mov esp,s pop esi pop edi pop ebx end; procedure MulMem16MMX(Dst,Src1,Src2:Pointer;Size:Integer); // Dst = eax // Src1 = edx // Src2 = ecx // Size = [ebp + 8] // HB:LB = [ebp - 8] // HG:LG = [ebp - 16] // HR:LR = [ebp - 24] // AA:BB = [ebp - 32] var HB,LB,HG,LG,HR,LR,AA,BB: Integer; asm push edi push esi mov HR,$F800F800 mov LR,$F800F800 mov HG,$07E007E0 mov LG,$07E007E0 mov HB,$001F001F mov LB,$001F001F mov AA,0 mov BB,0 mov edi,edx mov esi,ecx mov ecx,[ebp+8] push ecx shr ecx,3 jz @skip @quads: movq mm0,[edi] movq mm1,[esi] @cleanup: movq mm2,mm0 movq mm3,mm0 movq mm4,mm1 movq mm5,mm1 pand mm0,[ebp-24] pand mm1,[ebp-24] pmullw mm0,mm1 psrlw mm0,5 pand mm2,[ebp-16] pand mm4,[ebp-16] psrlw mm2,5 psrlw mm4,5 pmullw mm2,mm4 psrlw mm2,6 psllw mm2,5 por mm0,mm2 pand mm3,[ebp-8] pand mm5,[ebp-8] psrlw mm3,11 psrlw mm5,11 pmullw mm3,mm5 psrlw mm3,5 psllw mm3,11 por mm0,mm3 movq [eax],mm0 add edi,8 add esi,8 add eax,8 dec ecx jnz @quads cmp edi,0 je @last @skip: pop ecx and ecx,111b shr ecx,1 jz @exit mov edx,ecx push edi mov edi,ebp sub edi,32 // edi = ebp-32 rep movsw movq mm1,[ebp-32] pop esi sub edi,edx // edi = ebp-32 mov ecx,edx rep movsw movq mm0,[ebp-32] mov ecx,1 mov edi,-8 push eax mov eax,ebp sub eax,32 jmp @cleanup @last: mov ecx,edx pop edi mov esi,ebp sub esi,32 rep movsw @exit: emms pop esi pop edi end; } procedure xMulBlend16(Dst,Src1,Src2:TFastDIB); type TMulMem16REG = array[0..150]of Byte; PMulMem16REG =^TMulMem16REG; TMulMem16MMX = array[0..294]of Byte; PMulMem16MMX =^TMulMem16MMX; TMulMemProc = procedure(Dst,Src1,Src2:Pointer;Size:Integer); const MulMem16REG: TMulMem16REG = ($55,$8B,$EC,$83,$C4,$F4,$53,$57,$56,$89,$65,$FC,$89,$D7,$89,$CE,$89,$C4,$8B, $4D,$08,$D1,$E9,$74,$72,$0F,$B7,$1F,$0F,$B7,$16,$89,$5D,$F8,$89,$55,$F4,$81, $E3,$1F,$00,$00,$00,$81,$E2,$1F,$00,$00,$00,$0F,$AF,$DA,$C1,$EB,$05,$8B,$45, $F8,$8B,$55,$F4,$25,$E0,$07,$00,$00,$81,$E2,$E0,$07,$00,$00,$C1,$E8,$05,$C1, $EA,$05,$0F,$AF,$C2,$C1,$E8,$06,$C1,$E0,$05,$09,$C3,$8B,$45,$F8,$8B,$55,$F4, $25,$00,$F8,$00,$00,$81,$E2,$00,$F8,$00,$00,$C1,$E8,$0B,$C1,$EA,$0B,$0F,$AF, $C2,$C1,$E8,$05,$C1,$E0,$0B,$09,$C3,$66,$89,$1C,$24,$83,$C7,$02,$83,$C6,$02, $83,$C4,$02,$49,$75,$8E,$8B,$65,$FC,$5E,$5F,$5B,$8B,$E5,$5D,$C2,$04,$00); MulMem16MMX: TMulMem16MMX = ($55,$8B,$EC,$83,$C4,$E0,$57,$56,$C7,$45,$FC,$00,$F8,$00,$F8,$C7,$45,$F8,$00, $F8,$00,$F8,$C7,$45,$F4,$E0,$07,$E0,$07,$C7,$45,$F0,$E0,$07,$E0,$07,$C7,$45, $EC,$1F,$00,$1F,$00,$C7,$45,$E8,$1F,$00,$1F,$00,$C7,$45,$E4,$00,$00,$00,$00, $C7,$45,$E0,$00,$00,$00,$00,$89,$D7,$89,$CE,$8B,$4D,$08,$51,$C1,$E9,$03,$0F, $84,$83,$00,$00,$00,$0F,$6F,$07,$0F,$6F,$0E,$0F,$6F,$D0,$0F,$6F,$D8,$0F,$6F, $E1,$0F,$6F,$E9,$0F,$DB,$85,$E8,$FF,$FF,$FF,$0F,$DB,$8D,$E8,$FF,$FF,$FF,$0F, $D5,$C1,$0F,$71,$D0,$05,$0F,$DB,$95,$F0,$FF,$FF,$FF,$0F,$DB,$A5,$F0,$FF,$FF, $FF,$0F,$71,$D2,$05,$0F,$71,$D4,$05,$0F,$D5,$D4,$0F,$71,$D2,$06,$0F,$71,$F2, $05,$0F,$EB,$C2,$0F,$DB,$9D,$F8,$FF,$FF,$FF,$0F,$DB,$AD,$F8,$FF,$FF,$FF,$0F, $71,$D3,$0B,$0F,$71,$D5,$0B,$0F,$D5,$DD,$0F,$71,$D3,$05,$0F,$71,$F3,$0B,$0F, $EB,$C3,$0F,$7F,$00,$83,$C7,$08,$83,$C6,$08,$83,$C0,$08,$49,$75,$82,$83,$FF, $00,$74,$3E,$59,$83,$E1,$07,$D1,$E9,$74,$41,$89,$CA,$57,$89,$EF,$83,$EF,$20, $66,$F3,$A5,$0F,$6F,$8D,$E0,$FF,$FF,$FF,$5E,$29,$D7,$89,$D1,$66,$F3,$A5,$0F, $6F,$85,$E0,$FF,$FF,$FF,$B9,$01,$00,$00,$00,$BF,$F8,$FF,$FF,$FF,$50,$89,$E8, $83,$E8,$20,$E9,$45,$FF,$FF,$FF,$89,$D1,$5F,$89,$EE,$83,$EE,$20,$66,$F3,$A5, $0F,$77,$5E,$5F,$8B,$E5,$5D,$C2,$04,$00); var i: Integer; Code: PLine8; begin if cfMMX in CPUInfo.Features then begin GetMem(Code,SizeOf(TMulMem16MMX)); PMulMem16MMX(Code)^:=MulMem16MMX; i:=Dst.RMask shl 16 or Dst.RMask; PDWord(@Code[11])^:=i; PDWord(@Code[18])^:=i; i:=Dst.GMask shl 16 or Dst.GMask; PDWord(@Code[25])^:=i; PDWord(@Code[32])^:=i; i:=Dst.BMask shl 16 or Dst.BMask; PDWord(@Code[39])^:=i; PDWord(@Code[46])^:=i; Code[119]:=Dst.Bpb; Code[137]:=Dst.GShl; Code[141]:=Dst.GShl; Code[148]:=Dst.Bpg; Code[152]:=Dst.GShl; Code[173]:=Dst.RShl; Code[177]:=Dst.RShl; Code[184]:=Dst.Bpr; Code[188]:=Dst.RShl; end else begin GetMem(Code,SizeOf(TMulMem16REG)); PMulMem16REG(Code)^:=MulMem16REG; PDWord(@Code[39])^:=Dst.BMask; PDWord(@Code[45])^:=Dst.BMask; PDWord(@Code[62])^:=Dst.GMask; PDWord(@Code[68])^:=Dst.GMask; PDWord(@Code[96])^:=Dst.RMask; PDWord(@Code[102])^:=Dst.RMask; Code[54]:=Dst.Bpb; Code[74]:=Dst.GShl; Code[77]:=Dst.GShl; Code[83]:=Dst.Bpg; Code[86]:=Dst.GShl; Code[108]:=Dst.RShl; Code[111]:=Dst.RShl; Code[117]:=Dst.Bpr; Code[120]:=Dst.RShl; end; for i:=0 to Dst.AbsHeight-1 do TMulMemProc(Code)(Dst.Scanlines[i],Src1.Scanlines[i],Src2.Scanlines[i],Dst.BWidth-Dst.Gap); FreeMem(Code); end; // no-MMX proc removed - no advantage over PAS version // 2 times faster than PAS version procedure xMulMem8MMX(Dst,Src1,Src2:PLine8;Size:Integer); // Dst = eax // Src1 = edx // Src2 = ecx // Size = [ebp + 8] asm push ebx push edi push esi mov edi,edx mov esi,ecx mov ecx,[ebp+8] push ecx shr ecx,2 jz @skip db $0F,$EF,$D2 /// pxor mm2,mm2 @dwords: db $0F,$6E,$07 /// movd mm0,[edi] db $0F,$6E,$0E /// movd mm1,[esi] db $0F,$60,$C2 /// punpcklbw mm0,mm2 db $0F,$60,$CA /// punpcklbw mm1,mm2 db $0F,$D5,$C1 /// pmullw mm0,mm1 db $0F,$71,$D0,$08 /// psrlw mm0,8 db $0F,$67,$C0 /// packuswb mm0,mm0 db $0F,$7E,$00 /// movd [eax],mm0 add edi,4 add esi,4 add eax,4 dec ecx jnz @dwords db $0F,$77 // emms @skip: pop ecx and ecx,11b jz @exit @bytes: movzx ebx,Byte([edi]) movzx edx,Byte([esi]) imul ebx,edx shr ebx,8 mov [eax],bl inc edi inc esi inc eax dec ecx jnz @bytes @exit: pop esi pop edi pop ebx end; {$ENDIF} {$IFDEF CPUX64} // Dst = rcx, Src1 = rdx, Src2 = r8, Size = r9 procedure xMulMem8MMX(Dst,Src1,Src2:PLine8;Size:Integer); asm mov rax, r9 shr rax, 2 jz @skip pxor mm2,mm2 @quads: movd mm0,[rdx] movd mm1,[r8] punpcklbw mm0,mm2 punpcklbw mm1,mm2 pmullw mm0,mm1 psrlw mm0,8 packuswb mm0,mm0 movd [rcx],mm0 add rdx,4 add r8,4 add rcx,4 dec rax jnz @quads emms @skip: and r9,11b jz @exit @bytes: movzx r10, byte ptr [rdx] movzx rax, byte ptr [r8] imul rax, r10 shr rax,8 mov [rcx],al inc rdx inc r8 inc rcx dec r9 jnz @bytes @exit: end; {$ENDIF} procedure xLine_MulSameBpp(Dst, Src1, Src2 : PLine8; Size : Integer); Var x : Integer; begin For x:=0 to (Size shr 2)-1 do begin // sort of loop unrolling... Dst[0] := (Src1[0] * Src2[0]) shr 8; Dst[1] := (Src1[1] * Src2[1]) shr 8; Dst[2] := (Src1[2] * Src2[2]) shr 8; Dst[3] := (Src1[3] * Src2[3]) shr 8; Inc(PByte(Dst), 4); Inc(PByte(Src1), 4); Inc(PByte(Src2), 4); end; For x:=0 to (Size and 3)-1 do begin Dst[0] := (Src1[0] * Src2[0]) shr 8; Inc(PByte(Dst)); Inc(PByte(Src1)); Inc(PByte(Src2)); end; end; procedure MulBlend(Dst,Src1,Src2:TFastDIB); begin {$IFDEF CPUX86} If (Src1.Bpp = 16) and (Src2.Bpp = 16) and (Dst.Bpp = 16) then xMulBlend16(Dst, Src1, Src2) else xAnyBlend(Dst, Src1, Src2, xLine_MulSameBpp, xMulMem8MMX); {$ELSE} //xAnyBlend(Dst, Src1, Src2, xLine_MulSameBpp, xLine_MulSameBpp); xAnyBlend(Dst, Src1, Src2, xMulMem8MMX, xMulMem8MMX); {$ENDIF} end; // ******************************** AlphaBlend ********************************* {$IFDEF CPUX86} { procedure BlendMem16(Dst,Src1,Src2:Pointer;Size,Alpha:Integer); // Dst = eax // Src1 = edx // Src2 = ecx // Size = [ebp + 12] // Alpha = [ebp + 8] // a = [ebp - 4] // b = [ebp - 8] // c = [ebp - 12] var a,b,c: Cardinal; asm push ebx push edi push esi mov edi,edx mov esi,ecx mov ecx,[ebp+12] and ecx,3 push ecx sub [ebp+12],ecx jz @skip add [ebp+12],eax @dwords: mov edx,[edi] // edx = src1 mov ecx,[esi] // ecx = src2 @words: // mov a,edx // a = copy of src1 mov b,ecx // b = copy of src2 // and edx,$001F001F // edx = blue_src1 and ecx,$001F001F // ecx = blue_src2 sub edx,ecx // (blue_src1-blue_src2) imul edx,[ebp+8] // (blue_src1-blue_src2)*blue_alpha shr edx,8 // (blue_src1-blue_src2)*blue_alpha / 256 add edx,ecx // (blue_src1-blue_src2)*blue_alpha / 256 + blue_src2 and edx,$001F001F // edx = [-----------bbbbb-----------bbbbb] // mov ebx,a // ebx = src1 mov ecx,b // ecx = src2 and ebx,$03E003E0 // ebx = green_src1 and ecx,$03E003E0 // ecx = green_src2 shr ebx,5 // [------ggggg-----] >> [-----------ggggg] shr ecx,5 // [------ggggg-----] >> [-----------ggggg] sub ebx,ecx // (green_src1-green_src2) imul ebx,[ebp+8] // (green_src1-green_src2)*green_alpha shr ebx,8 // (green_src1-green_src2)*green_alpha / 256 add ebx,ecx // (green_src1-green_src2)*green_alpha / 256 + green_src2 shl ebx,5 // [------ggggg-----] << [-----------ggggg] and ebx,$03E003E0 // ebx = [------ggggg-----------ggggg-----] or edx,ebx // edx = [------gggggbbbbb------gggggbbbbb] // mov ebx,a // ebx = src1 mov ecx,b // ecx = src2 and ebx,$7C007C00 // ebx = red_src1 and ecx,$7C007C00 // ecx = red_src2 shr ebx,10 // [-rrrrr----------] >> [-----------rrrrr] shr ecx,10 // [-rrrrr----------] >> [-----------rrrrr] sub ebx,ecx // (red_src1-red_src2) imul ebx,[ebp+8] // (red_src1-red_src2)*red_alpha shr ebx,8 // (red_src1-red_src2)*red_alpha / 256 add ebx,ecx // (red_src1-red_src2)*red_alpha / 256 + red_src2 shl ebx,10 // [-rrrrr----------] << [-----------rrrrr] and ebx,$7C007C00 // ebx = [-rrrrr-----------rrrrr----------] or edx,ebx // edx = [-rrrrrgggggbbbbb-rrrrrgggggbbbbb] mov [eax],edx add eax,4 add edi,4 add esi,4 cmp eax,[ebp+12] jne @dwords mov ebx,ebp sub ebx,8 cmp eax,ebx je @last //eax = @c (ebp-12) @skip: pop ecx and ecx,2 jz @exit push eax mov ebx,ebp sub ebx,12 mov eax,ebx //eax = @c (ebp-12) add ebx,4 mov [ebp+12],ebx mov dx,[edi] mov cx,[esi] jmp @words @last: mov ebx,c pop eax mov [eax],bx @exit: pop esi pop edi pop ebx end; procedure BlendMem16MMX(Dst,Src1,Src2:Pointer;Size,Alpha:Integer); // Dst = eax // Src1 = edx // Src2 = ecx // Size = [ebp + 12] // Alpha = [ebp + 8] // HA:LA = [ebp - 8] // HB:LB = [ebp - 16] var HA,LA,HB,LB: Integer; asm push ebx push edi push esi mov edi,edx mov esi,ecx mov ecx,[ebp+12] shr ecx,3 jz @skip mov ebx,[ebp+8] shl ebx,16 or ebx,[ebp+8] mov HA,ebx mov LA,ebx // HA:LA = 00aa00aa00aa00aa mov HB,0 mov LB,0 mov ebx,$001F001F movd mm2,ebx movd mm3,ebx psllq mm2,32 por mm2,mm3 // mm2 = 001F001F001F001F mov ebx,$03E003E0 movd mm3,ebx movd mm4,ebx psllq mm3,32 por mm3,mm4 // mm3 = 03E003E003E003E0 mov ebx,$7C007C00 movd mm4,ebx movd mm5,ebx psllq mm4,32 por mm4,mm5 // mm4 = 7C007C007C007C00 @quads: movq mm7,[edi] movq mm1,[esi] @words: movq mm0,mm7 movq mm5,mm1 pand mm7,mm2 pand mm1,mm2 psubw mm7,mm1 pmullw mm7,[ebp-8] psrlw mm7,8 paddb mm7,mm1 movq mm1,mm0 movq mm6,mm5 pand mm0,mm3 pand mm5,mm3 psrlw mm0,5 psrlw mm5,5 psubw mm0,mm5 pmullw mm0,[ebp-8] psrlw mm0,8 paddb mm0,mm5 psllw mm0,5 por mm7,mm0 pand mm1,mm4 pand mm6,mm4 psrlw mm1,10 psrlw mm6,10 psubw mm1,mm6 pmullw mm1,[ebp-8] psrlw mm1,8 paddb mm1,mm6 psllw mm1,10 por mm7,mm1 movq [eax],mm7 add eax,8 add edi,8 add esi,8 dec ecx jnz @quads mov ebx,ebp sub ebx,8 cmp eax,ebx je @last @skip: mov ecx,[ebp+12] and ecx,7 shr ecx,1 jz @exit push ecx push edi push ecx mov edi,ebp sub edi,16 rep movsw movq mm1,[ebp-16] pop ecx pop esi mov edi,ebp sub edi,16 rep movsw movq mm7,[ebp-16] push eax mov eax,ebp sub eax,16 mov ecx,1 jmp @words @last: pop edi pop ecx mov esi,ebp sub esi,16 rep movsw @exit: pop esi pop edi pop ebx emms end; } procedure xAlphaBlend16(Dst,Src1,Src2:TFastDIB;Alpha:Integer); type TBlendMem16REG = array[0..238]of Byte; PBlendMem16REG =^TBlendMem16REG; TBlendMem16MMX = array[0..334]of Byte; PBlendMem16MMX =^TBlendMem16MMX; TBlendMemProc = procedure(Dst,Src1,Src2:Pointer;Size,Alpha:Integer); const BlendMem16REG: TBlendMem16REG = ($55,$8B,$EC,$83,$C4,$F4,$53,$57,$56,$89,$D7,$89,$CE,$8B,$4D,$0C,$83,$E1,$03,$51, $29,$4D,$0C,$0F,$84,$A3,$00,$00,$00,$01,$45,$0C,$8B,$17,$8B,$0E,$89,$55,$FC,$89, $4D,$F8,$81,$E2,$1F,$00,$1F,$00,$81,$E1,$1F,$00,$1F,$00,$29,$CA,$0F,$AF,$55,$08, $C1,$EA,$08,$01,$CA,$81,$E2,$1F,$00,$1F,$00,$8B,$5D,$FC,$8B,$4D,$F8,$81,$E3,$E0, $03,$E0,$03,$81,$E1,$E0,$03,$E0,$03,$C1,$EB,$05,$C1,$E9,$05,$29,$CB,$0F,$AF,$5D, $08,$C1,$EB,$08,$01,$CB,$C1,$E3,$05,$81,$E3,$E0,$03,$E0,$03,$09,$DA,$8B,$5D,$FC, $8B,$4D,$F8,$81,$E3,$00,$7C,$00,$7C,$81,$E1,$00,$7C,$00,$7C,$C1,$EB,$0A,$C1,$E9, $0A,$29,$CB,$0F,$AF,$5D,$08,$C1,$EB,$08,$01,$CB,$C1,$E3,$0A,$81,$E3,$00,$7C,$00, $7C,$09,$DA,$89,$10,$83,$C0,$04,$83,$C7,$04,$83,$C6,$04,$3B,$45,$0C,$0F,$85,$69, $FF,$FF,$FF,$89,$EB,$83,$EB,$08,$39,$D8,$74,$1F,$59,$83,$E1,$02,$74,$20,$50,$89, $EB,$83,$EB,$0C,$89,$D8,$83,$C3,$04,$89,$5D,$0C,$66,$8B,$17,$66,$8B,$0E,$E9,$45, $FF,$FF,$FF,$8B,$5D,$F4,$58,$66,$89,$18,$5E,$5F,$5B,$8B,$E5,$5D,$C2,$08,$00); BlendMem16MMX: TBlendMem16MMX = ($55,$8B,$EC,$83,$C4,$F0,$53,$57,$56,$89,$D7,$89,$CE,$8B,$4D,$0C,$C1,$E9,$03,$0F, $84,$E4,$00,$00,$00,$8B,$5D,$08,$C1,$E3,$10,$0B,$5D,$08,$89,$5D,$FC,$89,$5D,$F8, $C7,$45,$F4,$00,$00,$00,$00,$C7,$45,$F0,$00,$00,$00,$00,$BB,$1F,$00,$1F,$00,$0F, $6E,$D3,$0F,$6E,$DB,$0F,$73,$F2,$20,$0F,$EB,$D3,$BB,$E0,$03,$E0,$03,$0F,$6E,$DB, $0F,$6E,$E3,$0F,$73,$F3,$20,$0F,$EB,$DC,$BB,$00,$7C,$00,$7C,$0F,$6E,$E3,$0F,$6E, $EB,$0F,$73,$F4,$20,$0F,$EB,$E5,$0F,$6F,$3F,$0F,$6F,$0E,$0F,$6F,$C7,$0F,$6F,$E9, $0F,$DB,$FA,$0F,$DB,$CA,$0F,$F9,$F9,$0F,$D5,$BD,$F8,$FF,$FF,$FF,$0F,$71,$D7,$08, $0F,$FC,$F9,$0F,$6F,$C8,$0F,$6F,$F5,$0F,$DB,$C3,$0F,$DB,$EB,$0F,$71,$D0,$05,$0F, $71,$D5,$05,$0F,$F9,$C5,$0F,$D5,$85,$F8,$FF,$FF,$FF,$0F,$71,$D0,$08,$0F,$FC,$C5, $0F,$71,$F0,$05,$0F,$EB,$F8,$0F,$DB,$CC,$0F,$DB,$F4,$0F,$71,$D1,$0A,$0F,$71,$D6, $0A,$0F,$F9,$CE,$0F,$D5,$8D,$F8,$FF,$FF,$FF,$0F,$71,$D1,$08,$0F,$FC,$CE,$0F,$71, $F1,$0A,$0F,$EB,$F9,$0F,$7F,$38,$83,$C0,$08,$83,$C7,$08,$83,$C6,$08,$49,$0F,$85, $78,$FF,$FF,$FF,$89,$EB,$83,$EB,$08,$39,$D8,$74,$3D,$8B,$4D,$0C,$83,$E1,$07,$D1, $E9,$74,$3D,$51,$57,$51,$89,$EF,$83,$EF,$10,$66,$F3,$A5,$0F,$6F,$8D,$F0,$FF,$FF, $FF,$59,$5E,$89,$EF,$83,$EF,$10,$66,$F3,$A5,$0F,$6F,$BD,$F0,$FF,$FF,$FF,$50,$89, $E8,$83,$E8,$10,$B9,$01,$00,$00,$00,$E9,$38,$FF,$FF,$FF,$5F,$59,$89,$EE,$83,$EE, $10,$66,$F3,$A5,$5E,$5F,$5B,$0F,$77,$8B,$E5,$5D,$C2,$08,$00); var i: Integer; Code: PLine8; begin if cfMMX in CPUInfo.Features then begin GetMem(Code,SizeOf(BlendMem16MMX)); PBlendMem16MMX(Code)^:=BlendMem16MMX; PDWord(@Code[55])^:=Dst.BMask shl 16 or Dst.BMask; PDWord(@Code[73])^:=Dst.GMask shl 16 or Dst.GMask; PDWord(@Code[91])^:=Dst.RMask shl 16 or Dst.RMask; Code[158]:=Dst.GShl; Code[162]:=Dst.GShl; Code[183]:=Dst.GShl; Code[196]:=Dst.RShl; Code[200]:=Dst.RShl; Code[221]:=Dst.RShl; end else begin GetMem(Code,SizeOf(BlendMem16REG)); PBlendMem16REG(Code)^:=BlendMem16REG; i:=Dst.BMask shl 16 or Dst.BMask; PDWord(@Code[44])^:=i; PDWord(@Code[50])^:=i; PDWord(@Code[67])^:=i; i:=Dst.GMask shl 16 or Dst.GMask; PDWord(@Code[79])^:=i; PDWord(@Code[85])^:=i; PDWord(@Code[111])^:=i; i:=Dst.RMask shl 16 or Dst.RMask; PDWord(@Code[125])^:=i; PDWord(@Code[131])^:=i; PDWord(@Code[157])^:=i; Code[91]:=Dst.GShl; Code[94]:=Dst.GShl; Code[108]:=Dst.GShl; Code[137]:=Dst.RShl; Code[140]:=Dst.RShl; Code[154]:=Dst.RShl; end; for i:=0 to Dst.AbsHeight-1 do TBlendMemProc(Code)(Dst.Scanlines[i],Src1.Scanlines[i],Src2.Scanlines[i],Dst.BWidth-Dst.Gap,Alpha); FreeMem(Code); end; // 30% faster than PAS version procedure xBlendMem8(Dst,Src1,Src2:PLine32;Size,Alpha:Integer); // Dst = eax // Src1 = edx // Src2 = ecx // Size = [ebp + 12] // Alpha = [ebp + 8] asm push ebx push edi push esi mov edi,edx mov esi,ecx mov ebx,[ebp+12] and ebx,3 push ebx sub [ebp+12],ebx jz @skip add [ebp+12],eax @dwords: mov ebx,[edi] mov edx,[esi] and ebx,$00FF00FF and edx,$00FF00FF sub ebx,edx imul ebx,[ebp+8] shr ebx,8 add ebx,edx and ebx,$00FF00FF mov ecx,[edi] mov edx,[esi] and ecx,$FF00FF00 and edx,$FF00FF00 shr ecx,8 shr edx,8 sub ecx,edx imul ecx,[ebp+8] shr ecx,8 add ecx,edx shl ecx,8 and ecx,$FF00FF00 or ecx,ebx mov [eax],ecx add eax,4 add esi,4 add edi,4 cmp eax,[ebp+12] jne @dwords @skip: pop ebx cmp ebx,0 je @exit add ebx,eax mov [ebp+12],ebx @bytes: mov bl,[edi] mov cl,[esi] and ebx,$FF and ecx,$FF sub ebx,ecx imul ebx,[ebp+8] shr ebx,8 add ebx,ecx mov [eax],bl inc eax inc esi inc edi cmp eax,[ebp+12] jne @bytes @exit: pop esi pop edi pop ebx end; // 3.5 times faster than PAS version procedure xBlendMem8MMX(Dst,Src1,Src2:PLine32;Size,Alpha:Integer); // Dst = eax // Src1 = edx // Src2 = ecx // Size = [ebp + 12] // Alpha = [ebp + 8] asm push ebx push edi push esi mov edi,edx mov esi,ecx mov ecx,[ebp+12] shr ecx,3 jz @skip mov ebx,[ebp+8] shl ebx,16 or ebx,[ebp+8] db $0F,$6E,$F3 /// movd mm6,ebx db $0F,$6E,$EB /// movd mm5,ebx db $0F,$73,$F5,$20 /// psllq mm5,32 db $0F,$EB,$F5 /// por mm6,mm5 // mm6 = 00aa00aa00aa00aa db $0F,$EF,$FF /// pxor mm7,mm7 @quads: db $0F,$6F,$07 /// movq mm0,[edi] // src1 db $0F,$6F,$0E /// movq mm1,[esi] // src2 db $0F,$6F,$D0 /// movq mm2,mm0 // second copy of src1 db $0F,$6F,$D9 /// movq mm3,mm1 // second copy of src2 db $0F,$6F,$E1 /// movq mm4,mm1 // third copy of src2 db $0F,$60,$C7 /// punpcklbw mm0,mm7 // mm0 = unpacked low half of src1 db $0F,$60,$CF /// punpcklbw mm1,mm7 // mm1 = unpacked low half of src2 db $0F,$68,$D7 /// punpckhbw mm2,mm7 // mm2 = unpacked high half of src1 db $0F,$68,$DF /// punpckhbw mm3,mm7 // mm3 = unpacked high half of src2 db $0F,$F9,$C1 /// psubw mm0,mm1 // mm0 = low half of (src1-src2) db $0F,$F9,$D3 /// psubw mm2,mm3 // mm2 = high half of (src1-src2) db $0F,$D5,$C6 /// pmullw mm0,mm6 // low (src1-src2)*alpha db $0F,$D5,$D6 /// pmullw mm2,mm6 // high (src1-src2)*alpha db $0F,$71,$D0,$08 /// psrlw mm0,8 // low (src1-src2)*alpha / 256 db $0F,$71,$D2,$08 /// psrlw mm2,8 // high (src1-src2)*alpha / 256 db $0F,$67,$C2 /// packuswb mm0,mm2 // combine with unsigned saturation db $0F,$FC,$C4 /// paddb mm0,mm4 // (src1-src2)*alpha / 256 + src2 db $0F,$7F,$00 /// movq [eax],mm0 // store the result add eax,8 add edi,8 add esi,8 dec ecx jnz @quads @skip: mov ecx,[ebp+12] and ecx,111b jz @exit add ecx,eax mov [ebp+12],ecx @bytes: mov bl,[edi] mov cl,[esi] and ebx,$FF and ecx,$FF sub ebx,ecx imul ebx,[ebp+8] shr ebx,8 add ebx,ecx mov [eax],bl inc eax inc edi inc esi cmp eax,[ebp+12] jne @bytes @exit: pop esi pop edi pop ebx db $0F,$77 // emms end; {$ENDIF} procedure xLine_AlphaSameBpp(Dst, Src1, Src2 : PLine32; Size, Alpha : Integer); Var x, ia : Integer; begin ia := 255 - Alpha; For x:=0 to (Size shr 2)-1 do begin // sort of loop unrolling... Dst[0].b := (Src1[0].b * Alpha + Src2[0].b * ia) shr 8; Dst[0].g := (Src1[0].g * Alpha + Src2[0].g * ia) shr 8; Dst[0].r := (Src1[0].r * Alpha + Src2[0].r * ia) shr 8; Dst[0].a := (Src1[0].a * Alpha + Src2[0].a * ia) shr 8; Inc(PByte(Dst), 4); Inc(PByte(Src1), 4); Inc(PByte(Src2), 4); end; For x:=0 to (Size and 3)-1 do begin Dst[0].b := (Src1[0].b * Alpha + Src2[0].b * ia) shr 8; Inc(PByte(Dst)); Inc(PByte(Src1)); Inc(PByte(Src2)); end; end; procedure AlphaBlend(Dst,Src1,Src2:TFastDIB;Alpha:Integer); begin {$IFDEF CPUX86} If (Src1.Bpp = 16) and (Src2.Bpp = 16) and (Dst.Bpp = 16) then xAlphaBlend16(Dst, Src1, Src2, Alpha) else xAnyBlendP(Dst, Src1, Src2, xBlendMem8, xBlendMem8MMX, Alpha, [8, 24, 32]); {$ELSE} xAnyBlendP(Dst, Src1, Src2, xLine_AlphaSameBpp, xLine_AlphaSameBpp, Alpha, [8, 24, 32]); // for better performance use DrawAlpha, it has x64 MMX version {$ENDIF} end; // ******************************** Draw-procs ********************************* {$IFDEF CPUX86} // code based on SpriteUtils-2 // using pshufw (integer SSE) command for alpha replication // if pand command is disabled, Dst.Alpha is not cleared // (calculated as: Dst.alpha = Src.Alpha * Src.Alpha + (255 - Src.Alpha) * Dst.Alpha ) procedure xLine_DrawAlpha32_SSE(Src, Dst : Pointer; Count : Integer); Const Mask : Int64 = $000000FF00FF00FF; asm push esi mov esi, eax lea eax, [Mask] db $0F,$6F,$28 /// movq mm5, [eax] // mm5 - $0000.00FF|00FF.00FF db $0F,$EF,$FF /// pxor mm7, mm7 // mm7 = 0 @inner_loop: mov eax, [esi] test eax, $FF000000 jz @noblend db $0F,$6E,$06 /// movd mm0, [esi] db $0F,$6E,$0A /// movd mm1, [edx] db $0F,$60,$C7 /// punpcklbw mm0, mm7 // mm0 - src db $0F,$60,$CF /// punpcklbw mm1, mm7 // mm1 - dst db $0F,$70,$F0,$FF /// pshufw mm6, mm0, 255 // mm6 - src alpha // db $0F,$DB,$F5 /// pand mm6, mm5 // clear alpha component of mm6 - can be skipped if not needed // add esi, 4 db $0F,$D5,$C6 /// pmullw mm0, mm6 // получить произведение источника в mm0 db $0F,$EF,$F5 /// pxor mm6, mm5 // получить обратную прозрачность в mm6 db $0F,$D5,$CE /// pmullw mm1, mm6 // получить произведение источника в mm0 db $0F,$FD,$C1 /// paddw mm0, mm1 // сложить db $0F,$71,$D0,$08 /// psrlw mm0, 8 // переместить в младшую сторону для упаковки db $0F,$67,$C7 /// packuswb mm0, mm7 // упаковать перед записью на место db $0F,$7E,$02 /// movd [edx], mm0 // записать результат @noblend: add esi, 4 add edx, 4 dec ecx jnz @inner_loop db $0F,$77 /// emms pop esi end; // same combining per-pixel and constant Alpha procedure xLine_DrawAlpha32_SSE_2(Src, Dst : Pointer; Count, AlphaC : Integer); Const Mask : Int64 = $000000FF00FF00FF; asm push esi mov esi, eax lea eax, [Mask] db $0F,$6F,$28 /// movq mm5, [eax] // mm5 - $0000.00FF|00FF.00FF db $0F,$EF,$FF /// pxor mm7, mm7 // mm7 = 0 mov eax, AlphaC db $0F,$6E,$C0 /// movd mm0, eax db $0F,$70,$E0,$00 /// pshufw mm4, mm0, 0 // mm4 - const alpha @inner_loop: mov eax, [esi] test eax, $FF000000 // alpha = 0 - can skip blending; this check jz @noblend // makes proc faster at CoreDuo, but slower at P4 (also depends on data) db $0F,$6E,$06 /// movd mm0, [esi] db $0F,$6E,$0A /// movd mm1, [edx] db $0F,$60,$C7 /// punpcklbw mm0, mm7 // mm0 - src db $0F,$60,$CF /// punpcklbw mm1, mm7 // mm1 - dst db $0F,$70,$F0,$FF /// pshufw mm6, mm0, 255 // mm6 - src alpha db $0F,$D5,$F4 /// pmullw mm6, mm4 // alpha = alpha * [const alpha] db $0F,$71,$D6,$08 /// psrlw mm6, 8 // db $0F,$DB,$F5 /// pand mm6, mm5 // clear alpha component of mm6 - can be skipped if not needed db $0F,$D5,$C6 /// pmullw mm0, mm6 // src = src * alpha db $0F,$EF,$F5 /// pxor mm6, mm5 // alpha = 1 - alpha db $0F,$D5,$CE /// pmullw mm1, mm6 // dst = dst * (1 - alpha) db $0F,$FD,$C1 /// paddw mm0, mm1 // src = src + dst db $0F,$71,$D0,$08 /// psrlw mm0, 8 // div 256 db $0F,$67,$C7 /// packuswb mm0, mm7 // packing to bytes db $0F,$7E,$02 /// movd [edx], mm0 @noblend: add esi, 4 add edx, 4 dec ecx jnz @inner_loop db $0F,$77 /// emms pop esi end; {$ENDIF} {$IFDEF CPUX64} // Src = rcx, Dst = rdx, Count = r8, AlphaC = r9 procedure xLine_DrawAlpha32_SSE_2(Src, Dst : Pointer; Count, AlphaC : Integer); Const Mask : Int64 = $000000FF00FF00FF; asm movq mm5, Mask // mm5 - $0000.00FF|00FF.00FF pxor mm7, mm7 // mm7 = 0 mov eax, AlphaC movd mm0, eax pshufw mm4, mm0, 0 // mm4 - const alpha @inner_loop: mov eax, [rcx] test eax, $FF000000 // alpha = 0 - can skip blending; this check jz @noblend // makes proc faster at CoreDuo, but slower at P4 (also depends on data) movd mm0, [rcx] // movd mm0, eax movd mm1, [rdx] punpcklbw mm0, mm7 // mm0 - src punpcklbw mm1, mm7 // mm1 - dst pshufw mm6, mm0, 255 // mm6 - src alpha pmullw mm6, mm4 // alpha = alpha * [const alpha] psrlw mm6, 8 // pand mm6, mm5 // clear alpha component of mm6 - can be skipped if not needed pmullw mm0, mm6 // src = src * alpha pxor mm6, mm5 // alpha = 1 - alpha pmullw mm1, mm6 // dst = dst * (1 - alpha) paddw mm0, mm1 // src = src + dst psrlw mm0, 8 // div 256 packuswb mm0, mm7 // packing to bytes movd [rdx], mm0 @noblend: add rcx, 4 add rdx, 4 dec r8 jnz @inner_loop emms end; {$ENDIF} procedure xLine_DrawAlpha8(Src : PByte; Dst : PFColorA; SrcPal : PFColorTable; Count, dStep : Integer; Alpha : Integer; UsePalAlpha : Boolean = False); Var x, a, ia : Integer; sc : PFColorA; begin If (UsePalAlpha) then For x:=0 to Count-1 do begin sc := @SrcPal[Src^]; a := sc.a * Alpha; ia := (65535 - a); Dst.b := (sc.b * a + Dst.b * ia) shr 16; Dst.g := (sc.g * a + Dst.g * ia) shr 16; Dst.r := (sc.r * a + Dst.r * ia) shr 16; Inc(Src); Inc(PByte(Dst), dStep); end else begin a := Alpha; ia := 255 - Alpha; For x:=0 to Count-1 do begin sc := @SrcPal[Src^]; Dst.b := (sc.b * a + Dst.b * ia) shr 8; Dst.g := (sc.g * a + Dst.g * ia) shr 8; Dst.r := (sc.r * a + Dst.r * ia) shr 8; Inc(Src); Inc(PByte(Dst), dStep); end end; end; // Drawing Src to Dst with per-pixel alpha // Src is 8 (alpha from palette), 24 (separate 8 bpp Alpha), 32 bpp // Dst is 24, 32 bpp // using constant alpha at same proc makes it 10-12% slower // MMX/SSE version is 1.5 times faster function DrawAlpha(Src, Dst : TFastDIB; AlphaConst : Integer = 255; dx : Integer = 0; dy : Integer = 0; Alpha : TFastDIB = nil): Boolean; var x, y, a, ia, sStep, dStep: Integer; sc, dc: PFColorA; pa : PByte; UseMMX : Boolean; begin Result := ( (Src.Bpp in [8, 32]) or ((Src.Bpp = 24) and (Alpha <> nil)) ) and (Dst.Bpp >= 24); If (not Result) or (AlphaConst = 0) then Exit; sStep := Src.Bpp shr 3; dStep := Dst.Bpp shr 3; If (AlphaConst > 255) then AlphaConst := 255; UseMMX := (sStep = 4) and (dStep = 4) and (Alpha = nil) and ([cfSSE, cfMMX2] * CpuInfo.Features <> []); for y:=0 to Src.AbsHeight-1 do begin sc := Src.Scanlines[y]; dc := Dst.Scanlines[y + dy]; Inc(PByte(dc), dx * dStep); If UseMMX then begin {$IFDEF CPUX86} If (AlphaConst = 255) then xLine_DrawAlpha32_SSE(sc, dc, Src.Width) else {$ENDIF} xLine_DrawAlpha32_SSE_2(sc, dc, Src.Width, AlphaConst); end else If (Alpha <> nil) then begin pa := Alpha.Scanlines[y]; For x:=0 to Src.Width-1 do begin a := pa^ * AlphaConst; If (a <> 0) then begin ia := (65535 - a); dc.b := (sc.b * a + dc.b * ia) shr 16; dc.g := (sc.g * a + dc.g * ia) shr 16; dc.r := (sc.r * a + dc.r * ia) shr 16; end; Inc(PByte(sc), sStep); Inc(PByte(dc), dStep); Inc(pa); end; end else If (sStep = 1) then xLine_DrawAlpha8(PByte(sc), dc, Src.Colors, Src.Width, dStep, AlphaConst, True) else For x:=0 to Src.Width-1 do begin a := sc.a * (AlphaConst); // checking alpha = 0 for typical data is faster at CoreDuo, // but can be slower at P4 for bad data If (a <> 0) then begin ia := (65535 - a); dc.b := (sc.b * a + dc.b * ia) shr 16; dc.g := (sc.g * a + dc.g * ia) shr 16; dc.r := (sc.r * a + dc.r * ia) shr 16; end; Inc(sc); Inc(PByte(dc), dStep); end; end; end; {$IFDEF CPUX86} // Additive blending with MMX // Src - 8 bpp, Dst - 32 bpp procedure xLine_Add8_32_MMX(Src, Dst : Pointer; Count : Integer; SrcPal : PFColorTable); asm push esi push edi push ebx mov esi, eax mov edi, edx mov edx, SrcPal @loop: movzx eax, byte ptr [esi] movzx ebx, byte ptr [esi + 1] db $0F,$6E,$04,$82 /// movd mm0, [eax * 4 + edx] db $0F,$6E,$0C,$9A /// movd mm1, [ebx * 4 + edx] db $0F,$73,$F1,$20 /// psllq mm1, 32 db $0F,$EB,$C1 /// por mm0, mm1 db $0F,$6F,$17 /// movq mm2, [edi] db $0F,$DC,$C2 /// paddusb mm0, mm2 db $0F,$7F,$07 /// movq [edi], mm0 add esi, 2 add edi, 8 dec ecx jnz @loop db $0F,$77 /// emms pop ebx pop edi pop esi end; procedure xLine_AddK32_MMX(Src, Dst : Pointer; Count, K : Integer); asm push esi mov esi, eax // запихиваем коэфф. во все word'ы MMX-регистра // несколько корявый вариант на "чистом" MMX imul eax, K, $10001 db $0F,$6E,$E8 /// movd mm5, eax db $0F,$6F,$E5 /// movq mm4, mm5 db $0F,$73,$F4,$20 /// psllq mm4, 32 db $0F,$EB,$EC /// por mm5, mm4 // или более изящный на enhanced MMX (P3): // pshufw mm5, [ebp + 8], 0 db $0F,$EF,$FF /// pxor mm7, mm7 // mm7 = 0 db $0F,$74,$F6 /// pcmpeqb mm6, mm6 // mm6 = $FFFFFFFF.FFFFFFFF @inner_loop: db $0F,$6E,$06 /// movd mm0, [esi] db $0F,$6E,$0A /// movd mm1, [edx] db $0F,$60,$C7 /// punpcklbw mm0, mm7 db $0F,$6F,$D5 /// movq mm2, mm5 // copy Alpha db $0F,$E5,$D0 /// pmulhw mm2, mm0 // HiWord(Res) db $0F,$D5,$C5 /// pmullw mm0, mm5 // LoWord(Res) db $0F,$75,$D7 /// pcmpeqw mm2, mm7 // HiWord = 0? db $0F,$DB,$C2 /// pand mm0, mm2 // да - используем LoWord db $0F,$EF,$D6 /// pxor mm2, mm6 // иначе инверсию маски db $0F,$EB,$C2 /// por mm0, mm2 // (= $FFFFFFFF.FFFFFFFF) db $0F,$71,$D0,$08 /// psrlw mm0, 8 // сокращаем до байтов db $0F,$67,$C7 /// packuswb mm0, mm7 // пакуем db $0F,$DC,$C1 /// paddusb mm0, mm1 // складываем db $0F,$7E,$02 /// movd [edx], mm0 add esi, 4 add edx, 4 dec ecx jnz @inner_loop db $0F,$77 /// emms pop esi end; // from SpriteUtils-2 procedure xLine_Add32_MMX(Src, Dst : Pointer; Count : Integer); asm push ecx shr ecx, 5 jz @tail @inner_loop: db $0F,$6F,$00 /// movq mm0, [eax] db $0F,$6F,$48,$08 /// movq mm1, [eax+8] db $0F,$6F,$50,$10 /// movq mm2, [eax+16] db $0F,$6F,$58,$18 /// movq mm3, [eax+24] db $0F,$6F,$22 /// movq mm4, [edx] db $0F,$6F,$6A,$08 /// movq mm5, [edx+8] db $0F,$6F,$72,$10 /// movq mm6, [edx+16] db $0F,$6F,$7A,$18 /// movq mm7, [edx+24] db $0F,$DC,$E0 /// paddusb mm4, mm0 db $0F,$DC,$E9 /// paddusb mm5, mm1 db $0F,$DC,$F2 /// paddusb mm6, mm2 db $0F,$DC,$FB /// paddusb mm7, mm3 db $0F,$7F,$22 /// movq [edx], mm4 db $0F,$7F,$6A,$08 /// movq [edx+8], mm5 db $0F,$7F,$72,$10 /// movq [edx+16], mm6 db $0F,$7F,$7A,$18 /// movq [edx+24], mm7 add eax, 32 add edx, 32 dec ecx jnz @inner_loop // db $0F,$77 /// emms @tail: pop ecx and ecx, 31 jz @exit push esi push ebx mov esi, eax @bytes: mov al, [esi] add [edx], al setnc bl dec bl or [edx], bl inc esi inc edx dec ecx jnz @bytes pop ebx pop esi @exit: end; {$ENDIF} procedure xLine_Add8_32(Src : PByte; Dst : PFColorA; SrcPal : PFColorTable; Count, dStep : Integer); Var x, i : Integer; sc : PFColorA; begin For x:=0 to Count-1 do begin sc := @SrcPal[Src^]; i := sc.b + Dst.b; If i > 255 then Dst.b := 255 else Dst.b := i; i := sc.g + Dst.g; If i > 255 then Dst.g := 255 else Dst.g := i; i := sc.r + Dst.r; If i > 255 then Dst.r := 255 else Dst.r := i; Inc(Src); Inc(PByte(Dst), dStep); end; end; procedure xLine_AddK32(sc, dc : PFColorA; Count, K, sStep, dStep : Integer); Var x, i : Integer; begin For x:=0 to Count-1 do begin i := sc.b * K shr 8 + dc.b; If i > 255 then dc.b := 255 else dc.b := i; i := sc.g * K shr 8 + dc.g; If i > 255 then dc.g := 255 else dc.g := i; i := sc.r * K shr 8 + dc.r; If i > 255 then dc.r := 255 else dc.r := i; Inc(PByte(sc), sStep); Inc(PByte(dc), dStep); end; end; procedure xLine_Add24_32(sc, dc : PFColorA; Count, sStep, dStep : Integer); Var x, i : Integer; begin For x:=0 to Count-1 do begin i := sc.b + dc.b; If i > 255 then dc.b := 255 else dc.b := i; i := sc.g + dc.g; If i > 255 then dc.g := 255 else dc.g := i; i := sc.r + dc.r; If i > 255 then dc.r := 255 else dc.r := i; Inc(PByte(sc), sStep); Inc(PByte(dc), dStep); end; end; // Additive blending with optional mult. by K // Dst = Src * K + Dst [K <> 256] // Dst = Src + Dst [K = 256] // (8 || 24 || 32) -> (24 || 32) // also 8 -> 8 without scaling function DrawAdd(Src, Dst : TFastDIB; K : Integer = 256; dx : Integer = 0; dy : Integer = 0): Boolean; var x, y, w, w2, gap: Integer; sc, dc: PFColorA; UseMMX : Boolean; begin Result := ( Src.Bpp in [8, 24, 32] ) and ( (Dst.Bpp >= 24) or (Dst.Bpp = Src.Bpp) ); If (not Result) then Exit; UseMMX := False; {.$IFDEF CPUX86} UseMMX := (cfMMX in CPUInfo.Features); If (UseMMX) and (Dst.Bpp = Src.Bpp) and (K = 256) then for y:=0 to Src.AbsHeight-1 do begin dc := Dst.Scanlines[y + dy]; Inc(PByte(dc), dx * Dst.BytesPP); xAddMem8MMX(PLine8(dc), Src.Scanlines[y], PLine8(dc), Src.Width * Src.BytesPP); // xLine_Add32_MMX(Src.Scanlines[y], dc, Src.Width * Src.BytesPP) end else {.$ENDIF} begin If (Src.BytesPP = 1) then begin w2 := Src.Width shr 1; gap := Src.Width - w2 * 2; end; for y:=0 to Src.AbsHeight-1 do begin sc := Src.Scanlines[y]; dc := Dst.Scanlines[y + dy]; Inc(PByte(dc), dx * Dst.BytesPP); // 8 -> 24, 32 If (Src.BytesPP = 1) then begin {$IFDEF CPUX86} If (UseMMX) and (Dst.BytesPP = 4) then begin xLine_Add8_32_MMX(sc, dc, w2, Src.Colors); Inc(PByte(sc), w2*2); Inc(PByte(dc), w2*2*Dst.BytesPP); w := gap; end else {$ENDIF} w := Src.Width; If (w <> 0) then xLine_Add8_32(PByte(sc), dc, Src.Colors, w, Dst.BytesPP); end else // 24,32 -> 24,32 If (K <> 256) then {$IFDEF CPUX86} If (UseMMX) and (Src.BytesPP = 4) and (Dst.BytesPP = 4) then xLine_AddK32_MMX(sc, dc, Src.Width, K) else {$ENDIF} xLine_AddK32(sc, dc, Src.Width, K, Src.BytesPP, Dst.BytesPP) else xLine_Add24_32(sc, dc, Src.Width, Src.BytesPP, Dst.BytesPP); end; end; If UseMMX then EMMS; end; // code mainly from SpriteUtils-2 procedure xLine_Trans8_MMX(Src, Dst : PByte; Count : Integer; TransColor : PByte); // EAX = Src, EDX = Dst, ECX = Count asm {$IFDEF CPUX86} push eax mov eax, TransColor db $0F,$6F,$10 /// movq mm2, [eax] pop eax db $0F,$74,$E4 /// pcmpeqb mm4, mm4 @quads: db $0F,$6F,$18 /// movq mm3, [eax] db $0F,$6F,$00 /// movq mm0, [eax] db $0F,$74,$DA /// pcmpeqb mm3, mm2 db $0F,$EF,$DC /// pxor mm3, mm4 db $0F,$DB,$C3 /// pand mm0, mm3 db $0F,$DF,$1A /// pandn mm3, [edx] db $0F,$EB,$C3 /// por mm0, mm3 db $0F,$7F,$02 /// movq [edx], mm0 add eax, 8 add edx, 8 dec ecx jnz @quads {$ENDIF} end; procedure xLine_Trans8(Src, Dst : PByte; Count : Integer; Trans : Byte); var x: Integer; begin for x := 0 to Count - 1 do begin If (Src^ <> Trans) then Dst^ := Src^; Inc(Src); Inc(Dst); end; end; procedure xLine_Trans16(Src, Dst : PWord; Count : Integer; Trans : Word); var x: Integer; begin for x := 0 to Count - 1 do begin If (Src^ <> Trans) then Dst^ := Src^; Inc(Src); Inc(Dst); end; end; procedure xLine_Trans24(Src, Dst : PFColor; Count : Integer; Trans : TFColorA); var x : Integer; t24 : DWord; begin t24 := DWord(Trans) and $FFFFFF00; for x := 0 to Count - 2 do begin If (PDWord(Src)^ and $FFFFFF00) <> t24 then Dst^ := Src^; Inc(Src); Inc(Dst); end; If (Src.r <> Trans.r) or (Src.g <> Trans.g) or (Src.b <> Trans.b) then Dst^ := Src^; end; {$IFDEF CPUX86} procedure xLine_Trans32(Src, Dst : PDWord; Count : Integer; Trans : DWord); asm push esi push edi mov esi, eax mov edi, edx mov edx, Trans @inner_loop: mov eax, [esi] cmp eax, edx jz @skip mov [edi], eax @skip: add esi, 4 add edi, 4 dec ecx jnz @inner_loop pop edi pop esi end; {$ELSE} procedure xLine_Trans32(Src, Dst : PDWord; Count : Integer; Trans : DWord); var x: Integer; begin for x := 0 to Count - 1 do begin If (Src^ <> Trans) then Dst^ := Src^; Inc(Src); Inc(Dst); end; end; {$ENDIF} // Drawing Src to Dst with transparent color // TransColor for 8 bpp - palette index, // for other modes - $BBGGRRAA (TFColorA) // GDI TransparentBlt (TransBlit) function can also be used for this procedure DrawTrans(Src, Dst : TFastDIB; dx : Integer = 0; dy : Integer = 0; TransColor : DWord = 0); Var TransArr : array[ 0..7 ] of Byte; y, w, gap, c16 : Integer; dp : PByte; begin // Note: seems surprising a bit, but calling procedure // for each scanline is FASTER than writing double loop here... // due to better variable-to-register fitting, I suppose. Case Src.Bpp of 8 : begin w := 0; gap := Src.Width; // MMX is nearly 2 times faster here, more with x alignment If (cfMMX in CPUInfo.Features) then begin For y := 0 to 7 do TransArr[y] := TransColor; w := Src.Width shr 3; gap := Src.Width mod 8; end; For y := 0 to Src.AbsHeight-1 do begin dp := @Dst.Pixels8[y + dy, dx]; If (w <> 0) then xLine_Trans8_MMX(Src.Scanlines[y], dp, w, @TransArr ); If (gap <> 0) then begin Inc(dp, w*8); xLine_Trans8(@Src.Pixels16[y, w*8], dp, gap, TransColor); end; end; If (w <> 0) then EMMS; end; 16 : begin // can also be done with MMX, but it has very few effect here c16 := (TransColor shr Src.RShr) or (TransColor shr (8 + Src.GShr)) or (TransColor shr (16 + Src.BShr)); For y := 0 to Src.AbsHeight-1 do // 8 ms xLine_Trans16(Src.Scanlines[y], @Dst.Pixels16[y + dy, dx], Src.Width, c16); end; 24 : For y := 0 to Src.AbsHeight-1 do // 15 ms xLine_Trans24(Src.Scanlines[y], @Dst.Pixels24[y + dy, dx], Src.Width, TFColorA(TransColor)); 32 : For y := 0 to Src.AbsHeight-1 do // 19/12 ms xLine_Trans32(Src.Scanlines[y], @Dst.Pixels32[y + dy, dx], Src.Width, TransColor); end; end; end.
unit AbstractDataSetFactory; interface uses AbstractDataSetHolder, SysUtils, Classes; type TAbstractDataSetHolderFactory = class abstract public function CreateDataSetHolder( DataSetFieldDefs: TAbstractDataSetFieldDefs ): TAbstractDataSetHolder; virtual; abstract; end; implementation end.
unit aPushMethods; interface uses System.SysUtils, System.Classes, System.Json, Datasnap.DSServer, Datasnap.DSAuth, System.IniFiles, lPushData; type {$METHODINFO ON} TPushMethods = class(TDataModule) procedure DataModuleCreate(Sender: TObject); private FGooglePushServerKey: string; FDatabase: string; FDBUser: string; FDBPassword: string; public { Public declarations } //Consulta function Device(const DeviceId: string): TJSONObject; function Devices(PageNumber: integer; ItemsPerPage: integer): TJSONObject; function UserDevices(const UserId: string): TJSONObject; //Registro function UpdateDevice(const DeviceInfo: TPushDevice): TJSONObject; function UpdatePushOption(const DeviceId: string; PushOption: boolean): TJSONObject; //Envio function SendMessageToUser(const UserId, Title, Msg: string): TJSONObject; function SendMessageToAll(const Title, Msg: string): TJSONObject; end; {$METHODINFO OFF} implementation {%CLASSGROUP 'System.Classes.TPersistent'} {$R *.dfm} uses aDBPush; { TPushMethods } function GetAppFileName: string; begin result:= GetModuleName(HInstance); result:= result.Substring(result.IndexOf(':') - 1); end; function GetIniFileName: string; begin result:= ChangeFileExt(GetAppFileName, '.ini'); end; procedure TPushMethods.DataModuleCreate(Sender: TObject); begin with TIniFile.Create(GetIniFileName) do try FDatabase:= ReadString('DB', 'Database', ''); FDBUser:= ReadString('DB', 'DBUser', ''); FDBPassword:= ReadString('DB', 'DBPassword', ''); FGooglePushServerKey:= ReadString('PUSH', 'Google', ''); finally Free; end; end; function TPushMethods.Device(const DeviceId: string): TJSONObject; var Obj: TJSONObject; begin Obj:= TJSONObject.Create; try With TdmPush.Create(Self, FGooglePushServerKey, FDatabase, FDBUser, FDBPassword) do try Obj.AddPair('success', DoGetDevice(DeviceID)); finally Free; end; except on E: Exception do Obj.AddPair('error', E.Message); end; result:= Obj; end; function TPushMethods.Devices(PageNumber: integer; ItemsPerPage: integer): TJSONObject; var ja: TJSONArray; begin result:= TJSONObject.Create; try With TdmPush.Create(Self, FGooglePushServerKey, FDatabase, FDBUser, FDBPassword) do try ja:= DoGetDevices(PageNumber, ItemsPerPage); result.AddPair(TJSONPair.Create('success', ja)); finally Free; end; except on E: Exception do result.AddPair('error', E.Message); end; end; function TPushMethods.UserDevices(const UserId: string): TJSONObject; var ja: TJSONArray; begin result:= TJSONObject.Create; try With TdmPush.Create(Self, FGooglePushServerKey, FDatabase, FDBUser, FDBPassword) do try ja:= DoGetUserDevices(UserId); result.AddPair(TJSONPair.Create('success', ja)); finally Free; end; except on E: Exception do result.AddPair('error', E.Message); end; end; function TPushMethods.UpdateDevice(const DeviceInfo: TPushDevice): TJSONObject; begin result:= TJSONObject.Create; try with TdmPush.Create(Self, FGooglePushServerKey, FDatabase, FDBUser, FDBPassword) do try result.AddPair('success', DoUpdateDevice(DeviceInfo).ToString); finally Free; end; except on E: Exception do result.AddPair('error', E.Message); end; end; function TPushMethods.UpdatePushOption(const DeviceId: string; PushOption: boolean): TJSONObject; begin result:= TJSONObject.Create; try with TdmPush.Create(Self, FGooglePushServerKey, FDatabase, FDBUser, FDBPassword) do try result.AddPair('success', DoUpdatePushOption(DeviceId, PushOption).ToString); finally Free; end; except on E: Exception do result.AddPair('error', E.Message); end; end; function TPushMethods.SendMessageToUser(const UserId, Title, Msg: string): TJSONObject; begin result:= TJSONObject.Create; try with TdmPush.Create(Self, FGooglePushServerKey, FDatabase, FDBUser, FDBPassword) do try result.AddPair('success', DoSendMessageToUser(UserId, Title, Msg)); finally Free; end; except on E: Exception do result.AddPair('error', E.Message); end; end; function TPushMethods.SendMessageToAll(const Title, Msg: string): TJSONObject; begin result:= TJSONObject.Create; try with TdmPush.Create(Self, FGooglePushServerKey, FDatabase, FDBUser, FDBPassword) do try result.AddPair('success', DoSendMessageToAll(Title, Msg)); finally Free; end; except on E: Exception do result.AddPair('error', E.Message); end; end; end.
unit dmConsulta; interface uses SysUtils, Classes, DB, kbmMemTable, IBCustomDataSet, IBQuery, ScriptEditorCodigoDatos, Tipos, UtilThread, Messages, Windows, dmTareas, IBSQL; const WM_NEW_ROW = WM_USER + 12; WM_FINISH_SEARCH = WM_USER + 13; type TConsulta = class; TColumnScript = class(TScriptEditorCodigoDatos) private ColumnCompiledCode: string; end; TConsultaThread = class(TTarea) private MustRecalcular: boolean; idSearch, idSearchRecalcular: integer; Data: TConsulta; OIDSesion: integer; Valores: TArrayInteger; NuevosValores: PArrayInteger; Fields: array of TField; NumFields: Integer; MostrarSimbolo, MostrarNombre: boolean; ColumnsScript: array of TColumnScript; ScriptSearch: TScriptEditorCodigoDatos; procedure AnadirValor(OIDValor: integer); protected constructor Create(const Data: TConsulta; const OIDSesion: integer; const Valores: PArrayInteger; const idSearch: integer); reintroduce; procedure InternalExecute; override; procedure InitializeResources; override; procedure FreeResources; override; procedure InternalCancel; override; public procedure Recalcular(const nuevosValores: PArrayInteger; const nuevoIdSearch: integer); procedure CrearGrupo(const nombre: string); end; TOnNewRow = procedure(NumRows: integer) of object; TConsulta = class(TDataModule) qColumnas: TIBQuery; qColumnasOR_CONSULTA: TIntegerField; qColumnasPOSICION: TSmallintField; qColumnasNOMBRE: TIBStringField; qColumnasTIPO: TSmallintField; qColumnasCODIGO: TMemoField; Consulta: TkbmMemTable; qCaracteristica: TIBQuery; qCaracteristicaCODIGO: TMemoField; qColumnasANCHO: TSmallintField; qConsulta: TIBQuery; qConsultaOR_FS: TIntegerField; qConsultaTIPO: TIBStringField; qConsultaOR_CARACTERISTICA: TIntegerField; qConsultaCODIGO: TMemoField; ConsultaOID_VALOR: TIntegerField; qConsultaCOLUMNA_SIMBOLO: TIBStringField; qConsultaCOLUMNA_NOMBRE: TIBStringField; ConsultaSIMBOLO: TStringField; ConsultaNOMBRE: TStringField; qConsultaCODIGO_COMPILED: TMemoField; qColumnasCODIGO_COMPILED: TMemoField; qConsultaCONTAR_VALORES: TIBStringField; qConsultaNOMBRE: TIBStringField; qValoresSesion: TIBSQL; procedure ConsultaAfterInsert(DataSet: TDataSet); private rows: integer; ConsultaThread: TConsultaThread; MostrarSimbolo, MostrarNombre: boolean; FValores: TArrayInteger; FHandleNotification: HWND; OIDSesion: integer; ValoresSesion: TArrayInteger; CompiledCode: string; ThreadTerminated: boolean; procedure OnTerminateThread(Sender: TObject); procedure CreateColumns(const OIDConsulta: integer); // procedure ExecuteCaracteristica(const OIDConsulta: integer); procedure ExecuteCodigo(const idSearch: integer); function NormalizeName(const nombre: string): string; function CreateField(const tipo: integer): TField; function GetCount: integer; procedure OnFinish(const idSearch: integer); function GetValores: PArrayInteger; procedure SetValores(const Value: PArrayInteger); public destructor Destroy; override; procedure Load(const OIDConsulta: integer); procedure Reset; procedure Search(const idSearch: integer); function HayColumnas: boolean; procedure Cancel; property Count: integer read GetCount; property Valores: PArrayInteger read GetValores write SetValores; property HandleNotification: HWND read FHandleNotification write FHandleNotification; end; implementation uses dmBD, BDConstants, UtilDB, dmData, fmConsultas, BusCommunication, dmDataComun, ScriptEngine, dmConsultaGrupo, Forms; {$R *.dfm} resourcestring CONSULTA_TITLE = 'Listado'; { TConsulta } procedure TConsulta.ConsultaAfterInsert(DataSet: TDataSet); begin PostMessage(HandleNotification, WM_NEW_ROW, rows, 0); inc(rows); end; procedure TConsulta.CreateColumns(const OIDConsulta: integer); procedure CreateColumn; var field: TField; nombre: string; begin field := CreateField(qColumnasTIPO.Value); nombre := qColumnasNOMBRE.Value; field.FieldName := NormalizeName(nombre); field.DataSet := Consulta; field.DisplayLabel := nombre; field.DisplayWidth := qColumnasANCHO.Value; field.Tag := qColumnas.RecNo; end; begin qColumnas.Close; qColumnas.Params[0].AsInteger := OIDConsulta; OpenDataSetRecordCount(qColumnas); while not qColumnas.Eof do begin CreateColumn; qColumnas.Next; end; Consulta.Active := HayColumnas; end; function TConsulta.CreateField(const tipo: integer): TField; begin case TResultType(tipo) of rtBoolean: result := TBooleanField.Create(Self); rtString: begin result := TStringField.Create(Self); result.Size := 255; end; rtInteger: result := TIntegerField.Create(Self); rtCurrency: result := TCurrencyField.Create(Self); else raise Exception.Create('Tipo de field incorrecto'); end; end; destructor TConsulta.Destroy; begin Cancel; inherited; end; {procedure TConsulta.ExecuteCaracteristica(const OIDConsulta: integer); var script: TScriptCaracteristicas; begin qCaracteristica.Close; qCaracteristica.Params[0].AsInteger := OIDConsulta; qCaracteristica.Open; script := TScriptCaracteristicas.Create(nil); try script.ResultType := rtBoolean; script.Code.Text := qCaracteristicaCODIGO.Value; if script.Compile then script.Execute; finally script.Free; end; end;} procedure TConsulta.ExecuteCodigo(const idSearch: integer); var reloaded: boolean; procedure ReloadValoresSesion; var i, j, num: integer; field: TIBXSQLVAR; OIDValor: integer; begin qValoresSesion.Close; qValoresSesion.Params[0].AsInteger := OIDSesion; qValoresSesion.ExecQuery; num := Length(FValores); SetLength(ValoresSesion, num); i := 0; dec(num); field := qValoresSesion.Fields[0]; while not qValoresSesion.Eof do begin OIDValor := field.Value; for j := 0 to num do begin if OIDValor = FValores[j] then begin ValoresSesion[i] := OIDValor; Inc(i); break; end; end; qValoresSesion.Next; end; SetLength(ValoresSesion, i); qValoresSesion.Close; end; begin if compiledCode <> '' then begin if OIDSesion <> Data.OIDSesion then begin OIDSesion := Data.OIDSesion; ReloadValoresSesion; reloaded := true; end else reloaded := false; if ConsultaThread <> nil then begin ConsultaThread.OIDSesion := OIDSesion; if reloaded then ConsultaThread.Recalcular(@ValoresSesion, idSearch) else ConsultaThread.Recalcular(nil, idSearch); end else begin ThreadTerminated := false; ConsultaThread := TConsultaThread.Create(Self, OIDSesion, @ValoresSesion, idSearch); ConsultaThread.OnTerminate := OnTerminateThread; ConsultaThread.Resume; // Tareas.EjecutarTarea(ConsultaThread, CONSULTA_TITLE, qConsultaNOMBRE.Value); end; end; end; function TConsulta.GetCount: integer; begin result := Consulta.RecordCount; end; function TConsulta.GetValores: PArrayInteger; begin Result := @FValores; end; function TConsulta.HayColumnas: boolean; begin // Siempre hay 3, que es el OID_VALOR, NOMBRE y SIMBOLO result := (Consulta.FieldCount > 3) or (ConsultaSIMBOLO.Visible) or (ConsultaNOMBRE.Visible); end; procedure TConsulta.Load(const OIDConsulta: integer); begin qConsulta.Close; qConsulta.Params[0].AsInteger := OIDConsulta; OpenDataSet(qConsulta); CompiledCode := qConsultaCODIGO_COMPILED.Value; MostrarSimbolo := qConsultaCOLUMNA_SIMBOLO.Value = 'S'; MostrarNombre := qConsultaCOLUMNA_NOMBRE.Value = 'S'; qConsulta.Close; ConsultaSIMBOLO.Visible := MostrarSimbolo; ConsultaNOMBRE.Visible := MostrarNombre; CreateColumns(OIDConsulta); end; function TConsulta.NormalizeName(const nombre: string): string; var i: integer; begin result := '_'; for i := 1 to length(nombre) do if nombre[i] in ['a'..'z', 'A'..'Z', '0'..'9'] then result := result + nombre[i]; i := 0; while i < Consulta.FieldCount do begin if Consulta.Fields[i].FieldName = result then begin result := result + '_'; i := 0; end else inc(i); end; end; procedure TConsulta.OnFinish(const idSearch: integer); begin Consulta.First; PostMessage(HandleNotification, WM_FINISH_SEARCH, idSearch , 0); end; procedure TConsulta.OnTerminateThread(Sender: TObject); begin ThreadTerminated := true; end; procedure TConsulta.Reset; begin OIDSesion := -1; Cancel; end; procedure TConsulta.Search(const idSearch: integer); begin { if qConsultaTIPO.Value = CONSULTA_TIPO_CARACTERISTICA then ExecuteCaracteristica(OIDConsulta) else} if HayColumnas then begin rows := 0; ExecuteCodigo(idSearch); end; end; procedure TConsulta.SetValores(const Value: PArrayInteger); begin FValores := Copy(Value^, 0, Length(Value^)); end; procedure TConsulta.Cancel; begin if ConsultaThread <> nil then begin ConsultaThread.Cancel; while not ThreadTerminated do Application.ProcessMessages; ConsultaThread := nil; end; end; { TConsultaThread } procedure TConsultaThread.AnadirValor(OIDValor: integer); var i: integer; Script: TColumnScript; dataValor: PDataComunValor; executed: boolean; begin Data.Consulta.Append; Fields[0].AsInteger := OIDValor; if MostrarSimbolo or MostrarNombre then begin dataValor := DataComun.FindValor(OIDValor); if MostrarSimbolo then Fields[1].AsString := dataValor^.Simbolo; if Data.MostrarNombre then Fields[2].AsString := dataValor^.Nombre; end; for i := 3 to NumFields do begin Script := ColumnsScript[i]; Script.OIDValor := OIDValor; if Script.IsLoadedCompiledCode then begin try executed := Script.Execute; if executed then begin case Script.ResultType of rtBoolean: Fields[i].AsBoolean := Script.ValueBoolean; rtCurrency: Fields[i].AsCurrency := Script.ValueCurrency; rtInteger: Fields[i].AsInteger := Script.ValueInteger; rtString: Fields[i].AsString := Script.ValueString; end; end else begin Fields[i].Clear; Script.CompiledCode := Script.ColumnCompiledCode; end; except on EStopScript do begin if Script.EDatoNotFound then begin Fields[i].Clear; Script.CompiledCode := Script.ColumnCompiledCode; end else raise; end; end; end; end; Data.Consulta.Post; end; procedure TConsultaThread.CrearGrupo(const nombre: string); var ConsultaGrupo: TConsultaGrupo; begin end; constructor TConsultaThread.Create(const Data: TConsulta; const OIDSesion: integer; const Valores: PArrayInteger; const idSearch: integer); begin inherited Create; Self.Valores := Copy(Valores^, 0, Length(Valores^)); Self.OIDSesion := OIDSesion; Self.Data := Data; Self.idSearch := idSearch; FreeOnTerminate := true; end; procedure TConsultaThread.FreeResources; var i: Integer; begin for i := 3 to NumFields do ColumnsScript[i].Free; if ScriptSearch <> nil then ScriptSearch.Free; inherited; end; procedure TConsultaThread.InitializeResources; var i: integer; codigoCompiled: string; Script: TColumnScript; begin MostrarSimbolo := Data.MostrarSimbolo; MostrarNombre := Data.MostrarNombre; numFields := Data.Consulta.Fields.Count; SetLength(Fields, NumFields); Dec(NumFields); //zero based for i := 0 to NumFields do Fields[i] := Data.Consulta.Fields[i]; // + 3 del OID_VALOR, SIMBOLO y NOMBRE SetLength(ColumnsScript, Data.qColumnas.RecordCount + 3); for i := 3 to NumFields do begin Data.qColumnas.RecNo := Fields[i].Tag; Script := TColumnScript.Create(true); Script.ResultType := TResultType(Data.qColumnasTIPO.Value); Script.OutVariableName := OUT_VARIABLE_NAME_LISTADO; codigoCompiled := Data.qColumnasCODIGO_COMPILED.Value; if codigoCompiled <> '' then begin Script.CompiledCode := codigoCompiled; Script.ColumnCompiledCode := codigoCompiled; end; Script.OIDSesion := OIDSesion; ColumnsScript[i] := Script; end; ScriptSearch := TScriptEditorCodigoDatos.Create(true); end; procedure TConsultaThread.InternalExecute; var i, num: Integer; OIDValor: integer; procedure MustRecalcularInit; begin if NuevosValores <> nil then begin Valores := Copy(NuevosValores^, 0, Length(NuevosValores^)); NuevosValores := nil; end; idSearch := idSearchRecalcular; end; begin ScriptSearch.ResultType := rtBoolean; ScriptSearch.OutVariableName := OUT_VARIABLE_NAME_BUSQUEDA; ScriptSearch.CompiledCode := Data.CompiledCode; MustRecalcular := true; while MustRecalcular do begin if Terminated then raise ETerminateThread.Create; num := length(Valores) - 1; MustRecalcular := False; ScriptSearch.OIDSesion := OIDSesion; for i := 3 to NumFields do ColumnsScript[i].OIDSesion := OIDSesion; Data.Consulta.EmptyTable; if Terminated then raise ETerminateThread.Create; for i := 0 to num do begin OIDValor := Valores[i]; ScriptSearch.OIDValor := OIDValor; try if (ScriptSearch.Execute) and (ScriptSearch.ValueBoolean) then AnadirValor(OIDValor); except on EStopScript do; end; if MustRecalcular then break; if Terminated then raise ETerminateThread.Create; end; if MustRecalcular then begin MustRecalcularInit; end else begin Data.OnFinish(idSearch); Suspend; if MustRecalcular then MustRecalcularInit; end; end; end; procedure TConsultaThread.InternalCancel; begin inherited; MustRecalcular := false; ScriptSearch.Stop; end; procedure TConsultaThread.Recalcular(const nuevosValores: PArrayInteger; const nuevoIdSearch: integer); begin if Suspended then begin if nuevosValores <> nil then Valores := Copy(nuevosValores^, 0, Length(nuevosValores^)); Self.NuevosValores := nil; end else begin Suspend; Self.NuevosValores := nuevosValores; ScriptSearch.Stop; end; idSearchRecalcular := nuevoIdSearch; MustRecalcular := true; Resume; end; end.
unit RTObjInspector; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ZPropLst, ObjStructViews, ExtCtrls; type TObjectInspector = class(TFrame) Splitter1: TSplitter; StructView: TObjStructViews; Properties: TZPropList; procedure StructViewSelectedChanged(Sender: TObject); private FOnSelectedChanged: TNotifyEvent; { Private declarations } function GetRoot: TObject; function GetSelected: TObject; procedure SetRoot(const Value: TObject); procedure SetSelected(const Value: TObject); protected procedure SelectedChanged; virtual; public { Public declarations } procedure AddObject(Obj : TObject); property Root : TObject read GetRoot write SetRoot; property Selected : TObject read GetSelected write SetSelected; published property OnSelectedChanged : TNotifyEvent read FOnSelectedChanged write FOnSelectedChanged; end; implementation uses ZPEdits, PicEdit, DsgnIntf; {$R *.DFM} { TObjectInspector } procedure TObjectInspector.AddObject(Obj: TObject); begin StructView.AddObject(Obj); end; function TObjectInspector.GetRoot: TObject; begin Result := StructView.Root; end; function TObjectInspector.GetSelected: TObject; begin Result := Properties.CurObj; end; procedure TObjectInspector.SelectedChanged; begin if Assigned(FOnSelectedChanged) then FOnSelectedChanged(Self); end; procedure TObjectInspector.SetRoot(const Value: TObject); begin StructView.Root := Value; if Value is TComponent then Properties.Root := TComponent(Value) else Properties.Root := nil; end; procedure TObjectInspector.SetSelected(const Value: TObject); begin if Selected<>Value then begin Properties.CurObj := Value; StructView.Selected := Value; SelectedChanged; end; end; procedure TObjectInspector.StructViewSelectedChanged(Sender: TObject); begin Selected := StructView.Selected; end; initialization RegisterPropertyEditor(TypeInfo(TPicture),nil,'',TPictureProperty); end.
unit AT.ShortName.FMX.Forms.Main; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.TMSFNCRibbon, FMX.TMSFNCTypes, FMX.TMSFNCUtils, FMX.TMSFNCGraphics, FMX.TMSFNCGraphicsTypes, FMX.Controls.Presentation, FMX.StdCtrls, FMX.TMSCustomControl, FMX.TMSTabSet, FMX.TMSPageControl, FMX.TMSFNCPageControl, FMX.TMSFNCTabSet, FMX.TMSFNCHTMLText, FMX.TMSFNCToolBar, FMX.TMSFNCCustomControl, FMX.TMSFNCCustomComponent, FMX.TMSFNCBitmapContainer, FMX.Objects, Radiant.Shapes, AT.FMX.ClockLabel; type TfrmMain = class(TTMSFNCRibbonForm) ribMain: TTMSFNCRibbon; barQAT: TTMSFNCRibbonQAT; ribcapNain: TTMSFNCRibbonCaption; TMSFNCRibbon1BottomContainer: TTMSFNCRibbonBottomContainer; rsmicoSysMenu: TTMSFNCRibbonIcon; rsmButtons: TTMSFNCRibbonSystemMenu; rsmbtnHelp: TTMSFNCRibbonSystemMenuToolBarButton; rsmbtnMaxRestore: TTMSFNCRibbonSystemMenuToolBarButton; rsmbtnMinimize: TTMSFNCRibbonSystemMenuToolBarButton; rsmbtnClose: TTMSFNCRibbonSystemMenuToolBarButton; TMSFNCRibbon1Wrapper: TTMSFNCRibbonToolBarWrapper; ribpcMain: TTMSFNCRibbonPageControl; TMSFNCRibbon1PageControlFileButton: TTMSFNCRibbonFileButton; rctrTAT: TTMSFNCRibbonContainer; TMSFNCRibbon1PageControlPage0: TTMSFNCRibbonPageControlContainer; pcMain: TTMSFMXPageControl; barFile: TTMSFNCRibbonToolBar; cmdQATEditUndo: TTMSFNCRibbonDefaultToolBarButton; barClipboard: TTMSFNCRibbonToolBar; barEditing: TTMSFNCRibbonToolBar; bmpcRibbon: TTMSFNCBitmapContainer; cmdClipPaste: TTMSFNCRibbonDefaultToolBarButton; cmdClipCut: TTMSFNCRibbonDefaultToolBarButton; cmdClipCopy: TTMSFNCRibbonDefaultToolBarButton; cmdFileNewBlank: TTMSFNCRibbonDefaultToolBarButton; cmdFileOpen: TTMSFNCRibbonDefaultToolBarButton; cmdFileSaveDD: TTMSFNCRibbonDefaultToolBarButton; cmdQATEditRedo: TTMSFNCRibbonDefaultToolBarButton; sepQAT1: TTMSFNCRibbonToolBarSeparator; cmdQATNewBlank: TTMSFNCRibbonDefaultToolBarButton; cmdQATFileOpen: TTMSFNCRibbonDefaultToolBarButton; cmdQATFileSaveDD: TTMSFNCRibbonDefaultToolBarButton; rdntrctngl1: TRadiantRectangle; szgrp1: TSizeGrip; cmdEditUndo: TTMSFNCRibbonDefaultToolBarButton; cmdEditRedo: TTMSFNCRibbonDefaultToolBarButton; sepEdit1: TTMSFNCRibbonToolBarSeparator; cmdSearchFind: TTMSFNCRibbonDefaultToolBarButton; cmdSearchReplace: TTMSFNCRibbonDefaultToolBarButton; cmdSelectDD: TTMSFNCRibbonDefaultToolBarButton; cmdTATSearchFind: TTMSFNCRibbonDefaultToolBarButton; cmdTATSearchReplace: TTMSFNCRibbonDefaultToolBarButton; sep1: TTMSFNCRibbonToolBarSeparator; cmdTATHelpContents: TTMSFNCRibbonDefaultToolBarButton; barSaveDD: TTMSFNCRibbonToolBar; cmdFileSave: TTMSFNCRibbonDefaultToolBarButton; cmdFileSaveAs: TTMSFNCRibbonDefaultToolBarButton; cmdFileSaveAll: TTMSFNCRibbonDefaultToolBarButton; private { Private declarations } public { Public declarations } end; var frmMain: TfrmMain; implementation {$R *.fmx} uses AT.ShortName.DM.Images; end.
unit uRegras; interface uses System.SysUtils, System.Classes,unBase, FireDAC.Comp.Client; type TProdutoRec = Record Codigo :Integer; Descricao:string; Valor :Double; end; type TPedido =class numeropedido :Integer; dataemissao :TDateTime; codigocliente:Integer; valortotal :Double; end; type TPedidoProduto =class numeropedido :Integer; codigproduto :Integer; quantidade :Integer; vlrunitario :Double; vlrtotal :Double; end; function GetProduto(pCodigo: string): TProdutoRec; function GetCliente(pCodigo: string): string; procedure GravarPedido(pPedido:TPedido; PedidoProdutos:TFDMemTable); function GravarItensPedido(pNumeroPedido:string; pPedidoItens:TFDMemTable):Boolean; function GetGenerator(pTabela: string): Integer; function CancelarPedido(pNumPedido: string): Boolean; function ExistePedido(pNumeroPedido:string):Boolean; procedure CarregarPedidos(pNumeroPedido:string; oPedido:TPedido); function CarregarPedidoProdutos(pNumeroPedido:string; FDMemItens:TFDMemTable):Boolean; implementation function GetCliente(pCodigo: string): string; var QryAux:TFDQuery; cSql:string; begin cSql:='Select NOME From CLIENTES Where CODIGO='+pCodigo.Trim; QryAux:=TFDQuery.Create(nil); QryAux.Connection:=dmBase.FDConexao; QryAux.Close; QryAux.SQL.Clear; QryAux.SQL.Add(cSql); QryAux.Open; try if not QryAux.IsEmpty then Result:=QryAux.FieldByName('NOME').AsString else Result:='-1'; finally QryAux.Close; FreeAndNil(QryAux); end; end; function GetProduto(pCodigo: string): TProdutoRec; var QryAux:TFDQuery; cSql:string; begin cSql:='Select CODIGO,DESCRICAO,PRECOVENDA From PRODUTOS Where CODIGO='+pCodigo.Trim; QryAux:=TFDQuery.Create(nil); QryAux.Connection:=dmBase.FDConexao; QryAux.Close; QryAux.SQL.Clear; QryAux.SQL.Add(cSql); QryAux.Open; try if not QryAux.IsEmpty then begin Result.Codigo :=QryAux.FieldByName('CODIGO').AsInteger; Result.Descricao:=QryAux.FieldByName('DESCRICAO').AsString; Result.Valor :=QryAux.FieldByName('PRECOVENDA').AsFloat; end else begin Result.Codigo :=-1; Result.Descricao:=''; Result.Valor :=0; end; finally QryAux.Close; FreeAndNil(QryAux); end; end; procedure GravarPedido(pPedido:TPedido; PedidoProdutos:TFDMemTable); var FQryPed :TFDQuery; cSql :string; cNew :string; cInsert :string; cUpdate :string; cValues :string; cAux1 :string; cNumeroPedido :string; cDataEmissao :string; cCodigoCliente :string; cValor :string; begin cInsert:='Insert into PEDIDOS (numpedido, dataemissao, codigocliente, valortotal)'; cNumeroPedido :=pPedido.numeropedido.ToString; cDataEmissao :=FormatDateTime('dd.mm.yyyy', pPedido.dataemissao); cCodigoCliente:=pPedido.codigocliente.ToString; cAux1 :=StringReplace(pPedido.valortotal.ToString,'.','',[rfReplaceAll]); cValor:=StringReplace(cAux1,',','.',[rfReplaceAll]); cValues := cNumeroPedido + ',' + '"' + cDataEmissao + '"' + ',' + cCodigoCliente + ',' + cValor; cSql:=cInsert + ' Values (' + cValues + ')'; try if dmBase.FDConexao.Connected then begin FQryPed:=TFDQuery.Create(nil); try FQryPed.Connection:=dmBase.FDConexao; FQryPed.Close; FQryPed.SQL.Clear; FQryPed.SQL.Add(cSql); try dmBase.FDConexao.StartTransaction; FQryPed.ExecSQL; dmBase.FDConexao.CommitRetaining; cNumeroPedido:=pPedido.numeropedido.ToString; GravarItensPedido(cNumeroPedido, PedidoProdutos); except dmBase.FDConexao.RollbackRetaining; end; finally FreeAndNil(FQryPed); end; end; except dmBase.FDConexao.RollbackRetaining; end; end; function GravarItensPedido(pNumeroPedido:string; pPedidoItens:TFDMemTable):Boolean; var FQryItens :TFDQuery; cInsert :string; cUpdate :string; cValues :string; cSql :string; cNumeroPedido :string; cCodigoProduto:string; cQuantidade :string; cValorUnitario:string; cValorTotal :string; sAux :string; begin Result:=FALSE; cInsert:='Insert into pedidos_produtos (numeropedido, codigoproduto, quantidade, valorunitario, valortotal )'; pPedidoItens.First; while not pPedidoItens.Eof do begin cNumeroPedido :=pNumeroPedido; cCodigoProduto:=pPedidoItens.FieldByName('CODIGO').AsString; cQuantidade :=pPedidoItens.FieldByName('QUANTIDADE').AsString; cValorUnitario:=pPedidoItens.FieldByName('VLR_UNITARIO').AsString; sAux:=StringReplace(cValorUnitario,'.','',[rfReplaceAll]); cValorUnitario:=StringReplace(sAux,',','.',[rfReplaceAll]); cValorTotal :=pPedidoItens.FieldByName('VLR_TOTAL').AsString; sAux:=StringReplace(cValorTotal,'.','',[rfReplaceAll]); cValorTotal :=StringReplace(sAux,',','.',[rfReplaceAll]); cValues:=cNumeroPedido + ',' + cCodigoProduto + ',' + cQuantidade + ',' + cValorUnitario + ',' + cValorTotal; cSql :=cInsert + ' Values (' + cValues +')'; FQryItens:=TFDQuery.Create(nil); try FQryItens.Connection:=dmBase.FDConexao; FQryItens.Close; FQryItens.SQL.Clear; FQryItens.SQL.Add(cSql); try dmBase.FDConexao.StartTransaction; FQryItens.ExecSQL; dmBase.FDConexao.CommitRetaining; Result:=TRUE; except dmBase.FDConexao.RollbackRetaining; result:=FALSE; Break; end; finally FreeAndNil(FQryItens); end; pPedidoItens.Next; end; end; function GetGenerator(pTabela: string): Integer; var QryAux :TFDQuery; cSql :string; cUpdate:string; begin Result:=-1; dmBase.FDConexao.StartTransaction; try cUpdate:='UPDATE generator_tabela set id_value = id_value + 1 Where Tabela = '+QuotedStr(pTabela); dmBase.FDConexao.ExecSQL(cUpdate); dmBase.FDConexao.CommitRetaining; except dmBase.FDConexao.RollbackRetaining; end; QryAux:=TFDQuery.Create(nil); try cSql:='Select id_value From generator_tabela where tabela=' + QuotedStr(pTabela); QryAux.Connection:=dmBase.FDConexao; QryAux.Close; QryAux.SQL.Clear; QryAux.SQL.Add(cSql); QryAux.Open; if not QryAux.IsEmpty then Result:=QryAux.FieldByName('id_value').AsInteger; finally FreeAndNil(QryAux); end; end; function CancelarPedido(pNumPedido: string): Boolean; var cSql :string; begin Result:=TRUE; dmBase.FDConexao.StartTransaction; try cSql:='Delete From pedidos_produtos where numeropedido=' + pNumPedido; dmBase.FDConexao.ExecSQL(cSql); dmBase.FDConexao.CommitRetaining; except dmBase.FDConexao.RollbackRetaining; Result:=FALSE; Exit; end; try cSql:='Delete From PEDIDOS where numpedido=' + pNumPedido; dmBase.FDConexao.ExecSQL(cSql); dmBase.FDConexao.CommitRetaining; except dmBase.FDConexao.RollbackRetaining; Result:=FALSE; Exit; end; end; function ExistePedido(pNumeroPedido:string):Boolean; var QryPed:TFDQuery; cSql :string; begin Result:=FALSE; cSql:='Select * From PEDIDOS Where numpedido=' + pNumeroPedido; QryPed:=TFDQuery.Create(nil); try QryPed.Connection:=dmBase.FDConexao; QryPed.Close; QryPed.SQL.Clear; QryPed.SQL.Add(cSql); QryPed.Open(cSql); if not QryPed.IsEmpty then Result:=TRUE; finally FreeAndNil(QryPed); end; end; procedure CarregarPedidos(pNumeroPedido:string; oPedido:TPedido); var QryPed:TFDQuery; cSql :string; begin cSql:='Select * From PEDIDOS Where numpedido=' + pNumeroPedido; QryPed:=TFDQuery.Create(nil); try QryPed.Connection:=dmBase.FDConexao; QryPed.Close; QryPed.SQL.Clear; QryPed.SQL.Add(cSql); QryPed.Open(cSql); if not QryPed.IsEmpty then begin oPedido.numeropedido :=QryPed.FieldByName('numpedido').AsInteger; oPedido.dataemissao :=QryPed.FieldByName('dataemissao').AsDateTime; oPedido.codigocliente:=QryPed.FieldByName('codigocliente').AsInteger; oPedido.valortotal :=QryPed.FieldByName('valortotal').AsFloat; end else begin oPedido.numeropedido :=-1; oPedido.dataemissao :=0; oPedido.codigocliente:=0; oPedido.valortotal :=0; end; finally FreeAndNil(QryPed); end; end; function CarregarPedidoProdutos(pNumeroPedido:string; FDMemItens:TFDMemTable):Boolean; var QryItens:TFDQuery; cSql :string; begin Result:=TRUE; cSql:='Select P.numeropedido, ' + ' P.codigoproduto, ' + ' P.quantidade, ' + ' P.valorunitario, ' + ' P.valortotal, ' + ' R.Descricao ' + ' From PEDIDOS_PRODUTOS P ' + ' inner join PRODUTOS R on (R.codigo=P.codigoproduto) ' + ' Where numeropedido=' + pNumeroPedido; QryItens:=TFDQuery.Create(nil); try QryItens.Connection:=dmBase.FDConexao; QryItens.Close; QryItens.SQL.Clear; QryItens.SQL.Add(cSql); QryItens.Open(cSql); if not QryItens.IsEmpty then begin if FDMemItens.Active then FDMemItens.EmptyDataSet; QryItens.First; while not QryItens.EOF do begin FDMemItens.Append; FDMemItens.FieldByName('CODIGO').AsInteger := QryItens.FieldByName('CODIGOPRODUTO').AsInteger; FDMemItens.FieldByName('DESCRICAO').AsString := QryItens.FieldByName('DESCRICAO').AsString; FDMemItens.FieldByName('QUANTIDADE').AsInteger := QryItens.FieldByName('QUANTIDADE').AsInteger; FDMemItens.FieldByName('VLR_UNITARIO').AsFloat := QryItens.FieldByName('VALORUNITARIO').AsFloat; FDMemItens.FieldByName('VLR_TOTAL').AsFloat := QryItens.FieldByName('VALORTOTAL').AsFloat; FDMemItens.Post; QryItens.Next; end; end else begin Result:=FALSE; end; finally FreeAndNil(QryItens); end; end; end.
(******************************************************************************) (** Suite : AtWS **) (** Object : TfMain **) (** Framework : **) (** Developed by : Nuno Picado **) (******************************************************************************) (** Interfaces : **) (******************************************************************************) (** Dependencies : AtWS **) (******************************************************************************) (** Description : Demo project for AtWS.dll **) (******************************************************************************) (** Licence : MIT (https://opensource.org/licenses/MIT) **) (** Contributions : You can create pull request for all your desired **) (** contributions as long as they comply with the guidelines **) (** you can find in the readme.md file in the main directory **) (** of the Reusable Objects repository **) (** Disclaimer : The licence agreement applies to the code in this unit **) (** and not to any of its dependencies, which have their own **) (** licence agreement and to which you must comply in their **) (** terms **) (******************************************************************************) unit uMain; interface uses Classes , Controls , Forms , StdCtrls , AtWSvcIntf , Vcl.ExtCtrls ; type TfMain = class(TForm) memoRequest: TMemo; bSetupProductionDTWS: TButton; bSetupTestingDTWS: TButton; memoResponse: TMemo; bSendDoc: TButton; bSetupTestingFTWS: TButton; bSetupProductionFTWS: TButton; pnlTools: TPanel; Splitter: TSplitter; bSetupTestingSEWS: TButton; bSetupProductionSEWS: TButton; procedure bSetupProductionDTWSClick(Sender: TObject); procedure bSetupTestingDTWSClick(Sender: TObject); procedure bSendDocClick(Sender: TObject); procedure bSetupTestingFTWSClick(Sender: TObject); procedure bSetupProductionFTWSClick(Sender: TObject); procedure bSetupTestingSEWSClick(Sender: TObject); procedure bSetupProductionSEWSClick(Sender: TObject); private FAtWS: IAtWSvc; public { Public declarations } end; var fMain: TfMain; function ATWebService(const SoapURL, SoapAction, PubKeyFile, PFXFile, PFXPass: WideString): IAtWSvc; stdcall; external 'AtWS.dll'; implementation uses Dialogs , XMLDoc , SysUtils ; const SampleFTXML = '<?xml version="1.0" standalone="no"?>'+ ' <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">'+ ' <S:Header>'+ ' <wss:Security xmlns:wss="http://schemas.xmlsoap.org/ws/2002/12/secext">'+ ' <wss:UsernameToken>'+ ' <wss:Username>555555550/1</wss:Username>'+ ' <wss:Password>123456789</wss:Password>'+ ' <wss:Nonce></wss:Nonce>'+ ' <wss:Created></wss:Created>'+ ' </wss:UsernameToken>'+ ' </wss:Security>'+ ' </S:Header>'+ ' <S:Body>'+ ' <ns2:RegisterInvoiceElem xmlns:ns2="http://servicos.portaldasfinancas.gov.pt/faturas/">'+ ' <TaxRegistrationNumber>555555550</TaxRegistrationNumber>'+ ' <ns2:InvoiceNo>FT 1/1</ns2:InvoiceNo>'+ ' <ns2:InvoiceDate>2017-08-23</ns2:InvoiceDate>'+ ' <ns2:InvoiceType>FT</ns2:InvoiceType>'+ ' <ns2:InvoiceStatus>N</ns2:InvoiceStatus>'+ ' <CustomerTaxID>111111111</CustomerTaxID>'+ ' <Line>'+ ' <ns2:DebitAmount>100</ns2:DebitAmount>'+ ' <ns2:Tax>'+ ' <ns2:TaxType>IVA</ns2:TaxType>'+ ' <ns2:TaxCountryRegion>PT</ns2:TaxCountryRegion>'+ ' <ns2:TaxPercentage>23</ns2:TaxPercentage>'+ ' </ns2:Tax>'+ ' </Line>'+ ' <DocumentTotals>'+ ' <ns2:TaxPayable>23</ns2:TaxPayable>'+ ' <ns2:NetTotal>100</ns2:NetTotal>'+ ' <ns2:GrossTotal>123</ns2:GrossTotal>'+ ' </DocumentTotals>'+ ' </ns2:RegisterInvoiceElem>'+ ' </S:Body>'+ ' </S:Envelope>'; SampleDTXML = '<?xml version="1.0" standalone="no"?>'+ ' <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">'+ ' <S:Header>'+ ' <wss:Security xmlns:wss="http://schemas.xmlsoap.org/ws/2002/12/secext">'+ ' <wss:UsernameToken>'+ ' <wss:Username>555555550/1</wss:Username>'+ ' <wss:Nonce></wss:Nonce>'+ ' <wss:Password>123456789</wss:Password>'+ ' <wss:Created></wss:Created>'+ ' </wss:UsernameToken>'+ ' </wss:Security>'+ ' </S:Header>'+ ' <S:Body>'+ ' <ns2:envioDocumentoTransporteRequestElem xmlns:ns2="https://servicos.portaldasfinancas.gov.pt/sgdtws/documentosTransporte/">'+ ' <TaxRegistrationNumber>555555550</TaxRegistrationNumber>'+ ' <CompanyName>Coiso e Tal Lda.</CompanyName>'+ ' <CompanyAddress>'+ ' <Addressdetail>Lá Mesmo N 6 Lj 3</Addressdetail>'+ ' <City>Cascos de Rolha</City>'+ ' <PostalCode>8050-000</PostalCode>'+ ' <Country>PT</Country>'+ ' </CompanyAddress>'+ ' <DocumentNumber>GT TESTE20200630/1</DocumentNumber>'+ ' <MovementStatus>N</MovementStatus>'+ ' <MovementDate>2020-06-30</MovementDate>'+ ' <MovementType>GT</MovementType>'+ ' <CustomerTaxID>999999990</CustomerTaxID>'+ ' <CustomerAddress>'+ ' <Addressdetail>Curral de Moinas</Addressdetail>'+ ' <City>Portada</City>'+ ' <PostalCode>8888-000</PostalCode>'+ ' <Country>PT</Country>'+ ' </CustomerAddress>'+ ' <CustomerName>Ti Manel</CustomerName>'+ ' <AddressTo>'+ ' <Addressdetail>Vale da Moita</Addressdetail>'+ ' <City>Portel</City>'+ ' <PostalCode>8884-144</PostalCode>'+ ' <Country>PT</Country>'+ ' </AddressTo>'+ ' <AddressFrom>'+ ' <Addressdetail>Vilar Paraiso</Addressdetail>'+ ' <City>Terra Dele</City>'+ ' <PostalCode>9999-144</PostalCode>'+ ' <Country>PT</Country>'+ ' </AddressFrom>'+ ' <MovementStartTime>2020-07-01T14:50:00</MovementStartTime>'+ ' <VehicleID>AA-00-00</VehicleID>'+ ' <Line>'+ ' <ProductDescription>Papel A4</ProductDescription>'+ ' <Quantity>5</Quantity>'+ ' <UnitOfMeasure>Un</UnitOfMeasure>'+ ' <UnitPrice>3.00</UnitPrice>'+ ' </Line>'+ ' </ns2:envioDocumentoTransporteRequestElem>'+ ' </S:Body>'+ ' </S:Envelope>'; SampleSEXML = '<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">' + sLineBreak + ' <S:Header>' + sLineBreak + ' <wss:Security xmlns:wss="http://schemas.xmlsoap.org/ws/2002/12/secext">' + sLineBreak + ' <wss:UsernameToken>' + sLineBreak + ' <wss:Username>555555550/1</wss:Username>' + sLineBreak + ' <wss:Nonce></wss:Nonce>' + sLineBreak + ' <wss:Password>123456789</wss:Password>' + sLineBreak + ' <wss:Created></wss:Created>' + sLineBreak + ' </wss:UsernameToken>' + sLineBreak + ' </wss:Security>' + sLineBreak + ' </S:Header>' + sLineBreak + ' <S:Body>' + sLineBreak + ' <ns2:registarSerie xmlns:ns2="http://at.gov.pt/">' + sLineBreak + ' <serie>A2008212353</serie>' + sLineBreak + ' <tipoSerie>N</tipoSerie>' + sLineBreak + ' <classeDoc>SI</classeDoc>' + sLineBreak + ' <tipoDoc>FT</tipoDoc>' + sLineBreak + ' <numInicialSeq>1</numInicialSeq>' + sLineBreak + ' <dataInicioPrevUtiliz>2022-01-01</dataInicioPrevUtiliz>' + sLineBreak + ' <numCertSWFatur>0000</numCertSWFatur>' + sLineBreak + ' <meioProcessamento>PI</meioProcessamento>' + sLineBreak + ' </ns2:registarSerie>' + sLineBreak + ' </S:Body>' + sLineBreak + '</S:Envelope>'; {$R *.dfm} procedure TfMain.bSetupTestingDTWSClick(Sender: TObject); begin FAtWS := ATWebService( 'https://servicos.portaldasfinancas.gov.pt:701/sgdtws/documentosTransporte', 'https://servicos.portaldasfinancas.gov.pt/sgdtws/documentosTransporte/', 'ChaveCifraPublicaAT2023.pem', 'TESTEWebServices.pfx', 'TESTEwebservice' ); bSendDoc.Caption := 'Enviar documento DT de Teste'; bSendDoc.Enabled := True; memoRequest.Text := FormatXMLData(SampleDTXML); end; procedure TfMain.bSetupTestingFTWSClick(Sender: TObject); begin FAtWS := ATWebService( 'https://servicos.portaldasfinancas.gov.pt:700/fews/faturas', 'https://servicos.portaldasfinancas.gov.pt/faturas/RegisterInvoice', 'ChaveCifraPublicaAT2023.pem', 'TESTEWebServices.pfx', 'TESTEwebservice' ); bSendDoc.Caption := 'Enviar documento FT de Teste'; bSendDoc.Enabled := True; memoRequest.Text := FormatXMLData(SampleFTXML); end; procedure TfMain.bSetupTestingSEWSClick(Sender: TObject); begin FAtWS := ATWebService( 'https://servicos.portaldasfinancas.gov.pt:722/SeriesWSService', 'http://at.gov.pt', 'ChaveCifraPublicaAT2023.pem', 'TESTEWebServices.pfx', 'TESTEwebservice' ); bSendDoc.Caption := 'Enviar documento SE de Teste'; bSendDoc.Enabled := True; memoRequest.Text := FormatXMLData(SampleSEXML); end; procedure TfMain.bSetupProductionFTWSClick(Sender: TObject); begin FAtWS := ATWebService( 'https://servicos.portaldasfinancas.gov.pt:400/fews/faturas', 'https://servicos.portaldasfinancas.gov.pt/faturas/RegisterInvoice', 'ChaveCifraPublicaAT2023.pem', ParamStr(1), ParamStr(2) ); bSendDoc.Caption := 'Enviar documento FT de Produção'; bSendDoc.Enabled := True; memoRequest.Text := FormatXMLData(SampleFTXML); end; procedure TfMain.bSetupProductionSEWSClick(Sender: TObject); begin FAtWS := ATWebService( 'https://servicos.portaldasfinancas.gov.pt:722/SeriesWSService', 'http://at.gov.pt', 'ChaveCifraPublicaAT2023.pem', ParamStr(1), ParamStr(2) ); bSendDoc.Caption := 'Enviar documento SE de Teste'; bSendDoc.Enabled := True; memoRequest.Text := FormatXMLData(SampleSEXML); end; procedure TfMain.bSendDocClick(Sender: TObject); begin if not Assigned(FAtWS) then raise Exception.Create('Webservice not initialized.'); memoResponse.Text := FormatXMLData( FAtWS.Send( memoRequest.Text ) ); end; procedure TfMain.bSetupProductionDTWSClick(Sender: TObject); begin FAtWS := ATWebService( 'https://servicos.portaldasfinancas.gov.pt:401/sgdtws/documentosTransporte', 'https://servicos.portaldasfinancas.gov.pt/sgdtws/documentosTransporte/', 'ChaveCifraPublicaAT2023.pem', ParamStr(1), ParamStr(2) ); bSendDoc.Caption := 'Enviar documento DT de Produção'; bSendDoc.Enabled := True; memoRequest.Text := FormatXMLData(SampleDTXML); end; end.
{ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. } // Copyright (c) 2010 - J. Aldo G. de Freitas Junior Unit XMLConsole; Interface Uses Classes, SysUtils, StrUtils, Stacks, XMLScanner, XMLParser, XMLNodes, ExprNodes, ExpressionParser; Type EUnknownCommand = Class(Exception); ENoSuchChild = Class(Exception); TXMLCustomConsole = Class; TTokenList = Array Of String; TXMLObjectMessage = Record MsgStr : String[255]; Data : Pointer; End; TXMLAccessStack = Class; TXMLConsoleMessageKind = (mkDebug, mkError, mkResponse, mkInfo); TXMLVerbosity = Array[mkDebug..mkInfo] Of Boolean; TXMLCustomConsole = Class Private fCommandLine : String; fFocused : TXMLNode; fRunning : Boolean; fStack : TXMLAccessStack; fVerbosity : TXMLVerbosity; fPrompt : String; Public Constructor Create; Destructor Destroy; Override; { Virtual Console Handling } Function ReadLine: String; Virtual; Abstract; Procedure Out(Const aKind : TXMLConsoleMessageKind; Const aLine : String); Virtual; Abstract; Procedure OutLn(Const aKind : TXMLConsoleMessageKind; Const aLine : String); Virtual; Abstract; Procedure Process; Virtual; Function AtLeast(Const aCount : Integer): Boolean; { Command handlers } Procedure Submit; Virtual; Procedure DefaultHandlerStr(Var Message); Override; Procedure Save(Var Message); Message 'save'; Procedure Load(Var Message); Message 'load'; Procedure Focus(Var Message); Message 'focus'; Procedure Up(Var Message); Message 'up'; Procedure ListChilds(Var Message); Message 'list'; Procedure ListCommands(Var Message); Message 'help'; Procedure AddChild(Var Message); Message 'add'; Procedure DeleteChild(Var Message); Message 'delete'; Procedure SetProperty(Var Message); Message 'setproperty'; Procedure SetText(Var Message); Message 'settext'; Procedure DelProp(Var Message); Message 'deleteproperty'; Procedure PurgeProp(Var Message); Message 'purgeproperties'; Procedure Quit(Var Message); Message 'quit'; Procedure Print(Var Message); Message 'print'; Procedure SetVerbosity(Var Message); Message 'setverbosity'; Procedure GetVerbosity(Var Message); Message 'verbosity'; Procedure SetPrompt(Var Message); Message 'setprompt'; { Event Handlers } Procedure DoLoadFromFile(Const aFileName : String); Procedure DoSaveToFile(Const aFileName : String); Procedure DoFocus(Const aTarget : TXMLNode); Virtual; { Properties } Property CommandLine : String Read fCommandLine; Property Stack: TXMLAccessStack Read fStack; Property Focused : TXMLNode Read fFocused; Property Running : Boolean Read fRunning; Property Verbosity : TXMLVerbosity Read fVerbosity Write fVerbosity; Property Prompt : String Read fPrompt Write fPrompt; End; TXMLAccessStack = Class(TVirtualMachineStack) Private fConsole : TXMLCustomConsole; Public { Function handlers } Procedure GetProperty(Var aMessage); Message 'getproperty'; Procedure GetText(Var aMessage); Message 'gettext'; Procedure Accept(Var aMessage); Message 'accept'; Property Console : TXMLCustomConsole Read fConsole Write fConsole; End; Function ConcatenateStrings(Const aStrings : TTokenList): String; Implementation Function ConcatenateStrings(Const aStrings : TTokenList): String; Var lCtrl : Integer; Begin Result := ''; For lCtrl := Low(aStrings) To High(aStrings) Do If lCtrl <> High(aStrings) Then Result := Result + aStrings[lCtrl] + ', ' Else Result := Result + aStrings[lCtrl]; End; { TXMLCustomConsole } Constructor TXMLCustomConsole.Create; Begin Inherited Create; fRunning := True; fStack := TXMLAccessStack.Create; fStack.Console := Self; fVerbosity[mkDebug] := True; fVerbosity[mkError] := True; fVerbosity[mkResponse] := True; fVerbosity[mkInfo] := True; fPrompt := '$F>'; End; Destructor TXMLCustomConsole.Destroy; Begin fStack.Free; Inherited Destroy; End; Procedure TXMLCustomConsole.Process; Var lTmp : String; lParser : TExpressionParser; Begin Try Try lTmp := ReadLine; If Length(lTmp) > 0 Then Begin fCommandLine := Copy2SymbDel(lTmp, ' '); lParser := TExpressionParser.Create(lTmp, fStack); If Length(lTmp) > 0 Then lParser.Evaluate(False); If lParser.Error Then OutLn(mkError, 'At Expression "' + lTmp + '" column ' + IntToStr(lParser.ErrorCol) + ' got : ' + lParser.ErrorString) Else Submit; End Else OutLn(mkError, 'Empty command line.'); Finally lParser.Free; End; Except On E : Exception Do OutLn(mkError, E.Message); End; End; Function TXMLCustomConsole.AtLeast(Const aCount : Integer): Boolean; Begin Result := fStack.Top.AtLeast(aCount); End; Procedure TXMLCustomConsole.Submit; Var lMsg : TXMLObjectMessage; Begin lMsg.MsgStr := fCommandLine; lMsg.Data := Nil; DispatchStr(lMsg); End; Procedure TXMLCustomConsole.DefaultHandlerStr(Var Message); Begin OutLn(mkError, 'No handler for the command : ' + fCommandLine); fStack.Purge; End; Procedure TXMLCustomConsole.Save(Var Message); Begin If AtLeast(1) Then Begin fStack.Enter(1); OutLn(mkInfo, 'Saving to file ' + fStack.Top.Peek(0)); DoSaveToFile(fStack.Top.Top); OutLn(mkInfo, 'Done.'); fStack.Leave(0); End Else Begin OutLn(mkError, 'Not enough parameters.'); OutLn(mkInfo, 'Format : '); OutLn(mkInfo, ' SAVE <filename>'); End; fStack.Purge; End; Procedure TXMLCustomConsole.Load(Var Message); Begin If AtLeast(1) Then Begin fStack.Enter(1); If FileExists(fStack.Top.Peek(0)) Then Begin OutLn(mkInfo, 'Loading from file ' + fStack.Top.Peek(0)); DoLoadFromFile(fStack.Top.Top); OutLn(mkInfo, 'Done.'); End Else OutLn(mkError, 'Cannot find file : "' + fStack.Top.Peek(0) + '".'); fStack.Leave(0); End Else Begin OutLn(mkError, 'Not enough parameters.'); OutLn(mkInfo, 'Format : '); OutLn(mkInfo, ' LOAD <filename>'); End; End; Procedure TXMLCustomConsole.Focus(Var Message); Var lTarget : TXMLNode; Begin If AtLeast(1) Then Begin fStack.Enter(1); lTarget := fFocused.Locate(fStack.Top.Peek(0)) As TXMLNode; If Assigned(lTarget) Then fFocused := lTarget Else OutLn(mkError, 'Cannot locate node : "' + fStack.Top.Peek(0) + '".'); fStack.Leave(0); End Else Begin OutLn(mkError, 'Please specify target.'); OutLn(mkInfo, 'Format :'); OutLn(mkInfo, ' FOCUS <dom>'); End; End; Procedure TXMLCustomConsole.Up(Var Message); Begin If Assigned(fFocused.Owner) Then fFocused := fFocused.Owner As TXMLNode Else OutLn(mkError, 'Cannot go upper than root node.'); End; Procedure TXMLCustomConsole.ListChilds(Var Message); Begin OutLn(mkInfo, 'Listing childs :'); fFocused.First; While Not(fFocused.IsAfterLast) Do Begin OutLn(mkResponse, '"' + (fFocused.GetCurrent As TXMLNode).IndexedName + '", "' + IntToStr(fFocused.GetCurrentIndex) + '"'); fFocused.Next; End; OutLn(mkInfo, 'Done.'); End; Procedure TXMLCustomConsole.ListCommands(Var Message); Var lCtrl : Integer; lCommands : TTokenList; lClass : TClass; Begin SetLength(lCommands, 0); lClass := Self.ClassType; While Assigned(lClass) Do Begin If lClass.StringMessageTable <> Nil Then If lClass.StringMessageTable^.Count > 0 Then For lCtrl := 0 To lClass.StringMessageTable^.Count - 1 Do Begin SetLength(lCommands, Length(lCommands) + 1); lCommands[High(lCommands)] := UpCase((lClass.StringMessageTable^.MsgStrTable[lCtrl].Name^)); End; lClass := lClass.ClassParent; End; OutLn(mkInfo, 'Available Commands :'); OutLn(mkResponse, '"' + ConcatenateStrings(lCommands) + '"'); End; Procedure TXMLCustomConsole.AddChild(Var Message); Begin If AtLeast(1) Then Begin fStack.Enter(1); OutLn(mkInfo, 'Creating a child with tag ' + fStack.Top.Peek(0)); (XMLClassFactory.Build(fStack.Top.Peek(0), fFocused) As TXMLNode).Name := fStack.Top.Peek(0); OutLn(mkInfo, 'Done.'); fStack.Leave(0); End Else Begin OutLn(mkError, 'Must specify child class'); OutLn(mkInfo, 'Format :'); OutLn(mkInfo, ' ADD <tag>'); End; End; Procedure TXMLCustomConsole.DeleteChild(Var Message); Var lTargetOwner, lTarget : TXMLNode; Begin If AtLeast(1) Then Begin fStack.Enter(1); lTarget := fFocused.Locate(fStack.Top.Peek(0)) As TXMLNode; If Assigned(lTarget) Then If lTarget <> (fFocused.FindRoot As TXMLNode) Then Begin OutLn(mkInfo, 'Deleting node "' + fStack.Top.Peek(0) + '".'); If fFocused = lTarget Then fFocused := lTarget.Owner As TXMLNode; lTargetOwner := lTarget.Owner As TXMLNode; lTargetOwner.Delete(lTarget); OutLn(mkInfo, 'Done.'); End Else OutLn(mkError, 'Cannot delete the root node.') Else OutLn(mkError, 'Cannot locate node.'); fStack.Leave(0); End Else Begin OutLn(mkError, 'Must specify child name'); OutLn(mkInfo, 'Format : '); OutLn(mkInfo, ' DELETE <dom>'); End; End; Procedure TXMLCustomConsole.SetProperty(Var Message); Begin If AtLeast(2) Then Begin fStack.Enter(2); fStack.Enter(2); (fFocused As TXMLNode).Properties.SetValue(fStack.Top.Peek(0), fStack.Top.Peek(1)); fStack.Enter(2); fStack.Leave(0); End Else Begin OutLn(mkError, 'Not enough parameters.'); OutLn(mkInfo, 'Format : '); OutLn(mkInfo, ' SETPROPERTY <propertyname>, <propertyvalue>'); End; End; Procedure TXMLCustomConsole.SetText(Var Message); Begin If AtLeast(1) Then Begin fStack.Enter(1); fFocused.SetTextChild(fStack.Top.Peek(0)); fStack.Leave(0); End Else Begin OutLn(mkError, 'Not enough parameters.'); OutLn(mkInfo, 'Format : '); OutLn(mkInfo, ' SETTEXT <propertyname>, <propertyvalue>'); End; End; Procedure TXMLCustomConsole.DelProp(Var Message); Begin If AtLeast(1) Then Begin fStack.Enter(1); fFocused.Properties.Delete(fFocused.Properties.Find(fStack.Top.Peek(0))); fStack.Leave(0); End Else Begin OutLn(mkError, 'Not enough parameters.'); OutLn(mkInfo, 'Format :'); OutLn(mkInfo, ' DELPROP <propertyname>'); End; End; Procedure TXMLCustomConsole.PurgeProp(Var Message); Begin OutLn(mkDebug, 'Deleting all properties of current node.'); fFocused.Properties.Purge; End; Procedure TXMLCustomConsole.Quit(Var Message); Begin OutLn(mkInfo, 'Quitting'); fRunning := False; End; Procedure TXMLCustomConsole.SetVerbosity(Var Message); Begin If AtLeast(2) Then Begin fStack.Enter(2); fStack.Enter(2); If LowerCase(fStack.Top.Peek(0)) = 'debug' Then fVerbosity[mkDebug] := fStack.Top.Peek(1) Else If LowerCase(fStack.Top.Peek(0)) = 'error' Then fVerbosity[mkError] := fStack.Top.Peek(1) Else If LowerCase(fStack.Top.Peek(0)) = 'response' Then fVerbosity[mkResponse] := fStack.Top.Peek(1) Else If LowerCase(fStack.Top.Peek(0)) = 'info' Then fVerbosity[mkInfo] := fStack.Top.Peek(1); fStack.Leave(0); fStack.Leave(0); End Else Begin OutLn(mkError, 'Not enough parameters.'); OutLn(mkInfo, 'Format : '); OutLn(mkInfo, ' SETVERBOSE { ''debug'' | ''error'' | ''response'' | ''info'' }, { ''true'' | ''false'' }'); End; End; Procedure TXMLCustomConsole.GetVerbosity(Var Message); Begin OutLn(mkInfo, 'Verbosity options :'); If fVerbosity[mkDebug] Then OutLn(mkResponse, 'DEBUG = TRUE') Else OutLn(mkResponse, 'DEBUG = FALSE'); If fVerbosity[mkError] Then OutLn(mkResponse, 'ERROR = TRUE') Else OutLn(mkResponse, 'ERROR = FALSE'); If fVerbosity[mkResponse] Then OutLn(mkResponse, 'RESPONSE = TRUE') Else OutLn(mkResponse, 'RESPONSE = FALSE'); If fVerbosity[mkInfo] Then OutLn(mkResponse, 'INFO = TRUE') Else OutLn(mkResponse, 'INFO = FALSE'); End; Procedure TXMLCustomConsole.SetPrompt(Var Message); Begin If AtLeast(1) Then Begin fStack.Enter(1); fPrompt := fStack.Top.Peek(0); fStack.Leave(0); End Else Begin OutLn(mkError, 'Must specify child class'); OutLn(mkInfo, 'Format :'); OutLn(mkInfo, ' SETPROMPT <prompt>'); End; End; Procedure TXMLCustomConsole.Print(Var Message); Begin While fStack.Top.AtLeast(1) Do OutLn(mkResponse, fStack.Top.Pop); End; Procedure TXMLCustomConsole.DoLoadFromFile(Const aFileName : String); Var lFile : TFileStream; lSource : TXMLSource; lTokens : TMemoryStream; lScanner : TXMLScanner; lTokenIterator : TXMLTokenIterator; lParser : TXMLParser; Begin fFocused.Purge; lFile := Nil; lSource := Nil; lTokens := Nil; lScanner := Nil; lTokenIterator := Nil; lParser := Nil; Try lFile := TFileStream.Create(aFileName, fmOpenRead); lSource := TXMLSource.Create(lFile, False); lTokens := TMemoryStream.Create; lScanner := TXMLScanner.Create(lSource, lTokens, False); lScanner.Scan; lTokenIterator := TXMLTokenIterator.Create(lTokens, False); lParser := TXMLParser.Create(lTokenIterator, fFocused, False); lParser.Parse; Finally FreeAndNil(lFile); FreeAndNil(lSource); FreeAndNil(lTokens); FreeAndNil(lScanner); FreeAndNil(lTokenIterator); FreeAndNil(lParser); End; End; Procedure TXMLCustomConsole.DoSaveToFile(Const aFileName : String); Var lFile : TStringList; lAsXMLIterator : TXMLAsTextIterator; Begin lFile := Nil; lAsXMLIterator := Nil; Try lFile := TStringList.Create; lAsXMLIterator := TXMLAsTextIterator.Create; lAsXMLIterator.Visit(fFocused); lFile.Text := lAsXMLIterator.Output; lFile.SaveToFile(aFileName); Finally FreeAndNil(lAsXMLIterator); FreeAndNil(lFile); End; End; Procedure TXMLCustomConsole.DoFocus(Const aTarget : TXMLNode); Begin fFocused := aTarget; End; { TXMLAccessStack } Procedure TXMLAccessStack.GetProperty(Var aMessage); Begin Top.Push((fConsole.Focused.Locate(Top.Pop) As TXMLNode).Properties.GetValue(Top.Pop)); End; Procedure TXMLAccessStack.GetText(Var aMessage); Begin Top.Push((fConsole.Focused.Locate(Top.Pop) As TXMLNode).GetTextChild); End; Procedure TXMLAccessStack.Accept(Var aMessage); Var lTmp : String; Begin ReadLn(lTmp); Top.Push(lTmp); End; End.
unit ClrBandInterface; interface uses Spring.Collections, Graphics; type IBandFill = interface(IInvokable) ['{97595126-64A6-4246-8FF9-E53024C5223C}'] procedure SetTestDimWithoutWhiteBorder(const ImgX, ImgY, bandWidth, bandShift: integer); procedure SetTestDimWhiteBorder(const ImgX, ImgY, bandWidth, bandShift: integer); procedure SetSingleCellWhiteBorder(const ImgX, ImgY, bandWidth, BandShift: integer); procedure SetColorAndShift(Colors: IList<TColor>; BandShift: integer); procedure Teardown; function PerimeterTop:string; function PerimeterBottom: string; function GetSVGFragment: string; end; implementation end.
unit MediaInfoDll; { MediaInfoLib (MediaInfo.dll v0.7.7.6) Interface for Delphi (c)2008 by Norbert Mereg (Icebob) http://MediaArea.net/MediaInfo } // Defines how the DLL is called (dynamic or static) //{$DEFINE STATIC} interface uses {$IFDEF WIN32} Windows; {$ELSE} Wintypes, WinProcs; {$ENDIF} type TMIStreamKind = ( Stream_General, Stream_Video, Stream_Audio, Stream_Text, Stream_Other, Stream_Image, Stream_Menu, Stream_Max ); type TMIInfo = ( Info_Name, Info_Text, Info_Measure, Info_Options, Info_Name_Text, Info_Measure_Text, Info_Info, Info_HowTo, Info_Max ); type TMIInfoOption = ( InfoOption_ShowInInform, InfoOption_Reserved, InfoOption_ShowInSupported, InfoOption_TypeOfValue, InfoOption_Max ); {$IFDEF STATIC} // Unicode methods function MediaInfo_New(): Cardinal cdecl {$IFDEF WIN32} stdcall {$ENDIF};external 'MediaInfo.Dll'; procedure MediaInfo_Delete(Handle: Cardinal) cdecl {$IFDEF WIN32} stdcall {$ENDIF}; external 'MediaInfo.Dll'; function MediaInfo_Open(Handle: Cardinal; File__: PWideChar): Cardinal cdecl {$IFDEF WIN32} stdcall {$ENDIF};external 'MediaInfo.Dll'; procedure MediaInfo_Close(Handle: Cardinal) cdecl {$IFDEF WIN32} stdcall {$ENDIF};external 'MediaInfo.Dll'; function MediaInfo_Inform(Handle: Cardinal; Reserved: Integer): PWideChar cdecl {$IFDEF WIN32} stdcall {$ENDIF};external 'MediaInfo.Dll'; function MediaInfo_GetI(Handle: Cardinal; StreamKind: TMIStreamKind; StreamNumber: Integer; Parameter: Integer; KindOfInfo: TMIInfo): PWideChar cdecl {$IFDEF WIN32} stdcall {$ENDIF};external 'MediaInfo.Dll'; //Default: KindOfInfo=Info_Text function MediaInfo_Get(Handle: Cardinal; StreamKind: TMIStreamKind; StreamNumber: Integer; Parameter: PWideChar; KindOfInfo: TMIInfo; KindOfSearch: TMIInfo): PWideChar cdecl {$IFDEF WIN32} stdcall {$ENDIF};external 'MediaInfo.Dll'; //Default: KindOfInfo=Info_Text, KindOfSearch=Info_Name function MediaInfo_Option(Handle: Cardinal; Option: PWideChar; Value: PWideChar): PWideChar cdecl {$IFDEF WIN32} stdcall {$ENDIF};external 'MediaInfo.Dll'; function MediaInfo_State_Get(Handle: Cardinal): Integer cdecl {$IFDEF WIN32} stdcall {$ENDIF};external 'MediaInfo.Dll'; function MediaInfo_Count_Get(Handle: Cardinal; StreamKind: TMIStreamKind; StreamNumber: Integer): Integer cdecl {$IFDEF WIN32} stdcall {$ENDIF};external 'MediaInfo.Dll'; // Ansi methods function MediaInfoA_New(): Cardinal cdecl {$IFDEF WIN32} stdcall {$ENDIF};external 'MediaInfo.Dll'; procedure MediaInfoA_Delete(Handle: Cardinal) cdecl {$IFDEF WIN32} stdcall {$ENDIF};external 'MediaInfo.Dll'; function MediaInfoA_Open(Handle: Cardinal; File__: PAnsiChar): Cardinal cdecl {$IFDEF WIN32} stdcall {$ENDIF};external 'MediaInfo.Dll'; procedure MediaInfoA_Close(Handle: Cardinal) cdecl {$IFDEF WIN32} stdcall {$ENDIF};external 'MediaInfo.Dll'; function MediaInfoA_Inform(Handle: Cardinal; Reserved: Integer): PAnsiChar cdecl {$IFDEF WIN32} stdcall {$ENDIF};external 'MediaInfo.Dll'; function MediaInfoA_GetI(Handle: Cardinal; StreamKind: TMIStreamKind; StreamNumber: Integer; Parameter: Integer; KindOfInfo: TMIInfo): PAnsiChar cdecl {$IFDEF WIN32} stdcall {$ENDIF};external 'MediaInfo.Dll'; //Default: KindOfInfo=Info_Text function MediaInfoA_Get(Handle: Cardinal; StreamKind: TMIStreamKind; StreamNumber: Integer; Parameter: PAnsiChar; KindOfInfo: TMIInfo; KindOfSearch: TMIInfo): PAnsiChar cdecl {$IFDEF WIN32} stdcall {$ENDIF};external 'MediaInfo.Dll'; //Default: KindOfInfo=Info_Text, KindOfSearch=Info_Name function MediaInfoA_Option(Handle: Cardinal; Option: PAnsiChar; Value: PAnsiChar): PAnsiChar cdecl {$IFDEF WIN32} stdcall {$ENDIF};external 'MediaInfo.Dll'; function MediaInfoA_State_Get(Handle: Cardinal): Integer cdecl {$IFDEF WIN32} stdcall {$ENDIF};external 'MediaInfo.Dll'; function MediaInfoA_Count_Get(Handle: Cardinal; StreamKind: TMIStreamKind; StreamNumber: Integer): Integer cdecl {$IFDEF WIN32} stdcall {$ENDIF};external 'MediaInfo.Dll'; {$ELSE} var LibHandle: THandle = 0; // Unicode methods MediaInfo_New: function (): THandle cdecl stdcall; MediaInfo_Delete: procedure (Handle: THandle) cdecl stdcall; MediaInfo_Open: function (Handle: THandle; File__: PWideChar): Cardinal cdecl stdcall; MediaInfo_Close: procedure (Handle: THandle) cdecl stdcall; MediaInfo_Inform: function (Handle: THandle; Reserved: Integer): PWideChar cdecl stdcall; MediaInfo_GetI: function (Handle: THandle; StreamKind: TMIStreamKind; StreamNumber: Integer; Parameter: Integer; KindOfInfo: TMIInfo): PWideChar cdecl stdcall; //Default: KindOfInfo=Info_Text, MediaInfo_Get: function (Handle: THandle; StreamKind: TMIStreamKind; StreamNumber: Integer; Parameter: PWideChar; KindOfInfo: TMIInfo; KindOfSearch: TMIInfo): PWideChar cdecl stdcall; //Default: KindOfInfo=Info_Text, KindOfSearch=Info_Name MediaInfo_Option: function (Handle: THandle; Option: PWideChar; Value: PWideChar): PWideChar cdecl stdcall; MediaInfo_State_Get: function (Handle: THandle): Integer cdecl stdcall; MediaInfo_Count_Get: function (Handle: THandle; StreamKind: TMIStreamKind; StreamNumber: Integer): Integer cdecl stdcall; // Ansi methods MediaInfoA_New: function (): THandle cdecl stdcall; MediaInfoA_Delete: procedure (Handle: THandle) cdecl stdcall; MediaInfoA_Open: function (Handle: THandle; File__: PAnsiChar): Cardinal cdecl stdcall; MediaInfoA_Close: procedure (Handle: THandle) cdecl stdcall; MediaInfoA_Inform: function (Handle: THandle; Reserved: Integer): PAnsiChar cdecl stdcall; MediaInfoA_GetI: function (Handle: THandle; StreamKind: TMIStreamKind; StreamNumber: Integer; Parameter: Integer; KindOfInfo: TMIInfo): PAnsiChar cdecl stdcall; //Default: KindOfInfo=Info_Text MediaInfoA_Get: function (Handle: THandle; StreamKind: TMIStreamKind; StreamNumber: Integer; Parameter: PAnsiChar; KindOfInfo: TMIInfo; KindOfSearch: TMIInfo): PAnsiChar cdecl stdcall; //Default: KindOfInfo=Info_Text, KindOfSearch=Info_Name MediaInfoA_Option: function (Handle: THandle; Option: PAnsiChar; Value: PAnsiChar): PAnsiChar cdecl stdcall; MediaInfoA_State_Get: function (Handle: THandle): Integer cdecl stdcall; MediaInfoA_Count_Get: function (Handle: THandle; StreamKind: TMIStreamKind; StreamNumber: Integer): Integer cdecl stdcall; function MediaInfoDLL_Load(LibPath: string): boolean; {$ENDIF} implementation {$IFNDEF STATIC} function MI_GetProcAddress(Name: PChar; var Addr: Pointer): boolean; begin Addr := GetProcAddress(LibHandle, Name); Result := Addr <> nil; end; function MediaInfoDLL_Load(LibPath: string): boolean; begin Result := False; if LibHandle = 0 then LibHandle := LoadLibrary(PChar(LibPath)); if LibHandle <> 0 then begin MI_GetProcAddress('MediaInfo_New', @MediaInfo_New); MI_GetProcAddress('MediaInfo_Delete', @MediaInfo_Delete); MI_GetProcAddress('MediaInfo_Open', @MediaInfo_Open); MI_GetProcAddress('MediaInfo_Close', @MediaInfo_Close); MI_GetProcAddress('MediaInfo_Inform', @MediaInfo_Inform); MI_GetProcAddress('MediaInfo_GetI', @MediaInfo_GetI); MI_GetProcAddress('MediaInfo_Get', @MediaInfo_Get); MI_GetProcAddress('MediaInfo_Option', @MediaInfo_Option); MI_GetProcAddress('MediaInfo_State_Get', @MediaInfo_State_Get); MI_GetProcAddress('MediaInfo_Count_Get', @MediaInfo_Count_Get); MI_GetProcAddress('MediaInfoA_New', @MediaInfoA_New); MI_GetProcAddress('MediaInfoA_Delete', @MediaInfoA_Delete); MI_GetProcAddress('MediaInfoA_Open', @MediaInfoA_Open); MI_GetProcAddress('MediaInfoA_Close', @MediaInfoA_Close); MI_GetProcAddress('MediaInfoA_Inform', @MediaInfoA_Inform); MI_GetProcAddress('MediaInfoA_GetI', @MediaInfoA_GetI); MI_GetProcAddress('MediaInfoA_Get', @MediaInfoA_Get); MI_GetProcAddress('MediaInfoA_Option', @MediaInfoA_Option); MI_GetProcAddress('MediaInfoA_State_Get', @MediaInfoA_State_Get); MI_GetProcAddress('MediaInfoA_Count_Get', @MediaInfoA_Count_Get); Result := True; end; end; {$ENDIF} end.
unit usettings; { winted by mnt - http://codeninja.de } interface uses classes, sysutils, inifiles, filectrl; type TEntry = class // if you add new items, modify also TEntryList.read/write public beingscanned: boolean; beingedited: boolean; disabled: boolean; virgin: boolean; //freshly created. needed to kill a new entry if cancel was pressed xmltype: integer; name: string; urls: TStringList; currseason, currepisode: integer; lastseason, lastepisode: integer; minsize, maxsize: integer; wanted: TStringList; ignore: TStringList; allwanted: boolean; lastnew, lastpoll: TDateTime; datelimit: TDateTime; usedatelimit: boolean; downloadanything: boolean; probedanything: boolean; //if false build visited.txt, but dont download anything useepguide: boolean; epguideurl: string; filenamewanted: TStringList; filenameignore: TStringList; filenameallwanted: boolean; pauseuntil: TDateTime; dopause: boolean; pausedays: integer; warning: string; procedure WriteIni(ini: TIniFile; section: string); procedure ReadIni(ini: TIniFile; section: string); constructor Create; destructor Destroy; override; end; TEntryList = class procedure Write(name: string); procedure Read(name: string); function EntryFactory(): TEntry; procedure Remove(entry: TEntry); function Count: Integer; function GetItem(i: integer): TEntry; constructor Create; destructor Destroy; override; private FList: TList; procedure Clear; end; const _listdelim = '|'; implementation uses umainwin; procedure stringtolist(str: string; list: TSTringList); var x: integer; begin list.Clear; repeat x := pos(_listdelim, str); if (x = 0) then break; list.Append(copy(str, 1, x - 1)); delete(str, 1, x); until (x = 0); end; function listtostring(list: TSTringList): string; var i: integer; begin result := ''; for i := 0 to pred(list.Count) do result := result + list.Strings[i] + _listdelim; end; { TEntry } constructor TEntry.Create; begin name := 'New Item'; urls := TStringList.Create; xmltype := -1; disabled := False; beingscanned := False; beingedited := False; wanted := TStringList.Create; ignore := TSTringList.Create; currseason := 0; currepisode := 0; lastseason := 0; lastepisode := 0; minsize := 0; maxsize := maxlongint; datelimit := Now; usedatelimit := False; lastnew := 0; downloadanything := False; probedanything := False; useepguide := False; epguideurl := ''; filenamewanted := TStringList.Create; filenameignore := TStringList.Create; filenameallwanted := False; pauseuntil := 0; dopause := false; pausedays := 7; warning := ''; end; destructor TEntry.Destroy; begin wanted.Free; ignore.Free; end; procedure TEntry.ReadIni(ini: TIniFile; section: string); var i: integer; urlname: string; begin name := ini.ReadString(section, 'name', ''); if (name = '') then exit; disabled := ini.ReadBool(section, 'disabled', false); for i := 0 to ini.ReadInteger(section, 'urls', 1) do begin urlname := 'url' + inttostr(i); if (urlname = 'url0') then urlname := 'url'; if (ini.ReadString(Section, urlname, '') = '') then continue; urls.AddObject(ini.ReadString(Section, urlname, ''), TObject( round(ini.ReadDate(Section, urlname + 'visited', 0)))); end; xmltype := ini.ReadInteger(Section, 'xmltype', -1); currseason := ini.ReadInteger(section, 'season', 0); currepisode := ini.ReadInteger(section, 'episode', 0); lastseason := ini.ReadInteger(section, 'lastseason', 0); lastepisode := ini.ReadInteger(section, 'lastepisode', 0); minsize := ini.ReadInteger(section, 'minsize', 0); maxsize := ini.ReadInteger(section, 'maxsize', maxint); lastnew := ini.ReadDate(section, 'lastnew', 0); lastpoll := ini.ReadDate(section, 'lastpoll', 0); datelimit := ini.ReadDate(section, 'datelimit', Now); usedatelimit := ini.Readbool(section, 'usedatelimit', false); allwanted := ini.ReadBool(section, 'alldo', false); downloadanything := ini.ReadBool(section, 'anything', false); probedanything := ini.ReadBool(section, 'probedanything', false); useepguide := ini.ReadBool(section, 'useepguide', false); epguideurl := ini.readstring(section, 'epguideurl', ''); filenameallwanted := ini.ReadBool(section, 'filenamealldo', false); pauseuntil := ini.ReadDate(section, 'pauseuntil', 0); dopause := ini.ReadBool(section, 'pause', false); pausedays := ini.ReadInteger(section, 'pausedays', 7); stringtolist(ini.ReadString(section, 'do', ''), wanted); stringtolist(ini.ReadString(section, 'dont', ''), ignore); stringtolist(ini.ReadString(section, 'filenamedo', ''), filenamewanted); stringtolist(ini.ReadString(section, 'filenamedont', ''), filenameignore); end; procedure TEntry.WriteIni(ini: TIniFile; section: string); var i: integer; urlname: string; begin ini.WriteString(section, 'name', name); ini.WriteBool(section, 'disabled', disabled); for i := 0 to pred(urls.count) do begin urlname := 'url' + inttostr(i); if (urlname = 'url0') then urlname := 'url'; ini.WriteString(Section, urlname, urls.strings[i]); ini.WriteDate(Section, urlname + 'visited', Integer(urls.objects[i])); end; ini.WriteInteger(Section, 'urls', urls.count); ini.WriteIntegeR(Section, 'xmltype', xmltype); ini.WriteInteger(section, 'season', currseason); ini.WriteInteger(section, 'episode', currepisode); ini.WriteInteger(section, 'lastseason', lastseason); ini.WriteInteger(section, 'lastepisode', lastepisode); ini.WriteInteger(section, 'minsize', minsize); ini.WriteInteger(section, 'maxsize', maxsize); ini.WriteDate(section, 'lastnew', lastnew); ini.WriteDate(section, 'lastpoll', lastpoll); ini.WriteDate(section, 'datelimit', datelimit); ini.WriteBool(section, 'alldo', allwanted); ini.WriteBool(section, 'anything', downloadanything); ini.WriteBool(section, 'probedanything', probedanything); ini.WriteBool(section, 'useepguide', useepguide); ini.writestring(section, 'epguideurl', epguideurl); ini.WriteBool(section, 'usedatelimit', usedatelimit); ini.WriteBool(section, 'filenamealldo', filenameallwanted); ini.WriteDate(section, 'pauseuntil', pauseuntil); ini.WriteBool(section, 'pause', dopause); ini.WriteInteger(section, 'pausedays', pausedays); ini.WriteString(section, 'do', listtostring(wanted)); ini.WriteString(section, 'dont', listtostring(ignore)); ini.WriteString(section, 'filenamedo', listtostring(filenamewanted)); ini.WriteString(section, 'filenamedont', listtostring(filenameignore)); end; { TEntryList } procedure TEntryList.Clear; var i: integer; begin for i := 0 to pred(Flist.Count) do TEntry(FList.Items[i]).Free; FList.Clear; end; function TEntryList.Count: Integer; begin result := Flist.Count; end; constructor TEntryList.Create; begin FList := TList.Create; end; destructor TEntryList.Destroy; begin Clear; FList.Free; inherited; end; function TEntryList.EntryFactory: TEntry; var e: TEntry; begin e := TEntry.Create; FList.Add(e); result := e; end; function TEntryList.GetItem(i: integer): TEntry; begin if (i < 0) or (i >= FList.Count) then begin result := nil; end else begin result := TEntry(FList.Items[i]); end; end; procedure TEntryList.Read(name: string); var ini: TIniFile; i, cnt: integer; begin try ini := TIniFile.Create(name); cnt := ini.ReadInteger(umainwin._inisect, 'entries', 0); if (cnt > 0) then for i := 0 to pred(cnt) do EntryFactory.ReadIni(ini, 'entry' + inttostr(i)); finally ini.Free; end; end; procedure TEntryList.Remove(entry: TEntry); var i: integer; begin i := FList.IndexOf(entry); if (i >= 0) then begin TEntry(FList.Items[i]).Free; FList.Items[i] := nil; FList.Delete(i); end; end; procedure TEntryList.Write(name: string); var cnt, i: integer; ini: TIniFile; begin try ini := TIniFile.Create(name); for i := 0 to (FList.Count + 10) do ini.EraseSection('entry' + inttostr(i)); //avoid file trashing, clumsy cnt := 0; for i := 0 to pred(FList.Count) do begin TEntry(Flist.Items[i]).WriteIni(ini, 'entry' + inttostr(cnt)); inc(cnt); end; ini.WriteInteger('WinTED', 'entries', FList.Count); finally ini.Free; end; end; end.
unit Exemplo2; interface uses System.Classes, System.SysUtils, Xml.XMLDoc, Xml.XMLIntf, System.Json, Data.DBXJSONReflect; type TTipoFicha = (tfTexto, tfXml, tfJson); TFichaUsuario = class private FCodigo: integer; FNome: String; FData: TDateTime; FCargo: string; public procedure Exportar(pArquivo: string; pTipoFicha: TTipoFicha); published property Codigo: integer read FCodigo write FCodigo; property Nome: String read FNome write FNome; property Data: TDateTime read FData write FData; property Cargo: string read FCargo write FCargo; end; implementation { TFichaUsuario } procedure TFichaUsuario.Exportar(pArquivo: string; pTipoFicha: TTipoFicha); var lTexto : TStringList; lXml: IXMLDocument; lNode: IXMLNode; lJson : TJsonValue; lJSONMarshal: TJSONMarshal; begin if pTipoFicha = tfTexto then begin lTexto := TStringList.Create; try lTexto.Add('Código: ' + FCodigo.ToString); lTexto.Add('Nome: ' + FNome); lTexto.Add('Data: ' + FormatDateTime('DD/MM/YYYY', FData)); lTexto.Add('Cargo: ' + FCargo); lTexto.SaveToFile(pArquivo); finally lTexto.Free; end; end else if pTipoFicha = tfXml then begin lXml := TXmlDocument.Create(nil); lXml.Active := True; lXml.Version := '1.0'; lXml.Encoding := 'UTF-8'; lNode := lXml.AddChild('Ficha'); lNode.AddChild('Codigo').NodeValue := FCodigo; lNode.AddChild('Nome').NodeValue := FNome; lNode.AddChild('Data').NodeValue := FData; lNode.AddChild('Cargo').NodeValue := FCargo; lXml.SaveToFile(pArquivo); end else if pTipoFicha = tfJson then begin lJSONMarshal := TJSONMarshal.Create(TJSONConverter.Create); try lJson := lJSONMarshal.Marshal(Self); lTexto := TStringList.Create; try lTexto.Text := lJson.ToString; lTexto.SaveToFile(pArquivo); finally lTexto.Free; end; finally lJSONMarshal.Free; lJson.Free; end; end; end; end.
unit MusicEntities; interface uses Generics.Collections, Aurelius.Types.Blob, Aurelius.Types.Nullable, Aurelius.Types.Proxy, Aurelius.Mapping.Attributes; type [Entity, Automapping] TGenre = class strict private FId: integer; FName: string; public constructor Create(const AName: string); overload; property Id: Integer read FId write FId; property Name: string read FName write FName; end; [Entity, Automapping] TArtist = class strict private FId: integer; FName: string; public constructor Create(const AName: string); overload; property Id: Integer read FId write FId; property Name: string read FName write FName; end; [Entity, Automapping] TTrack = class strict private FId: integer; FName: string; FGenre: TGenre; FComposer: Nullable<string>; FMilliseconds: Nullable<integer>; private function GetDuration: string; public constructor Create(const AName: string); overload; constructor Create(const AName: string; AGenre: TGenre); overload; constructor Create(const AName: string; AGenre: TGenre; const AComposer: string); overload; constructor Create(const AName: string; AGenre: TGenre; const AComposer: string; AMilliSeconds: integer); overload; property Id: integer read FId write FId; property Name: string read FName write FName; property Genre: TGenre read FGenre write FGenre; property Composer: Nullable<string> read FComposer write FComposer; property Milliseconds: Nullable<integer> read FMilliseconds write FMilliseconds; property Duration: string read GetDuration; end; [Entity, Automapping] TAlbum = class strict private FId: integer; FName: string; FArtist: TArtist; [ManyValuedAssociation([TAssociationProp.Lazy], CascadeTypeAllRemoveOrphan)] FTracks: Proxy<TList<TTrack>>; function GetTracks: TList<TTrack>; public constructor Create; overload; constructor Create(const AName: string; AArtist: TArtist); overload; destructor Destroy; override; property Id: integer read FId write FId; property Name: string read FName write FName; property Artist: TArtist read FArtist write FArtist; property Tracks: TList<TTrack> read GetTracks; end; implementation uses System.SysUtils; { TGenre } constructor TGenre.Create(const AName: string); begin FName := AName; end; { TArtist } constructor TArtist.Create(const AName: string); begin FName := AName; end; { TTrack } constructor TTrack.Create(const AName: string; AGenre: TGenre); begin FName := AName; FGenre := AGenre; end; constructor TTrack.Create(const AName: string); begin FName := AName; end; constructor TTrack.Create(const AName: string; AGenre: TGenre; const AComposer: string; AMilliSeconds: integer); begin FName := AName; FGenre := AGenre; FComposer := AComposer; FMilliSeconds := AMilliSeconds; end; function TTrack.GetDuration: string; begin Result := Format('%d:%.2d', [ (Milliseconds.ValueOrDefault div 1000) div 60, Milliseconds.ValueOrDefault div 1000 mod 60 ]); end; constructor TTrack.Create(const AName: string; AGenre: TGenre; const AComposer: string); begin FName := AName; FGenre := AGenre; FComposer := AComposer; end; { TAlbum } constructor TAlbum.Create; begin FTracks.SetInitialValue(TList<TTrack>.Create); end; constructor TAlbum.Create(const AName: string; AArtist: TArtist); begin Create; FName := AName; FArtist := AArtist; end; destructor TAlbum.Destroy; begin FTracks.DestroyValue; inherited; end; function TAlbum.GetTracks: TList<TTrack>; begin Result := FTracks.Value; end; initialization RegisterEntity(TAlbum); RegisterEntity(TArtist); RegisterEntity(TGenre); RegisterEntity(TTrack); end.
unit libojcd; interface uses windows, sysutils, Forms, Graphics, classes, IdTCPConnection, registry; const FILEPART_SIZE = 16384; PO_WHO_IS_ONLINE = 0 ; // 广播 PO_ONLINE = 1 ; // 上线 PO_CHANGESETTING = 2 ; // 修改设置 PO_OFFLINE = 3 ; // 下线 PO_NAME_CONF = 4 ; // 名称冲突 // PO_ONLINE_TO_CLIENT = 5 ; // 告诉别的客户端 上线 PO_SHOW_TEST_MESSAGE = 6 ; // 测试客户端连接 { PO_FETCH_REQUEST = 7 ; // 请求收程序 PO_FETCH_REPLY = 8 ; // 收程序的回应。 PO_FILE_INFO = 12 ; // 文件的信息 PO_SEND_RESULT = 9 ; // 发送结果 PO_UPDATE_REQUEST = 10 ; // 请求自动更新 PO_UPDATE_REPLY = 11 ; // 回复自动更新 } PO_OK = 0 ; // 这个文件片段正常 PO_ERROR = 1 ; // 发生错误 PO_BEGIN_SEND = 13 ; PO_COMMAND_EC = 100 ; CS_OK = 0 ; CS_NAME_CONF = 1 ; ClientPort = 12574; ServerPort = 12575; type TName=array[0..63] of char; TClientID=array[0..31] of byte; TClientInfo=record Version: integer; ClientID: TClientID; // 维一标识一个客户端,客户端每次运行时随机生成 Name: TName; WorkDir: array[0..255] of char; AutoStartUp: boolean; Status: integer; OperatingSystem: array[0..255] of char; Permissions: cardinal; UsesComputerName: boolean; end; TPacket=record // cb: cardinal; dwProtocolVersion: cardinal; case dwOperation:cardinal of PO_ONLINE, PO_CHANGESETTING: (ClientInfo: TClientInfo); { PO_FETCH_REPLY: (FileCount: integer);} end; TTCPPacket=record dwOperation:cardinal; FileCount: integer; FileName: string; FileSize: integer; end; TPropertyList=class(TStringList) private function GetName(index: integer): string; procedure SetName(index: integer; ANewName: string); function GetValue(index: integer): string; procedure SetValue(index: integer; ANewValue: string); public property Name[index: integer]:string read GetName write SetName; property Value[index: integer]:string read GetValue write SetValue; end; THeader=object Command: string; Properties: TPropertyList; procedure ReadFrom(Connection: TIdTCPConnection); procedure WriteTo(Connection: TIdTCPConnection); end; { TFilePart=record Status: integer; Data: array[0..65535] of byte; end; } var ClientInfo: TClientInfo; procedure InitPacket(var APacket: TPacket); implementation procedure InitPacket(var APacket: TPacket); begin APacket.dwProtocolVersion:=1; APacket.ClientInfo:=ClientInfo; end; function TPropertyList.GetName(index: integer): string; begin Result:=trim(copy(Strings[index],1,pos(':',Strings[index])-1)); end; procedure TPropertyList.SetName(index: integer; ANewName: string); begin Strings[index]:=ANewName+': '+Value[index]; end; function TPropertyList.GetValue(index: integer): string; begin Result:=trim(copy(Strings[index],pos(':',Strings[index])+1,maxint)); end; procedure TPropertyList.SetValue(index: integer; ANewValue: string); begin Strings[index]:=Name[index]+': '+ANewValue; end; procedure THeader.ReadFrom(Connection: TIdTCPConnection); var s: string; begin // writeln('======== RECV ========'); Properties.Clear; Command:=Connection.ReadLn; // writeln(command); repeat s:=Connection.ReadLn; // writeln(s); if s='' then break; Properties.Add(s); until false; // writeln('======================'); end; procedure THeader.WriteTo(Connection: TIdTCPConnection); var i:integer; begin // writeln('======== SEND ========'); // writeln(command); Connection.WriteLn(Command); for i:=0 to Properties.Count-1 do begin Connection.WriteLn(Properties.Strings[i]); // writeln(Properties.Strings[i]); end; // writeln; Connection.WriteLn; // writeln('======================'); end; initialization ClientInfo.Version:=95; end.
// Fit4Delphi Copyright (C) 2008. Sabre Inc. // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software Foundation; // either version 2 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with this program; // if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // Derived from Fixture.java by Martin Chernenkoff, CHI Software Design // Ported to Delphi by Michal Wojcik. // unit MusicPlayer; interface uses Music; type TMusicPlayer = class end; var playing : TMusic; paused : integer; function MinutesRemaining : double; function SecondsRemaining : double; procedure Pause; procedure Play(m : TMusic); procedure PlayComplete; procedure PlayStarted; procedure Stop; implementation uses MusicLibrary, Simulator; procedure Stop; begin (* static void stop() { Simulator.nextPlayStarted = 0; Simulator.nextPlayComplete = 0; playComplete(); } *) Simulator.nextPlayStarted := 0; Simulator.nextPlayComplete := 0; playComplete(); end; procedure Pause; begin (* static void pause() { Music.status = "pause"; if (playing != null && paused == 0) { paused = (Simulator.nextPlayComplete - Simulator.time) / 1000.0; Simulator.nextPlayComplete = 0; } } *) Music.status := 'pause'; if (playing <> nil) and (paused = 0) then begin paused := Trunc((Simulator.nextPlayComplete - Simulator.time) * (60 * 60 * 24)); Simulator.nextPlayComplete := 0; end; end; procedure play(m : TMusic); var seconds : double; begin (* static void play(Music m) { if (paused == 0) { Music.status = "loading"; double seconds = m == playing ? 0.3 : 2.5 ; Simulator.nextPlayStarted = Simulator.schedule(seconds); } else { Music.status = "playing"; Simulator.nextPlayComplete = Simulator.schedule(paused); paused = 0; } } *) if (paused = 0) then begin Music.status := 'loading'; if m = playing then seconds := 0.3 else seconds := 2.5; Simulator.nextPlayStarted := Simulator.schedule(seconds); end else begin Music.status := 'playing'; Simulator.nextPlayComplete := Simulator.schedule(paused); paused := 0; end; end; procedure PlayStarted; begin (* static void playStarted() { Music.status = "playing"; playing = MusicLibrary.looking; Simulator.nextPlayComplete = Simulator.schedule(playing.seconds); } *) Music.status := 'playing'; playing := MusicLibrary.looking; Simulator.nextPlayComplete := Simulator.schedule(playing.seconds); end; procedure PlayComplete; begin (* static void playComplete() { Music.status = "ready"; playing = null; } *) Music.status := 'ready'; playing := nil; end; function SecondsRemaining : double; (* static double secondsRemaining() { if (paused != 0) { return paused; } else if (playing != null) { return (Simulator.nextPlayComplete - Simulator.time) / 1000.0; } else { return 0; } } *) begin if (paused <> 0) then result := paused else if (playing <> nil) then result := (Simulator.nextPlayComplete - Simulator.time) * (60*60*24) else result := 0; end; function MinutesRemaining : double; begin result := secondsRemaining / 60; end; initialization playing := nil; paused := 0; end.
unit uCadastroCredoresDevedores; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uBaseCadastro, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Mask, uDmCadastro, uCredoresDevedores, uCrudCredoresDevedores; type TfCadastroCredoresDevedores = class(TfBaseCadastro) Label1: TLabel; Label2: TLabel; edtCodigo: TMaskEdit; edtCredDev: TMaskEdit; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormShow(Sender: TObject); procedure btnSalvarClick(Sender: TObject); procedure dbgCadastroDblClick(Sender: TObject); procedure dbgCadastroKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnAlterarClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); private CredDevCrud : ICrudCredoresDevedores; CredDev: ICredoresDevedores; function ValidaCampos: Boolean; procedure AtualizaGrid; procedure PreencheCampos; procedure PreencheCredDevComEdits; procedure LimpaObjetoCredDev; public { Public declarations } end; var fCadastroCredoresDevedores: TfCadastroCredoresDevedores; implementation uses uUtilidades; {$R *.dfm} { TfCadastroCredoresDevedores } procedure TfCadastroCredoresDevedores.AtualizaGrid; begin CredDevCrud.AtualizaGridCredDev; end; procedure TfCadastroCredoresDevedores.btnAlterarClick(Sender: TObject); begin inherited; PreencheCredDevComEdits; CredDevCrud.Alterar(CredDev); AtualizaGrid; LimparCampos; LimpaObjetoCredDev; end; procedure TfCadastroCredoresDevedores.btnExcluirClick(Sender: TObject); begin inherited; CredDevCrud.Excluir(CredDev); AtualizaGrid; LimparCampos; LimpaObjetoCredDev; end; procedure TfCadastroCredoresDevedores.btnSalvarClick(Sender: TObject); begin inherited; CredDev.Nome := edtCredDev.Text; if not ValidaCampos then Exit; if not TUtilidades.IsEmpty(CredDevCrud.ConsultaPeloNome(CredDev.Nome).Nome) then ShowMessage('Credor/Devedor jŠ existe.') else CredDevCrud.Incluir(CredDev); AtualizaGrid; LimparCampos; LimpaObjetoCredDev; edtCredDev.SetFocus; end; procedure TfCadastroCredoresDevedores.dbgCadastroDblClick(Sender: TObject); begin inherited; PreencheCampos; PreencheCredDevComEdits; end; procedure TfCadastroCredoresDevedores.dbgCadastroKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = VK_RETURN then begin PreencheCampos; PreencheCredDevComEdits; end; end; procedure TfCadastroCredoresDevedores.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; FreeAndNil(dmCadastro); end; procedure TfCadastroCredoresDevedores.FormCreate(Sender: TObject); begin inherited; CredDevCrud := TCrudCredoresDevedores.Create; CredDev := TCredoresDevedores.Create; Application.CreateForm(TdmCadastro, dmCadastro); end; procedure TfCadastroCredoresDevedores.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = VK_F5 then AtualizaGrid; end; procedure TfCadastroCredoresDevedores.FormShow(Sender: TObject); begin inherited; AtualizaGrid; end; procedure TfCadastroCredoresDevedores.LimpaObjetoCredDev; begin CredDev.Codigo := 0; CredDev.Nome := EmptyStr; end; procedure TfCadastroCredoresDevedores.PreencheCampos; begin edtCodigo.Text := IntToStr(dmCadastro.cdsCredDevCODIGO.AsInteger); edtCredDev.Text := dmCadastro.cdsCredDevNOME.AsString; end; procedure TfCadastroCredoresDevedores.PreencheCredDevComEdits; begin CredDev.Codigo := StrToInt(edtCodigo.Text); CredDev.Nome := edtCredDev.Text; end; function TfCadastroCredoresDevedores.ValidaCampos: Boolean; begin Result := True; if TUtilidades.IsEmpty(edtCredDev.Text) then begin Result := False; ShowMessage('Informe o Credor/Devedor.'); edtCredDev.SetFocus; end; end; end.
{******************************************************************************* * * * TksCircleProgress - Circular Progress Component * * * * https://github.com/gmurt/KernowSoftwareFMX * * * * Copyright 2016 Graham Murt * * * * email: graham@kernow-software.co.uk * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * *******************************************************************************} unit ksCircleProgress; interface {$I ksComponents.inc} uses Classes, ksTypes, FMX.Graphics, System.UITypes, System.UIConsts; type TksCircleProgressCaptionType = (ksCirclePercent, ksCircleNone, ksCircleCustom); [ComponentPlatformsAttribute(pidWin32 or pidWin64 or {$IFDEF XE8_OR_NEWER} pidiOSDevice32 or pidiOSDevice64 {$ELSE} pidiOSDevice {$ENDIF} or pidiOSSimulator or pidAndroid)] TksCircleProgress = class(TksControl) private FBitmap: TBitmap; FValue: single; FBackgroundColor: TAlphaColor; FColor: TAlphaColor; FCaptionType: TksCircleProgressCaptionType; FText: string; procedure RecreateBitmap; procedure SetValue(const Value: single); procedure SetColor(const Value: TAlphaColor); procedure SetBackgroundColor(const Value: TAlphaColor); procedure SetCaptionType(const Value: TksCircleProgressCaptionType); procedure SetText(const Value: string); protected procedure Paint; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AnimateToValue(AValue: single; const ADurationSecs: integer = 1); published property CaptionType: TksCircleProgressCaptionType read FCaptionType write SetCaptionType default ksCirclePercent; property Height; property Width; property Size; property Position; property BackgroundColor: TAlphaColor read FBackgroundColor write SetBackgroundColor default claGainsboro; property Color: TAlphaColor read FColor write SetColor default claDodgerblue; property Value: single read FValue write SetValue; property Text: string read FText write SetText; end; procedure Register; implementation uses FMX.Controls, Math, SysUtils, Types, FMX.Types, FMX.Ani; const C_SCALE = 3; procedure Register; begin RegisterComponents('Kernow Software FMX', [TksCircleProgress]); end; { TksCircleProgress } procedure TksCircleProgress.AnimateToValue(AValue: single; const ADurationSecs: integer = 1); begin TAnimator.AnimateFloat(Self, 'Value', AValue, ADurationSecs); end; constructor TksCircleProgress.Create(AOwner: TComponent); begin inherited; FBitmap := TBitmap.Create; FCaptionType := TksCircleProgressCaptionType.ksCirclePercent; FColor := claDodgerblue; FBackgroundColor := claGainsboro; FText := ''; FValue := 0; Width := 150; Height := 150; end; destructor TksCircleProgress.Destroy; begin FreeAndNil(FBitmap); inherited; end; procedure TksCircleProgress.Paint; var r: TRectF; ACaption: string; begin inherited; RecreateBitmap; r := RectF(0, 0, Width, Height); Canvas.DrawBitmap(FBitmap, RectF(0, 0, FBitmap.Width, FBitmap.Height), r, 1, True); ACaption := ''; case FCaptionType of ksCirclePercent: ACaption := ' '+InTToStr(Round(FValue))+'%'; ksCircleCustom: ACaption := Text; end; Canvas.Fill.Color := FColor; Canvas.Font.Size := 24; Canvas.FillText(ClipRect, ACaption, False, 1, [], TTextAlign.Center, TTextAlign.Center); end; procedure TksCircleProgress.RecreateBitmap; var AAngle: single; x1, y1, x2, y2, x3, y3: single; AThickness: integer; begin FBitmap.SetSize(Round(Width*C_SCALE), Round(Height*C_SCALE)); FBitmap.Clear(claNull); FBitmap.Canvas.BeginScene(nil); try AAngle := 0; x1 := Round((Width * C_SCALE)/2); y1 := Round((Height * C_SCALE)/2); AThickness := Round(25 * C_SCALE); FBitmap.Canvas.StrokeThickness := 4; FBitmap.Canvas.Stroke.Color := FBackgroundColor; FBitmap.Canvas.Stroke.Kind := TBrushKind.Solid; while AAngle < 360 do begin x2 := x1 + (cos(DegToRad(AAngle-90)) * (((Width*C_SCALE)/2)-AThickness)); y2 := y1 + (sin(DegToRad(AAngle-90)) * (((Height*C_SCALE)/2)-AThickness)); x3 := x1 + (cos(DegToRad(AAngle-90)) * (((Width*C_SCALE)/2)-4)); y3 := y1 + (sin(DegToRad(AAngle-90)) * (((Height*C_SCALE)/2)-4)); FBitmap.Canvas.DrawLine(PointF(x2, y2), PointF(x3, y3), 1); AAngle := AAngle + 1; end; AAngle := 0; FBitmap.Canvas.StrokeThickness := 4; FBitmap.Canvas.Stroke.Color := FColor; FBitmap.Canvas.Stroke.Kind := TBrushKind.Solid; while AAngle < ((360 / 100) * FValue) do begin x2 := x1 + (cos(DegToRad(AAngle-90)) * (((Width*C_SCALE)/2)-AThickness)); y2 := y1 + (sin(DegToRad(AAngle-90)) * (((Height*C_SCALE)/2)-AThickness)); x3 := x1 + (cos(DegToRad(AAngle-90)) * (((Width*C_SCALE)/2)-4)); y3 := y1 + (sin(DegToRad(AAngle-90)) * (((Height*C_SCALE)/2)-4)); FBitmap.Canvas.DrawLine(PointF(x2, y2), PointF(x3, y3), 1); AAngle := AAngle + 1; end; finally FBitmap.Canvas.EndScene; end; end; procedure TksCircleProgress.SetBackgroundColor(const Value: TAlphaColor); begin if FBackgroundColor <> Value then begin FBackgroundColor := Value; InvalidateRect(ClipRect); end; end; procedure TksCircleProgress.SetCaptionType( const Value: TksCircleProgressCaptionType); begin if FCaptionType <> Value then begin FCaptionType := Value; InvalidateRect(ClipRect); end; end; procedure TksCircleProgress.SetColor(const Value: TAlphaColor); begin if FColor <> Value then begin FColor := Value; InvalidateRect(ClipRect); end; end; procedure TksCircleProgress.SetText(const Value: string); begin if FText <> Value then begin FText := Value; InvalidateRect(ClipRect); end; end; procedure TksCircleProgress.SetValue(const Value: single); begin if FValue <> Value then begin FValue := Value; FValue := Max(FValue, 0); FValue := Min(FValue, 100); InvalidateRect(ClipRect); end; end; end.
unit Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, DataModule, Data.Bind.EngExt, Vcl.Bind.DBEngExt, Data.Bind.Components, Data.Bind.DBScope, Vcl.StdCtrls, System.Rtti, System.Bindings.Outputs, Vcl.Bind.Editors; type TForm1 = class(TForm) btConnectar: TButton; btInserir: TButton; Label1: TLabel; Label2: TLabel; edNome: TEdit; edCod: TEdit; edUltimo: TButton; Memo1: TMemo; btPrimeiro: TButton; btAlterar: TButton; btDeletar: TButton; btAnterior: TButton; btProximo: TButton; procedure btConnectarClick(Sender: TObject); procedure btInserirClick(Sender: TObject); procedure receber_dados(); procedure atualizar(); procedure edUltimoClick(Sender: TObject); procedure btPrimeiroClick(Sender: TObject); procedure btDeletarClick(Sender: TObject); procedure btAlterarClick(Sender: TObject); procedure btAnteriorClick(Sender: TObject); procedure btProximoClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.atualizar; begin with dm do begin Query.SQL.Clear; Query.SQL.Text:='SELECT * FROM cadastro'; Query.Active:=true; Query.Open; ClientDataset.ApplyUpdates(0); //(aplica as modificações) ClientDataSet.Refresh; end; end; procedure TForm1.btAlterarClick(Sender: TObject); begin dm.Query.SQL.Clear; dm.Query.SQL.Add('UPDATE cadastro SET nome = :noum WHERE codigo = :cod'); dm.Query.ParamByName('cod').AsInteger:=strtoint(edCod.Text); dm.Query.ParamByName('noum').AsString:=edNome.Text; dm.Query.ExecSQL(); end; procedure TForm1.btAnteriorClick(Sender: TObject); begin atualizar(); dm.ClientDataSet.Prior; receber_dados(); end; procedure TForm1.btConnectarClick(Sender: TObject); begin with dm do begin try Conn.Connected:=true; Query.SQL.Clear; Query.SQL.Text:='SELECT * FROM cadastro'; Query.Active:=true; Query.Open; ClientDataSet.Active:=true; Showmessage('Conectado ao Banco.'); except On E:Exception Do begin if (E.ClassName = 'EDatabaseError') then begin Showmessage('Conectado a um Banco vazio.'); end else begin Showmessage('Não é possível se conectar ao Banco.'); end; end; end; end; end; procedure TForm1.btDeletarClick(Sender: TObject); begin dm.Query.SQL.Clear; dm.Query.SQL.Add('DELETE FROM cadastro WHERE codigo = :cod'); dm.Query.ParamByName('cod').AsInteger:=strtoint(edCod.Text); dm.Query.ExecSQL(); end; procedure TForm1.btInserirClick(Sender: TObject); begin dm.Query.SQL.Clear; dm.Query.SQL.Add('INSERT INTO cadastro VALUES (:cod, :noum)'); dm.Query.ParamByName('cod').AsInteger:=strtoint(edCod.Text); dm.Query.ParamByName('noum').AsString:=edNome.Text; dm.Query.ExecSQL(); //OBS: O SQL não inseri os registros por ordem de inclusão, fazendo o //remanejamento das linhas de forma automática. Caso queira ordenar dessa //forma é interessante incluir um campo ID ou Data-Hora. end; procedure TForm1.btPrimeiroClick(Sender: TObject); begin atualizar(); dm.ClientDataSet.First; receber_dados(); end; procedure TForm1.btProximoClick(Sender: TObject); begin atualizar(); dm.ClientDataSet.Next; receber_dados(); end; procedure TForm1.edUltimoClick(Sender: TObject); begin atualizar(); dm.ClientDataSet.Last; receber_dados(); end; procedure TForm1.receber_dados; begin edCod.Text:=dm.ClientDataSet.FieldByName('codigo').AsString; edNome.Text:=dm.ClientDataSet.FieldByName('nome').AsString; end; end.
unit mnResStrsU; interface resourcestring {$IFDEF MN_CHINESE} // common SOK = '确定'; SCancel = '取消'; SSave = '保存'; SCheckAll = '全选'; SCheckNone = '全部清除'; // in mnArray SArrayCopySrcIndexError = 'mnArrayCopy的源数组索引越界: %d(总长度:%d)'; SArrayCopyDstIndexError = 'mnArrayCopy的目标数组索引越界: %d(总长度:%d)'; SArrayInsertIndexError = 'mnArrayInsert索引越界: %d(总长度:%d)'; SArrayDeleteIndexError = 'mnArrayDelete索引越界: %d(总长度:%d)'; SArrayTooShort = '数组太短,装不下转换后的variant array:%d < %d'; SVANotDim1 = 'Variant array不是一维的'; SVANotDim2 = 'Variant array不是二维的'; SVANotContainRangeDim2 = 'Variant array[%d, %d, %d, %d]不能包含范围[%d, %d, %d, %d]'; // in mnChinese SDigitNotIn0To9 = '数字必须是0-9中的一个: %d'; SWrongWanYiStrFormat = 'WanYi字符串却不以''万''或''亿''结尾: %s'; // in mnCOM SExcelFileNameNotAssigned = 'Excel文件名未赋值。请使用SaveAs'; SExcelBookNotAssigned = 'ExcelBook未赋值。请调用New或Open'; SSheetIndexError = '工作表索引越界: %d(总长度:%d)'; SAtLeastOneSheet = '必须至少有一个工作表'; SArrayTooShortForExcelRange = '数组太短,装不下Excel范围内的所有元素'; SWordFileNameNotAssigned = 'Word文件名未赋值。请使用SaveAs'; // in mnControl SErrorMsgNotEmpty = '%s不能为空'; SErrorMsgNotEmptyAbs = '%s不能为空,也不能全为空格'; SErrorMsgIsInt = '%s必须是整数'; SErrorMsgIsFloat = '%s必须是浮点数'; SErrorMsgIsDT = '%s必须是有效的时间'; SErrorMsgIsCurr = '%s必须是有效的货币'; SErrorMsgNE0 = '%s不能等于0'; SErrorMsgLT0 = '%s必须小于0'; SErrorMsgLE0 = '%s必须小于或等于0'; SErrorMsgGT0 = '%s必须大于0'; SErrorMsgGE0 = '%s必须大于或等于0'; SErrorMsgSelected = '请选择%s'; // in mnDateTime SIllegalYear = '非法的年份: %d'; SIllegalMonth = '非法的月份: %d'; SDateToLunarOutOfRange = 'mnDateToLunar中,需转换的公历日期超出范围'; SLunarToDateOutOfRange = 'mnLunarToDate中,需转换的农历日期超出范围'; // in mnDB SReleaseActiveDataSet = '尝试释放一个活动的数据集'; SReleaseWildDataSet = '尝试释放一个野数据集: %s'; SUsedDBNotAssigned = 'mnUsedDB没有赋值'; SIllegalTableJoinStyle = '非法的表连接方式'; STableListIndexError = 'mnTTableList索引越界'; SMatchEditNotSupported = 'MatchEdit不被支持'#13#10'名称: %s 类: %s'; SIllegalItemClass = '非法的mnTFieldFilterCombination类: %s'; SPKNameNotFound = '主键名没有找到: %s'; SFieldSchemaNotMatch = '字段结构不匹配数据集'; SIllegalTableSchemaType = '非法的TableSchemaType'; // in mnDebug SGoesToNeverGoesHere = '程序运行到一个NeverGoesHere点'; SAssertionFailed = '断言失败'; SAssertionFailedWithDesc = '断言失败:%s'; // in mnDialog SShouldBeCorrect = '实际值: %s (正确)'; SShouldBeWrong = '实际值: %s (应当是%s)'; SSaveSuccessfully = '成功保存'; SDialogFilterAll = '所有文件(*.*)|*.*'; SDialogFilterText = '文本文件(*.txt)|*.txt'; SDialogFilterExcel = 'Excel文件(*.xls;*.xlsx)|*.xls;*.xlsx'; SDialogFilterWord = 'Word文件(*.doc;*.docx)|*.doc;*.docx'; SDialogFilterXML = 'XML文件(*.xml)|*.xml'; // in mnFile SFileNotExists = '文件不存在: %s'; // in mnGraphics SDrawingCanvasNotAssigned = 'DrawingCanvas没有赋值'; SGraphicListIndexError = 'mnTGraphicList访问内部图像时索引越界: %d(总长度:%d)'; SPixeledImageNameNotFound = '没有在mnTPixeledImageList里找到名称'; // in mnMath SSectionsTooShort = 'Sections太短了,装不下Ordinal'; // in mnNetwork SHTTPThreadTerminated = 'HTTP线程被终止'; // in mnSQL SCompareDTNotSupportExcel = 'Excel数据库不支持mnSQLCompareDT'; // in mnString SAnsiPosOffsetOnTrailByte = '在尝试调用mnAnsiPosEx时,起始位置在一个尾字节上: 起始位置:%d 字符串:%s'; STruncMiddleIndexError = 'mnTruncMiddle索引越界: %d(总长度:%d)'; STruncBMiddleIndexError = 'mnTruncBMiddle索引越界: %d(总长度:%d)'; SSplitWithoutBorder = '被分割的字符串没有带边: %s'; SSplittedLenNegative = '分割长度必须是正整数: %d'; SContinuousTwoParams = '连续的两个参数: %s'; // in mnSystem SIllegalRelationOp = '非法的关系运算符'; SWrongPercentStrTail = '带百分号的字符串没有以"%%"结尾: %s'; SIllegalLLStrForInt = '非法的用于整数的LL文法字符串: %s'; SIllegalLLStrForFloat = '非法的用于浮点数的LL文法字符串: %s'; SIllegalStrConstraint = '非法的字符串约束'; SMethodNotFound = '名字"%s"不是对象"%s"的一个published成员'; STryToAddDuplicateItem = '尝试往TypeList里添加一个重复成员: %s'; SArrayTooShortForList = '数组太短,无法装载TypeList的所有元素'; SMakeStatOnEmptyList = '尝试对一个空列表进行统计'; SWrongBOM = '错误的BOM'; SIllegalTimeUnit = '非法的时间单位'; SCoordinatesTableColumnIndexError = 'mnTCoordinatesTable列的索引越界: %d(总长度:%d)'; SCoordinatesTableRowIndexError = 'mnTCoordinatesTable行的索引越界: %d(总长度:%d)'; SIllegalExternalCommandExecutionResult = '非法的外部命令执行结果'; SExternalCommandExecutionException = '外部命令执行出现异常:'; SExternalCommandExecutionHalted = '外部命令执行中止:'; SExternalCommandExecutionFreezed = '外部命令执行冻结:'; SAbnormalExternalCommandAnnouncementFile = '外部命令的宣告文件没有正常生成'; // in mnTPC SItemPrecisionShoudBeNumeric = 'SetItemPrecision只能用于TcxCalcEditProperties或TcxCurrencyEditProperties'; // in mnWindows SShutdownPrivilegeError = '设置关机权限时出错'; SWindowNotExists = '窗口不存在'; {$ELSE} // common SOK = 'OK'; SCancel = 'Cancel'; SSave = 'Save'; SCheckAll = 'Check All'; SCheckNone = 'Check None'; // in mnArray SArrayCopySrcIndexError = 'mnArrayCopy source index out of bounds: %d of length %d'; SArrayCopyDstIndexError = 'mnArrayCopy destination index out of bounds: %d of length %d'; SArrayInsertIndexError = 'mnArrayInsert index out of bounds: %d of length %d'; SArrayDeleteIndexError = 'mnArrayDelete index out of bounds: %d of length %d'; SArrayTooShort = 'Array is too short to hold converted variant array: %d < %d'; SVANotDim1 = 'Variant array is not one-dimensional'; SVANotDim2 = 'Variant array is not two-dimensional'; SVANotContainRangeDim2 = 'Variant array[%d, %d, %d, %d] can''t contain range[%d, %d, %d, %d]'; // in mnChinese SDigitNotIn0To9 = 'Digit must be in 0-9: %d'; SWrongWanYiStrFormat = 'WanYi string doesn''t end with ''万'' or ''亿'': %s'; // in mnCOM SExcelFileNameNotAssigned = 'Excel file name not assigned. Please use SaveAs'; SExcelBookNotAssigned = 'ExcelBook not assigned. Please call New or Open'; SSheetIndexError = 'Work sheet index out of bounds: %d of length %d'; SAtLeastOneSheet = 'Must have at least one work sheet'; SArrayTooShortForExcelRange = 'Array is too short to hold all elements of excel range'; SWordFileNameNotAssigned = 'Word file name not assigned. Please use SaveAs'; // in mnControl SErrorMsgNotEmpty = '%s must not be empty'; SErrorMsgNotEmptyAbs = '%s must not be empty or space-only'; SErrorMsgIsInt = '%s must be an integer'; SErrorMsgIsFloat = '%s must be a float'; SErrorMsgIsDT = '%s must be a valid datetime'; SErrorMsgIsCurr = '%s must be a valid currency'; SErrorMsgNE0 = '%s must not be equal to 0'; SErrorMsgLT0 = '%s must be less than 0'; SErrorMsgLE0 = '%s must be less than or equal to 0'; SErrorMsgGT0 = '%s must be greater than 0'; SErrorMsgGE0 = '%s must be greater than or equal to 0'; SErrorMsgSelected = '%s must be selected'; // in mnDateTime SIllegalYear = 'Illegal year: %d'; SIllegalMonth = 'Illegal month: %d'; SDateToLunarOutOfRange = 'mnDateToLunar out of range'; SLunarToDateOutOfRange = 'mnLunarToDate out of range'; // in mnDB SReleaseActiveDataSet = 'Try to release an active dataset'; SReleaseWildDataSet = 'Try to release a wild dataset: %s'; SUsedDBNotAssigned = 'mnUsedDB not assigned'; SIllegalTableJoinStyle = 'Illegal table join style'; STableListIndexError = 'mnTTableList index out of bounds'; SMatchEditNotSupported = 'MatchEdit not supported'#13#10'Name: %s Class: %s'; SIllegalItemClass = 'Illegal item class of mnTFieldFilterCombination: %s'; SPKNameNotFound = 'Primary key name not found: %s'; SFieldSchemaNotMatch = 'Field schema doesn''t match dataset'; SIllegalTableSchemaType = 'Illegal TableSchemaType'; // in mnDebug SGoesToNeverGoesHere = 'Goes to a NeverGoesHere point'; SAssertionFailed = 'Assertion failed'; SAssertionFailedWithDesc = 'Assertion failed: %s'; // in mnDialog SShouldBeCorrect = 'Actual: %s (correct)'; SShouldBeWrong = 'Actual: %s (should be %s)'; SSaveSuccessfully = 'Save successfully'; SDialogFilterAll = 'All Files(*.*)|*.*'; SDialogFilterText = 'Text Files(*.txt)|*.txt'; SDialogFilterExcel = 'Excel Files(*.xls;*.xlsx)|*.xls;*.xlsx'; SDialogFilterWord = 'Word Files(*.doc;*.docx)|*.doc;*.docx'; SDialogFilterXML = 'XML Files(*.xml)|*.xml'; // in mnFile SFileNotExists = 'File does not exist: %s'; // in mnGraphics SDrawingCanvasNotAssigned = 'DrawingCanvas not assigned'; SGraphicListIndexError = 'mnTGraphicList index out of bounds: %d of length %d'; SPixeledImageNameNotFound = 'Name not found in mnTPixeledImageList'; // in mnMath SSectionsTooShort = 'Sections is too short for Ordinal'; // in mnNetwork SHTTPThreadTerminated = 'HTTP thread terminated'; // in mnSQL SCompareDTNotSupportExcel = 'mnSQLCompareDT is not supported by Excel database'; // in mnString SAnsiPosOffsetOnTrailByte = 'Try to call mnAnsiPosEx with offset on a trail byte: %d of %s'; STruncMiddleIndexError = 'mnTruncMiddle index out of bounds: %d of length %d'; STruncBMiddleIndexError = 'mnTruncBMiddle index out of bounds: %d of length %d'; SSplitWithoutBorder = 'No border in the splitted string: %s'; SSplittedLenNegative = 'Splitted length should be a positive integer: %d'; SContinuousTwoParams = 'Continuous two parameters: %s'; // in mnSystem SIllegalRelationOp = 'Illegal relation operator'; SWrongPercentStrTail = 'Percent string doesn''t end with "%%": %s'; SIllegalLLStrForInt = 'Illegal LL grammar string for integer: %s'; SIllegalLLStrForFloat = 'Illegal LL grammar string for float: %s'; SIllegalStrConstraint = 'Illegal string constraint'; SMethodNotFound = 'Name "%s" does not specify a published method for the object "%s"'; STryToAddDuplicateItem = 'Try to add a duplicate item into TypeList: %s'; SArrayTooShortForList = 'Array is too short to hold all elements of TypeList'; SMakeStatOnEmptyList = 'Try to make statistics on an empty list'; SWrongBOM = 'Wrong BOM'; SIllegalTimeUnit = 'Illegal time unit'; SCoordinatesTableColumnIndexError = 'mnTCoordinatesTable column index out of bounds: %d of length %d'; SCoordinatesTableRowIndexError = 'mnTCoordinatesTable row index out of bounds: %d of length %d'; SIllegalExternalCommandExecutionResult = 'Illegal external command execution result'; SExternalCommandExecutionException = 'Execution with exception:'; SExternalCommandExecutionHalted = 'Execution halted:'; SExternalCommandExecutionFreezed = 'Execution freezed:'; SAbnormalExternalCommandAnnouncementFile = 'Abnormal announcement file of external command'; // in mnTPC SItemPrecisionShoudBeNumeric = 'SetItemPrecision should be used only on TcxCalcEditProperties or TcxCurrencyEditProperties'; // in mnWindows SShutdownPrivilegeError = 'Error in setting shutdown privilege'; SWindowNotExists = 'Window does not exist'; {$ENDIF} implementation end.