text
stringlengths
14
6.51M
unit SaleOrder; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, DBGridEh, ExtCtrls, StdCtrls, ComCtrls, ToolWin, DateUtils; type TSaleOrderForm = class(TForm) Panel1: TPanel; CloseButton: TButton; DBGridEh1: TDBGridEh; DBGridEh2: TDBGridEh; ToolBar1: TToolBar; ToolButton1: TToolButton; InsertButton: TToolButton; EditButton: TToolButton; DeleteButton: TToolButton; ToolButton2: TToolButton; Edit1: TEdit; ToolButton3: TToolButton; PayButton: TToolButton; PrintButton: TToolButton; Splitter1: TSplitter; ToolButton4: TToolButton; RefreshButton: TToolButton; procedure EnabledButtons; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure CloseButtonClick(Sender: TObject); procedure Edit1Change(Sender: TObject); procedure InsertButtonClick(Sender: TObject); procedure EditButtonClick(Sender: TObject); procedure DeleteButtonClick(Sender: TObject); procedure PayButtonClick(Sender: TObject); procedure PrintButtonClick(Sender: TObject); procedure RefreshButtonClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DBGridEh1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumnEh; State: TGridDrawState); procedure DBGridEh1TitleBtnClick(Sender: TObject; ACol: Integer; Column: TColumnEh); procedure DBGridEh2DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumnEh; State: TGridDrawState); private { Private declarations } public { Public declarations } end; var SaleOrderForm: TSaleOrderForm; implementation uses Main, StoreDM, SaleProperSelect, SaleOrderItem, SaleStructure, PaymentOrder, PrintOrder; {$R *.dfm} procedure TSaleOrderForm.EnabledButtons; begin // Если записей нету, то Деактивируем кнопки "Редактировать" и "Удалить", // а если есть, Активируем. if StoreDataModule.SaleOrderDataSet.IsEmpty then begin EditButton.Enabled := False; EditButton.ShowHint := False; DeleteButton.Enabled := False; DeleteButton.ShowHint := False; PayButton.Enabled := False; PayButton.ShowHint := False; PrintButton.Enabled := False; PrintButton.ShowHint := False; end else begin EditButton.Enabled := True; EditButton.ShowHint := True; DeleteButton.Enabled := True; DeleteButton.ShowHint := True; PayButton.Enabled := True; PayButton.ShowHint := True; PrintButton.Enabled := True; PrintButton.ShowHint := True; end; end; procedure TSaleOrderForm.FormCreate(Sender: TObject); begin with StoreDataModule do begin // SaleOrderDataSet.SelectSQL.Strings[3] := 'AND ("Orders"."Date" >= ''' + TopDate + ''' AND ' + '"Orders"."Date" <= ''' + BottomDate + ''')'; // ShowMessage(SaleOrderDataSet.SelectSQL.Text); SaleOrderDataSet.Open; SaleStructureDataSet.Open; end; CloseButton.Left := Panel1.Width - CloseButton.Width - 10; Caption := 'Расходные документы (' + TopDate + '-' + BottomDate + ')'; EnabledButtons; end; procedure TSaleOrderForm.FormClose(Sender: TObject; var Action: TCloseAction); begin CurOrderID := 0; with StoreDataModule do begin SaleOrderDataSet.Close; SaleOrderDataSet.SelectSQL.Strings[4] := ''; SaleOrderDataSet.SelectSQL.Strings[SaleOrderDataSet.SelectSQL.Count - 1] := 'ORDER BY "Date", "OrderID"'; SaleStructureDataSet.Close; end; // Удаление форму при ее закрытии SaleOrderForm := nil; Action := caFree; end; procedure TSaleOrderForm.CloseButtonClick(Sender: TObject); begin Close; end; procedure TSaleOrderForm.Edit1Change(Sender: TObject); var Find : String; begin Find := AnsiUpperCase(Edit1.Text); with StoreDataModule.SaleOrderDataSet do begin Close; SelectSQL.Strings[4] := 'AND (UPPER("CustomerName") CONTAINING ''' + Find + ''')'; Open; end; end; procedure TSaleOrderForm.InsertButtonClick(Sender: TObject); begin StoreDataModule.SaleOrderDataSet.Append; StoreDataModule.SaleOrderDataSet['FirmID'] := MainFirm; StoreDataModule.SaleOrderDataSet['OutDivisionID'] := MainDivision; StoreDataModule.SaleOrderDataSet['Date'] := Now; StoreDataModule.SaleOrderDataSet['PayDate'] := Now; StoreDataModule.SaleOrderDataSet['PriceID'] := MainPrice; //Выбираем Вид Расхода: Опт или Розница SaleProperSelectForm := TSaleProperSelectForm.Create(Self); SaleProperSelectForm.ShowModal; if SaleProperSelectForm.ModalResult = mrOK then begin StoreDataModule.SaleOrderDataSet['ProperID'] := CurProperID; if CurProperID = 2 then StoreDataModule.SaleOrderDataSet['CustomerID'] := RetailCustomerID; //Проставляем Покупателя "Розница" StoreDataModule.SaleOrderDataSet.Post; EnabledButtons; SaleOrderItemForm := TSaleOrderItemForm.Create(Self); SaleOrderItemForm.ShowModal; end else begin StoreDataModule.SaleOrderDataSet.Cancel; end; end; procedure TSaleOrderForm.EditButtonClick(Sender: TObject); begin // StoreDataModule.SaleOrderDataSet.Edit; SaleOrderItemForm := TSaleOrderItemForm.Create(Self); SaleOrderItemForm.ShowModal; end; procedure TSaleOrderForm.DeleteButtonClick(Sender: TObject); var SaleOrderStr : String; begin with StoreDataModule do try SaleOrderStr := SaleOrderDataSet.FieldByName('OrderID').AsString; if Application.MessageBox(PChar('Вы действительно хотите удалить запись "' + SaleOrderStr + '"?'), 'Удаление записи', mb_YesNo + mb_IconQuestion + mb_DefButton2) = idYes then try SaleOrderDataSet.Delete; SaleOrderTransaction.Commit; EnabledButtons; except Application.MessageBox(PChar('Запись "' + SaleOrderStr + '" удалять нельзя.'), 'Ошибка удаления', mb_IconStop); end; {try except} finally if SaleOrderDataSet.Active = False then SaleOrderDataSet.Open; end; {try finally} end; procedure TSaleOrderForm.PayButtonClick(Sender: TObject); begin CurProperID := StoreDataModule.SaleOrderDataSet['ProperID']; PaymentOrderForm := TPaymentOrderForm.Create(Self); PaymentOrderForm.ShowModal; CurOrderID := StoreDataModule.SaleOrderDataSet['OrderID']; StoreDataModule.SaleOrderDataSet.Close; StoreDataModule.SaleOrderDataSet.Open; end; procedure TSaleOrderForm.PrintButtonClick(Sender: TObject); begin PrintOrderForm := TPrintOrderForm.Create(Self); PrintOrderForm.ShowModal; end; procedure TSaleOrderForm.RefreshButtonClick(Sender: TObject); begin CurOrderID := StoreDataModule.SaleOrderDataSet['OrderID']; StoreDataModule.SaleOrderDataSet.Close; StoreDataModule.SaleOrderDataSet.Open; Caption := 'Расходные документы (' + TopDate + '-' + BottomDate + ')'; end; procedure TSaleOrderForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_F2 : InsertButton.Click; VK_F3 : EditButton.Click; VK_F8 : DeleteButton.Click; VK_F4 : Edit1.SetFocus; VK_F9 : PayButton.Click; VK_F10 : PrintButton.Click; VK_F5 : RefreshButton.Click; end; end; procedure TSaleOrderForm.DBGridEh1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumnEh; State: TGridDrawState); begin //Выделяем КРАСНЫМ (СИНИМ) просроченную Оплату with DBGridEh1.Canvas do begin if (StoreDataModule.SaleOrderDataSet['Debt'] > 0) and not (gdFocused in State) then begin if (StoreDataModule.SaleOrderDataSet['PayDate'] < now) then Font.Color := clRed else Font.Color := clBlue; FillRect(Rect); TextOut(Rect.Left, Rect.Top, Column.DisplayText); end else DBGridEh1.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; end; procedure TSaleOrderForm.DBGridEh1TitleBtnClick(Sender: TObject; ACol: Integer; Column: TColumnEh); var i: Integer; begin //Сортировка по клику на заголовке столбца CurOrderID := StoreDataModule.SaleOrderDataSet['OrderID']; if Column.Title.Font.Color = clRed then with StoreDataModule.SaleOrderDataSet do begin SelectSQL.Strings[SelectSQL.Count - 1] := 'ORDER BY "OrderID"'; Close; Open; for i := 0 to DBGridEh1.Columns.Count - 1 do begin DBGridEh1.Columns.Items[i].Title.Font.Color := clWindowText; end; end else with StoreDataModule.SaleOrderDataSet do begin SelectSQL.Strings[SelectSQL.Count - 1] := 'ORDER BY "' + Column.FieldName + '", "OrderID"'; Close; Open; for i := 0 to DBGridEh1.Columns.Count - 1 do begin DBGridEh1.Columns.Items[i].Title.Font.Color := clWindowText; end; Column.Title.Font.Color := clRed; end; end; procedure TSaleOrderForm.DBGridEh2DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumnEh; State: TGridDrawState); var ItemNo: String; begin //Проставляем номера по порядку в строках Документа with DBGridEh2.Canvas do begin if StoreDataModule.SaleStructureDataSet.RecNo <> 0 then ItemNo := IntToStr(StoreDataModule.SaleStructureDataSet.RecNo) else ItemNo := ''; if Column.Index = 0 then begin FillRect(Rect); TextOut(Rect.Right - 3 - TextWidth(ItemNo), Rect.Top, ItemNo); end else DBGridEh2.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; end; end.
unit uTurtle; {$mode delphi}{$H+} interface uses Classes, SysUtils, fgl, uGrammatik, uStringEntwickler, uZeichnerBase, fpjson, jsonparser, jsonConf, uZeichnerInit; // Die Entitaet, die sich auf dem Bildschirm herumbewegt, // um den L-Baum zu zeichnen type TTurtle = class private FGrammatik: TGrammatik; FZeichner: TZeichnerBase; // poly... FStringEntwickler: TStringEntwickler; FName: String; FVisible: Boolean; FMaximaleStringLaenge: Int64; // setter-Funktionen fuer die properties procedure setzeWinkel(const phi: Real); procedure setzeRekursionsTiefe(const tiefe: Cardinal); procedure setzeVisible(const vis: Boolean); procedure setzeName(const name: String); procedure setzeMaximaleStringLaenge(const mxStringLaenge: Int64); // getter-Funktionen fuer die properties function gibAxiom : String; function gibRawRegeln : TRegelDictionary; function gibRekursionsTiefe : Cardinal; function gibWinkel : Real; function gibStartPunkt : TPunkt3D; function gibZeichnerName : String; function gibEntwickelterString : String; function gibZuZeichnenderString : String; public constructor Create(gram: TGrammatik; zeichner: TZeichnerBase; maximaleStringLaenge: Int64=100000); overload; constructor Create(gram: TGrammatik; zeichner: TZeichnerBase; stringEntwickler: TStringEntwickler; maximaleStringLaenge: Int64=100000); overload; { Aufgabe: Liest eine Turtle aus einer json-Datei aus. } constructor Create(datei: String); overload; destructor Destroy; override; // properties //// FGrammatik property axiom: String read gibAxiom; property regeln: TRegelDictionary read gibRawRegeln; //// FZeichner property zeichnerName: String read gibZeichnerName; property winkel: Real read gibWinkel write setzeWinkel; property rekursionsTiefe: Cardinal read gibRekursionsTiefe write setzeRekursionsTiefe; property startPunkt: TPunkt3D read gibStartPunkt; //// property visible: Boolean read FVisible write setzeVisible; property name: String read FName write setzeName; property maximaleStringLaenge: Int64 read FMaximaleStringLaenge write setzeMaximaleStringLaenge; property entwickelterString: String read gibEntwickelterString; property zuZeichnenderString: String read gibZuZeichnenderString; // setter-Funktionen (public) procedure setzeStartPunkt(const x,y,z: Real); procedure setzeZeichnerName(const neuerName: String); procedure aendereParameter(para: TStringList); // getter-Funktionen (public) function gibParameter : TStringList; { Aufgabe: Zeichenen des Strings, der in dem Stringentwickler ist. Sollte der String eine bestimmte Laenge ueberschritten haben, so wird dieser String nicht gezeichnet. Rueckgabe: Wenn der String gezeichet wurde, so wird wahr zurueckgegeben. Wenn der String nicht gezeichnet wurde, so wird falsch zurueckgegeben. } function zeichnen : Boolean; { Aufgabe: Speichert die Turtle mit seinen Eigenschaften in einer json-Datei } procedure speichern(datei: String); function copy : TTurtle; end; implementation uses uMatrizen,dglOpenGL; constructor TTurtle.Create(gram: TGrammatik; zeichner: TZeichnerBase; maximaleStringLaenge: Int64 = 100000); begin FGrammatik := gram; FZeichner := zeichner; FStringEntwickler := TStringEntwickler.Create(gram); FStringEntwickler.entwickeln(FZeichner.rekursionsTiefe); FMaximaleStringLaenge := maximaleStringLaenge; FName := ''; FVisible := true; end; constructor TTurtle.Create(gram: TGrammatik; zeichner: TZeichnerBase; stringEntwickler: TStringEntwickler; maximaleStringLaenge:Int64 = 100000); begin FGrammatik := gram; FZeichner := zeichner; FStringEntwickler := stringEntwickler; FMaximaleStringLaenge := maximaleStringLaenge; FName := ''; FVisible := true; end; constructor TTurtle.Create(datei: String); var conf: TJSONConfig; tmp_pfad, tmp_produktion, zeichenArt: String; tmp_zufaelligkeit: Real; regelnLinkeSeite, regelnRechteSeite: TStringList; regelnLinkeSeiteIdx, regelnRechteSeiteIdx: Cardinal; zeichenPara: TZeichenParameter; zeichnerInit: TZeichnerInit; begin FGrammatik := TGrammatik.Create; conf:= TJSONConfig.Create(nil); regelnLinkeSeite := TStringList.Create; try conf.filename:= datei; FName := AnsiString(conf.getValue('name', '')); FVisible := conf.getValue('visible', true); FMaximaleStringLaenge := conf.getValue('Maximale Stringlaenge',0); zeichenArt := AnsiString(conf.getValue('Zeichen Art', '')); zeichenPara.winkel := conf.getValue( 'Zeichen Parameter/winkel', 45 ); zeichenPara.rekursionsTiefe := conf.getValue( 'Zeichen Parameter/rekursions Tiefe', 0 ); zeichenPara.setzeStartPunkt( conf.getValue('Zeichen Parameter/startPunkt/x', 0), conf.getValue('Zeichen Parameter/startPunkt/y', 0), conf.getValue('Zeichen Parameter/startPunkt/z', 0) ); FGrammatik.axiom := AnsiString(conf.getValue('Grammatik/axiom', '')); // if axiom = '' then // exception conf.EnumSubKeys(UnicodeString('Grammatik/regeln/'),regelnLinkeSeite); for regelnLinkeSeiteIdx := 0 to regelnLinkeSeite.Count - 1 do begin tmp_pfad := 'Grammatik/regeln/' + regelnLinkeSeite[regelnLinkeSeiteIdx]; regelnRechteSeite := TStringList.Create; conf.EnumSubKeys(UnicodeString(tmp_pfad), regelnRechteSeite); for regelnRechteSeiteIdx := 0 to regelnRechteSeite.Count - 1 do begin tmp_produktion := AnsiString(conf.getValue( UnicodeString(tmp_pfad + '/' + regelnRechteSeite[regelnRechteSeiteIdx] + '/produktion'), '' )); tmp_zufaelligkeit := conf.getValue( UnicodeString(tmp_pfad + '/' + regelnRechteSeite[regelnRechteSeiteIdx] + '/zufaelligkeit'), 0.0 ); FGrammatik.addRegel( regelnLinkeSeite[regelnLinkeSeiteIdx], tmp_produktion, tmp_zufaelligkeit ); end; FreeAndNil(regelnRechteSeite); end; FreeAndNil(regelnLinkeSeite); finally conf.Free; end; FStringEntwickler := TStringEntwickler.Create(FGrammatik); zeichnerinit := TZeichnerInit.Create; FZeichner := zeichnerinit.initialisiere(zeichenArt, zeichenPara); FStringEntwickler.entwickeln(FZeichner.rekursionsTiefe); end; destructor TTurtle.Destroy; begin FreeAndNil(FGrammatik); FreeAndNil(FZeichner); FreeAndNil(FStringEntwickler); FreeAndNil(FName); FreeAndNil(FVisible); FreeAndNil(FMaximaleStringLaenge); inherited; end; ////////////////////////////////////////////////////////// // setter-Funktionen ////////////////////////////////////////////////////////// procedure TTurtle.setzeWinkel(const phi: Real); begin FZeichner.winkel := phi; end; procedure TTurtle.setzeRekursionsTiefe(const tiefe: Cardinal); begin FZeichner.rekursionsTiefe := tiefe; FStringEntwickler.entwickeln(FZeichner.rekursionsTiefe); end; procedure TTurtle.setzeStartPunkt(const x,y,z: Real); begin FZeichner.setzeStartPunkt(x,y,z); end; procedure TTurtle.setzeZeichnerName(const neuerName: String); var zeichnerInit: TZeichnerInit; begin zeichnerInit := TZeichnerInit.Create; FZeichner := zeichnerInit.initialisiere(neuerName, FZeichner.gibZeichenParameter); end; procedure TTurtle.aendereParameter(para: TStringList); begin FGrammatik.aendereParameter(para); FStringEntwickler.aendereParameter(para); end; procedure TTurtle.setzeVisible(const vis: Boolean); begin FVisible := vis; end; procedure TTurtle.setzeName(const name: String); begin FName := name; end; procedure TTurtle.setzeMaximaleStringLaenge(const mxStringLaenge: Int64); begin FMaximaleStringLaenge := mxStringLaenge; end; // Parameter: Startpunkt der Turtle procedure init(sx,sy,sz:Real); begin glMatrixMode(GL_ModelView); ObjKOSInitialisieren; ObjInEigenKOSVerschieben(sx,sy,sz); end; ////////////////////////////////////////////////////////// // getter-Funktionen ////////////////////////////////////////////////////////// function TTurtle.gibRekursionsTiefe : Cardinal; begin result := FZeichner.rekursionsTiefe; end; function TTurtle.gibWinkel : Real; begin result := FZeichner.winkel; end; function TTurtle.gibStartPunkt : TPunkt3D; begin result := FZeichner.startPunkt; end; function TTurtle.gibZeichnerName : String; begin result := FZeichner.name; end; function TTurtle.gibEntwickelterString : String; begin result := FStringEntwickler.entwickelterString; end; function TTurtle.gibZuZeichnenderString : String; begin result := FStringEntwickler.zuZeichnenderString; end; function TTurtle.gibAxiom : String; begin result := FGrammatik.axiom; end; function TTurtle.gibRawRegeln : TRegelDictionary; begin result := FGrammatik.rawRegeln; end; function TTurtle.gibParameter : TStringList; begin result := FGrammatik.gibParameter; end; // zeichner function TTurtle.zeichnen : Boolean; VAR i: Cardinal; paraList : TStringList; zuZeichnenderBuchstabe: Char; tmp_string: String; begin if length(FStringEntwickler.zuZeichnenderString) > FMaximaleStringLaenge then exit(false); init(FZeichner.startPunkt.x,FZeichner.startPunkt.y,FZeichner.startPunkt.z); paralist:=TStringList.Create; i := 1; while (i <= length(FStringEntwickler.zuZeichnenderString)) do begin FreeAndNil(paraList); // damit es keine leaks gibt paraList := TStringList.Create; zuZeichnenderBuchstabe := FStringEntwickler.zuZeichnenderString[i]; if (i <> length(FStringEntwickler.zuZeichnenderString) - 1) and (FStringEntwickler.zuZeichnenderString[i+1] = '(') then begin inc(i); while (true) do begin if (FStringEntwickler.zuZeichnenderString[i] = ';') then begin paraList.add(tmp_string); tmp_string := ''; inc(i); continue; end else if (FStringEntwickler.zuZeichnenderString[i] = ')') then begin paraList.add(tmp_string); tmp_string := ''; break; end else if (FStringEntwickler.zuZeichnenderString[i] = '(') then begin tmp_string := ''; inc(i); continue; end; tmp_string += FStringEntwickler.zuZeichnenderString[i]; inc(i); end; end; FZeichner.zeichneBuchstabe(zuZeichnenderBuchstabe,paraList); inc(i); end; FreeAndNil(paraList); result := true; end; // speichern procedure TTurtle.speichern(datei: String); var regelIdx, produktionIdx: Cardinal; conf: TJSONConfig; tmp_path: String; begin conf:= TJSONConfig.Create(Nil); try DeleteFile(datei); conf.Filename:= datei; conf.setValue('name', UnicodeString(FName)); conf.setValue('visible', FVisible); conf.setValue('Maximale Stringlaenge', FMaximaleStringLaenge); conf.setValue('Zeichen Art', UnicodeString(FZeichner.name)); conf.setValue('Zeichen Parameter/winkel', FZeichner.winkel); conf.setValue('Zeichen Parameter/rekursions Tiefe', FZeichner.rekursionsTiefe); conf.setValue('Zeichen Parameter/startPunkt/x', FZeichner.startPunkt.x); conf.setValue('Zeichen Parameter/startPunkt/y', FZeichner.startPunkt.y); conf.setValue('Zeichen Parameter/startPunkt/z', FZeichner.startPunkt.z); conf.setValue('Grammatik/axiom', UnicodeString(FGrammatik.axiom)); for regelIdx := 0 to FGrammatik.rawRegeln.Count - 1 do begin tmp_path := 'Grammatik/regeln/' + FGrammatik.rawRegeln.keys[regelIdx] + '/Regel '; for produktionIdx := 0 to (FGrammatik.rawRegeln.data[regelIdx]).Count - 1 do begin conf.setValue( UnicodeString(tmp_path + IntToStr(produktionIdx+1) + '/produktion'), UnicodeString(FGrammatik.rawRegeln.data[regelIdx][produktionIdx].produktion) ); conf.setValue( UnicodeString(tmp_path + IntToStr(produktionIdx+1) + '/zufaelligkeit'), FGrammatik.rawRegeln.data[regelIdx][produktionIdx].zufaelligkeit ); end; end; finally conf.Free; end; end; function TTurtle.copy : TTurtle; var turtle: TTurtle; gram: TGrammatik; zeichner: TZeichnerBase; entwickler:TStringEntwickler; begin gram := FGrammatik.copy; zeichner := FZeichner.copy; entwickler := FStringEntwickler.copy; turtle := TTurtle.Create(gram,zeichner,entwickler); turtle.name := system.copy(FName,1,length(FName)); turtle.visible := FVisible; turtle.maximaleStringLaenge := FMaximaleStringLaenge; result := turtle; end; end.
program calcfivenubmers; const numbersCount:integer = 5; number1:integer = 45; number2:integer = 7; number3:integer = 68; number4:integer = 2; number5:integer = 34; var sum:integer; average:real; begin writeln('Number of integers = ', numbersCount); writeln('Number1 = ', number1); writeln('Number2 = ', number2); writeln('Number3 = ', number3); writeln('Number4 = ', number4); writeln('Number5 = ', number5); sum := number1 + number2 + number3 + number4 + number5; average := sum / numbersCount; writeln('Sum = ', sum); writeln('Average = ', average); end.
unit UCompression; interface uses ZLib, Classes; procedure CompressionStream(var ASrcStream: TMemoryStream; ACompressionLevel: integer = 2); // 压缩流 procedure UnCompressionStream(var ASrcStream: TMemoryStream); // 解压缩 implementation procedure UnCompressionStream(var ASrcStream: TMemoryStream); // 解压缩 var nTmpStream: TDecompressionStream; nDestStream: TMemoryStream; nBuf: array [1 .. 512] of Byte; nSrcCount: integer; begin ASrcStream.Position := 0; nDestStream := TMemoryStream.Create; nTmpStream := TDecompressionStream.Create(ASrcStream); try repeat // 读入实际大小 nSrcCount := nTmpStream.Read(nBuf, SizeOf(nBuf)); if nSrcCount > 0 then nDestStream.Write(nBuf, nSrcCount); until (nSrcCount = 0); ASrcStream.Clear; ASrcStream.LoadFromStream(nDestStream); ASrcStream.Position := 0; finally nDestStream.Clear; nDestStream.Free; nTmpStream.Free; end; end; procedure CompressionStream(var ASrcStream: TMemoryStream; ACompressionLevel: integer = 2); // 压缩流 var nDestStream: TMemoryStream; nTmpStream: TCompressionStream; nCompressionLevel: TCompressionLevel; begin ASrcStream.Position := 0; nDestStream := TMemoryStream.Create; try // 级别 case ACompressionLevel of 0: nCompressionLevel := clNone; 1: nCompressionLevel := clFastest; 2: nCompressionLevel := clDefault; 3: nCompressionLevel := clMax; else nCompressionLevel := clMax; end; // 开始压缩 nTmpStream := TCompressionStream.Create(nCompressionLevel, nDestStream); try ASrcStream.SaveToStream(nTmpStream); finally nTmpStream.Free; // 释放后nDestStream才会有数据 end; ASrcStream.Clear; ASrcStream.LoadFromStream(nDestStream); ASrcStream.Position := 0; finally nDestStream.Clear; nDestStream.Free; end; end; end.
{****************************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 2000-2002 Borland Software Corporation } { } {****************************************************************} unit SockApp; interface uses SockHTTP, Classes, IdTCPConnection, IdTCPServer; type TStartMode = (smNormal, smRegServer, smUnregServer); TWebAppSockObjectFactory = class(TObject) private FClassName: string; FStartMode: TStartMode; function GetProgID: string; function GetFileName: string; procedure Initialize; public procedure UpdateRegistry(Register: Boolean); constructor Create(const ClassName: string); property ProgID: string read GetProgID; property StartMode: TStartMode read FStartMode; property FileName: string read GetFileName; end; implementation uses SysUtils, WebReq, WebCntxt, SockRequestInterpreter, SockTransport, IndySockTransport, SockAppReg, SockAppNotify; var FSockWebRequestHandler: TSockWebRequestHandler; function SockWebRequestHandler: TWebRequestHandler; begin if not Assigned(FSockWebRequestHandler) then FSockWebRequestHandler := TSockWebRequestHandler.Create(nil); Result := FSockWebRequestHandler; end; type // Implement the IWebRequest interface using a socket data block interpreter TSockWebRequestAccess = class(TInterfacedObject, ISockWebRequestAccess) private FInterpreter: TWebRequestDataBlockInterpreter; function GetFieldByName(const Name: string): string; function ReadClient(var Buffer: string; Count: Integer): Integer; function TranslateURI(const Value: string): string; function WriteClient(const Buffer: string): Integer; function GetStringVariable(Index: Integer): string; function WriteHeaders(StatusCode: Integer; StatusText: string; Headers: string): Boolean; function UsingStub: Boolean; function ReadString(var Buffer: string; Count: Integer): Integer; public constructor Create(AInterpreter: TWebRequestDataBlockInterpreter); end; // Interpret a web request encapsulated in a socket data block TWebRequestDataBlockInterpreterHandleRequest = class(TWebRequestDataBlockInterpreter) protected function DoHandleRequest(Data: IDataBlock): IDataBlock; override; end; // Listen for requests from web app debugger TWebRequestListener = class(TObject) private FConnection: TIdTCPServer; procedure ServerExecute(AThread: TIdPeerThread); function GetPort: Integer; public constructor Create; destructor Destroy; override; property Port: Integer read GetPort; end; constructor TWebRequestListener.Create; begin inherited; FConnection := TIdTCPServer.Create(nil); FConnection.DefaultPort := 0; FConnection.Active := True; FConnection.OnExecute := ServerExecute; end; destructor TWebRequestListener.Destroy; begin FConnection.Active := False; FConnection.Free; inherited; end; function TWebRequestListener.GetPort: Integer; begin Result := FConnection.Bindings[0].Port; end; procedure TWebRequestListener.ServerExecute(AThread: TIdPeerThread); var DataBlockInterpreter: TWebRequestDataBlockInterpreter; Transport: ITransport; DataBlock: IDataBlock; begin with AThread.Connection do begin try Transport := TIndyTCPConnectionTransport.Create(AThread.Connection); DataBlock := Transport.Receive(True, 0); try Assert(DataBlock <> nil, 'nil datablock'); DataBlockInterpreter := TWebRequestDataBlockInterpreterHandleRequest.Create(TLogSendDataBlock.Create(Transport)); try DataBlockInterpreter.InterpretData(DataBlock); finally DataBlockInterpreter.Free; end; finally Transport := nil; DataBlock := nil; end; finally // jmt.!!! Don't disconnect? // Disconnect; end; end; end; // Handle a request from web app debugger function TWebRequestDataBlockInterpreterHandleRequest.DoHandleRequest(Data: IDataBlock): IDataBlock; var RetVal: Variant; begin try TSockWebRequestHandler(SockWebRequestHandler).Run(TSockWebRequestAccess.Create(Self)); except on E: Exception do begin WriteVariant(E.Message, Data); Data.Signature := ResultSig or asError; Exit; end; end; RetVal := True; WriteVariant(RetVal, Data); Data.Signature := ResultSig or asHandleRequest; Result := FSendDataBlock.Send(Data, True); end; var WebRequestListener: TWebRequestListener; { TSockWebRequestAccess } constructor TSockWebRequestAccess.Create(AInterpreter: TWebRequestDataBlockInterpreter); begin FInterpreter := AInterpreter; inherited Create; end; function TSockWebRequestAccess.GetFieldByName(const Name: string): string; begin Result := FInterpreter.CallGetFieldByName(Name); end; function TSockWebRequestAccess.GetStringVariable(Index: Integer): string; begin Result := FInterpreter.CallGetStringVariable(Index); end; function TSockWebRequestAccess.ReadClient(var Buffer: string; Count: Integer): Integer; begin Result := FInterpreter.CallReadClient(Buffer, Count); end; function TSockWebRequestAccess.ReadString(var Buffer: string; Count: Integer): Integer; begin Result := FInterpreter.CallReadString(Buffer, Count); end; function TSockWebRequestAccess.TranslateURI(const Value: string): string; begin Result := FInterpreter.CallTranslateURI(Value); end; function TSockWebRequestAccess.UsingStub: Boolean; begin Result := FInterpreter.CallUsingStub; end; function TSockWebRequestAccess.WriteClient(const Buffer: string): Integer; begin Result := FInterpreter.CallWriteClient(Buffer); end; function TSockWebRequestAccess.WriteHeaders(StatusCode: Integer; StatusText, Headers: string): Boolean; begin Result := FInterpreter.CallWriteHeaders(StatusCode, StatusText, Headers); end; var RunningWebAppNotifier: TRunningWebAppNotifier; WebAppSockObjectFactory: TWebAppSockObjectFactory; { TWebAppSockObjectFactory } constructor TWebAppSockObjectFactory.Create( const ClassName: string); function FindSwitch(const Switch: string): Boolean; begin Result := FindCmdLineSwitch(Switch, ['-', '/'], True); end; begin WebAppSockObjectFactory := Self; FClassName := ClassName; if FindSwitch('REGSERVER') then FStartMode := smRegServer else if FindSwitch('UNREGSERVER') then FStartMode := smUnregServer else FStartMode := smNormal; end; function TWebAppSockObjectFactory.GetFileName: string; begin Result := GetModuleName(hinstance); end; function TWebAppSockObjectFactory.GetProgID: string; begin if FClassName <> '' then Result := ChangeFileExt(ExtractFileName(FileName), '') + '.' + FClassName else Result := ''; end; {$IFDEF LINUX} procedure NotifyWebAppDbg; var fd: Integer; PipeStream: THandleStream; S: string; begin if ParamStr(1) = sExecWaitToken then begin fd := StrToInt(ParamStr(2)); PipeStream := THandleStream.Create(fd); try S := ParamStr(1); PipeStream.Write(S[1], Length(S)); finally PipeStream.Free; end; end; end; {$ENDIF} procedure TWebAppSockObjectFactory.Initialize; begin UpdateRegistry(StartMode <> smUnregServer); if StartMode <> smNormal then Halt; WebRequestListener := TWebRequestListener.Create; RunningWebAppNotifier := TRunningWebAppNotifier.Create(WebRequestListener.Port, WebAppSockObjectFactory.ProgID, WebAppSockObjectFactory.FileName); RunningWebAppNotifier.Register; {$IFDEF LINUX} NotifyWebAppDbg; {$ENDIF} end; procedure TWebAppSockObjectFactory.UpdateRegistry(Register: Boolean); begin if Register then SockAppReg.RegisterWebApp(GetModuleName(hinstance), GetProgID) else SockAppReg.UnregisterWebApp(GetProgID); end; var SaveInitProc: Pointer = nil; SaveExitProc: Pointer = nil; procedure InitApp; begin if SaveInitProc <> nil then TProcedure(SaveInitProc); if WebAppSockObjectFactory <> nil then WebAppSockObjectFactory.Initialize; end; procedure FinalizeApp; begin if RunningWebAppNotifier <> nil then begin RunningWebAppNotifier.Unregister; RunningWebAppNotifier.Free; end; if SaveExitProc <> nil then TProcedure(ExitProc); FreeAndNil(WebAppSockObjectFactory); FreeAndNil(WebRequestListener); FreeAndNil(FSockWebRequestHandler); end; initialization WebReq.WebRequestHandlerProc := SockWebRequestHandler; SaveInitProc := InitProc; InitProc := @InitApp; SaveExitProc := ExitProc; ExitProc := @FinalizeApp; end.
unit UMyWin; {$mode objfpc}{$H+} interface uses Classes, Windows,SysUtils, Registry, ShellAPI, ComObj; type TMyWin=class Public function IsAdministrator(): Boolean; function IsAdministratorAccount(): Boolean; function IsUACEnabled(): Boolean; Function IsElevated(): Boolean; Private // Procedure GenWarDir(RutaBase,javahome:String;var Memo:TRichMemo;var TrayIcon1:TTrayIcon;var StausBar1:TStatusBar;var QErrores:Integer;nomwar:String=''); end; implementation function CheckTokenMembership(TokenHandle: THANDLE; SidToCheck: Pointer; var IsMember: BOOL): BOOL; stdcall; external advapi32 name 'CheckTokenMembership'; function TMyWin.IsAdministrator(): Boolean; var psidAdmin: Pointer; B: BOOL; const SECURITY_NT_AUTHORITY: TSidIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 5)); SECURITY_BUILTIN_DOMAIN_RID = $00000020; DOMAIN_ALIAS_RID_ADMINS = $00000220; SE_GROUP_USE_FOR_DENY_ONLY = $00000010; begin psidAdmin := nil; try // Создаём SID группы админов для проверки Win32Check(AllocateAndInitializeSid(SECURITY_NT_AUTHORITY, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, psidAdmin)); // Проверяем, входим ли мы в группу админов (с учётов всех проверок на disabled SID) if CheckTokenMembership(0, psidAdmin, B) then Result := B else Result := False; finally if psidAdmin <> nil then FreeSid(psidAdmin); end; end; {$R-} function IsAdministratorAccount: Boolean; var psidAdmin: Pointer; Token: THandle; Count: DWORD; TokenInfo: PTokenGroups; HaveToken: Boolean; I: Integer; const SECURITY_NT_AUTHORITY: TSidIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 5)); SECURITY_BUILTIN_DOMAIN_RID = $00000020; DOMAIN_ALIAS_RID_ADMINS = $00000220; SE_GROUP_USE_FOR_DENY_ONLY = $00000010; begin Result := Win32Platform <> VER_PLATFORM_WIN32_NT; if Result then Exit; psidAdmin := nil; TokenInfo := nil; HaveToken := False; try Token := 0; HaveToken := OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, Token); if (not HaveToken) and (GetLastError = ERROR_NO_TOKEN) then HaveToken := OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, Token); if HaveToken then begin Win32Check(AllocateAndInitializeSid(SECURITY_NT_AUTHORITY, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, psidAdmin)); if GetTokenInformation(Token, TokenGroups, nil, 0, Count) or (GetLastError <> ERROR_INSUFFICIENT_BUFFER) then RaiseLastOSError; TokenInfo := PTokenGroups(AllocMem(Count)); Win32Check(GetTokenInformation(Token, TokenGroups, TokenInfo, Count, Count)); for I := 0 to TokenInfo^.GroupCount - 1 do begin Result := EqualSid(psidAdmin, TokenInfo^.Groups[I].Sid); if Result then Break; end; end; finally if TokenInfo <> nil then FreeMem(TokenInfo); if HaveToken then CloseHandle(Token); if psidAdmin <> nil then FreeSid(psidAdmin); end; end; {$R+} function IsUACEnabled: Boolean; var Reg: TRegistry; begin Result := CheckWin32Version(6, 0); if Result then begin Reg := TRegistry.Create(KEY_READ); try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey('\Software\Microsoft\Windows\CurrentVersion\Policies\System', False) then if Reg.ValueExists('EnableLUA') then Result := (Reg.ReadInteger('EnableLUA') <> 0) else Result := False else Result := False; finally FreeAndNil(Reg); end; end; end; function TMyWin.IsElevated(): Boolean; const TokenElevation = TTokenInformationClass(20); type TOKEN_ELEVATION = record TokenIsElevated: DWORD; end; var TokenHandle: THandle; ResultLength: Cardinal; ATokenElevation: TOKEN_ELEVATION; HaveToken: Boolean; begin if CheckWin32Version(6, 0) then begin TokenHandle := 0; HaveToken := OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, TokenHandle); if (not HaveToken) and (GetLastError = ERROR_NO_TOKEN) then HaveToken := OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, TokenHandle); if HaveToken then begin try ResultLength := 0; if GetTokenInformation(TokenHandle, TokenElevation, @ATokenElevation, SizeOf(ATokenElevation), ResultLength) then Result := ATokenElevation.TokenIsElevated <> 0 else Result := False; finally CloseHandle(TokenHandle); end; end else Result := False; end else Result := IsAdministrator; end; end.
unit LongFilenameOperations; interface // These procedures should replace the Delphi internal AssignFile(), Reset(), etc. // functions. These functions should be able to support long file names // by using the WinAPI (the "long filename" mode is switched when the file // name format \\?\ is used). procedure MyAssignFile(var hFile: THandle; filename: string); procedure MyReset(hFile: THandle); procedure MyRewrite(hFile: THandle); procedure MyWriteLn(hFile: THandle; s: AnsiString); procedure MyReadLn(hFile: THandle; var s: string); procedure MyCloseFile(hFile: THandle); function MyEOF(hFile: THandle): boolean; procedure MyBlockRead(var hFile: THandle; var Buffer; RecordCount: integer; var RecordsRead: integer); implementation uses Windows, SysUtils; procedure MyAssignFile(var hFile: THandle; filename: string); begin hFile := CreateFile(PChar(filename), GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, 0); if hFile = INVALID_HANDLE_VALUE then begin if GetLastError = ERROR_ACCESS_DENIED then begin hFile := CreateFile(PChar(filename), GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, 0); if hFile = INVALID_HANDLE_VALUE then RaiseLastOSError; end else RaiseLastOSError; end; end; procedure MyReset(hFile: THandle); begin SetFilePointer(hFile, 0, nil, FILE_BEGIN); end; procedure MyRewrite(hFile: THandle); begin SetFilePointer(hFile, 0, nil, FILE_BEGIN); SetEndOfFile(hFile); end; procedure MyWriteLn(hFile: THandle; s: AnsiString); var numWritten: Cardinal; begin s := s + #13#10; WriteFile(hFile, s[1], Length(s), numWritten, nil); if Cardinal(Length(s)) <> numWritten then RaiseLastOSError; end; procedure MyReadLn(hFile: THandle; var s: string); var buf: array [0..0] of ansichar; dwread: LongWord; begin s := ''; ReadFile(hFile, buf, 1, dwread, nil); while (dwread > 0) do begin if buf[0] <> #13 then // Note: The first line of SFV files contains a comment ended with LF while the other lines end with CR-LF begin if buf[0] = #10 then exit; s := s + string(buf[0]); end; Readfile(hFile, buf, 1, dwread, nil); end; end; procedure MyCloseFile(hFile: THandle); begin CloseHandle(hFile); end; function MyEOF(hFile: THandle): boolean; var buf: array [0..0] of ansichar; dwread: LongWord; begin Readfile(hFile, buf, 1, dwread, nil); if dwread > 0 then begin SetFilePointer(hFile, -dwread, nil, FILE_CURRENT); result := false; end else begin result := true; end; end; procedure MyBlockRead(var hFile: THandle; var Buffer; RecordCount: integer; var RecordsRead: integer); var RecordCount2, RecordsRead2: Cardinal; begin RecordCount2 := RecordCount; RecordsRead2 := RecordsRead; ReadFile(hFile, Buffer, RecordCount2, RecordsRead2, nil); //RecordCount := RecordCount2; RecordsRead := RecordsRead2; end; end.
unit pkc11302; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, Datelib, db, Func, OnEditBaseCtrl, OnEditStdCtrl, OnEditBtnCtrl, OnEditCombo, OnEditNumCtl, Mask; type TAllData = Record Empno :array[1..3000] of String[04]; { 사번 } Taxrate :array[1..3000] of String[03]; { 세율 } Taxamt :array[1..3000] of String[10]; { 세액 } End; TFpkc11302 = class(TForm) Phelpmsg: TPanel; Panel5: TPanel; Panel1: TPanel; Label3: TLabel; Label5: TLabel; BB_Save: TBitBtn; OpenDialog1: TOpenDialog; Panel2: TPanel; CBpaytype: TComboBox; Panel3: TPanel; CB_Type1: TComboBox; Panel6: TPanel; Panel7: TPanel; Label4: TLabel; Label6: TLabel; Label7: TLabel; Label9: TLabel; Label1: TLabel; Panel4: TPanel; Edatafile: TEdit; Button2: TButton; Label2: TLabel; CB_Type2: TOnNumberEdit; MEPaydate: TMaskEdit; Panel8: TPanel; SBfrdate: TSpeedButton; Eerrorfile: TEdit; Label8: TLabel; Label10: TLabel; procedure Button2Click(Sender: TObject); procedure BB_SaveClick(Sender: TObject); procedure CB_Type1Change(Sender: TObject); procedure FormShow(Sender: TObject); procedure SBfrdateClick(Sender: TObject); private { Private declarations } Function CSV_Save(Idx:Integer):Boolean; Function new_PassEmp(var cmd : Pchar; gu : integer; separ:String) : string; public { Public declarations } LastRec : Integer; k : integer; All_data : TAllData; F1, F2 : TextFile; ErrorText : string; // 오류 내용 Error_file : string; P : PChar; ch: string; A: array[0..50] of Char; end; var Fpkc11302: TFpkc11302; implementation uses pkc11303, pkc11301, FormMon1; {$R *.DFM} procedure TFpkc11302.Button2Click(Sender: TObject); begin if OpenDialog1.Execute then begin AssignFile(F1, OpenDialog1.Filename); Reset(F1); Edatafile.text := OpenDialog1.FileName; p := pchar(Edatafile.text); Eerrorfile.text := ExtractFileDir(OpenDialog1.FileName) + '\급여세금계산관리엑셀업로드.bad'; Error_file := Eerrorfile.text; AssignFile(F2, Error_file); Rewrite(F2); end; end; procedure TFpkc11302.BB_SaveClick(Sender: TObject); var Error_text: String; GoodData,BadData: Integer; //정상,비정상 자료 count j: integer; begin if IDNo = Application.MessageBox(PChar('일괄생성작업을 하시겠습니까?'),'작업안내',MB_YesNo+MB_ICONWARNING) then Exit; if (CB_Type1.ItemIndex = 3) and (Edatafile.text = '') then begin ShowMessage('엑셀 CSV 화일명이 없습니다. 확인후 다시 작업하세요.'); Edatafile.SetFocus; Exit; end; Try Ora_Session.StartTransaction; //일괄삭제 DM.Query2.Close; DM.Query2.SQL.Clear; DM.Query2.SQL.Add('delete from Pkyeartax '); DM.Query2.SQL.Add(' where paydate = :paydate '); DM.Query2.SQL.Add(' and paytype = :paytype '); DM.Query2.ParamByName('Paydate').AsString := MEPaydate.text; DM.Query2.ParamByName('paytype').AsString := InttoStr(CBpaytype.ItemIndex); DM.Query2.ExecSQL; if (CB_Type1.ItemIndex = 0) or (CB_Type1.ItemIndex = 1) then //기본세율, 세액으로 생성 begin DM.Ory_Pkyeartax_Save.Close; DM.Ory_Pkyeartax_Save.ParamByName('workyy').AsString := copy(MEPaydate.text,1,4); DM.Ory_Pkyeartax_Save.ParamByName('Paydate').AsString := MEPaydate.text; DM.Ory_Pkyeartax_Save.ParamByName('paytype').AsString := InttoStr(CBpaytype.ItemIndex); DM.Ory_Pkyeartax_Save.ParamByName('WRITEMAN').AsString := Pempno; if CB_Type1.ItemIndex = 0 then begin DM.Ory_Pkyeartax_Save.ParamByName('TaxRate').AsFloat := CB_Type2.Value; DM.Ory_Pkyeartax_Save.ParamByName('TaxAmt').AsFloat := 0; end else begin DM.Ory_Pkyeartax_Save.ParamByName('TaxRate').AsFloat := 0; DM.Ory_Pkyeartax_Save.ParamByName('TaxAmt').AsFloat := CB_Type2.Value; end; DM.Ory_Pkyeartax_Save.ExecSQL; end else if CB_Type1.ItemIndex = 2 then //전월로 동일하게 생성 begin DM.Ory_Pkyeartax_Save2.Close; DM.Ory_Pkyeartax_Save2.ParamByName('workyy').AsString := copy(MEPaydate.text,1,4); DM.Ory_Pkyeartax_Save2.ParamByName('Paydate').AsString := MEPaydate.text; DM.Ory_Pkyeartax_Save2.ParamByName('BPaydate').AsString := Copy(AddMonStr(MEPaydate.text +'01',-1),1,6); //전월 DM.Ory_Pkyeartax_Save2.ParamByName('paytype').AsString := InttoStr(CBpaytype.ItemIndex); DM.Ory_Pkyeartax_Save2.ParamByName('WRITEMAN').AsString := Pempno; DM.Ory_Pkyeartax_Save2.ExecSQL; end else if CB_Type1.ItemIndex = 3 then //엑셀 csv 자료를 일괄업로드 begin //일괄생성 DM.Ory_Pkyeartax_Save.Close; DM.Ory_Pkyeartax_Save.ParamByName('workyy').AsString := copy(MEPaydate.text,1,4); DM.Ory_Pkyeartax_Save.ParamByName('Paydate').AsString := MEPaydate.text; DM.Ory_Pkyeartax_Save.ParamByName('paytype').AsString := InttoStr(CBpaytype.ItemIndex); DM.Ory_Pkyeartax_Save.ParamByName('WRITEMAN').AsString := Pempno; DM.Ory_Pkyeartax_Save.ParamByName('TaxRate').AsFloat := 100; //기본으로 셋팅 DM.Ory_Pkyeartax_Save.ParamByName('TaxAmt').AsFloat := 0; DM.Ory_Pkyeartax_Save.ExecSQL; //엑셀자료를 반영 (세율과, 세액만 갱신) k := 1; GoodData := 0; BadData := 0; while not Eof(F1) do begin with All_data do begin Readln(F1, Ch); StrPCopy(A,ch); P := A; Empno[k] := new_passemp(P,0,','); //사번 Taxrate[k] := new_passemp(P,1,','); //세율 Taxamt[k] := new_passemp(P,2,','); //세액 k := k+1; end; end; LastRec := k - 1; k := 1; For j := 1 to LastRec do begin ErrorText := ''; PHelpMsg.Caption := ' [ ' + IntToStr(k) + ' / ' + IntToStr(LastRec) + ' ] 에 대해 저장 작업 중...'; Application.ProcessMessages; if CSV_Save(k) then Inc(Gooddata) else begin Error_text := All_data.empno[k] +','+All_data.Taxrate[k] +','+ All_data.Taxamt[k]+','+ ErrorText; Writeln(F2, Error_text); // Error File에 기록 Inc(Baddata); end; Inc(k); end; CloseFIle(F2); PHelpMsg.Caption := Format('작업을 모두 마쳤습니다.. 총자료건수 %d 건 , 저장건수 %d 건, 오류건수 %d 건', [LastRec , GoodData, BadData]); end; Ora_Session.Commit; Except on E: EDatabaseError do begin MessageBox(handle,PChar(E.Message),'에 러',MB_OK or $0010); Ora_Session.Rollback; Exit; end; end; phelpmsg.caption := '생성되었습니다... '; end; {=============================================================================== Insert_Record Function ================================================================================} Function TFpkc11302.CSV_Save(Idx:Integer):Boolean; begin with Dm.Query1 do begin Close; Sql.Clear; SQL.Add('update Pkyeartax set '); SQL.Add(' TaxRate = :TaxRate, '); SQL.Add(' TaxAmt = :TaxAmt, '); SQL.Add(' writetime = to_char(sysdate, ''YYYYMMDDHH24miss''), '); SQL.Add(' writeman = :WRITEMAN '); Sql.Add('where Paydate = :Paydate and paytype = :paytype and empno = :empno '); ParamByName('empno').AsString := All_Data.EmpNo[Idx]; ParamByName('Paydate').AsString := MEPaydate.text; ParamByName('paytype').AsString := InttoStr(CBpaytype.ItemIndex); ParamByName('TaxRate').AsString := All_Data.TaxRate[Idx]; ParamByName('TaxAmt').AsString := All_Data.TaxAmt[Idx]; ParamByName('WRITEMAN').AsString := Pempno; Try Execsql; Except On E:EDATABASEERROR Do begin close; Result := False; ErrorText := 'SQL ERROR'; Application.MessageBox('SQL ERROR','경고',Mb_Ok +Mb_IconError); end; end; Result := True; Close; end; end; Function TFpkc11302.new_PassEmp(var cmd : Pchar; gu : integer; separ:String) : string; var str : string; begin new_PassEmp := ''; str := ''; str := strpas(cmd); case gu of 0 : new_PassEmp := pasString(str,separ,1); 1 : new_PassEmp := pasString(str,separ,2); 2 : new_PassEmp := pasString(str,separ,3); 3 : new_PassEmp := pasString(str,separ,4); 4 : new_PassEmp := pasString(str,separ,5); 5 : new_PassEmp := pasString(str,separ,6); 6 : new_PassEmp := pasString(str,separ,7); 7 : new_PassEmp := pasString(str,separ,8); 8 : new_PassEmp := pasString(str,separ,9); 9 : new_PassEmp := pasString(str,separ,10); end; end; procedure TFpkc11302.CB_Type1Change(Sender: TObject); begin if CB_Type1.ItemIndex = 3 then Panel6.Visible := True else Panel6.Visible := False; if (CB_Type1.ItemIndex = 0) or (CB_Type1.ItemIndex = 1) then begin CB_Type2.Visible := True; if CB_Type1.ItemIndex = 0 then Label2.Visible := True else Label2.Visible := False; end else begin CB_Type2.Visible := False; Label2.Visible := False; end; end; procedure TFpkc11302.FormShow(Sender: TObject); begin CBpaytype.ItemIndex := 0; CB_Type1.ItemIndex := 0; MEPaydate.Text := FormatDateTime('YYYYMM', Now); end; procedure TFpkc11302.SBfrdateClick(Sender: TObject); begin Try MonthForm := TMonthForm.Create(Application); MonthForm.rDayCaption := MEPaydate.Text; MonthForm.ShowModal; MEPaydate.Text := MonthForm.DayCaption; Finally MonthForm.Free; End; end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC db command preprocessor } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.Phys.SQLPreprocessor; interface uses System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Param, FireDAC.Phys.Intf; type TFDPhysPreprocessorInstr = (piCreateParams, piCreateMacros, piExpandParams, piExpandMacros, piExpandEscapes, piParseSQL, piTransformQuestions, piTransformEOLs); TFDPhysPreprocessorInstrs = set of TFDPhysPreprocessorInstr; TFDPhysPreprocessor = class(TObject) private // control FConnMetadata: IFDPhysConnectionMetadata; FParams: TFDParams; FMacrosUpd, FMacrosRead: TFDMacros; FInstrs: TFDPhysPreprocessorInstrs; FDesignMode: Boolean; FNameDelims1, FNameDelims2: TFDByteSet; FParamMark: TFDPhysParamMark; FNested: Boolean; // runtime FPrevCh, FCh: Char; FSource, FDestination: String; FSourceLen: Integer; FSrcIndex, FCommitedIndex, FDestinationIndex: Integer; FInComment1, FInComment2, FInStr1, FInStr2, FInStr3, FInMySQLConditional, FInProgramBlock: Boolean; FInNames: TFDPhysNameQuoteLevels; FEscapeLevel, FBraceLevel, FParamCount, FSkipEscapes: Integer; FParamCache: TFDStringList; FDestStack: TFDStringList; FTokens: TFDStringList; FQuoteTags: TFDStringList; FSQLCommandKind: TFDPhysCommandKind; FSQLFromValue: String; FSQLOrderByPos: Integer; FSQLValuesPos: Integer; FSQLValuesPosEnd: Integer; FSQLLimitSkip: Integer; FSQLLimitRows: Integer; FInIntoEscape, FWasIntoEscape: Boolean; procedure Commit(ASkip: Integer = 0); procedure Uncommit(AChars: Integer); procedure WriteStr(const AStr: String); procedure PushWriter; function PopWriter: String; function GetChar: Char; procedure PutBack; procedure SkipWS; function ProcessIdentifier(ADotAllowed: Boolean; var AIsQuoted: Boolean): String; procedure ProcessParam; procedure ProcessQuestion; procedure ProcessMacro(AFirstCh: Char); function ProcessEscape: TFDPhysEscapeKind; function TranslateEscape(var AEscape: TFDPhysEscapeData): String; function ProcessCommand: String; procedure ParseDestination; procedure Missed(const AStr: String); procedure ProcessQuoteTag; public constructor Create; destructor Destroy; override; procedure Init; procedure Execute; // R/W property ConnMetadata: IFDPhysConnectionMetadata read FConnMetadata write FConnMetadata; property Source: String read FSource write FSource; property Destination: String read FDestination; property Params: TFDParams read FParams write FParams; property MacrosUpd: TFDMacros read FMacrosUpd write FMacrosUpd; property MacrosRead: TFDMacros read FMacrosRead write FMacrosRead; property Instrs: TFDPhysPreprocessorInstrs read FInstrs write FInstrs; property DesignMode: Boolean read FDesignMode write FDesignMode; // R/O property SQLCommandKind: TFDPhysCommandKind read FSQLCommandKind; property SQLFromValue: String read FSQLFromValue; property SQLOrderByPos: Integer read FSQLOrderByPos; property SQLValuesPos: Integer read FSQLValuesPos; property SQLValuesPosEnd: Integer read FSQLValuesPosEnd; property SQLLimitSkip: Integer read FSQLLimitSkip; property SQLLimitRows: Integer read FSQLLimitRows; end; implementation uses System.SysUtils, Data.DB, System.Character, FireDAC.Stan.Util, FireDAC.Stan.Error, FireDAC.Stan.Consts; { ---------------------------------------------------------------------------- } { TFDPhysPreprocessor } { ---------------------------------------------------------------------------- } constructor TFDPhysPreprocessor.Create; begin inherited Create; FDestStack := TFDStringList.Create; FParamCache := TFDStringList.Create(dupAccept, True, False); FTokens := TFDStringList.Create; FQuoteTags := TFDStringList.Create; FSQLLimitSkip := -1; FSQLLimitRows := -1; end; { ---------------------------------------------------------------------------- } destructor TFDPhysPreprocessor.Destroy; begin FDFreeAndNil(FTokens); FDFreeAndNil(FParamCache); FDFreeAndNil(FDestStack); FDFreeAndNil(FQuoteTags); inherited Destroy; end; { ---------------------------------------------------------------------------- } procedure TFDPhysPreprocessor.Init; begin FTokens.Clear; FParamCache.Clear; FDestStack.Clear; FQuoteTags.Clear; FDestination := ''; FSQLFromValue := ''; FSQLOrderByPos := 0; FSQLValuesPos := 0; FSQLValuesPosEnd := 0; FSQLCommandKind := skUnknown; FSQLLimitSkip := -1; FSQLLimitRows := -1; FInComment1 := False; FInMySQLConditional := False; FInComment2 := False; FInStr1 := False; FInStr2 := False; FInStr3 := False; FInNames := []; FInProgramBlock := False; FSrcIndex := 0; FCommitedIndex := 0; FEscapeLevel := 0; FBraceLevel := 0; FParamCount := 0; FCh := #0; FPrevCh := #0; FWasIntoEscape := False; end; { ---------------------------------------------------------------------------- } procedure TFDPhysPreprocessor.Execute; var i: Integer; eQuote: TFDPhysNameQuoteLevel; begin ASSERT(not ((MacrosRead = nil) and (piExpandMacros in Instrs) or (MacrosUpd = nil) and (piCreateMacros in Instrs) or (Params = nil) and (Instrs * [piCreateParams, piExpandParams] <> []) or (ConnMetadata = nil) and (Instrs * [piExpandEscapes, piParseSQL] <> []))); if FSource = '' then Exit; Include(FInstrs, piTransformQuestions); FNameDelims1 := []; FNameDelims2 := []; if ConnMetadata <> nil then begin for eQuote := Low(TFDPhysNameQuoteLevel) to High(TFDPhysNameQuoteLevel) do begin Include(FNameDelims1, Byte(ConnMetadata.NameQuoteChar[eQuote, nsLeft])); Include(FNameDelims2, Byte(ConnMetadata.NameQuoteChar[eQuote, nsRight])); end; FNameDelims1 := FNameDelims1 - [0, Byte(' ')]; FNameDelims2 := FNameDelims2 - [0, Byte(' ')]; if (Params <> nil) and (Params.BindMode = pbByNumber) then FParamMark := ConnMetadata.PositionedParamMark else FParamMark := ConnMetadata.NamedParamMark; end; FDestinationIndex := 1; SetLength(FDestination, 512); FSourceLen := Length(FSource); if piCreateParams in Instrs then begin for i := 0 to Params.Count - 1 do FParamCache.AddObject(AnsiUpperCase(Params[i].Name), Params[i]); FParamCount := Params.Count; Params.BeginUpdate; end; if ([piCreateParams, piExpandParams] * Instrs <> []) and not FNested then Params.Markers.Clear; try FDestination := ProcessCommand; if piParseSQL in Instrs then begin if FEscapeLevel > 0 then Missed('}'); ParseDestination; end; finally if piCreateParams in Instrs then Params.EndUpdate; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysPreprocessor.Missed(const AStr: String); begin FDException(Self, [S_FD_LPhys], er_FD_AccPrepMissed, [AStr]); end; {-------------------------------------------------------------------------------} procedure TFDPhysPreprocessor.Commit(ASkip: Integer = 0); var iLen: Integer; begin iLen := FSrcIndex - FCommitedIndex + ASkip; if FCommitedIndex + iLen >= FSourceLen then iLen := FSourceLen - FCommitedIndex; if iLen > 0 then begin while FDestinationIndex + iLen - 1 > Length(FDestination) do SetLength(FDestination, Length(FDestination) * 2); Move((PChar(FSource) + FCommitedIndex)^, (PChar(FDestination) + FDestinationIndex - 1)^, iLen * SizeOf(Char)); FDestinationIndex := FDestinationIndex + iLen; end; FCommitedIndex := FSrcIndex; end; {-------------------------------------------------------------------------------} procedure TFDPhysPreprocessor.Uncommit(AChars: Integer); begin Dec(FCommitedIndex, AChars); end; {-------------------------------------------------------------------------------} procedure TFDPhysPreprocessor.WriteStr(const AStr: String); var iLen: Integer; begin iLen := Length(AStr); if iLen > 0 then begin while FDestinationIndex + iLen - 1 > Length(FDestination) do SetLength(FDestination, Length(FDestination) * 2); Move(PChar(AStr)^, (PChar(FDestination) + FDestinationIndex - 1)^, iLen * SizeOf(Char)); FDestinationIndex := FDestinationIndex + iLen; end; FCommitedIndex := FSrcIndex; end; {-------------------------------------------------------------------------------} procedure TFDPhysPreprocessor.PushWriter; begin FDestStack.AddInt(FDestination, FDestinationIndex); SetLength(FDestination, 512); FDestinationIndex := 1; FCommitedIndex := FSrcIndex; end; {-------------------------------------------------------------------------------} function TFDPhysPreprocessor.PopWriter: String; begin Commit; Result := Copy(FDestination, 1, FDestinationIndex - 1); FDestination := FDestStack[FDestStack.Count - 1]; FDestinationIndex := FDestStack.Ints[FDestStack.Count - 1]; FDestStack.Delete(FDestStack.Count - 1); FCommitedIndex := FSrcIndex; end; {-------------------------------------------------------------------------------} function TFDPhysPreprocessor.GetChar: Char; begin Inc(FSrcIndex); if FSrcIndex > FSourceLen then Result := #0 else Result := FSource[FSrcIndex]; FPrevCh := FCh; FCh := Result; end; {-------------------------------------------------------------------------------} procedure TFDPhysPreprocessor.PutBack; begin Dec(FSrcIndex); FPrevCh := FSource[FSrcIndex]; FCh := FPrevCh; end; {-------------------------------------------------------------------------------} procedure TFDPhysPreprocessor.SkipWS; var ch: Char; begin repeat ch := GetChar; until (ch > ' ') or (ch = #0); if ch <> #0 then PutBack; end; {-------------------------------------------------------------------------------} function TFDPhysPreprocessor.ProcessIdentifier(ADotAllowed: Boolean; var AIsQuoted: Boolean): String; var aBuff: array [0 .. 255] of Char; i: Integer; eQuote: TFDPhysNameQuoteLevel; function ProcessQuotedDelim(ADelim1, ADelim2: Char; var AName: String): Boolean; begin Result := False; if not FDInSet(ADelim1, [#0, ' ']) and (FCh = ADelim1) then begin AIsQuoted := True; repeat Inc(i); if i = 256 then FDException(Self, [S_FD_LPhys], er_FD_AccPrepTooLongIdent, []); aBuff[i] := GetChar; until FDInSet(aBuff[i], [#0, ADelim2]); SetString(AName, aBuff, i); Result := True; end end; begin Result := ''; AIsQuoted := False; i := -1; if ConnMetadata <> nil then begin GetChar; for eQuote := Low(TFDPhysNameQuoteLevel) to High(TFDPhysNameQuoteLevel) do if ProcessQuotedDelim(ConnMetadata.NameQuoteChar[eQuote, nsLeft], ConnMetadata.NameQuoteChar[eQuote, nsRight], Result) then Exit; PutBack; end; repeat Inc(i); if i = 256 then FDException(Self, [S_FD_LPhys], er_FD_AccPrepTooLongIdent, []); aBuff[i] := GetChar; until not (FDInSet(aBuff[i], ['0'..'9', 'a'..'z', 'A'..'Z', '#', '$', '_']) or ADotAllowed and (aBuff[i] = '.')) and not aBuff[i].IsLetter; PutBack; SetString(Result, aBuff, i); Result := AnsiUpperCase(Result); end; {-------------------------------------------------------------------------------} procedure TFDPhysPreprocessor.ProcessParam; var sName, sSubst: String; lIsQuoted: Boolean; oPar: TFDParam; iPar: Integer; cPrevCh, cCh: Char; procedure BuildSubstName; begin if (ConnMetadata.ParamNameMaxLength > 0) and (Length(sName) > ConnMetadata.ParamNameMaxLength - 1) then begin if oPar <> nil then iPar := oPar.Index else if iPar <> -1 then begin oPar := TFDParam(FParamCache.Objects[iPar]); iPar := oPar.Index; end else iPar := Params.Count; Inc(iPar); sSubst := Copy(sSubst, 1, ConnMetadata.ParamNameMaxLength - 2 - Length(IntToStr(iPar))) + '_' + IntToStr(iPar); end else oPar := Params.FindParam(sName); if lIsQuoted then sSubst := ':' + ConnMetadata.QuoteObjName(sSubst, npObject) else sSubst := ':' + sSubst; end; begin cPrevCh := FPrevCh; cCh := GetChar; if FDInSet(cCh, ['=', ' ', #13, #10, #9, #0]) or (Byte(cPrevCh) in FNameDelims1) or (Byte(cPrevCh) in FNameDelims2) or FDInSet(cPrevCh, ['0'..'9', 'a'..'z', 'A'..'Z', '#', '$', '_']) then begin // skip: // - PL/SQL assignment operator - := // - TSQL label - name: // - Informix - catalog:schema.object // - if before ':' is an identifier end else if cCh = ':' then if (ConnMetadata.Kind in [TFDRDBMSKinds.PostgreSQL, TFDRDBMSKinds.MSSQL, TFDRDBMSKinds.Advantage, TFDRDBMSKinds.Informix]) or (ConnMetadata.Kind = TFDRDBMSKinds.SQLite) and FNested then begin // skip: // - PostgreSQL, Informix :: // - MSSQL SELECT ... FROM ::fn_xxxx() // - ADS SELECT ::conn.TransactionCount FROM system.iota // - SQLite SELECT xxxx AS "nm&1", &1=::type end else Commit(-1) else begin Commit(-2); PutBack; lIsQuoted := False; if ConnMetadata.Kind = TFDRDBMSKinds.Oracle then begin sName := ProcessIdentifier(False, lIsQuoted); // skip: // - Oracle triggers :new. / :old. if GetChar = '.' then begin UnCommit(2); Commit(0); Exit; end else PutBack; end else sName := ProcessIdentifier(True, lIsQuoted); iPar := -1; oPar := nil; sSubst := sName; if piCreateParams in Instrs then begin iPar := FParamCache.IndexOf(AnsiUpperCase(sName)); if (Params.BindMode = pbByNumber) or (iPar = -1) then begin BuildSubstName; if (oPar = nil) or (Params.BindMode = pbByNumber) then begin oPar := Params.Add; oPar.Name := sName; if Params.BindMode = pbByNumber then oPar.Position := Params.Count; oPar.IsCaseSensitive := lIsQuoted; FParamCache.AddObject(AnsiUpperCase(sName), oPar); end; end else begin sSubst := ':' + sSubst; oPar := TFDParam(FParamCache.Objects[iPar]); end; if oPar.ParamType in [ptUnknown, ptInput] then if FInIntoEscape then if (iPar = -1) and (ConnMetadata.Kind = TFDRDBMSKinds.Firebird) then oPar.ParamType := ptOutput else oPar.ParamType := ptInputOutput else if DesignMode then oPar.ParamType := ptInput; end else if FParamMark = prName then begin // The following is needed, when piCreateParams is not included, but a SQL // will be written in any case. So, we should take into account ParamNameMaxLength // and lIsQuoted for prName markers. oPar := FParams.FindParam(sName); BuildSubstName; end else sSubst := ':' + sSubst; if piExpandParams in Instrs then begin Params.Markers.Add(sName); case FParamMark of prQMark: sSubst := '?'; prNumber: begin Inc(FParamCount); sSubst := ':' + IntToStr(FParamCount); end; prDollar: if Params.BindMode = pbByNumber then begin Inc(FParamCount); sSubst := '$' + IntToStr(FParamCount); end else begin if oPar = nil then oPar := FParams.FindParam(sName); if oPar <> nil then sSubst := '$' + IntToStr(oPar.Index + 1) else sSubst := '$0'; end; prQNumber: begin Inc(FParamCount); sSubst := '?' + IntToStr(FParamCount); end; end; end; WriteStr(sSubst); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysPreprocessor.ProcessQuestion; var sSubst: String; oPar: TFDParam; cCh: Char; begin if FParamMark = prQNumber then Exit; cCh := GetChar; if cCh = '?' then Commit(-1) else begin Commit(-2); PutBack; oPar := nil; sSubst := '?'; if piExpandParams in Instrs then Params.BindMode := pbByNumber; if piCreateParams in Instrs then begin oPar := Params.Add; if DesignMode then oPar.ParamType := ptInput; if Params.BindMode = pbByNumber then oPar.Position := Params.Count; end; if piExpandParams in Instrs then if oPar = nil then oPar := FParams.FindParam(Params.Markers.Count + 1); if oPar <> nil then Params.Markers.Add(oPar.Name) else Params.Markers.Add(''); case FParamMark of prName, prNumber: begin Inc(FParamCount); sSubst := ':' + IntToStr(FParamCount); end; prDollar: begin Inc(FParamCount); sSubst := '$' + IntToStr(FParamCount); end; prQNumber: begin Inc(FParamCount); sSubst := '?' + IntToStr(FParamCount); end; end; WriteStr(sSubst); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysPreprocessor.ProcessMacro(AFirstCh: Char); var sName: String; oMacro: TFDMacro; lIsRaw, lIsQuoted, lProcessRes: Boolean; sRes: String; i: Integer; oPP: TFDPhysPreprocessor; cCh: Char; begin lIsRaw := (AFirstCh = '!'); cCh := GetChar; if FDInSet(cCh, ['=', '<', '>', '&', '''', ' ', #13, #10, #9, #0]) then begin // skip: // - !=, !<, !>, &=, &&, & operators // - end of string literal // - delimiters if cCh = '''' then PutBack; end else if cCh = AFirstCh then Commit(-1) else begin if piExpandMacros in Instrs then Commit(-2); PutBack; lIsQuoted := False; sName := ProcessIdentifier(False, lIsQuoted); if (MacrosUpd <> nil) and (piCreateMacros in Instrs) then begin oMacro := MacrosUpd.FindMacro(sName); if oMacro = nil then begin oMacro := TFDMacro.Create(MacrosUpd); oMacro.Name := sName; if lIsRaw then oMacro.DataType := mdRaw else oMacro.DataType := mdIdentifier; end; end else oMacro := nil; if piExpandMacros in Instrs then begin if (MacrosUpd <> MacrosRead) or (oMacro = nil) and not (piCreateMacros in Instrs) then oMacro := MacrosRead.FindMacro(sName); if oMacro <> nil then begin sRes := oMacro.SQL; lProcessRes := False; for i := 1 to Length(sRes) do if FDInSet(sRes[i], ['!', '&', ':', '{']) then begin lProcessRes := True; Break; end; if lProcessRes then begin oPP := TFDPhysPreprocessor.Create; try oPP.FNested := True; oPP.ConnMetadata := ConnMetadata; oPP.Params := Params; oPP.MacrosUpd := MacrosUpd; oPP.MacrosRead := MacrosRead; oPP.Instrs := Instrs - [piParseSQL]; oPP.DesignMode := DesignMode; oPP.Source := sRes; oPP.Execute; sRes := oPP.Destination; finally FDFree(oPP); end; end; WriteStr(sRes); end else WriteStr(''); end; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysPreprocessor.ProcessQuoteTag; var aBuff: array [0 .. 255] of Char; i, iPrevSrcIndex: Integer; sTag: String; begin iPrevSrcIndex := FSrcIndex; i := -1; repeat Inc(i); if i = 256 then FDException(Self, [S_FD_LPhys], er_FD_AccPrepTooLongIdent, []); aBuff[i] := GetChar; until not FDInSet(aBuff[i], ['0'..'9', 'a'..'z', 'A'..'Z', '#', '_']); if aBuff[i] <> '$' then begin FSrcIndex := iPrevSrcIndex - 1; GetChar; end else begin SetString(sTag, aBuff, i); if (FQuoteTags.Count > 0) and (FQuoteTags[FQuoteTags.Count - 1] = sTag) then FQuoteTags.Delete(FQuoteTags.Count - 1) else FQuoteTags.Add(sTag); FInStr3 := FQuoteTags.Count > 0; end; end; {-------------------------------------------------------------------------------} function TFDPhysPreprocessor.ProcessEscape: TFDPhysEscapeKind; procedure ErrorEmptyName; begin FDException(Self, [S_FD_LPhys], er_FD_AccEscapeEmptyName, []); end; var sKind: String; lTemp: Boolean; rEsc: TFDPhysEscapeData; iPrevSrcIndex, iCnt: Integer; ePrevInstrs: TFDPhysPreprocessorInstrs; begin // check for GUID and $DEFINE iPrevSrcIndex := FSrcIndex; iCnt := 0; while FDInSet(GetChar, ['0' .. '9', 'a' .. 'f', 'A' .. 'F', '-', '$']) do Inc(iCnt); if iCnt > 3 then begin Commit(0); Result := eskText; Exit; end; FSrcIndex := iPrevSrcIndex; // it is rather escape sequence Commit(-1); Inc(FEscapeLevel); SkipWS; lTemp := False; sKind := UpperCase(ProcessIdentifier(False, lTemp)); SkipWS; if sKind = 'E' then begin rEsc.FKind := eskFloat; SetLength(rEsc.FArgs, 1); rEsc.FArgs[0] := ProcessCommand; end else if sKind = 'D' then begin rEsc.FKind := eskDate; SetLength(rEsc.FArgs, 1); rEsc.FArgs[0] := ProcessCommand; end else if sKind = 'T' then begin rEsc.FKind := eskTime; SetLength(rEsc.FArgs, 1); rEsc.FArgs[0] := ProcessCommand; end else if sKind = 'DT' then begin rEsc.FKind := eskDateTime; SetLength(rEsc.FArgs, 1); rEsc.FArgs[0] := ProcessCommand; end else if sKind = 'ID' then begin rEsc.FKind := eskIdentifier; SetLength(rEsc.FArgs, 1); rEsc.FArgs[0] := ProcessCommand; end else if sKind = 'L' then begin rEsc.FKind := eskBoolean; SetLength(rEsc.FArgs, 1); rEsc.FArgs[0] := ProcessCommand; end else if sKind = 'S' then begin rEsc.FKind := eskString; SetLength(rEsc.FArgs, 1); PushWriter; repeat case GetChar of '!', '&': if Instrs * [piExpandMacros, piCreateMacros] <> [] then begin ProcessMacro(FCh); GetChar; end; '\': begin Commit(-1); GetChar; if FCh = '}' then GetChar; end; end; until (FCh = '}') or (FCh = #0); if FCh <> #0 then PutBack; rEsc.FArgs[0] := PopWriter; end else if sKind = 'ESCAPE' then begin rEsc.FKind := eskEscape; SkipWS; GetChar; if FCh <> '''' then Missed(''''); SetLength(rEsc.FArgs, 2); rEsc.FArgs[0] := GetChar; GetChar; if FCh <> '''' then Missed(''''); SkipWS; rEsc.FArgs[1] := ProcessCommand; end else if (sKind = 'INTO') or (sKind = 'RETURNING_VALUES') or (sKind = 'RETURNING') then begin if FInIntoEscape then Missed('}'); rEsc.FKind := eskInto; SetLength(rEsc.FArgs, 1); FInIntoEscape := True; try rEsc.FArgs[0] := ProcessCommand; finally FInIntoEscape := False; FWasIntoEscape := True; end; end else if sKind = 'IF' then begin rEsc.FKind := eskIF; SetLength(rEsc.FArgs, 1); ePrevInstrs := Instrs; Instrs := Instrs - [piExpandParams, piCreateParams]; try rEsc.FArgs[0] := ProcessCommand; finally Instrs := ePrevInstrs; end; end else if sKind = 'FI' then rEsc.FKind := eskFI else if sKind = 'IIF' then begin rEsc.FKind := eskIIF; GetChar; if FCh <> '(' then Missed('('); Inc(FBraceLevel); repeat GetChar; if not ((FCh = ')') or (FCh = #0)) then begin SetLength(rEsc.FArgs, Length(rEsc.FArgs) + 2); PutBack; rEsc.FArgs[Length(rEsc.FArgs) - 2] := ProcessCommand; GetChar; if FCh <> ')' then begin rEsc.FArgs[Length(rEsc.FArgs) - 1] := ProcessCommand; GetChar; end; end; until (FCh = ')') or (FCh = #0); if FCh = ')' then Dec(FBraceLevel); if rEsc.FArgs[Length(rEsc.FArgs) - 1] = '' then SetLength(rEsc.FArgs, Length(rEsc.FArgs) - 1); SkipWS; end else if sKind = 'STATIC' then begin rEsc.FKind := eskText; WriteStr('{static}'); end else begin rEsc.FKind := eskFunction; if sKind = 'FN' then rEsc.FName := ProcessIdentifier(False, lTemp) else rEsc.FName := sKind; if rEsc.FName = '' then ErrorEmptyName; SkipWS; GetChar; if FCh <> '(' then Missed('('); Inc(FBraceLevel); repeat GetChar; if FCh <> ')' then begin PutBack; SetLength(rEsc.FArgs, Length(rEsc.FArgs) + 1); rEsc.FArgs[Length(rEsc.FArgs) - 1] := ProcessCommand; GetChar; end; until (FCh = ')') or (FCh = #0); if FCh = ')' then Dec(FBraceLevel); SkipWS; end; if GetChar <> '}' then Missed('}'); Dec(FEscapeLevel); Result := rEsc.FKind; if Result = eskIF then if TranslateEscape(rEsc) = '' then begin ePrevInstrs := Instrs; Instrs := Instrs - [piExpandMacros, piExpandParams, piCreateParams]; Inc(FSkipEscapes); try ProcessCommand; finally Dec(FSkipEscapes); Instrs := ePrevInstrs; end; end else WriteStr(ProcessCommand) else if FSkipEscapes = 0 then WriteStr(TranslateEscape(rEsc)); end; {-------------------------------------------------------------------------------} function TFDPhysPreprocessor.TranslateEscape(var AEscape: TFDPhysEscapeData): String; begin Result := ConnMetadata.TranslateEscapeSequence(AEscape); if (AEscape.FKind = eskFunction) and (AEscape.FFunc = efLIMIT) then if Length(AEscape.FArgs) = 2 then begin FSQLLimitSkip := StrToInt(AEscape.FArgs[0]); FSQLLimitRows := StrToInt(AEscape.FArgs[1]); end else FSQLLimitRows := StrToInt(AEscape.FArgs[0]); end; {-------------------------------------------------------------------------------} function TFDPhysPreprocessor.ProcessCommand: String; var iEnterBraceLevel: Integer; eQuote: TFDPhysNameQuoteLevel; cQuote1, cQuote2: Char; begin PushWriter; iEnterBraceLevel := FBraceLevel; repeat case GetChar of '}': if (piExpandEscapes in Instrs) and not FInComment1 and not FInComment2 and not FInStr1 and not FInStr2 and (FInNames = []) then Break; '(': if not FInComment1 and not FInComment2 and not FInStr1 and not FInStr2 and (FInNames = []) then Inc(FBraceLevel); ')': if not FInComment1 and not FInComment2 and not FInStr1 and not FInStr2 and (FInNames = []) then begin if (FEscapeLevel > 0) and (FBraceLevel = iEnterBraceLevel) then Break; Dec(FBraceLevel); end; '\': // mkMySQL, mkDB2, mkASA, mkPostgreSQL - support '\' as escape character if (FInStr1 or FInStr2 or FInStr3 or (FInNames <> [])) and (ConnMetadata <> nil) and (ConnMetadata.BackslashEscSupported) then GetChar; '/': begin GetChar; if not FInComment1 and not FInComment2 and not FInStr1 and not FInStr2 and not FInStr3 and (FInNames = []) and (FCh = '*') then if ConnMetadata.Kind = TFDRDBMSKinds.MySQL then begin GetChar; if FCh = '!' then FInMySQLConditional := True else begin PutBack; FInComment1 := True; end end else FInComment1 := True else PutBack; end; '*': begin GetChar; if not FInComment2 and not FInStr1 and not FInStr2 and not FInStr3 and (FInNames = []) and (FCh = '/') then if FInMySQLConditional then FInMySQLConditional := False else FInComment1 := False else PutBack; end; '-': begin GetChar; if not FInComment1 and not FInStr1 and not FInStr2 and not FInStr3 and (FInNames = []) and (FCh = '-') then FInComment2 := True else PutBack; end; '''': if not FInComment1 and not FInComment2 and (FInNames = []) and not FInStr2 and not FInStr3 and ((GetChar <> '''') or not FInStr1) then begin PutBack; FInStr1 := not FInStr1; end; #13, #10: begin if not FInComment1 and FInComment2 then FInComment2 := False; if not FInStr1 and not FInStr2 and (piTransformEOLs in Instrs) then case ConnMetadata.LineSeparator of elPosix {$IFDEF POSIX}, elDefault {$ENDIF}: // #10 if FCh = #13 then begin Commit(-1); if GetChar <> #10 then begin PutBack; WriteStr(#10); end; end else begin Commit(0); if GetChar = #13 then Commit(-1) else PutBack; end; elWindows {$IFDEF MSWINDOWS}, elDefault {$ENDIF}: // #13#10 if FCh = #10 then begin Commit(-1); if GetChar <> #13 then PutBack else Commit(-1); WriteStr(#13#10); end else begin Commit(0); if GetChar = #10 then Commit(0) else begin PutBack; WriteStr(#10); end; end; end; end; ':': if not FInComment1 and not FInComment2 and not FInStr1 and not FInStr2 and not FInStr3 and (FInNames = []) and not FInProgramBlock and (Instrs * [piExpandParams, piCreateParams] <> []) then ProcessParam; '?': if not FInComment1 and not FInComment2 and not FInStr1 and not FInStr2 and not FInStr3 and (FInNames = []) and (piTransformQuestions in Instrs) and (Instrs * [piExpandParams, piCreateParams] <> []) then ProcessQuestion; '{': if not FInComment1 and not FInComment2 and not FInStr1 and not FInStr2 and (FInNames = []) and (piExpandEscapes in Instrs) then if ProcessEscape = eskFI then begin if FCh = '}' then GetChar; Break; end; ',': if not FInComment1 and not FInComment2 and not FInStr1 and not FInStr2 and (FInNames = []) then if (iEnterBraceLevel > 0) and (iEnterBraceLevel = FBraceLevel) then Break; '!', '&': if Instrs * [piExpandMacros, piCreateMacros] <> [] then ProcessMacro(FCh); '$': if (ConnMetadata <> nil) and (ConnMetadata.Kind = TFDRDBMSKinds.PostgreSQL) then ProcessQuoteTag; 'a'..'z', 'A'..'Z': if (ConnMetadata <> nil) and (ConnMetadata.Kind in [TFDRDBMSKinds.Interbase, TFDRDBMSKinds.Firebird]) and not FInComment1 and not FInComment2 and not FInStr1 and not FInStr2 and not FInStr3 and (FInNames = []) and not FInProgramBlock then begin FInProgramBlock := FDInSet(FCh, ['B', 'b']) and FDInSet(GetChar, ['E', 'e']) and FDInSet(GetChar, ['G', 'g']) and FDInSet(GetChar, ['I', 'i']) and FDInSet(GetChar, ['N', 'n']) and not FDInSet(GetChar, ['0'..'9', 'a'..'z', 'A'..'Z', '#', '$', '_']); while FDInSet(FCh, ['0'..'9', 'a'..'z', 'A'..'Z', '#', '$', '_']) do GetChar; PutBack; end; ';': if not FInComment1 and not FInComment2 and not FInStr1 and not FInStr2 and not FInStr3 and (FInNames = []) and not FInProgramBlock and not FInMySQLConditional and (FBraceLevel = 0) then FParamCount := 0; else if (FCh = '"') and not (Byte('"') in FNameDelims1) then begin if not FInComment1 and not FInComment2 and (FInNames = []) and not FInStr1 and not FInStr3 and ((GetChar <> '"') or not FInStr2) then begin PutBack; FInStr2 := not FInStr2; end; end else if ((Byte(FCh) in FNameDelims1) or (Byte(FCh) in FNameDelims2)) and not FInComment1 and not FInComment2 and not FInStr1 and not FInStr2 and not FInStr3 then for eQuote := Low(TFDPhysNameQuoteLevel) to High(TFDPhysNameQuoteLevel) do begin cQuote1 := ConnMetadata.NameQuoteChar[eQuote, nsLeft]; cQuote2 := ConnMetadata.NameQuoteChar[eQuote, nsRight]; if FCh = cQuote1 then begin if cQuote1 = cQuote2 then if eQuote in FInNames then Exclude(FInNames, eQuote) else Include(FInNames, eQuote) else Include(FInNames, eQuote); Break; end else if FCh = cQuote2 then begin if cQuote1 = cQuote2 then if eQuote in FInNames then Exclude(FInNames, eQuote) else Include(FInNames, eQuote) else Exclude(FInNames, eQuote); Break; end; end; end; until (FCh = #0); if FCh <> #0 then PutBack; Result := PopWriter; end; {-------------------------------------------------------------------------------} procedure TFDPhysPreprocessor.ParseDestination; var iPos, iLen: Integer; lResolved: Boolean; iFromStartedPos, iFromEndedPos, iCmdStartedPos: Integer; ch, cQuote1, cQuote2: Char; eQuote: TFDPhysNameQuoteLevel; oPP: TFDPhysPreprocessor; function CheckKeyword(const AKwd: String): Boolean; var c1: Char; begin c1 := AKwd[1]; Result := FDInSet(ch, [c1, Char(Word(c1) or $0020)]) and (CompareText(Copy(FDestination, iPos, Length(AKwd)), AKwd) = 0) and (iPos + Length(AKwd) <= Length(FDestination)) and not FDInSet(FDestination[iPos + Length(AKwd)], ['a' .. 'z', 'A' .. 'Z', '0' .. '9', '#', '$', '_']) end; procedure SkipKeyword(ALen: Integer); begin Inc(iPos, ALen); while (iPos <= Length(FDestination)) and FDInSet(FDestination[iPos], [' ', #13, #10, #9]) do Inc(iPos); end; function ProcessQuotedDelim(ADelim1, ADelim2: Char): Boolean; begin Result := False; if not FDInSet(ADelim1, [#0, ' ']) then while FDestination[iPos] = ADelim1 do begin Result := True; repeat Inc(iPos); until (iPos > Length(FDestination)) or FDInSet(FDestination[iPos], [ADelim2, #0]); if (iPos <= Length(FDestination)) and (FDestination[iPos] = ADelim2) then begin Inc(iPos); if (iPos <= Length(FDestination)) and (FDestination[iPos] = '.') then Inc(iPos) else Break; end else Break; end; end; begin iPos := 1; iLen := Length(FDestination); lResolved := False; iFromStartedPos := 0; iFromEndedPos := 0; FBraceLevel := 0; FInComment1 := False; FInMySQLConditional := False; FInComment2 := False; FInStr1 := False; FInStr2 := False; FInNames := []; FBraceLevel := 0; while iPos <= iLen do begin ch := FDestination[iPos]; case ch of '(': if not FInComment1 and not FInComment2 and not FInStr1 and not FInStr2 and (FInNames = []) then begin Inc(FBraceLevel); if (FBraceLevel = 1) and (iFromStartedPos <> 0) and (FDestination[iFromStartedPos] <> '(') and (iFromEndedPos = 0) then iFromEndedPos := iPos - 1; end; ')': if not FInComment1 and not FInComment2 and not FInStr1 and not FInStr2 and (FInNames = []) then begin Dec(FBraceLevel); if (FBraceLevel = 0) and (iFromStartedPos <> 0) and (FDestination[iFromStartedPos] = '(') and (iFromEndedPos = 0) then iFromEndedPos := iPos; if (FBraceLevel = 0) and (FSQLValuesPos <> 0) and (FSQLValuesPosEnd = 0) then FSQLValuesPosEnd := iPos; end; '/': begin Inc(iPos); if not FInComment1 and not FInComment2 and not FInStr1 and not FInStr2 and (FInNames = []) and (FDestination[iPos] = '*') then begin if (FBraceLevel = 0) and (iFromStartedPos <> 0) and (iFromEndedPos = 0) then iFromEndedPos := iPos - 2; if ConnMetadata.Kind = TFDRDBMSKinds.MySQL then begin Inc(iPos); if FDestination[iPos] = '!' then FInMySQLConditional := True else begin Dec(iPos); FInComment1 := True; end end else FInComment1 := True; end else Dec(iPos); end; '*': begin Inc(iPos); if not FInComment2 and not FInStr1 and not FInStr2 and (FInNames = []) and (FDestination[iPos] = '/') then if FInMySQLConditional then FInMySQLConditional := False else FInComment1 := False else Dec(iPos); end; '-': begin Inc(iPos); if not FInComment1 and not FInStr1 and not FInStr2 and (FInNames = []) and (FDestination[iPos] = '-') then begin if (FBraceLevel = 0) and (iFromStartedPos <> 0) and (iFromEndedPos = 0) then iFromEndedPos := iPos - 2; FInComment2 := True; end else Dec(iPos); end; '''': if not FInComment1 and not FInComment2 and (FInNames = []) and not FInStr2 then FInStr1 := not FInStr1; #13, #10, ' ', #9, ',', ';': begin if FDInSet(ch, [#13, #10]) then if not FInComment1 and FInComment2 then FInComment2 := False; if not FInComment1 and not FInComment2 and not FInStr1 and not FInStr2 and (FInNames = []) and (iFromStartedPos <> 0) and (iFromEndedPos = 0) and (FBraceLevel = 0) then iFromEndedPos := iPos - 1; end; 'A' .. 'Z', 'a' .. 'z': if not FInComment1 and not FInComment2 and not FInStr1 and not FInStr2 and (FInNames = []) and (FBraceLevel = 0) and ((iPos = 1) or not FDInSet(FDestination[iPos - 1], ['a' .. 'z', 'A' .. 'Z', '0' .. '9', '#', '$', '_', '@'])) then begin if not lResolved then begin iCmdStartedPos := iPos; repeat Inc(iPos); until (iPos > Length(FDestination)) or not FDInSet(FDestination[iPos], ['A' .. 'Z', 'a' .. 'z', '0' .. '9', '_']); FTokens.Add(UpperCase(Copy(FDestination, iCmdStartedPos, iPos - iCmdStartedPos))); FSQLCommandKind := ConnMetadata.GetSQLCommandKind(FTokens); Dec(iPos); end else if FSQLCommandKind in [skSelect, skSelectForLock, skSelectForUnLock] then begin if CheckKeyword('INTO') then begin // Special handling of SELECT INTO, which is more INSERT, than SELECT. // Because does not return a resultset and inserts the new records // (modifies DB). FTokens.Add('INTO'); FSQLCommandKind := ConnMetadata.GetSQLCommandKind(FTokens); end else if (FSQLFromValue = '') and ( (iFromStartedPos = 0) and CheckKeyword('FROM') or (iFromStartedPos <> 0) and (ConnMetadata <> nil) and (ConnMetadata.Kind = TFDRDBMSKinds.PostgreSQL) and CheckKeyword('ONLY')) then begin SkipKeyword(4); if (ConnMetadata <> nil) and (iPos <= Length(FDestination)) then begin iFromStartedPos := iPos; for eQuote := Low(TFDPhysNameQuoteLevel) to High(TFDPhysNameQuoteLevel) do if ProcessQuotedDelim(ConnMetadata.NameQuoteChar[eQuote, nsLeft], ConnMetadata.NameQuoteChar[eQuote, nsRight]) then Break; end; Dec(iPos); end else if (FSQLOrderByPos = 0) and CheckKeyword('ORDER BY') then begin FSQLOrderByPos := iPos; Inc(iPos, 7); end; end else if (FSQLCommandKind in [skDelete, skInsert, skMerge, skUpdate]) and CheckKeyword('RETURNING') then begin // Special handling of INSERT RETURNING without {INTO}, which is more // SELECT FOR UPDATE, than INSERT. Because returns a resultset and // inserts the new records (modifies DB). FTokens.Add('RETURNING'); if FWasIntoEscape then FTokens.Add('INTO'); FSQLCommandKind := ConnMetadata.GetSQLCommandKind(FTokens); end else if (FSQLValuesPos = 0) and CheckKeyword('VALUES') then begin FSQLValuesPos := iPos; Inc(iPos, 5); end; if FSQLCommandKind <> skNotResolved then lResolved := True; end; else if (ch = '"') and not (Byte('"') in FNameDelims1) then begin if not FInComment1 and not FInComment2 and (FInNames = []) and not FInStr1 then FInStr2 := not FInStr2; end else if (Byte(ch) in FNameDelims1) or (Byte(ch) in FNameDelims2) then begin for eQuote := Low(TFDPhysNameQuoteLevel) to High(TFDPhysNameQuoteLevel) do begin cQuote1 := ConnMetadata.NameQuoteChar[eQuote, nsLeft]; cQuote2 := ConnMetadata.NameQuoteChar[eQuote, nsRight]; if ch = cQuote1 then begin if cQuote1 = cQuote2 then if eQuote in FInNames then Exclude(FInNames, eQuote) else Include(FInNames, eQuote) else Include(FInNames, eQuote); Break; end else if ch = cQuote2 then begin if cQuote1 = cQuote2 then if eQuote in FInNames then Exclude(FInNames, eQuote) else Include(FInNames, eQuote) else Exclude(FInNames, eQuote); Break; end; end; end end; Inc(iPos); end; if (FSQLCommandKind = skNotResolved) and (FTokens.Count > 0) and (FTokens[FTokens.Count - 1] <> '') then begin FTokens.Add(''); FSQLCommandKind := ConnMetadata.GetSQLCommandKind(FTokens); end; if iFromStartedPos <> 0 then begin if iFromEndedPos = 0 then iFromEndedPos := iPos - 1; FSQLFromValue := Copy(FDestination, iFromStartedPos, iFromEndedPos - iFromStartedPos + 1); if (Length(FSQLFromValue) > 0) and (FSQLFromValue[1] = '(') and (FSQLFromValue[Length(FSQLFromValue)] = ')') then begin oPP := TFDPhysPreprocessor.Create; try oPP.FNested := True; oPP.ConnMetadata := ConnMetadata; oPP.Instrs := [piParseSQL]; oPP.DesignMode := DesignMode; oPP.Source := Copy(FSQLFromValue, 2, Length(FSQLFromValue) - 2); oPP.Execute; FSQLFromValue := oPP.SQLFromValue; finally FDFree(oPP); end; end; end; end; end.
{* ======================= Program Header ====================================== PROGRAM-NAME : PZN2000A(도급인력관리) SYSTEM-NAME : 기타 SUBSYSTEM-NAME : 도급인력관리 Programmer : Version : Date : Update Contents Version date(yy.mm.dd) programmer description relevant doc.no 1.00 2014.02.28 강륜종 도급인력시스템 개발 ============================================================================= *} unit PZN2000A1; interface uses Windows, WinProcs, Wintypes, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OnScheme, ExtCtrls, ComCtrls, OnListview, OnOutlook, OnVertScroller, ToolWin, Menus, OnPopupMenu, StdCtrls, OnFocusButton, ImgList, OnEditUtils, OnStringUtils, Db, OnMemDataset, OnEditBaseCtrl, OnEditStdCtrl, OnEditBtnCtrl, OnRichEdit, OleCtrls, OnTrayicon, OnSkinBtn, OnRegistry, Func, OnInternetFtp, jpeg, DBAccess, Ora, MemDS, pass, OnEditMemo; type TOnGDIRes = function : Word; stdcall; TFM_MainMenu = class(TForm) SB_Help: TStatusBar; Ora_Qry1: TOraQuery; BT_1: TOnFocusButton; BT_2: TOnFocusButton; BT_4: TOnFocusButton; HelpMemo: TOnMemo; SF_Main: TOnSchemeForm; BT_Title: TOnFocusButton; procedure ExitClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BT_1Click(Sender: TObject); procedure BT_2Click(Sender: TObject); procedure BT_4Click(Sender: TObject); private { Private declarations } public FG_Orgnum : String; FG_Empno : String; FG_UserName : String; P_Empno : String; { Public declarations } end; var FM_MainMenu: TFM_MainMenu; implementation uses SubPmas, SubCode; {$R *.DFM} /////////////////////////////////////////////////////////////////////////////// procedure TFM_MainMenu.ExitClick(Sender: TObject); begin Close; end; procedure TFM_MainMenu.FormCreate(Sender: TObject); begin OraConnect; Ora_Session.AutoCommit := True; //반드시... Ora_Session.Connected := False; Ora_Session.Connected := True; //AutoCommit 설정을 위하여 DB 재접속 FG_empno := Pempno; FG_UserName := Pkorname; end; procedure TFM_MainMenu.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFM_MainMenu.BT_1Click(Sender: TObject); begin FM_code := TFM_code.Create(Self); try FM_code.ShowModal; finally FM_code.Free; end; end; procedure TFM_MainMenu.BT_2Click(Sender: TObject); begin FM_PMas := TFM_PMas.Create(Self); try FM_PMas.ShowModal; finally FM_PMas.Free; end; end; procedure TFM_MainMenu.BT_4Click(Sender: TObject); begin Close; end; procedure TFM_MainMenu.FormShow(Sender: TObject); var FG_SysDate : String; begin if Copy(Pgrade,2,1) > 'C' then begin MessageBox(handle,'프로그램 사용권한이 없습니다 !!.','알 림',MB_OK or $0030); close; Exit; end; Ora_Qry1.Session := Ora_Session; with Ora_Qry1 do begin Close; SQL.Clear; SQL.ADD('Select Value1 From Pimvari Where gubun=''00'' And sgubun=''0001'' '); Open; FG_Orgnum := FieldByName('Value1').Asstring ; end; FG_SysDate := Fn_GetDateTimeStr; SB_Help.Panels[1].Text := ' [ ' + FG_Empno + ' ] ' + FG_UserName; SB_Help.Panels[3].Text := Copy(FG_SysDate, 1,4) + '.' + Copy(FG_SysDate, 5,2) + '.' + Copy(FG_SysDate, 7,2) + ' ' + Copy(FG_SysDate, 9,2) + ':' + Copy(FG_SysDate,11,2); end; end.
unit UnitProfiles; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Menus, INIFiles; type TFormProfiles = class(TForm) CbProfile: TComboBox; BtSave: TButton; BtDelete: TButton; procedure FindProfiles; procedure SaveProfile(pName: String); procedure LoadProfile(pName: String); procedure FormCreate(Sender: TObject); procedure MenuItmemClick(Sender: TObject); function IntToBool(val: Byte): Boolean; procedure SprawdzNazwe; function OdczytajString(a1, a2: String; vCount: Integer): Boolean; function OdczytajInteger(a1, a2: String; vCount, vMin, vMax: Integer): Boolean; function OdczytajBoolean(a1, a2: String; vCount: Integer): Boolean; procedure CbProfileKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure BtSaveClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure BtDeleteClick(Sender: TObject); procedure CbProfileChange(Sender: TObject); private { Private declarations } public { Public declarations } end; TReadProfThread = class(TThread) protected procedure Execute; override; end; var FormProfiles: TFormProfiles; ReadProfThread: TReadProfThread; tbl: array of Integer; str: TStrings; ini: TINIFile; LoadProfName: String; //nazwa profilu do zalatowania tthread implementation uses UnitMainForm, UnitChannel, UnitMixerAudio, UnitStats, UnitSettings, UnitAudioSettings, UnitAbout, UnitSineGenerator; {$R *.dfm} { TFormProfiles } //============================================================================== procedure TFormProfiles.MenuItmemClick(Sender: TObject); var i: Integer; s: String; begin i := MainForm.MenuProfiles.Items.IndexOf(TMenuItem(Sender)); s := TMenuItem(Sender).Caption; delete(s, pos('&',s), 1); MainForm.LbProfile.Caption := s; MainForm.LbProfile.Left := MainForm.ImgMain.Width div 2 - MainForm.LbProfile.Width div 2; CbProfile.ItemIndex := i; if i + 1 > DefProfCount then begin LoadProfName := s; ReadProfThread := TReadProfThread.Create(False); end; end; //============================================================================== procedure TFormProfiles.FindProfiles; var SRec: TSearchRec; res: Integer; st: TStrings; mi: TMenuItem; s: String; begin st := TStringList.Create; res := FindFirst(ExtractFilePath(Application.ExeName) + 'Profiles\*.ini', faAnyFile, SRec); while res = 0 do begin if (SRec.Name <> '.' ) and (SRec.Name <> '..')and (SRec.Size <> 0) then begin s := Copy(Srec.Name,1,Length(Srec.Name)-4); CbProfile.Items.Add(s); mi := TMenuItem.Create(Self); mi.Caption := s; mi.OnClick := FormProfiles.MenuItmemClick; MainForm.MenuProfiles.Items.Add(mi); if s = MainForm.LbProfile.Caption then CbProfile.ItemIndex := CbProfile.Items.Count-1; end; res := FindNext(SRec); end; FindClose(SRec); st.Free; end; //============================================================================== procedure TFormProfiles.FormCreate(Sender: TObject); begin Str := TStringList.Create; end; //============================================================================== function TFormProfiles.IntToBool(val: Byte): Boolean; begin if val = 1 then Result := True else Result := False; end; //============================================================================== procedure TReadProfThread.Execute; begin inherited; // ReadProfThread.FreeOnTerminate := True; FormProfiles.LoadProfile(LoadProfName); end; procedure TFormProfiles.LoadProfile(pName: String); var n: Integer; e: String; begin Str := TStringList.Create; //showmessage('safggdfgdfhgdfh'); if FileExists(ExtractFilePath (Application.ExeName) + 'Profiles\' + pName + '.ini') then begin ini := TIniFile.Create(ExtractFilePath( Application.ExeName) + 'Profiles\' + pName + '.ini'); try if OdczytajInteger('Main','Delay',1,1,30) then MainForm.TbDelay.Position := Tbl[0]; if OdczytajInteger('Main','Duty',1,20,98) then MainForm.TbDuty.Position := Tbl[0]; for n := 1 to 24 do begin e := 'Channel ' + IntToStr(n); if OdczytajString(e, 'Caption', 1) then begin Kanal[n].Caption := str[0]; Kanal[n].Panel.Caption := str[0]; end; if OdczytajInteger(e, 'Mode', 1, 0, 4) then Kanal[n].Mode := Tbl[0]; if OdczytajInteger(e, 'Color', 3, 0, 255) then Kanal[n].ColorLight := RGB(Tbl[0], Tbl[1], Tbl[2]); if OdczytajBoolean(e, 'PWM', 1) then Kanal[n].MajorPWM := IntToBool(Tbl[0]); if OdczytajBoolean(e, 'Negative', 1) then Kanal[n].Negative := IntToBool(Tbl[0]); if OdczytajBoolean(e, 'Strob', 1) then Kanal[n].StrobMode := IntToBool(Tbl[0]); if OdczytajInteger(e, 'OutChan', 1, 1, 24) then Kanal[n].OutChannel := Tbl[0]; if OdczytajInteger(e, 'Power', 1, 0, 255) then Kanal[n].OutPower := Tbl[0]; if OdczytajInteger(e, 'aFreq', 2, 20, 20000) then begin Kanal[n].Audio.FreqMin := Tbl[0]; Kanal[n].Audio.FreqMax := Tbl[1]; end; if OdczytajInteger(e, 'aPulseT', 2, 1, 5000) then begin Kanal[n].Audio.PulseTime := Tbl[0]; Kanal[n].Audio.PulseBreak := Tbl[1]; end; if OdczytajInteger(e, 'aTreshold', 2, 0, 100) then begin Kanal[n].Audio.SchmitMin := Tbl[0]; Kanal[n].Audio.SchmitMax := Tbl[1]; end; if OdczytajInteger(e, 'aAnalyze', 1, 0, 3) then Kanal[n].Audio.RefPoint := Tbl[0]; if OdczytajBoolean(e, 'aPwm', 1) then Kanal[n].Audio.PWM := IntToBool(Tbl[0]); if OdczytajBoolean(e, 'aPulse', 1) then Kanal[n].Audio.Pulse := IntToBool(Tbl[0]); if OdczytajBoolean(e, 'aDiff', 1) then Kanal[n].Audio.DiffMode := IntToBool(Tbl[0]); if OdczytajInteger(e, 'aAmplify', 1, 0, 150) then Kanal[n].Audio.Amplify := Tbl[0]; if OdczytajInteger(e, 'aDelay', 1, 0, 150) then Kanal[n].Audio.Delay := Tbl[0]; if OdczytajInteger(e, 'rFreq', 2, 1, 600) then begin Kanal[n].xRandom.FreqMin := Tbl[0]; Kanal[n].xRandom.FreqMax := Tbl[1]; end; if OdczytajBoolean(e, 'rModes', 4) then begin Kanal[n].xRandom.mAudio := IntToBool(Tbl[0]); Kanal[n].xRandom.mGen := IntToBool(Tbl[1]); Kanal[n].xRandom.mOn := IntToBool(Tbl[2]); Kanal[n].xRandom.mOff := IntToBool(Tbl[3]); end; if OdczytajInteger(e, 'gFreq', 2, 1, 10000) then begin Kanal[n].Gen.FreqMin := Tbl[0]; Kanal[n].Gen.FreqMax := Tbl[1]; end; if OdczytajInteger(e, 'gShapeMode', 2, 0, 4) then begin Kanal[n].Gen.ShapeUp := Tbl[0]; Kanal[n].Gen.ShapeDown := Tbl[1]; end; if OdczytajInteger(e, 'gStyle', 1, 0, FormChannel.CbGenStyle.Items.Count-1) then Kanal[n].Gen.Style := Tbl[0]; if OdczytajInteger(e, 'gFreqChng', 1, 0, 100) then Kanal[n].Gen.FreqChangeStep := Tbl[0]; if OdczytajInteger(e, 'gDuty', 1, 0, 99) then Kanal[n].Gen.Duty := Tbl[0]; if OdczytajInteger(e, 'gShapeVal', 1, 2, 198) then Kanal[n].Gen.Shape := Tbl[0]; if OdczytajBoolean(e, 'gNegative', 1) then begin Kanal[n].Gen.Negative := IntToBool(Tbl[0]); end; end; // for n := 1 to 24 finally ini.Free; end; end else // FileExists MessageBox(0, PChar('Brak pliku ' +pName + '.ini'), PChar('Błąd'), mb_IconError); end; //============================================================================== function TFormProfiles.OdczytajBoolean(a1, a2: String; vCount: Integer): Boolean; var nt: Integer; begin Result := False; if OdczytajString(a1,a2,vCount) = True then begin SetLength(Tbl, vCount); Result := True; for nt := 0 to vCount-1 do begin // showmessage(str[nt]+' '+inttostr(nt)); if (AnsiLowerCase(str[nt])='true') or (str[nt] = '1') then tbl[nt] := 1 else if (AnsiLowerCase(str[nt])='false') or (str[nt] = '0') then tbl[nt] := 0 else begin Result := False; MessageBox(0, PChar('Nieprawidłowa wartość zmiennej "' + a2 + '" w sekcji "' + a1 + '"!' + #13 + 'Może ona przyjmować tylko wartości True, False, 1, 0'), PChar('Błąd w pliku konfiguracyjnym!'), mb_IconError); showmessage('blad, wartosc zmienej '+a1+'/'+a2+' powinna wynosic True lub False'); Break; end; //if nd <> -2147483647 end; //for nt := 0 to Str.Count-1 end; //OdczytajString(a1,a2,vCount) = True end; //============================================================================== function TFormProfiles.OdczytajInteger(a1, a2: String; vCount, vMin, vMax: Integer): Boolean; var nt, nd: Integer; begin Result := False; if OdczytajString(a1,a2,vCount) = True then begin // Showmessage(str.Text); SetLength(Tbl, vCount); Result := True; for nt := 0 to vCount-1 do begin nd := StrToIntDef(Str[nt], -2147483647); // Showmessage(inttostr(nd)); if (nd <> -2147483647) and (nd >= vMin) and (nd <= vMax) then Tbl[nt] := nd else begin Result := False; MessageBox(0, PChar('Nieprawidłowa wartość zmiennej "' + a2 + '" w sekcji "' + a1 + '"!' + #13 + 'Wartość powinna zawierać się w przedziale ' + IntToStr(vMin) + '..' + IntToStr(vMax)), PChar('Błąd w pliku konfiguracyjnym!'), mb_IconError); Break; end; //if nd <> -2147483647 end; //for nt := 0 to Str.Count-1 end; //OdczytajString(a1,a2,vCount) = True end; //============================================================================== function TFormProfiles.OdczytajString(a1, a2: String; vCount: Integer): Boolean; var st, su: String; nt: Integer; begin Result := True; Str.Clear; su := ini.ReadString(a1, a2, #255); st := su + ','; if su = #255 then begin MessageBox(0, PChar('Nie można odnaleźć zmiennej "' + a2 + '" w sekcji "' + a1 + '"!'), PChar('Błąd w pliku konfiguracyjnym!'), mb_IconError); Result := False; end else for nt := 1 to vCount do begin Str.Add(Trim(Copy(st, 1, pos(',', st)-1))); //usun spacje i dodaj do listy if Pos(',', st) = 0 then begin MessageBox(0, PChar('Nieprawidłowa wartość zmiennej "' + a2 + '" w sekcji "' + a1 + '"!' + #13 + '(' + a2 + ' = ' + su + ')'), PChar('Błąd w pliku konfiguracyjnym!'), mb_IconError); Result := False; Break; end;//if Pos(',', st) = 0 delete(st, 1, Pos(',', st)); end;//for nt := 1 to vCount end; //============================================================================== procedure TFormProfiles.SaveProfile(pName: String); function BoolToStr(b: Boolean): ShortString; begin if b = True then Result := 'True' else Result := 'False'; end; function BoolToChr(b: Boolean): Char; begin if b = True then Result := '1' else Result := '0'; end; var s: TStrings; n: Integer; begin s := TStringList.Create; s.Add('==== Lumicom profile file ===='); s.Add(''); s.Add('[Main]'); s.Add(' Delay' + #9 + #9 + ' = ' + IntToStr(MainForm.TbDelay.Position)); s.Add(' Duty' + #9 + #9 + ' = ' + IntToStr(MainForm.TbDuty.Position)); for n := 1 to 24 do begin s.Add(''); s.Add('[Channel ' + IntToStr(n) + ']'); s.Add(' Caption' + #9 + ' = ' + Kanal[n].Caption); s.Add(' Mode' + #9 + #9 + ' = ' + IntToStr(Kanal[n].Mode)); s.Add(' Color' + #9 + #9 + ' = ' + IntToStr(GetRvalue(Kanal[n].ColorLight)) +','+IntToStr(GetGvalue(Kanal[n].ColorLight))+','+ IntToStr(GetBvalue(Kanal[n].ColorLight))); s.Add(' PWM' + #9 + #9 + ' = ' + BoolToStr(Kanal[n].MajorPWM)); s.Add(' Negative' + #9 + ' = ' + BoolToStr(Kanal[n].Negative)); s.Add(' Strob' + #9 + #9 + ' = ' + BoolToStr(Kanal[n].StrobMode)); s.Add(' OutChan' + #9 + ' = ' + IntToStr(Kanal[n].OutChannel)); s.Add(' Power' + #9 + #9 + ' = ' + IntToStr(Kanal[n].OutPower)); s.Add(' aFreq' + #9 + #9 + ' = ' + IntToStr(Kanal[n].Audio.FreqMin) + ',' + IntToStr(Kanal[n].Audio.FreqMax)); s.Add(' aPulseT' + #9 + ' = ' + IntToStr(Kanal[n].Audio.PulseTime) + ',' + IntToStr(Kanal[n].Audio.PulseBreak)); s.Add(' aTreshold' + #9 + ' = ' + IntToStr(Kanal[n].Audio.SchmitMin) + ',' + IntToStr(Kanal[n].Audio.SchmitMax)); s.Add(' aAnalyze' + #9 + ' = ' + IntToStr(Kanal[n].Audio.Analyze) + ',' + IntToStr(Kanal[n].Audio.RefPoint)); s.Add(' aPwm' + #9 + #9 + ' = ' + BoolToStr(Kanal[n].Audio.PWM)); s.Add(' aPulse' + #9 + #9 + ' = ' + BoolToStr(Kanal[n].Audio.Pulse)); s.Add(' aDiff' + #9 + #9 + ' = ' + BoolToStr(Kanal[n].Audio.DiffMode)); s.Add(' aAmplify' + #9 + ' = ' + IntToStr(Kanal[n].Audio.Amplify)); s.Add(' aDelay' + #9 + #9 + ' = ' + IntToStr(Kanal[n].Audio.Delay)); s.Add(' rFreq' + #9 + #9 + ' = ' + IntToStr(Kanal[n].xRandom.FreqMin) + ',' + IntToStr(Kanal[n].xRandom.FreqMax)); s.Add(' rModes' + #9 + #9 + ' = ' + BoolToChr(Kanal[n].xRandom.mAudio) + ',' + BoolToChr(Kanal[n].xRandom.mGen) + ',' + BoolToChr(Kanal[n].xRandom.mOn) + ',' + BoolToChr(Kanal[n].xRandom.mOff)); s.Add(' gFreq' + #9 + #9 + ' = ' + IntToStr(Kanal[n].Gen.FreqMin) + ',' + IntToStr(Kanal[n].Gen.FreqMax)); s.Add(' gShapeMode' + #9 + ' = ' + IntToStr(Kanal[n].Gen.ShapeUp) + ',' + IntToStr(Kanal[n].Gen.ShapeDown)); s.Add(' gStyle' + #9 + #9 + ' = ' + IntToStr(Kanal[n].Gen.Style)); s.Add(' gFreqChng' + #9 + ' = ' + IntToStr(Kanal[n].Gen.FreqChangeStep)); s.Add(' gDuty' + #9 + #9 + ' = ' + IntToStr(Kanal[n].Gen.Duty)); s.Add(' gShapeVal' + #9 + ' = ' + IntToStr(Kanal[n].Gen.Shape)); s.Add(' gNegative' + #9 + ' = ' + BoolToStr(Kanal[n].Gen.Negative)); end; s.SaveToFile(ExtractFilePath(Application.ExeName) + 'Profiles\' + pName + '.ini'); s.Free; end; //============================================================================== procedure TFormProfiles.CbProfileKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin SprawdzNazwe; if (Key = 13) and (BtSave.Enabled) then BtSaveClick(Self); end; //============================================================================== procedure TFormProfiles.SprawdzNazwe; var n: Integer; s: String; b: Boolean; begin Application.ProcessMessages; s := UpperCase(Trim(CbProfile.Text)); b := True; for n := 0 to CbProfile.Items.Count-1 do if s = UpperCase(CbProfile.Items.Strings[n]) then if n + 1 <= DefProfCount then b := False; if Trim(s) = '' then b := False; if b = False then begin BtSave.Enabled := False; BtDelete.Enabled := False; end else begin BtSave.Enabled := True; BtDelete.Enabled := True; end; end; //============================================================================== procedure TFormProfiles.BtSaveClick(Sender: TObject); var mi: TMenuItem; n: Integer; s: String; b: Boolean; begin b := True; s := UpperCase(Trim(CbProfile.Text)); for n := 0 to CbProfile.Items.Count-1 do if s = UpperCase(CbProfile.Items.Strings[n]) then if n + 1 > DefProfCount then b := False; n := ID_Yes; if b = False then n := MessageBox(0, PChar('Czy zastapic istniejacy profil?'), PChar('Pytanie'), mb_IconQuestion + mb_YesNo); if n = Id_Yes then begin SaveProfile(CbProfile.Text); CbProfile.Items.Add(CbProfile.Text); CbProfile.ItemIndex := CbProfile.Items.Count-1; mi := TMenuItem.Create(Self); mi.Caption := CbProfile.Text; mi.OnClick := FormProfiles.MenuItmemClick; if b = True then MainForm.MenuProfiles.Items.Add(mi); Self.Caption := 'Zapisano profil ' + Trim(CbProfile.Text); MainForm.LbProfile.Caption := CbProfile.Text; Application.ProcessMessages; MainForm.LbProfile.Left := MainForm.ImgMain.Width div 2 - MainForm.LbProfile.Width div 2; end; end; //============================================================================== procedure TFormProfiles.FormShow(Sender: TObject); begin SprawdzNazwe; end; //============================================================================== procedure TFormProfiles.BtDeleteClick(Sender: TObject); var n: Integer; s: String; begin s := Trim(CbProfile.Text); n := MessageBox(0, PChar('Czy napewno usunac profil ' + s + '?'), PChar('Pytanie'), mb_IconQuestion + mb_YesNo); if n = ID_Yes then begin DeleteFile(ExtractFilePath(Application.ExeName) + 'Profiles\' + s + '.ini'); MainForm.MenuProfiles.Items.Delete(CbProfile.ItemIndex); CbProfile.Items.Delete(CbProfile.ItemIndex); Self.Caption := 'Usunięto profil ' + s; end; end; procedure TFormProfiles.CbProfileChange(Sender: TObject); begin SprawdzNazwe; end; end.
unit MessageIntf; {$mode objfpc}{$H+} interface uses Classes, SysUtils, StdCtrls; type { TMessageIntf } TMessageIntf = class private FMessageView: TMemo; public constructor Create; destructor Destroy; override; procedure RegisterView(MessageView: TMemo); procedure Log(Msg: string); procedure LogFmt(Msg: string; Args: array of const); end; var Messages: TMessageIntf; implementation { TMessageIntf } constructor TMessageIntf.Create; begin end; destructor TMessageIntf.Destroy; begin inherited Destroy; end; procedure TMessageIntf.RegisterView(MessageView: TMemo); begin FMessageView := MessageView; end; procedure TMessageIntf.Log(Msg: string); begin if FMessageView <> nil then FMessageView.Lines.Add(Msg); end; procedure TMessageIntf.LogFmt(Msg: string; Args: array of const); begin if FMessageView <> nil then FMessageView.Lines.Add(Format(Msg, Args)); end; initialization Messages := TMessageIntf.Create; finalization Messages.Free; end.
unit JTimer; interface uses Windows; type TJTimer = packed record Inicio: DWord; Termino: DWord; Extrapolou: Boolean; end; procedure JTInicia(var JT: TJTimer; Intervalo: DWord); function JTFaltam(JT: TJTimer): DWord; function JTExpirou(JT: TJTimer): Boolean; const JTMinTime = 1; // 1 milisegundo JTMaxTime = 1000 * 60 * 60; // 1 Hora JTDefTime = 30 * 1000; // 30 segundos implementation procedure JTInicia(var JT: TJTimer; Intervalo: DWord); begin if (Intervalo < JTMinTime) or (Intervalo > JTMaxTime) then Intervalo := JTDefTime; JT.Inicio := GetTickCount; JT.Termino := JT.Inicio + Intervalo; if JT.Termino = 0 then Inc(JT.Termino); JT.Extrapolou := (JT.Termino < JT.Inicio); end; function JTFaltam(JT: TJTimer): DWord; var R : Int64; Now : DWord; begin with JT do begin Now := GetTickCount; if Extrapolou then R := High(DWord) + Termino else R := Termino; if Now = Inicio then Result := R - Inicio else if (R > Now) and ((Now > Inicio) or Extrapolou) then Result := (R - Now) else Result := 0; end; end; function JTExpirou(JT: TJTimer): Boolean; begin Result := (JTFaltam(JT) = 0); end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.3 2/8/2004 12:59:40 PM JPMugaas Start on DotNET port. Rev 1.2 10/16/2003 11:05:38 PM SPerry Reorganization Rev 1.1 2003.09.30 1:23:02 PM czhower Stack split for DotNet Rev 1.0 11/13/2002 08:45:44 AM JPMugaas } unit IdRawHeaders; interface {$I IdCompilerDefines.inc} uses {$IFDEF DOTNET} System.Net, {$ENDIF} IdGlobal, IdStruct; type //RFC 3542 definitions //IPv6 Extension Headers uint32_t = LongWord; uint16_t = Word; uint8_t = Byte; // types redeclared to avoid dependencies on stack declarations TIdSunB = class(TIdStruct) protected Fs_b1, Fs_b2, Fs_b3, Fs_b4: Byte; function GetBytesLen: LongWord; override; public procedure ReadStruct(const ABytes : TIdBytes; var VIndex : LongWord); override; procedure WriteStruct(var VBytes : TIdBytes; var VIndex : LongWord); override; property s_b1 : Byte read Fs_b1 write Fs_b1; property s_b2 : Byte read Fs_b2 write Fs_b2; property s_b3 : Byte read Fs_b3 write Fs_b3; property s_b4 : Byte read Fs_b4 write Fs_b4; end; TIdSunW = class(TIdStruct) protected Fs_w1, Fs_w2: Word; function GetBytesLen: LongWord; override; public procedure ReadStruct(const ABytes : TIdBytes; var VIndex : LongWord); override; procedure WriteStruct(var VBytes : TIdBytes; var VIndex : LongWord); override; property s_w1 : Word read Fs_w1 write Fs_w1; property s_w2 : Word read Fs_w2 write Fs_w2; end; TIdInAddr = class(TIdLongWord) public procedure CopyFrom(const ASource : TIdInAddr); end; { PIdInAddr = ^TIdInAddr; TIdInAddr = record case integer of 0: (S_un_b: TIdSunB); 1: (S_un_w: TIdSunW); 2: (S_addr: longword); end; } TIdNetTime = LongWord; // network byte order const //header sizes----------------------------------------------------------------// Id_ARP_HSIZE = $1C; // ARP header: 28 bytes Id_DNS_HSIZE = $0C; // DNS header base: 12 bytes Id_ETH_HSIZE = $0E; // Etherner header: 14 bytes Id_ICMP_HSIZE = $04; // ICMP header base: 4 bytes Id_ICMP_ECHO_HSIZE = $08; // ICMP_ECHO header: 8 bytes Id_ICMP6_ECHO_HSIZE = $08; // ICMPv6_ECHO header: 8 bytes icmp echo header len excluding time */ Id_ICMP_MASK_HSIZE = $0C; // ICMP_MASK header: 12 bytes Id_ICMP_UNREACH_HSIZE = $08; // ICMP_UNREACH header: 8 bytes Id_ICMP_TIMEXCEED_HSIZE = $08; // ICMP_TIMXCEED header: 8 bytes Id_ICMP_REDIRECT_HSIZE = $08; // ICMP_REDIRECT header: 8 bytes Id_ICMP_TS_HSIZE = $14; // ICMP_TIMESTAMP header: 20 bytes Id_IGMP_HSIZE = $08; // IGMP header: 8 bytes Id_IP_HSIZE = $14; // IP header: 20 bytes Id_IPv6_HSIZE = $28; // IPv6 header Id_RIP_HSIZE = $18; // RIP header base: 24 bytes Id_TCP_HSIZE = $14; // TCP header: 20 bytes Id_UDP_HSIZE = $08; // UDP header: 8 bytes //fragmentation flags---------------------------------------------------------// Id_IP_RF = $8000; // reserved fragment flag Id_IP_DF = $4000; // dont fragment flag Id_IP_MF = $2000; // more fragments flag Id_IP_OFFMASK = $1FFF; // mask for fragmenting bits //TCP control flags-----------------------------------------------------------// Id_TCP_FIN = $01; Id_TCP_SYN = $02; Id_TCP_RST = $04; Id_TCP_PUSH = $08; Id_TCP_ACK = $10; Id_TCP_URG = $20; //ICMP types------------------------------------------------------------------// Id_ICMP_ECHOREPLY = 0; Id_ICMP_UNREACH = 3; Id_ICMP_SOURCEQUENCH = 4; Id_ICMP_REDIRECT = 5; Id_ICMP_ECHO = 8; Id_ICMP_ROUTERADVERT = 9; Id_ICMP_ROUTERSOLICIT = 10; Id_ICMP_TIMXCEED = 11; Id_ICMP_PARAMPROB = 12; Id_ICMP_TSTAMP = 13; Id_ICMP_TSTAMPREPLY = 14; Id_ICMP_IREQ = 15; Id_ICMP_IREQREPLY = 16; Id_ICMP_MASKREQ = 17; Id_ICMP_MASKREPLY = 18; Id_ICMP_TRACEROUTE = 30; // RFC1393 Traceroute Id_ICMP_DATAGRAM_CONV = 31; // RFC1475 Id_ICMP_MOB_HOST_REDIR = 32; // Mobile Host Redirect Id_ICMP_IPv6_WHERE_ARE_YOU = 33; Id_ICMP_IPv6_I_AM_HERE = 34; Id_ICMP_MOB_REG_REQ = 35; Id_ICMP_MOB_REG_REPLY = 36; Id_ICMP_SKIP = 39; Id_ICMP_PHOTURIS = 40; // Photuris [RFC2521] //ICMP codes------------------------------------------------------------------// Id_ICMP_UNREACH_NET = 0; Id_ICMP_UNREACH_HOST = 1; Id_ICMP_UNREACH_PROTOCOL = 2; Id_ICMP_UNREACH_PORT = 3; Id_ICMP_UNREACH_NEEDFRAG = 4; Id_ICMP_UNREACH_SRCFAIL = 5; Id_ICMP_UNREACH_NET_UNKNOWN = 6; Id_ICMP_UNREACH_HOST_UNKNOWN = 7; Id_ICMP_UNREACH_ISOLATED = 8; Id_ICMP_UNREACH_NET_PROHIB = 9; Id_ICMP_UNREACH_HOST_PROHIB = 10; Id_ICMP_UNREACH_TOSNET = 11; Id_ICMP_UNREACH_TOSHOST = 12; Id_ICMP_UNREACH_FILTER_PROHIB = 13; Id_ICMP_UNREACH_HOST_PRECEDENCE = 14; Id_ICMP_UNREACH_PRECEDENCE_CUTOFF = 15; Id_ICMP_REDIRECT_NET = 0; Id_ICMP_REDIRECT_HOST = 1; Id_ICMP_REDIRECT_TOSNET = 2; Id_ICMP_REDIRECT_TOSHOST = 3; Id_ICMP_TIMXCEED_INTRANS = 0; Id_ICMP_TIMXCEED_REASS = 1; Id_ICMP_PARAMPROB_OPTABSENT = 1; // RFC 1393 Id_ICMP_TRACEROUTE_PACKET_FORWARDED = 0; Id_ICMP_TRACEROUTE_NO_ROUTE = 1; Id_ICMP_BAD_SPI = 0; //security parameter error 40 Id_ICMP_AUTH_FAILED = 1; Id_ICMP_DECOMPRESS_FAILED = 2; Id_ICMP_DECRYPTION_FAILED = 3; Id_ICMP_NEED_AUTHENTICATION = 4; Id_ICMP_NEED_AUTHORIZATION = 5; // RFC 1475 error codes // The type for Conversion Failed is 31 Id_ICMP_CONV_UNSPEC = 0; Id_ICMP_CONV_DONTCONV_OPTION = 1; Id_ICMP_CONV_UNKNOWN_MAN_OPTION = 2; Id_ICMP_CONV_UNKNWON_UNSEP_OPTION = 3; Id_ICMP_CONV_UNSEP_TRANSPORT = 4; Id_ICMP_CONV_OVERALL_LENGTH_EXCEEDED = 5; Id_ICMP_CONV_IP_HEADER_LEN_EXCEEDED = 6; Id_ICMP_CONV_TRANS_PROT_255 = 7; // transport protocol > 255 Id_ICMP_CONV_PORT_OUT_OF_RANGE = 8; Id_ICMP_CONV_TRANS_HEADER_LEN_EXCEEDED = 9; Id_ICMP_CONV_32BIT_ROLLOVER_AND_ACK = 10; // 32 Bit Rollover missing and ACK set Id_ICMP_CONV_UNKNOWN_MAN_TRANS_OPTION = 11; ICMP_MIN = 8; //ICMPv6 types----------------------------------------------------------------// ICMP6_DST_UNREACH = 1; ICMP6_PACKET_TOO_BIG = 2; ICMP6_TIME_EXCEEDED = 3; ICMP6_PARAM_PROB = 4; // Informational Messages ICMP6_INFOMSG_MASK = $80; //* all informational messages */ ICMP6_ECHO_REQUEST = 128; ICMP6_ECHO_REPLY = 129; ICMP6_MEMBERSHIP_QUERY = 130; ICMP6_MEMBERSHIP_REPORT = 131; ICMP6_MEMBERSHIP_REDUCTION = 132; //ICMPv6 codes----------------------------------------------------------------// ICMP6_DST_UNREACH_NOROUTE = 0; //* no route to destination */ ICMP6_DST_UNREACH_ADMIN = 1; //* communication with */ //* destination */ //* administratively */ //* prohibited */ ICMP6_DST_UNREACH_NOTNEIGHBOR = 2; //* not a neighbor */ ICMP6_DST_UNREACH_ADDR = 3; //* address unreachable */ ICMP6_DST_UNREACH_NOPORT = 4; //* bad port */ ICMP6_DST_UNREACH_SOURCE_FILTERING = 5; //source address failed ingress/egress policy ICMP6_DST_UNREACH_REJCT_DST = 6; //reject route to destination ICMP6_TIME_EXCEED_TRANSIT = 0; //* Hop Limit == 0 in transit */ ICMP6_TIME_EXCEED_REASSEMBLY = 1; //* Reassembly time out */ ICMP6_PARAMPROB_HEADER = 0; //* erroneous header field */ ICMP6_PARAMPROB_NEXTHEADER = 1; //* unrecognized Next Header */ ICMP6_PARAMPROB_OPTION = 2; //* unrecognized IPv6 option */ // ICMPv6 Neighbor Discovery Definitions ND_ROUTER_SOLICIT = 133; ND_ROUTER_ADVERT = 134; ND_NEIGHBOR_SOLICIT = 135; ND_NEIGHBOR_ADVERT = 136; ND_REDIRECT = 137; //IGMP types------------------------------------------------------------------// Id_IGMP_MEMBERSHIP_QUERY = $11; // membership query Id_IGMP_V1_MEMBERSHIP_REPORT = $12; // v1 membership report Id_IGMP_V2_MEMBERSHIP_REPORT = $16; // v2 membership report Id_IGMP_LEAVE_GROUP = $17; // leave-group message //ethernet packet types-------------------------------------------------------// Id_ETHERTYPE_PUP = $0200; // PUP protocol Id_ETHERTYPE_IP = $0800; // IP protocol Id_ETHERTYPE_ARP = $0806; // ARP protocol Id_ETHERTYPE_REVARP = $8035; // reverse ARP protocol Id_ETHERTYPE_VLAN = $8100; // IEEE 802.1Q VLAN tagging Id_ETHERTYPE_LOOPBACK = $9000; // used to test interfaces //hardware address formats----------------------------------------------------// Id_ARPHRD_ETHER = 1; // ethernet hardware format //ARP operation types---------------------------------------------------------// Id_ARPOP_REQUEST = 1; // req to resolve address Id_ARPOP_REPLY = 2; // resp to previous request Id_ARPOP_REVREQUEST = 3; // req protocol address given hardware Id_ARPOP_REVREPLY = 4; // resp giving protocol address Id_ARPOP_INVREQUEST = 8; // req to identify peer Id_ARPOP_INVREPLY = 9; // resp identifying peer //RIP commands----------------------------------------------------------------// Id_RIPCMD_REQUEST = 1; // want info Id_RIPCMD_RESPONSE = 2; // responding to request Id_RIPCMD_TRACEON = 3; // turn tracing on Id_RIPCMD_TRACEOFF = 4; // turn it off Id_RIPCMD_POLL = 5; // like request, but anyone answers Id_RIPCMD_POLLENTRY = 6; // like poll, but for entire entry Id_RIPCMD_MAX = 7; //RIP versions----------------------------------------------------------------// Id_RIPVER_0 = 0; Id_RIPVER_1 = 1; Id_RIPVER_2 = 2; //----------------------------------------------------------------------------// Id_MAX_IPOPTLEN = 40; Id_IP_MAXPACKET = 65535; Id_ETHER_ADDR_LEN = 6; type //////////////////////////////////////////////////////////////////////////////// //ICMP////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// TIdICMPEcho = class(TIdStruct) protected Fid: Word; // identifier to match requests with replies Fseq: Word; // sequence number to match requests with replies function GetBytesLen: LongWord; override; public procedure ReadStruct(const ABytes : TIdBytes; var VIndex : LongWord); override; procedure WriteStruct(var VBytes : TIdBytes; var VIndex : LongWord); override; property id: Word read Fid write FId; // identifier to match requests with replies property seq: Word read Fseq write FSeq; // sequence number to match requests with replies end; TIdICMPFrag = class(TIdStruct) protected Fpad: Word; Fmtu: Word; function GetBytesLen: LongWord; override; public procedure ReadStruct(const ABytes : TIdBytes; var VIndex : LongWord); override; procedure WriteStruct(var VBytes : TIdBytes; var VIndex : LongWord); override; property pad: Word read Fpad write Fpad; property mtu: Word read Fmtu write Fmtu; end; TIdICMPTs = class(TIdStruct) protected Fotime: TIdNetTime; // time message was sent, to calc roundtrip time Frtime: TIdNetTime; Fttime: TIdNetTime; function GetBytesLen: LongWord; override; public procedure ReadStruct(const ABytes : TIdBytes; var VIndex : LongWord); override; procedure WriteStruct(var VBytes : TIdBytes; var VIndex : LongWord); override; property otime: TIdNetTime read Fotime write Fotime; // time message was sent, to calc roundtrip time property rtime: TIdNetTime read Frtime write Frtime; property ttime: TIdNetTime read Fttime write Fttime; end; { packet header } TIdicmp_hun = class(TIdUnion) protected function Getecho_id: Word; function Getecho_seq: Word; function Getfrag_mtu: Word; function Getfrag_pad: Word; function Getgateway_s_b1: Byte; function Getgateway_s_b2: Byte; function Getgateway_s_b3: Byte; function Getgateway_s_b4: Byte; function Getgateway_s_l: LongWord; function Getgateway_s_w1: Word; function Getgateway_s_w2: Word; procedure Setecho_id(const Value: Word); procedure Setecho_seq(const Value: Word); procedure Setfrag_mtu(const Value: Word); procedure Setfrag_pad(const Value: Word); procedure Setgateway_s_b1(const Value: Byte); procedure Setgateway_s_b2(const Value: Byte); procedure Setgateway_s_b3(const Value: Byte); procedure Setgateway_s_b4(const Value: Byte); procedure Setgateway_s_l(const Value: LongWord); procedure Setgateway_s_w1(const Value: Word); procedure Setgateway_s_w2(const Value: Word); public constructor Create; override; property echo_id: word read Getecho_id write Setecho_id; // identifier to match requests with replies property echo_seq: word read Getecho_seq write Setecho_seq; property gateway_s_b1 : Byte read Getgateway_s_b1 write Setgateway_s_b1; property gateway_s_b2 : Byte read Getgateway_s_b2 write Setgateway_s_b2; property gateway_s_b3 : Byte read Getgateway_s_b3 write Setgateway_s_b3; property gateway_s_b4 : Byte read Getgateway_s_b4 write Setgateway_s_b4; property gateway_s_w1 : Word read Getgateway_s_w1 write Setgateway_s_w1; property gateway_s_w2 : Word read Getgateway_s_w2 write Setgateway_s_w2; property gateway_s_l : LongWord read Getgateway_s_l write Setgateway_s_l; property frag_pad: Word read Getfrag_pad write Setfrag_pad; property frag_mtu: Word read Getfrag_mtu write Setfrag_mtu; end; TIdicmp_dun = class(TIdUnion) protected function Getdata: Byte; function Getmask: LongWord; procedure setdata(const Value: Byte); procedure Setmask(const Value: LongWord); function Getts_otime: TIdNetTime; function Getts_rtime: TIdNetTime; function Getts_ttime: TIdNetTime; procedure Setts_otime(const Value: TIdNetTime); procedure Setts_rtime(const Value: TIdNetTime); procedure Setts_ttime(const Value: TIdNetTime); public constructor Create; override; property ts_otime: TIdNetTime read Getts_otime write Setts_otime; // time message was sent, to calc roundtrip time property ts_rtime: TIdNetTime read Getts_rtime write Setts_rtime; property ts_ttime: TIdNetTime read Getts_ttime write Setts_ttime; property mask : LongWord read Getmask write Setmask; property data : Byte read Getdata write setdata; end; TIdICMPHdr = class(TIdStruct) protected Ficmp_type: Byte; // message type Ficmp_code: Byte; // error code Ficmp_sum: Word; // one's complement checksum {Do not Localize} Ficmp_hun: TIdicmp_hun; Ficmp_dun: TIdicmp_dun; function GetBytesLen: LongWord; override; public constructor Create; override; destructor Destroy; override; procedure ReadStruct(const ABytes : TIdBytes; var VIndex : LongWord); override; procedure WriteStruct(var VBytes : TIdBytes; var VIndex : LongWord); override; property icmp_type: Byte read Ficmp_type write Ficmp_type; // message type property icmp_code: Byte read Ficmp_code write Ficmp_code; // error code property icmp_sum: Word read Ficmp_sum write Ficmp_sum; // one's complement checksum property icmp_hun: TIdicmp_hun read Ficmp_hun; property icmp_dun: TIdicmp_dun read Ficmp_dun; end; //ICMPv6 TIdicmp6_un = class(TIdUnion) protected function Geticmp6_data16: uint16_t; function Geticmp6_data8: uint8_t; procedure Seticmp6_data16(const Value: uint16_t); procedure Seticmp6_data8(const Value: uint8_t); function Geticmp6_seq: uint16_t; procedure Seticmp6_seq(const Value: uint16_t); function Geticmp6_un_data16(Index: Integer): uint16_t; function Geticmp6_un_data32: uint32_t; function Geticmp6_un_data8(Index: Integer): uint8_t; procedure Seticmp6_un_data16(Index: Integer; const Value: uint16_t); procedure Seticmp6_un_data32(const Value: uint32_t); procedure Seticmp6_un_data8(Index: Integer; const Value: uint8_t); { Ficmp6_un_data32 : uint32_t; //* type-specific field */ Ficmp6_un_data16 : array[0..1] of uint16_t; //* type-specific field */ icmp6_un_data8 : array[0..3] of uint8_t); //* type-specific field */ } public constructor Create; override; property icmp6_un_data32 : uint32_t read Geticmp6_un_data32 write Seticmp6_un_data32; //* type-specific field */ property icmp6_un_data16[Index:Integer] : uint16_t read Geticmp6_un_data16 write Seticmp6_un_data16; //array 0-1 * type-specific field */ property icmp6_un_data8[Index:Integer] : uint8_t read Geticmp6_un_data8 write Seticmp6_un_data8; //array[0-3] * type-specific field */ property icmp6_data32 : uint32_t read Geticmp6_un_data32 write Seticmp6_un_data32; property icmp6_data16 : uint16_t read Geticmp6_data16 write Seticmp6_data16; property icmp6_data8 : uint8_t read Geticmp6_data8 write Seticmp6_data8; property icmp6_pptr : uint32_t read Geticmp6_un_data32 write Seticmp6_un_data32; property icmp6_mtu : uint32_t read Geticmp6_un_data32 write Seticmp6_un_data32; property icmp6_id : uint16_t read Geticmp6_data16 write Seticmp6_data16; property icmp6_seq : uint16_t read Geticmp6_seq write Seticmp6_seq; property icmp6_maxdelay : uint16_t read Geticmp6_data16 write Seticmp6_data16; end; TIdicmp6_hdr = class(TIdStruct) protected Ficmp6_type : uint8_t; //* type field */ FIcmp6_code : uint8_t; //* code field */ Ficmp6_cksum : uint16_t; //* checksum field */ Fdata : TIdicmp6_un; function GetBytesLen: LongWord; override; public constructor Create; override; destructor Destroy; override; procedure ReadStruct(const ABytes : TIdBytes; var VIndex : LongWord); override; procedure WriteStruct(var VBytes : TIdBytes; var VIndex : LongWord); override; property icmp6_type : uint8_t read Ficmp6_type write Ficmp6_type; //* type field */ property icmp6_code : uint8_t read Ficmp6_code write Ficmp6_code; //* code field */ property icmp6_cksum : uint16_t read Ficmp6_cksum write Ficmp6_cksum; //* checksum field */ property data : TIdicmp6_un read Fdata; { case Integer of 1: (icmp6_un_data32 : uint32_t); //* type-specific field */ 2: (icmp6_un_data16 : array[0..1] of uint16_t); //* type-specific field */ 3: (icmp6_un_data8 : array[0..3] of uint8_t); //* type-specific field */ } end; //////////////////////////////////////////////////////////////////////////////// //IP//////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// { options struct } TIdIPOptions = class(TIdUnion) public constructor Create; override; //Delphi outputs warnings such as: //[Hint] H2368 Visibility of property accessor method TIdIPOptions.get_ipopt_list should match property TIdIPOptions.ipopt_list //[Hint] H2368 Visibility of property accessor method TIdIPOptions.set_ipopt_list should match property TIdIPOptions.ipopt_list //if these aren't public function get_ipopt_list(Index: Integer): Byte; procedure set_ipopt_list(Index: Integer; const Value: Byte); property ipopt_list[Index : Integer] : Byte read get_ipopt_list write set_ipopt_list; default; //options proper end; { packet header } TIdIPHdr = class(TIdStruct) protected Fip_verlen: Byte; // 1st nibble version, 2nd nibble header length div 4 (little-endian) Fip_tos: Byte; // type of service Fip_len: Word; // total length Fip_id: Word; // identification Fip_off: Word; // 1st nibble flags, next 3 nibbles fragment offset (little-endian) Fip_ttl: Byte; // time to live Fip_p: Byte; // protocol Fip_sum: Word; // checksum Fip_src: TIdInAddr; // source address Fip_dst: TIdInAddr; // dest address Fip_options: LongWord; // options + padding function GetBytesLen: LongWord; override; public constructor Create; override; destructor Destroy; override; procedure ReadStruct(const ABytes : TIdBytes; var VIndex : LongWord); override; procedure WriteStruct(var VBytes : TIdBytes; var VIndex : LongWord); override; procedure CopyFrom(const ASource : TIdIPHdr); property ip_verlen: Byte read Fip_verlen write Fip_verlen; // 1st nibble version, 2nd nibble header length div 4 (little-endian) property ip_tos: Byte read Fip_tos write Fip_tos; // type of service property ip_len: Word read Fip_len write Fip_len; // total length property ip_id: Word read Fip_id write Fip_id; // identification property ip_off: Word read Fip_off write Fip_off; // 1st nibble flags, next 3 nibbles fragment offset (little-endian) property ip_ttl: Byte read Fip_ttl write Fip_ttl; // time to live property ip_p: Byte read Fip_p write Fip_p; // protocol property ip_sum: Word read Fip_sum write Fip_sum; // checksum property ip_src: TIdInAddr read Fip_src; // source address property ip_dst: TIdInAddr read Fip_dst; // dest address property ip_options: LongWord read Fip_options write Fip_options; // options + padding end; //////////////////////////////////////////////////////////////////////////////// //TCP/////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// { options structure } TIdTCPOptions = class(TIdUnion) public constructor Create; override; //Delphi outputs warnings such as: //[Hint] H2368 Visibility of property accessor method TIdTCPOptions.gettcpopt_list should match property TIdTCPOptions.tcpopt_list //[Hint] H2368 Visibility of property accessor method TIdIPOptions.settcpopt_list should match property TIdTCPOptions.tcpopt_list //if these aren't public function gettcpopt_list(Index: Integer): Byte; procedure settcpopt_list(Index: Integer; const Value: Byte); property tcpopt_list[Index : Integer] : Byte read gettcpopt_list write settcpopt_list; default; end; { packet header } TIdTCPHdr = class(TIdStruct) protected Ftcp_sport: Word; // source port Ftcp_dport: Word; // destination port Ftcp_seq: LongWord; // sequence number Ftcp_ack: LongWord; // acknowledgement number Ftcp_x2off: Byte; // data offset Ftcp_flags: Byte; // control flags Ftcp_win: Word; // window Ftcp_sum: Word; // checksum Ftcp_urp: Word; // urgent pointer function GetBytesLen: LongWord; override; public procedure ReadStruct(const ABytes : TIdBytes; var VIndex : LongWord); override; procedure WriteStruct(var VBytes : TIdBytes; var VIndex : LongWord); override; property tcp_sport: Word read Ftcp_sport write Ftcp_sport; // source port property tcp_dport: Word read Ftcp_dport write Ftcp_dport; // destination port property tcp_seq: Longword read Ftcp_seq write Ftcp_seq; // sequence number property tcp_ack: Longword read Ftcp_ack write Ftcp_ack; // acknowledgement number property tcp_x2off: Byte read Ftcp_x2off write Ftcp_x2off; // data offset property tcp_flags: Byte read Ftcp_flags write Ftcp_flags; // control flags property tcp_win: Word read Ftcp_win write Ftcp_win; // window property tcp_sum: Word read Ftcp_sum write Ftcp_sum; // checksum property tcp_urp: Word read Ftcp_urp write Ftcp_urp; // urgent pointer end; //////////////////////////////////////////////////////////////////////////////// //UDP/////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// { packet header } TIdUDPHdr = class(TIdStruct) protected Fudp_sport: Word; // source port Fudp_dport: Word; // destination port Fudp_ulen: Word; // length Fudp_sum: Word; // checksum function GetBytesLen: LongWord; override; public procedure ReadStruct(const ABytes : TIdBytes; var VIndex : LongWord); override; procedure WriteStruct(var VBytes : TIdBytes; var VIndex : LongWord); override; property udp_sport: Word read Fudp_sport write Fudp_sport; // source port property udp_dport: Word read Fudp_dport write Fudp_dport; // destination port property udp_ulen: Word read Fudp_ulen write Fudp_ulen; // length property udp_sum: Word read Fudp_sum write Fudp_sum; // checksum end; //////////////////////////////////////////////////////////////////////////////// //IGMP////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// { packet header } TIdIGMPHdr = class(TIdStruct) protected Figmp_type: Byte; Figmp_code: Byte; Figmp_sum: Word; Figmp_group: TIdInAddr; function GetBytesLen: LongWord; override; public constructor Create; override; destructor Destroy; override; procedure ReadStruct(const ABytes : TIdBytes; var VIndex : LongWord); override; procedure WriteStruct(var VBytes : TIdBytes; var VIndex : LongWord); override; property igmp_type: Byte read Figmp_type write Figmp_type; property igmp_code: Byte read Figmp_code write Figmp_code; property igmp_sum: Word read Figmp_sum write Figmp_sum; property igmp_group: TIdInAddr read Figmp_group; end; //////////////////////////////////////////////////////////////////////////////// //ETHERNET////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// TIdEtherAddr = class(TIdUnion) public constructor Create; override; procedure CopyFrom(const ASource : TIdEtherAddr); procedure SetData(const Value: TIdBytes); //Delphi outputs warnings such as: //[Hint] H2368 Visibility of property accessor method TIdEtherAddr.getether_addr_octet should match property TIdEtherAddr.ether_addr_octet //[Hint] H2368 Visibility of property accessor method TIdEtherAddr.setether_addr_octet should match property TIdEtherAddr.ether_addr_octet //if these aren't public function getether_addr_octet(Index: Integer): Byte; procedure setether_addr_octet(Index: Integer; const Value: Byte); property ether_addr_octet[Index: Integer] : Byte read getether_addr_octet write setether_addr_octet; default; property Data: TIdBytes read FBuffer write SetData; end; { packet header } TIdEthernetHdr = class(TIdStruct) protected Fether_dhost: TIdEtherAddr; // destination ethernet address Fether_shost: TIdEtherAddr; // source ethernet address Fether_type: Word; // packet type ID function GetBytesLen: LongWord; override; public constructor Create; override; destructor Destroy; override; procedure CopyFrom(const ASource : TIdEthernetHdr); procedure ReadStruct(const ABytes : TIdBytes; var VIndex : LongWord); override; procedure WriteStruct(var VBytes : TIdBytes; var VIndex : LongWord); override; property ether_dhost: TIdEtherAddr read Fether_dhost; // destination ethernet address property ether_shost: TIdEtherAddr read Fether_shost; // source ethernet address property ether_type: Word read Fether_type write Fether_type; // packet type ID end; //////////////////////////////////////////////////////////////////////////////// //ARP/////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// { packet header } TIdARPHdr = class(TIdStruct) protected Farp_hrd: Word; // format of hardware address Farp_pro: Word; // format of protocol address Farp_hln: Byte; // length of hardware address Farp_pln: Byte; // length of protocol addres Farp_op: Word; // operation type // following hardcoded for ethernet/IP Farp_sha: TIdEtherAddr; // sender hardware address Farp_spa: TIdInAddr; // sender protocol address Farp_tha: TIdEtherAddr; // target hardware address Farp_tpa: TIdInAddr; // target protocol address function GetBytesLen: LongWord; override; public constructor Create; override; destructor Destroy; override; procedure ReadStruct(const ABytes : TIdBytes; var VIndex : LongWord); override; procedure WriteStruct(var VBytes : TIdBytes; var VIndex : LongWord); override; property arp_hrd: Word read Farp_hrd write Farp_hrd; // format of hardware address property arp_pro: Word read Farp_pro write Farp_pro; // format of protocol address property arp_hln: Byte read Farp_hln write Farp_hln; // length of hardware address property arp_pln: Byte read Farp_pln write Farp_pln; // length of protocol addres property arp_op: Word read Farp_op write Farp_op; // operation type // following hardcoded for ethernet/IP property arp_sha: TIdEtherAddr read Farp_sha; // sender hardware address property arp_spa: TIdInAddr read Farp_spa; // sender protocol address property arp_tha: TIdEtherAddr read Farp_tha; // target hardware address property arp_tpa: TIdInAddr read Farp_tpa; // target protocol address end; //////////////////////////////////////////////////////////////////////////////// //DNS/////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// { header } TIdDNSHdr = class(TIdStruct) protected Fdns_id: Word; // DNS packet ID Fdns_flags: Word; // DNS flags Fdns_num_q: Word; // number of questions Fdns_num_answ_rr: Word; // number of answer resource records Fdns_num_auth_rr: Word; // number of authority resource records Fdns_num_addi_rr: Word; // number of additional resource records function GetBytesLen: LongWord; override; public procedure ReadStruct(const ABytes : TIdBytes; var VIndex : LongWord); override; procedure WriteStruct(var VBytes : TIdBytes; var VIndex : LongWord); override; property dns_id: Word read Fdns_id write Fdns_id; // DNS packet ID property dns_flags: Word read Fdns_flags write Fdns_flags; // DNS flags property dns_num_q: Word read Fdns_num_q write Fdns_num_q; // number of questions property dns_num_answ_rr: Word read Fdns_num_answ_rr write Fdns_num_answ_rr; // number of answer resource records property dns_num_auth_rr: Word read Fdns_num_auth_rr write Fdns_num_auth_rr; // number of authority resource records property dns_num_addi_rr: Word read Fdns_num_addi_rr write Fdns_num_addi_rr; // number of additional resource records end; //////////////////////////////////////////////////////////////////////////////// //RIP/////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// { header } TIdRIPHdr = class(TIdStruct) protected Frip_cmd: Byte; // RIP command Frip_ver: Byte; // RIP version Frip_rd: Word; // zero (v1) or routing domain (v2) Frip_af: Word; // address family Frip_rt: Word; // zero (v1) or route tag (v2) Frip_addr: LongWord; // IP address Frip_mask: LongWord; // zero (v1) or subnet mask (v2) Frip_next_hop: LongWord; // zero (v1) or next hop IP address (v2) Frip_metric: LongWord; // metric function GetBytesLen: LongWord; override; public procedure ReadStruct(const ABytes : TIdBytes; var VIndex : LongWord); override; procedure WriteStruct(var VBytes : TIdBytes; var VIndex : LongWord); override; property rip_cmd: Byte read Frip_cmd write Frip_cmd; // RIP command property rip_ver: Byte read Frip_ver write Frip_ver; // RIP version property rip_rd: Word read Frip_rd write Frip_rd; // zero (v1) or routing domain (v2) property rip_af: Word read Frip_af write Frip_af; // address family property rip_rt: Word read Frip_rt write Frip_rt; // zero (v1) or route tag (v2) property rip_addr: LongWord read Frip_addr write Frip_addr; // IP address property rip_mask: LongWord read Frip_mask write Frip_mask; // zero (v1) or subnet mask (v2) property rip_next_hop: LongWord read Frip_next_hop write Frip_next_hop; // zero (v1) or next hop IP address (v2) property rip_metric: LongWord read Frip_metric write Frip_metric; // metric end; //////////////////////////////////////////////////////////////////////////////// implementation uses SysUtils; { TIdSunB } function TIdSunB.GetBytesLen: LongWord; begin Result := inherited GetBytesLen + 4; end; procedure TIdSunB.ReadStruct(const ABytes: TIdBytes; var VIndex: LongWord); begin inherited ReadStruct(ABytes, VIndex); Fs_b1 := ABytes[VIndex]; Inc(VIndex); Fs_b2 := ABytes[VIndex]; Inc(VIndex); Fs_b3 := ABytes[VIndex]; Inc(VIndex); Fs_b4 := ABytes[VIndex]; Inc(VIndex); end; procedure TIdSunB.WriteStruct(var VBytes: TIdBytes; var VIndex: LongWord); begin inherited WriteStruct(VBytes, VIndex); VBytes[VIndex] := Fs_b1; Inc(VIndex); VBytes[VIndex] := Fs_b2; Inc(VIndex); VBytes[VIndex] := Fs_b3; Inc(VIndex); VBytes[VIndex] := Fs_b4; Inc(VIndex); end; { TIdSunW } function TIdSunW.GetBytesLen: LongWord; begin Result := inherited GetBytesLen + 4; end; procedure TIdSunW.ReadStruct(const ABytes: TIdBytes; var VIndex: LongWord); begin inherited ReadStruct(ABytes, VIndex); Fs_w1 := BytesToWord(ABytes, VIndex); Inc(VIndex, 2); Fs_w2 := BytesToWord(ABytes, VIndex); Inc(VIndex, 2); end; procedure TIdSunW.WriteStruct(var VBytes: TIdBytes; var VIndex: LongWord); begin inherited WriteStruct(VBytes, VIndex); CopyTIdWord(HostToLittleEndian(Fs_w1), VBytes, VIndex); Inc(VIndex, 2); CopyTIdWord(HostToLittleEndian(Fs_w2), VBytes, VIndex); Inc(VIndex, 2); end; { TIdICMPEcho } function TIdICMPEcho.GetBytesLen: LongWord; begin Result := inherited GetBytesLen + 4; end; procedure TIdICMPEcho.ReadStruct(const ABytes: TIdBytes; var VIndex: LongWord); begin inherited ReadStruct(ABytes, VIndex); Fid := BytesToWord(ABytes, VIndex); Inc(VIndex, 2); seq := BytesToWord(ABytes, VIndex); Inc(VIndex, 2); end; procedure TIdICMPEcho.WriteStruct(var VBytes: TIdBytes; var VIndex: LongWord); begin inherited WriteStruct(VBytes, VIndex); CopyTIdWord(HostToLittleEndian(Fid), VBytes, VIndex); Inc(VIndex, 2); CopyTIdWord(HostToLittleEndian(seq), VBytes, VIndex); Inc(VIndex, 2); end; { TIdICMPFrag } function TIdICMPFrag.GetBytesLen: LongWord; begin Result := inherited GetBytesLen + 4; end; procedure TIdICMPFrag.ReadStruct(const ABytes: TIdBytes; var VIndex: LongWord); begin inherited ReadStruct(ABytes, VIndex); Fpad := BytesToWord(ABytes, VIndex); Inc(VIndex, 2); Fmtu := BytesToWord(ABytes, VIndex); Inc(VIndex, 2); end; procedure TIdICMPFrag.WriteStruct(var VBytes: TIdBytes; var VIndex: LongWord); begin inherited WriteStruct(VBytes, VIndex); CopyTIdWord(HostToLittleEndian(Fpad), VBytes, VIndex); Inc(VIndex, 2); CopyTIdWord(HostToLittleEndian(Fmtu), VBytes, VIndex); Inc(VIndex, 2); end; { TIdICMPTs } function TIdICMPTs.GetBytesLen: LongWord; begin Result := inherited GetBytesLen + 12; end; procedure TIdICMPTs.ReadStruct(const ABytes: TIdBytes; var VIndex: LongWord); begin inherited ReadStruct(ABytes, VIndex); Fotime := BytesToLongWord(ABytes, VIndex); // time message was sent, to calc roundtrip time Inc(VIndex, 4); Frtime := BytesToLongWord(ABytes, VIndex); Inc(VIndex, 4); Fttime := BytesToLongWord(ABytes, VIndex); Inc(VIndex, 4); end; procedure TIdICMPTs.WriteStruct(var VBytes: TIdBytes; var VIndex: LongWord); begin inherited WriteStruct(VBytes, VIndex); CopyTIdWord(HostToLittleEndian(Fotime), VBytes, VIndex); // time message was sent, to calc roundtrip time Inc(VIndex, 4); CopyTIdWord(HostToLittleEndian(Frtime), VBytes, VIndex); Inc(VIndex, 4); CopyTIdWord(HostToLittleEndian(Fttime), VBytes, VIndex); Inc(VIndex, 4); end; { TIdicmp_hun } constructor TIdicmp_hun.Create; begin inherited Create; SetBytesLen(4); end; function TIdicmp_hun.Getecho_id: word; begin Result := Getgateway_s_w1; end; procedure TIdicmp_hun.Setecho_id(const Value: word); begin Setgateway_s_w1(Value); end; function TIdicmp_hun.Getecho_seq: word; begin Result := Getgateway_s_w2; end; procedure TIdicmp_hun.Setecho_seq(const Value: word); begin Setgateway_s_w2(Value); end; function TIdicmp_hun.Getgateway_s_w1: word; begin Result := BytesToLongWord(FBuffer, 0); end; procedure TIdicmp_hun.Setgateway_s_w1(const Value: word); begin CopyTIdLongWord(Value, FBuffer, 0); end; function TIdicmp_hun.Getgateway_s_w2: word; begin Result := BytesToWord(FBuffer, 2); end; procedure TIdicmp_hun.Setgateway_s_w2(const Value: word); begin CopyTIdWord(HostToLittleEndian(Value), FBuffer, 2); end; function TIdicmp_hun.Getgateway_s_b1: Byte; begin Result := FBuffer[0]; end; procedure TIdicmp_hun.Setgateway_s_b1(const Value: Byte); begin FBuffer[0] := Value; end; function TIdicmp_hun.Getgateway_s_b2: Byte; begin Result := FBuffer[1]; end; procedure TIdicmp_hun.Setgateway_s_b2(const Value: Byte); begin FBuffer[1] := Value; end; function TIdicmp_hun.Getgateway_s_b3: Byte; begin Result := FBuffer[2]; end; procedure TIdicmp_hun.Setgateway_s_b3(const Value: Byte); begin FBuffer[2] := Value; end; function TIdicmp_hun.Getgateway_s_b4: Byte; begin Result := FBuffer[3]; end; procedure TIdicmp_hun.Setgateway_s_b4(const Value: Byte); begin FBuffer[3] := Value; end; function TIdicmp_hun.Getgateway_s_l: LongWord; begin Result := BytesToLongWord(FBuffer, 0); end; procedure TIdicmp_hun.Setgateway_s_l(const Value: LongWord); begin CopyTIdLongWord(Value, FBuffer, 0); end; function TIdicmp_hun.Getfrag_pad: word; begin Result := Getgateway_s_w1; end; procedure TIdicmp_hun.Setfrag_pad(const Value: word); begin Setgateway_s_w1(Value); end; function TIdicmp_hun.Getfrag_mtu: word; begin Result := Getgateway_s_w2; end; procedure TIdicmp_hun.Setfrag_mtu(const Value: word); begin Setgateway_s_w2(Value); end; { TIdicmp_dun } constructor TIdicmp_dun.Create; begin inherited Create; SetBytesLen(12); end; function TIdicmp_dun.Getts_otime: TIdNetTime; begin Result := BytesToLongWord(FBuffer, 0); end; procedure TIdicmp_dun.Setts_otime(const Value: TIdNetTime); begin CopyTIdLongWord(Value, FBuffer, 0); end; function TIdicmp_dun.Getts_rtime: TIdNetTime; begin Result := BytesToLongWord(FBuffer, 4); end; procedure TIdicmp_dun.Setts_rtime(const Value: TIdNetTime); begin CopyTIdLongWord(Value, FBuffer, 4); end; function TIdicmp_dun.Getts_ttime: TIdNetTime; begin Result := BytesToLongWord(FBuffer, 4); end; procedure TIdicmp_dun.Setts_ttime(const Value: TIdNetTime); begin CopyTIdLongWord(Value, FBuffer, 8); end; function TIdicmp_dun.Getmask: LongWord; begin Result := Getts_otime; end; procedure TIdicmp_dun.Setmask(const Value: LongWord); begin Setts_otime(Value); end; function TIdicmp_dun.Getdata: Byte; begin Result := FBuffer[0]; end; procedure TIdicmp_dun.setdata(const Value: Byte); begin FBuffer[0] := Value; end; { TIdICMPHdr } constructor TIdICMPHdr.Create; begin inherited Create; Ficmp_hun := TIdicmp_hun.Create; Ficmp_dun := TIdicmp_dun.Create; end; destructor TIdICMPHdr.Destroy; begin FreeAndNil(Ficmp_hun); FreeAndNil(Ficmp_dun); inherited Destroy; end; function TIdICMPHdr.GetBytesLen: LongWord; begin Result := inherited GetBytesLen + 4 + Ficmp_hun.BytesLen + Ficmp_dun.BytesLen; end; procedure TIdICMPHdr.ReadStruct(const ABytes: TIdBytes; var VIndex: LongWOrd); begin inherited ReadStruct(ABytes, VIndex); Ficmp_type := ABytes[VIndex]; Inc(VIndex); Ficmp_code := ABytes[Vindex]; Inc(VIndex); Ficmp_sum := BytesToWord(ABytes, VIndex); Inc(VIndex, 2); Ficmp_hun.ReadStruct(ABytes, VIndex); Ficmp_dun.ReadStruct(ABytes, VIndex); end; procedure TIdICMPHdr.WriteStruct(var VBytes: TIdBytes; var VIndex: LongWord); begin inherited WriteStruct(VBytes, VIndex); VBytes[VIndex] := Ficmp_type; Inc(VIndex); VBytes[Vindex] := Ficmp_code; Inc(VIndex); CopyTIdWord(Ficmp_sum, VBytes, VIndex); Inc(VIndex, 2); Ficmp_hun.WriteStruct(VBytes, VIndex); Ficmp_dun.WriteStruct(VBytes, VIndex); end; { TIdIPOptions } constructor TIdIPOptions.Create; begin inherited Create; SetBytesLen(Id_MAX_IPOPTLEN); end; function TIdIPOptions.get_ipopt_list(Index: Integer): byte; begin Assert(Index < Id_MAX_IPOPTLEN, 'Out of range'); {do not localize} Result := FBuffer[Index]; end; procedure TIdIPOptions.set_ipopt_list(Index: Integer; const Value: byte); begin Assert(Index < Id_MAX_IPOPTLEN, 'Out of range'); {do not localize} FBuffer[Index] := Value; end; { TIdIPHdr } constructor TIdIPHdr.Create; begin inherited Create; Fip_src := TIdInAddr.Create; Fip_dst := TIdInAddr.Create; end; destructor TIdIPHdr.Destroy; begin FreeAndNil(Fip_src); FreeAndNil(Fip_dst); inherited Destroy; end; function TIdIPHdr.GetBytesLen: LongWord; begin Result := inherited GetBytesLen + 12 + Fip_src.BytesLen + Fip_dst.BytesLen + 4; end; procedure TIdIPHdr.CopyFrom(const ASource: TIdIPHdr); begin Fip_verlen := ASource.ip_verlen; Fip_tos := ASource.ip_tos; Fip_len := ASource.ip_len; Fip_id := ASource.ip_id; Fip_off := ASource.ip_off; Fip_ttl := ASource.ip_ttl; Fip_p := ASource.ip_p; Fip_sum := ASource.ip_sum; Fip_src.CopyFrom(ASource.ip_src); Fip_dst.CopyFrom(ASource.ip_dst); Fip_options := ASource.ip_options; end; procedure TIdIPHdr.ReadStruct(const ABytes: TIdBytes; var VIndex: LongWord); var LIpHeaderLen : LongWord; begin inherited ReadStruct(ABytes, VIndex); Fip_verlen := ABytes[VIndex]; // 1st nibble version, 2nd nibble header length div 4 (little-endian) Inc(VIndex); LIpHeaderLen := (Fip_verlen and $0F) * 4; Fip_tos := ABytes[VIndex]; // type of service Inc(VIndex); Fip_len := BytesToWord(ABytes, VIndex); // total length Inc(VIndex, 2); Fip_id := BytesToWord(ABytes, VIndex); // identification Inc(VIndex, 2); Fip_off := BytesToWord(ABytes, VIndex); // 1st nibble flags, next 3 nibbles fragment offset (little-endian) Inc(VIndex, 2); Fip_ttl := ABytes[VIndex]; // time to live Inc(VIndex); Fip_p := ABytes[VIndex]; // protocol Inc(VIndex); Fip_sum := BytesToWord(ABytes, VIndex); // checksum Inc(VIndex, 2); Fip_src.ReadStruct(ABytes, VIndex); // source address Fip_dst.ReadStruct(ABytes, VIndex); // dest address //Fip_options may not be present in the packet if VIndex >= LIpHeaderLen then begin Fip_options := BytesToLongWord(ABytes, VIndex); // options + padding end; //be sure that we indicate we read the entire packet in case //the size varies. VIndex := LIpHeaderLen; end; procedure TIdIPHdr.WriteStruct(var VBytes: TIdBytes; var VIndex: LongWord); begin inherited WriteStruct(VBytes, VIndex); VBytes[VIndex] := Fip_verlen; // 1st nibble version, 2nd nibble header length div 4 (little-endian) Inc(VIndex); VBytes[VIndex] := Fip_tos; // type of service Inc(VIndex); CopyTIdWord(Fip_len, VBytes, VIndex); // total length Inc(VIndex, 2); CopyTIdWord(Fip_id, VBytes, VIndex); // identification Inc(VIndex, 2); CopyTIdWord(Fip_off, VBytes, VIndex); // 1st nibble flags, next 3 nibbles fragment offset (little-endian) Inc(VIndex, 2); Fip_ttl := VBytes[VIndex]; // time to live Inc(VIndex); Fip_p := VBytes[VIndex]; // protocol Inc(VIndex); CopyTIdWord(Fip_sum, VBytes, VIndex); // checksum Inc(VIndex, 2); Fip_src.WriteStruct(VBytes, VIndex); // source address Fip_dst.WriteStruct(VBytes, VIndex); // dest address CopyTIdLongWord(Fip_options, VBytes, VIndex); // options + padding Inc(VIndex, 4); end; { TIdTCPOptions } constructor TIdTCPOptions.Create; begin inherited Create; SetBytesLen(Id_MAX_IPOPTLEN); end; function TIdTCPOptions.gettcpopt_list(Index: Integer): Byte; begin Assert(Index < Id_MAX_IPOPTLEN, 'Out of range'); Result := FBuffer[Index]; end; procedure TIdTCPOptions.settcpopt_list(Index: Integer; const Value: Byte); begin Assert(Index < Id_MAX_IPOPTLEN, 'Out of range'); FBuffer[Index] := Value; end; { TIdTCPHdr } function TIdTCPHdr.GetBytesLen: LongWord; begin Result := inherited GetBytesLen + 20; end; procedure TIdTCPHdr.ReadStruct(const ABytes: TIdBytes; var VIndex: LongWord); begin inherited ReadStruct(ABytes, VIndex); Ftcp_sport := BytesToWord(ABytes, VIndex); // source port Inc(VIndex, 2); Ftcp_dport := BytesToWord(ABytes, VIndex); // destination port Inc(VIndex, 2); Ftcp_seq := BytesToLongWord(ABytes, VIndex); // sequence number Inc(VIndex, 4); Ftcp_ack := BytesToLongWord(ABytes, VIndex); // acknowledgement number Inc(VIndex, 4); Ftcp_x2off := ABytes[VIndex]; // data offset Inc(VIndex); Ftcp_flags := ABytes[VIndex]; // control flags Inc(VIndex); Ftcp_win := BytesToWord(ABytes, VIndex); // window Inc(VIndex, 2); Ftcp_sum := BytesToWord(ABytes, VIndex); // checksum Inc(VIndex, 2); Ftcp_urp := BytesToWord(ABytes, VIndex); // urgent pointer Inc(VIndex, 2); end; procedure TIdTCPHdr.WriteStruct(var VBytes: TIdBytes; var VIndex: LongWord); begin inherited WriteStruct(VBytes, VIndex); CopyTIdWord(Ftcp_sport, VBytes, VIndex); // source port Inc(VIndex, 2); CopyTIdWord(Ftcp_dport, VBytes, VIndex); // destination port Inc(VIndex, 2); CopyTIdLongWord(Ftcp_seq, VBytes, VIndex); // sequence number Inc(VIndex, 4); CopyTIdLongWord(Ftcp_ack, VBytes, VIndex); // acknowledgement number Inc(VIndex, 4); VBytes[VIndex] := Ftcp_x2off; // data offset Inc(VIndex); VBytes[VIndex] := Ftcp_flags; // control flags Inc(VIndex); CopyTIdWord(Ftcp_win, VBytes, VIndex); // window Inc(VIndex, 2); CopyTIdWord(Ftcp_sum, VBytes, VIndex); // checksum Inc(VIndex, 2); CopyTIdWord(Ftcp_urp, VBytes, VIndex); // urgent pointer Inc(VIndex, 2); end; { TIdUDPHdr } function TIdUDPHdr.GetBytesLen: LongWord; begin Result := inherited GetBytesLen + 8; end; procedure TIdUDPHdr.ReadStruct(const ABytes: TIdBytes; var VIndex: LongWord); begin inherited ReadStruct(ABytes, VIndex); Fudp_sport := BytesToWord(ABytes, VIndex); // source port Inc(VIndex, 2); Fudp_dport := BytesToWord(ABytes, VIndex); // destination port Inc(VIndex, 2); Fudp_ulen := BytesToWord(ABytes, VIndex); // length Inc(VIndex, 2); Fudp_sum := BytesToWord(ABytes, VIndex); // checksum Inc(VIndex, 2); end; procedure TIdUDPHdr.WriteStruct(var VBytes: TIdBytes; var VIndex: LongWord); begin inherited WriteStruct(VBytes, VIndex); CopyTIdWord(Fudp_sport, VBytes, VIndex); // source port Inc(VIndex, 2); CopyTIdWord(Fudp_dport, VBytes, VIndex); // destination port Inc(VIndex, 2); CopyTIdWord(Fudp_ulen, VBytes, VIndex); // length Inc(VIndex, 2); CopyTIdWord(Fudp_sum, VBytes, VIndex); // checksum Inc(VIndex, 2); end; { TIdIGMPHdr } constructor TIdIGMPHdr.Create; begin inherited Create; Figmp_group := TIdInAddr.Create; end; destructor TIdIGMPHdr.Destroy; begin FreeAndNil(Figmp_group); inherited Destroy; end; function TIdIGMPHdr.GetBytesLen: LongWord; begin Result := inherited GetBytesLen + 4 + Figmp_group.BytesLen; end; procedure TIdIGMPHdr.ReadStruct(const ABytes: TIdBytes; var VIndex: LongWord); begin inherited ReadStruct(ABytes, VIndex); Figmp_type := ABytes[VIndex]; Inc(VIndex); Figmp_code := ABytes[VIndex]; Inc(VIndex); Figmp_sum := BytesToWord(ABytes, VIndex); Inc(VIndex, 2); Figmp_group.ReadStruct(ABytes, VIndex); end; procedure TIdIGMPHdr.WriteStruct(var VBytes: TIdBytes; var VIndex: LongWord); begin inherited WriteStruct(VBytes, VIndex); VBytes[VIndex] := Figmp_type; Inc(VIndex); VBytes[VIndex] := Figmp_code; Inc(VIndex); CopyTIdWord(Figmp_sum, VBytes, VIndex); Inc(VIndex, 2); Figmp_group.WriteStruct(VBytes, VIndex); end; { TIdEtherAddr } constructor TIdEtherAddr.Create; begin inherited Create; SetBytesLen(Id_ETHER_ADDR_LEN); end; procedure TIdEtherAddr.setether_addr_octet(Index: Integer; const Value: Byte); begin Assert(Index < Id_ETHER_ADDR_LEN, 'Out of range'); FBuffer[Index] := Value; end; function TIdEtherAddr.getether_addr_octet(Index: Integer): Byte; begin Assert(Index < Id_ETHER_ADDR_LEN, 'Out of range'); Result := FBuffer[Index]; end; procedure TIdEtherAddr.CopyFrom(const ASource: TIdEtherAddr); begin SetData(ASource.Data); end; procedure TIdEtherAddr.SetData(const Value: TIdBytes); begin CopyTIdBytes(Value, 0, FBuffer, 0, Id_ETHER_ADDR_LEN); end; { TIdEthernetHdr } constructor TIdEthernetHdr.Create; begin inherited Create; Fether_dhost := TIdEtherAddr.Create; Fether_shost := TIdEtherAddr.Create; end; destructor TIdEthernetHdr.Destroy; begin FreeAndNil(Fether_dhost); FreeAndNil(Fether_shost); inherited Destroy; end; function TIdEthernetHdr.GetBytesLen: LongWord; begin Result := inherited GetBytesLen + Fether_dhost.BytesLen + Fether_shost.BytesLen + 2; end; procedure TIdEthernetHdr.ReadStruct(const ABytes: TIdBytes; var VIndex: LongWord); begin inherited ReadStruct(ABytes, VIndex); Fether_dhost.ReadStruct(ABytes, VIndex); // destination ethernet address Fether_shost.ReadStruct(ABytes, VIndex); // source ethernet address Fether_type := BytesToWord(ABytes, VIndex); // packet type ID Inc(VIndex, 2); end; procedure TIdEthernetHdr.WriteStruct(var VBytes: TIdBytes; var VIndex: LongWord); begin inherited WriteStruct(VBytes, VIndex); Fether_dhost.WriteStruct(VBytes, VIndex); // destination ethernet address Fether_shost.WriteStruct(VBytes, VIndex); // source ethernet address CopyTIdWord(Fether_type, VBytes, VIndex); // packet type ID Inc(VIndex, 2); end; procedure TIdEthernetHdr.CopyFrom(const ASource: TIdEthernetHdr); begin Fether_dhost.CopyFrom(ASource.Fether_dhost); Fether_shost.CopyFrom(ASource.Fether_shost); Fether_type := ASource.Fether_type; end; { TIdARPHdr } constructor TIdARPHdr.Create; begin inherited Create; Farp_sha := TIdEtherAddr.Create; // sender hardware address Farp_spa := TIdInAddr.Create; // sender protocol address Farp_tha := TIdEtherAddr.Create; // target hardware address Farp_tpa := TIdInAddr.Create; // target protocol address end; destructor TIdARPHdr.Destroy; begin FreeAndNil(Farp_sha); FreeAndNil(Farp_spa); FreeAndNil(Farp_tha); FreeAndNil(Farp_tpa); inherited Destroy; end; function TIdARPHdr.GetBytesLen: LongWord; begin Result := inherited GetBytesLen + 8 + Farp_sha.BytesLen + Farp_spa.BytesLen + Farp_tha.BytesLen + Farp_tpa.BytesLen; end; procedure TIdARPHdr.ReadStruct(const ABytes: TIdBytes; var VIndex: LongWord); begin inherited ReadStruct(ABytes, VIndex); Farp_hrd := BytesToWord(ABytes, VIndex); // format of hardware address Inc(VIndex, 2); Farp_pro := BytesToWord(ABytes, VIndex); // format of protocol address Inc(VIndex, 2); Farp_hln := ABytes[VIndex]; // length of hardware address Inc(VIndex); Farp_pln := ABytes[VIndex]; // length of protocol addres Inc(VIndex); Farp_op := BytesToWord(ABytes, VIndex); // operation type Inc(VIndex, 2); // following hardcoded for ethernet/IP Farp_sha.ReadStruct(ABytes, VIndex); // sender hardware address Farp_spa.ReadStruct(ABytes, VIndex); // sender protocol address Farp_tha.ReadStruct(ABytes, VIndex); // target hardware address Farp_tpa.ReadStruct(ABytes, VIndex); // target protocol address end; procedure TIdARPHdr.WriteStruct(var VBytes: TIdBytes; var VIndex: LongWord); begin inherited WriteStruct(VBytes, VIndex); CopyTIdWord(Farp_hrd, VBytes, VIndex); // format of hardware address Inc(VIndex, 2); CopyTIdWord(Farp_pro, VBytes, VIndex); // format of protocol address Inc(VIndex, 2); VBytes[VIndex] := Farp_hln; // length of hardware address Inc(VIndex); VBytes[VIndex] := Farp_pln; // length of protocol addres Inc(VIndex); CopyTIdWord(Farp_op, VBytes, VIndex); // operation type Inc(VIndex, 2); // following hardcoded for ethernet/IP Farp_sha.WriteStruct(VBytes, VIndex); // sender hardware address Farp_spa.WriteStruct(VBytes, VIndex); // sender protocol address Farp_tha.WriteStruct(VBytes, VIndex); // target hardware address Farp_tpa.WriteStruct(VBytes, VIndex); // target protocol address end; { TIdDNSHdr } function TIdDNSHdr.GetBytesLen: LongWord; begin Result := inherited GetBytesLen + 12; end; procedure TIdDNSHdr.ReadStruct(const ABytes: TIdBytes; var VIndex: LongWord); begin inherited ReadStruct(ABytes, VIndex); Fdns_id := BytesToWord(ABytes, VIndex); // DNS packet ID Inc(VIndex, 2); Fdns_flags := BytesToWord(ABytes, VIndex); // DNS flags Inc(VIndex, 2); Fdns_num_q := BytesToWord(ABytes, VIndex); // number of questions Inc(VIndex, 2); Fdns_num_answ_rr := BytesToWord(ABytes, VIndex);// number of answer resource records Inc(VIndex, 2); Fdns_num_auth_rr := BytesToWord(ABytes, VIndex); // number of authority resource records Inc(VIndex, 2); Fdns_num_addi_rr := BytesToWord(ABytes, VIndex); // number of additional resource records Inc(VIndex, 2); end; procedure TIdDNSHdr.WriteStruct(var VBytes: TIdBytes; var VIndex: LongWord); begin inherited WriteStruct(VBytes, VIndex); CopyTIdWord(Fdns_id, VBytes, VIndex); // DNS packet ID Inc(VIndex, 2); CopyTIdWord(Fdns_flags, VBytes, VIndex); // DNS flags Inc(VIndex, 2); CopyTIdWord(Fdns_num_q, VBytes, VIndex); // number of questions Inc(VIndex, 2); CopyTIdWord(Fdns_num_answ_rr, VBytes, VIndex); // number of answer resource records Inc(VIndex, 2); CopyTIdWord(Fdns_num_auth_rr, VBytes, VIndex); // number of authority resource records Inc(VIndex, 2); CopyTIdWord(Fdns_num_addi_rr, VBytes, VIndex); // number of additional resource records Inc(VIndex, 2); end; { TIdRIPHdr } function TIdRIPHdr.GetBytesLen: LongWord; begin Result := inherited GetBytesLen + 24; end; procedure TIdRIPHdr.ReadStruct(const ABytes: TIdBytes; var VIndex: LongWord); begin inherited ReadStruct(ABytes, VIndex); Frip_cmd := ABytes[VIndex]; // RIP command Inc(VIndex); Frip_ver := ABytes[VIndex]; // RIP version Inc(VIndex); Frip_rd := BytesToWord(ABytes, VIndex); // zero (v1) or routing domain (v2) Inc(VIndex, 2); Frip_af := BytesToWord(ABytes, VIndex); // address family Inc(VIndex, 2); Frip_rt := BytesToWord(ABytes, VIndex); // zero (v1) or route tag (v2) Inc(VIndex, 2); Frip_addr := BytesToLongWord(ABytes, VIndex); // IP address Inc(VIndex, 4); Frip_mask := BytesToLongWord(ABytes, VIndex); // zero (v1) or subnet mask (v2) Inc(VIndex, 4); Frip_next_hop := BytesToLongWord(ABytes, VIndex); // zero (v1) or next hop IP address (v2) Inc(VIndex, 4); Frip_metric := BytesToLongWord(ABytes, VIndex); // metric Inc(VIndex, 4); end; procedure TIdRIPHdr.WriteStruct(var VBytes: TIdBytes; var VIndex: LongWord); begin inherited WriteStruct(VBytes, VIndex); VBytes[VIndex] := Frip_cmd; // RIP command Inc(VIndex); VBytes[VIndex] := Frip_ver; // RIP version Inc(VIndex); CopyTIdWord(Frip_rd, VBytes, VIndex); // zero (v1) or routing domain (v2) Inc(VIndex, 2); CopyTIdWord(Frip_af, VBytes, VIndex); // address family Inc(VIndex, 2); CopyTIdWord(Frip_rt, VBytes, VIndex); // zero (v1) or route tag (v2) Inc(VIndex, 2); CopyTIdLongWord(Frip_addr, VBytes, VIndex); // IP address Inc(VIndex, 4); CopyTIdLongWord(Frip_mask, VBytes, VIndex); // zero (v1) or subnet mask (v2) Inc(VIndex, 4); CopyTIdLongWord(Frip_next_hop, VBytes, VIndex); // zero (v1) or next hop IP address (v2) Inc(VIndex, 4); CopyTIdLongWord(Frip_metric, VBytes, VIndex); // metric Inc(VIndex, 4); end; { TIdInAddr } procedure TIdInAddr.CopyFrom(const ASource: TIdInAddr); begin s_l := ASource.s_l; end; { TIdicmp6_un } constructor TIdicmp6_un.Create; begin inherited Create; SetBytesLen(4); end; function TIdicmp6_un.Geticmp6_un_data16(Index: Integer): uint16_t; begin Result := 0; case Index of 0 : Result := BytesToWord(FBuffer, 0); 1 : Result := BytesToWord(FBuffer, 2); end; end; procedure TIdicmp6_un.Seticmp6_un_data16(Index: Integer; const Value: uint16_t); begin case Index of 0 : CopyTIdWord(Value, FBuffer, 0); 1 : CopyTIdWord(Value, FBuffer, 2); end; end; function TIdicmp6_un.Geticmp6_un_data32: uint32_t; begin Result := BytesToLongWord(FBuffer, 0); end; procedure TIdicmp6_un.Seticmp6_un_data32(const Value: uint32_t); begin CopyTIdLongWord(Value, FBuffer, 0); end; function TIdicmp6_un.Geticmp6_un_data8(Index: Integer): uint8_t; begin Assert((Index>-1) and (Index<4), 'Out of range'); Result := FBuffer[Index]; end; procedure TIdicmp6_un.Seticmp6_un_data8(Index: Integer; const Value: uint8_t); begin Assert((Index>-1) and (Index<4), 'Out of range'); FBuffer[Index] := Value; end; function TIdicmp6_un.Geticmp6_data8: uint8_t; begin Result := FBuffer[0]; end; procedure TIdicmp6_un.Seticmp6_data8(const Value: uint8_t); begin FBuffer[0] := Value; end; function TIdicmp6_un.Geticmp6_data16: uint16_t; begin Result := BytesToWord(FBuffer, 0); end; procedure TIdicmp6_un.Seticmp6_data16(const Value: uint16_t); begin CopyTIdWord(Value, FBuffer, 0); end; function TIdicmp6_un.Geticmp6_seq: uint16_t; begin Result := Geticmp6_un_data16(1); end; procedure TIdicmp6_un.Seticmp6_seq(const Value: uint16_t); begin Seticmp6_un_data16(1, Value); end; { TIdicmp6_hdr } constructor TIdicmp6_hdr.Create; begin inherited Create; Fdata := TIdicmp6_un.Create; end; destructor TIdicmp6_hdr.Destroy; begin FreeAndNil(Fdata); inherited Destroy; end; function TIdicmp6_hdr.GetBytesLen: LongWord; begin Result := inherited GetBytesLen + 4 + Fdata.BytesLen; end; procedure TIdicmp6_hdr.ReadStruct(const ABytes: TIdBytes; var VIndex: LongWord); begin inherited ReadStruct(ABytes, VIndex); Ficmp6_type := ABytes[VIndex]; Inc(VIndex); FIcmp6_code := ABytes[VIndex]; Inc(VIndex); Ficmp6_cksum := BytesToWord(ABytes, VIndex); Inc(VIndex, 2); Fdata.ReadStruct(ABytes, VIndex); end; procedure TIdicmp6_hdr.WriteStruct(var VBytes: TIdBytes; var VIndex: LongWord); begin inherited WriteStruct(VBytes, VIndex); VBytes[VIndex] := Ficmp6_type; Inc(VIndex); VBytes[VIndex] := FIcmp6_code; Inc(VIndex); CopyTIdWord(Ficmp6_cksum, VBytes, VIndex); Inc(VIndex, 2); Fdata.WriteStruct(VBytes, VIndex); end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Android.Bluetooth; interface uses System.Bluetooth; {$SCOPEDENUMS ON} {$DEFINE BLUETOOTH_CLASSIC} {$DEFINE BLUETOOTH_LE} type {$IFDEF BLUETOOTH_CLASSIC} // --------------------------------------------------------------------- // TPlatformBluetoothClassicManager = class(TBluetoothManager) protected class function GetBluetoothManager: TBluetoothManager; override; end; {$ENDIF BLUETOOTH_CLASSIC} {$IFDEF BLUETOOTH_LE} // --------------------------------------------------------------------- // TPlatformBluetoothLEManager = class(TBluetoothLEManager) protected class function GetBluetoothManager: TBluetoothLEManager; override; end; /// <summary> Extra BLE Scan properties for Android </summary> IScanSettingsOptions = interface ['{353170C7-B913-4FF9-A0E6-C5825A9BAC71}'] /// <summary> Get Function </summary> function GetCALLBACK_TYPE_ALL_MATCHES: Integer; /// <summary> Get Function </summary> function GetCALLBACK_TYPE_FIRST_MATCH: Integer; /// <summary> Get Function </summary> function GetCALLBACK_TYPE_MATCH_LOST: Integer; /// <summary> Get Function </summary> function GetMATCH_MODE_AGGRESSIVE: Integer; /// <summary> Get Function </summary> function GetMATCH_MODE_STICKY: Integer; /// <summary> Get Function </summary> function GetMATCH_NUM_FEW_ADVERTISEMENT: Integer; /// <summary> Get Function </summary> function GetMATCH_NUM_MAX_ADVERTISEMENT: Integer; /// <summary> Get Function </summary> function GetMATCH_NUM_ONE_ADVERTISEMENT: Integer; /// <summary> Get Function </summary> function GetSCAN_MODE_BALANCED: Integer; /// <summary> Get Function </summary> function GetSCAN_MODE_LOW_LATENCY: Integer; /// <summary> Get Function </summary> function GetSCAN_MODE_LOW_POWER: Integer; /// <summary> Get Function </summary> function GetSCAN_MODE_OPPORTUNISTIC: Integer; /// <summary> From API 21. Trigger a callback for every Bluetooth advertisement found that matches the filter criteria. /// If no filter is active, all advertisement packets are reported. /// </summary> property CALLBACK_TYPE_ALL_MATCHES: Integer read GetCALLBACK_TYPE_ALL_MATCHES; /// <summary> From API 23. A result callback is only triggered for the first advertisement packet received that /// matches the filter criteria. /// </summary> property CALLBACK_TYPE_FIRST_MATCH: Integer read GETCALLBACK_TYPE_FIRST_MATCH; /// <summary> From API 23. Receive a callback when advertisements are no longer received from a device that has /// been previously reported by a first match callback. /// </summary> property CALLBACK_TYPE_MATCH_LOST: Integer read GetCALLBACK_TYPE_MATCH_LOST; /// <summary> From API 23. In Aggressive mode, hw will determine a match sooner even with feeble signal strength /// and few number of sightings/match in a duration. /// </summary> property MATCH_MODE_AGGRESSIVE: Integer read GetMATCH_MODE_AGGRESSIVE; /// <summary> From API 23. For sticky mode, higher threshold of signal strength and sightings is required before /// reporting by hw /// </summary> property MATCH_MODE_STICKY: Integer read GetMATCH_MODE_STICKY; /// <summary> From API 23. Match few advertisement per filter, depends on current capability and availibility /// of the resources in hw /// </summary> property MATCH_NUM_FEW_ADVERTISEMENT: Integer read GetMATCH_NUM_FEW_ADVERTISEMENT; /// <summary> From API 23. Match as many advertisement per filter as hw could allow, depends on current capability /// and availibility of the resources in hw /// </summary> property MATCH_NUM_MAX_ADVERTISEMENT: Integer read GetMATCH_NUM_MAX_ADVERTISEMENT; /// <summary> From API 23. Match one advertisement per filter </summary> property MATCH_NUM_ONE_ADVERTISEMENT: Integer read GetMATCH_NUM_ONE_ADVERTISEMENT; /// <summary> From API 21. Perform Bluetooth LE scan in balanced power mode. Scan results are returned at a rate /// that provides a good trade-off between scan frequency and power consumption. /// </summary> property SCAN_MODE_BALANCED: Integer read GetSCAN_MODE_BALANCED; /// <summary> From API 21. Scan using highest duty cycle. It's recommended to only use this mode when the application /// is running in the foreground. /// </summary> property SCAN_MODE_LOW_LATENCY: Integer read GetSCAN_MODE_LOW_LATENCY; /// <summary> From API 21. Perform Bluetooth LE scan in low power mode. This is the default scan mode as it consumes /// the least power. /// </summary> property SCAN_MODE_LOW_POWER: Integer read GetSCAN_MODE_LOW_POWER; /// <summary> From API 23. A special Bluetooth LE scan mode. Applications using this scan mode will passively listen /// for other scan results without starting BLE scans themselves. /// </summary> property SCAN_MODE_OPPORTUNISTIC: Integer read GetSCAN_MODE_OPPORTUNISTIC; end; /// <summary> Extra BLE properties for Android </summary> IExtraBLEAndroidProperties = interface ['{C14C69E8-C51B-4CF8-839B-FDE9CB96F15D}'] /// <summary> Get Function </summary> function GetScanSettingsOptions: IScanSettingsOptions; /// <summary> Get Function </summary> function GetScanSettings: Integer; /// <summary> Set procedure </summary> procedure SetScanSettings(Value: Integer); /// <summary> From API 21. Constants to set ScanSettings </summary> property ScanSettingsOptions: IScanSettingsOptions read GetScanSettingsOptions; /// <summary> From API 21. Settings for the BLE Scanner. </summary> property ScanSettings: Integer read GetScanSettings write SetScanSettings; end; // --------------------------------------------------------------------- // // --------------------------------------------------------------------- // {$ENDIF BLUETOOTH_LE} implementation uses Androidapi.JNI, Androidapi.JNIBridge, Androidapi.JNI.App, Androidapi.JNI.Embarcadero, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.JavaTypes, Androidapi.JNI.Os, Androidapi.NativeActivity, Androidapi.Helpers, Androidapi.JNI.Bluetooth, System.Classes, System.Messaging, System.SysUtils, System.SyncObjs, System.TypInfo, System.NetConsts, System.Generics.Collections, Androidapi.Looper, Androidapi.AppGlue, System.Types; // --------------------------------------------------------------------- // // Helper functions // --------------------------------------------------------------------- // function BluetoothUuidToJUuid(const AUuid: TBluetoothUUID): JUUID; var LAux: string; begin LAux := AUuid.ToString; LAux := LAux.Substring(1, LAux.Length - 2); Result := TJUUID.JavaClass.fromString(StringToJString(LAux)); end; function JUuidToBluetoothUuid(const AJUuid: JUUID): TBluetoothUUID; begin Result := TBluetoothUUID.Create('{' + JStringToString(AJUuid.toString) + '}'); end; // --------------------------------------------------------------------- // function BluetoothUUIDsListToJavaArrayUUID(const BluetoothUUIDsList: TBluetoothUUIDsList): TJavaObjectArray<JUUID>; var I: Integer; begin if BluetoothUUIDsList <> nil then begin Result := TJavaObjectArray<JUUID>.Create(BluetoothUUIDsList.Count); for I := 0 to BluetoothUUIDsList.Count - 1 do Result.Items[I] := BluetoothUuidToJUuid(BluetoothUUIDsList[I]); end else Result := nil; end; // --------------------------------------------------------------------- // procedure InternalProcessMessages; begin TThread.Sleep(1); end; // --------------------------------------------------------------------- // function CheckApiMethod(const AClassName, AMethodName, ASig: string): Boolean; var LJClass: JNIClass; begin LJClass := nil; try LJClass := JNIClass(TJNIResolver.GetJavaClassID(AClassName)); if LJClass <> nil then Result := TJNIResolver.GetJavaMethodID(LJClass, AMethodName, ASig) <> nil else Result := False finally if LJClass <> nil then TJNIResolver.DeleteLocalRef(LJClass); end; end; // --------------------------------------------------------------------- // // End helper functions // --------------------------------------------------------------------- // type TAndroidBluetoothAdapter = class; // --------------------------------------------------------------------- // // --------------------------------------------------------------------- // TBluetoothBroadcastListener = class(TJavaLocal, JFMXBroadcastReceiverListener) private [Weak] FAdapter: TAndroidBluetoothAdapter; public constructor Create(const AnAdapter: TAndroidBluetoothAdapter); procedure onReceive(context: JContext; intent: JIntent); cdecl; end; // --------------------------------------------------------------------- // TAndroidBluetoothManager = class(TPlatformBluetoothClassicManager) private FAdapter: TBluetoothAdapter; protected FContext: JContext; FJManager: JBluetoothManager; constructor Create; destructor Destroy; override; function DoGetClassicAdapter: TBluetoothAdapter; override; function GetAdapterState: TBluetoothAdapterState; function GetConnectionState: TBluetoothConnectionState; override; function DoEnableBluetooth: Boolean; override; end; // --------------------------------------------------------------------- // // --------------------------------------------------------------------- // TAndroidBluetoothAdapter = class(TBluetoothAdapter) private type TThreadTimer = class(TThread) private [Weak] FAdapter: TBluetoothAdapter; FTimeout: Cardinal; FOnTimer: TDiscoveryEndEvent; FDiscovering: Boolean; FEvent: TEvent; procedure Cancel; public constructor Create(const AnAdapter: TBluetoothAdapter; const AEvent: TDiscoveryEndEvent; Timeout: Cardinal); overload; destructor Destroy; override; procedure Execute; override; end; private FIntentFilter: JIntentFilter; FContext: JContext; FJAdapter: JBluetoothAdapter; FBroadcastReceiver: JFMXBroadcastReceiver; FBroadcastListener: TBluetoothBroadcastListener; FWaitingCallback: Boolean; FRequestEnableCallback: Boolean; FDiscoveryThreadTimer: TThreadTimer; FDiscoveryCancelled: Boolean; FOldScanMode: Integer; function GetAdapterName: string; override; function GetAddress: TBluetoothMacAddress; override; function GetPairedDevices: TBluetoothDeviceList; override; function GetScanMode: TBluetoothScanMode; override; function GetState: TBluetoothAdapterState; override; procedure SetAdapterName(const Value: string); override; procedure ResultCallback(const Sender: TObject; const M: TMessage); // Socket management functions function DoCreateServerSocket(const AName: string; const AUUID: TGUID; Secure: Boolean): TBluetoothServerSocket; override; // Device Discovery procedure DoStartDiscovery(Timeout: Cardinal); override; procedure DoCancelDiscovery; override; procedure DoStartDiscoverable(Timeout: Cardinal); override; function DoPair(const ADevice: TBluetoothDevice): Boolean; override; function DoUnPair(const ADevice: TBluetoothDevice): Boolean; override; public constructor Create(const AManager: TBluetoothManager; const AJAdapter: JBluetoothAdapter); destructor Destroy; override; function GetRemoteDevice(const AnAddress: TBluetoothMacAddress): TBluetoothDevice; //override; end; // --------------------------------------------------------------------- // // --------------------------------------------------------------------- // TScanSettingsOptions = class(TInterfacedObject,IScanSettingsOptions) const CALLBACK_TYPE_ALL_MATCHES = 1; CALLBACK_TYPE_FIRST_MATCH = 2; CALLBACK_TYPE_MATCH_LOST = 4; MATCH_MODE_AGGRESSIVE = 1; MATCH_MODE_STICKY = 2; MATCH_NUM_FEW_ADVERTISEMENT = 2; MATCH_NUM_MAX_ADVERTISEMENT = 3; MATCH_NUM_ONE_ADVERTISEMENT = 1; SCAN_MODE_BALANCED = 1; SCAN_MODE_LOW_LATENCY = 2; SCAN_MODE_LOW_POWER = 0; SCAN_MODE_OPPORTUNISTIC = -1; public function GetCALLBACK_TYPE_ALL_MATCHES: Integer; function GetCALLBACK_TYPE_FIRST_MATCH: Integer; function GetCALLBACK_TYPE_MATCH_LOST: Integer; function GetMATCH_MODE_AGGRESSIVE: Integer; function GetMATCH_MODE_STICKY: Integer; function GetMATCH_NUM_FEW_ADVERTISEMENT: Integer; function GetMATCH_NUM_MAX_ADVERTISEMENT: Integer; function GetMATCH_NUM_ONE_ADVERTISEMENT: Integer; function GetSCAN_MODE_BALANCED: Integer; function GetSCAN_MODE_LOW_LATENCY: Integer; function GetSCAN_MODE_LOW_POWER: Integer; function GetSCAN_MODE_OPPORTUNISTIC: Integer; end; TAndroidBluetoothLEManager = class(TPlatformBluetoothLEManager, IExtraBLEAndroidProperties) private FAdapter: TBluetoothLEAdapter; FIScanSettingsOptions: IScanSettingsOptions; FScanSettings: Integer; protected FContext: JContext; FJManager: JBluetoothManager; constructor Create; destructor Destroy; override; function DoGetAdapter: TBluetoothLEAdapter; override; function GetAdapterState: TBluetoothAdapterState; function GetConnectionState: TBluetoothConnectionState; override; function DoGetGattServer: TBluetoothGattServer; override; function DoGetSupportsGattClient: Boolean; override; function DoGetSupportsGattServer: Boolean; override; function DoEnableBluetooth: Boolean; override; function GetScanSettings: Integer; procedure SetScanSettings(Value: Integer); function GetScanSettingsOptions: IScanSettingsOptions; public property ScanSettings: Integer read GetScanSettings write SetScanSettings; end; // --------------------------------------------------------------------- // // --------------------------------------------------------------------- // TAndroidBluetoothLEAdapter = class(TBluetoothLEAdapter) private type TThreadTimer = class(TThread) private [Weak] FAdapter: TBluetoothLEAdapter; FTimeout: Cardinal; FOnTimer: TDiscoveryLEEndEvent; FEvent: TEvent; procedure Cancel; public constructor Create(const AnAdapter: TBluetoothLEAdapter; const AEvent: TDiscoveryLEEndEvent; Timeout: Cardinal); overload; destructor Destroy; override; procedure Execute; override; end; private FTimerThread: TThreadTimer; FLeCallback: JBluetoothAdapter_LeScanCallback; FJScanCallback: JRTLScanCallback; FJScanListener: JRTLScanListener; FContext: JContext; FJAdapter: JBluetoothAdapter; FJScanner: JBluetoothLeScanner; FRequestEnableCallback: Boolean; FJScanSettings: JScanSettings; FJArrayListOfAdvertiseData: JArrayList; FEventStartScan: TEvent; FStartScanFailed: Integer; FBluetoothLEScanFilterList: TBluetoothLEScanFilterList; FScanSettings: Integer; FBLEDiscovering: Boolean; function GetAdapterName: string; override; function GetAddress: TBluetoothMacAddress; override; function GetScanMode: TBluetoothScanMode; override; function GetState: TBluetoothAdapterState; override; procedure SetAdapterName(const Value: string); override; // LE Device Discovery function DoStartDiscovery(Timeout: Cardinal; const FilterUUIDList: TBluetoothUUIDsList; const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList = nil): Boolean; override; function DoStartDiscoveryRaw(const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList = nil; Refresh: Boolean = True): Boolean; override; procedure DoCancelDiscovery; override; procedure DoDiscoveryEnd(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); override; procedure ResultCallback(const Sender: TObject; const M: TMessage); public constructor Create(const AManager: TBluetoothLEManager; const AJAdapter: JBluetoothAdapter); destructor Destroy; override; function GetRemoteDevice(const AnAddress: TBluetoothMacAddress): TBluetoothLEDevice; //override; end; // --------------------------------------------------------------------- // // --------------------------------------------------------------------- // TAndroidBluetoothSocket = class(TBluetoothSocket) private type TBluetoothSocketReader = class(TThread) protected FJBytes: TJavaArray<System.Byte>; [Weak] FSocket: TAndroidBluetoothSocket; FBufferSize: Integer; FDestroying: Boolean; public constructor Create(const ASocket: TAndroidBluetoothSocket; ABuffSize: Integer); procedure Execute; override; destructor Destroy; override; function GetBufferedDataSize: Integer; inline; procedure GetBufferedData(const ABuffer: TBytes; AnOffset: Integer); inline; end; protected const BUFFER_SIZE = 4096; SocketEventTimeout = 1000; protected FJBytes: TJavaArray<System.Byte>; FJBluetoothSocket: JBluetoothSocket; FJIStream: JInputStream; FJOStream: JOutputStream; FConnected: Boolean; FDestroying: Boolean; FReader: TBluetoothSocketReader; FSocketEvent: TEvent; FReaderEvent: TEvent; function GetConnected: Boolean; override; function GetRemoteDevice: TBluetoothDevice; //override; procedure DoClose; override; procedure DoConnect; override; function DoReceiveData(ATimeout: Cardinal): TBytes; override; procedure DoSendData(const AData: TBytes); override; public constructor Create(const ASocket: JBluetoothSocket); destructor Destroy; override; end; TAndroidBluetoothServerSocket = class(TBluetoothServerSocket) protected FJServerSocket: JBluetoothServerSocket; function DoAccept(Timeout: Cardinal): TBluetoothSocket; override; procedure DoClose; override; public constructor Create(const AServerSocket: JBluetoothServerSocket); destructor Destroy; override; end; // --------------------------------------------------------------------- // // --------------------------------------------------------------------- // TBluetoothLeScanCallback = class(TJavaLocal, JBluetoothAdapter_LeScanCallback) private [Weak] FAdapter: TAndroidBluetoothLEAdapter; public constructor Create(const AnAdapter: TAndroidBluetoothLEAdapter); procedure onLeScan(device: JBluetoothDevice; rssi: Integer; scanRecord: TJavaArray<Byte>); cdecl; end; TScanCallback = class(TJavaLocal, JRTLScanListener) private [Weak] FAdapter: TAndroidBluetoothLEAdapter; public constructor Create(const AnAdapter: TAndroidBluetoothLEAdapter); procedure onBatchScanResults(results: JList); cdecl; procedure onScanFailed(errorCode: Integer); cdecl; procedure onScanResult(callbackType: Integer; result: Jle_ScanResult); cdecl; end; // --------------------------------------------------------------------- // // --------------------------------------------------------------------- // TAndroidBluetoothDevice = class(TBluetoothDevice) private const BluetoothServicesTimeout = 6600; private FJDevice: JBluetoothDevice; protected FEventUUIDS: TEvent; FDiscoverServiceEvent: TDiscoverServiceEvent; function GetOnDiscoverService: TDiscoverServiceEvent; procedure SetOnDiscoverService(const Value: TDiscoverServiceEvent); function GetAddress: TBluetoothMacAddress; override; function GetDeviceName: string; override; function GetPaired: Boolean; override; function GetState: TBluetoothDeviceState; override; function GetBluetoothType: TBluetoothType; override; function GetClassDevice: Integer; override; function GetClassDeviceMajor: Integer; override; function DoGetServices: TBluetoothServiceList; override; // Socket Management functions. function DoCreateClientSocket(const AUUID: TGUID; Secure: Boolean): TBluetoothSocket; override; public constructor Create(const AJDevice: JBluetoothDevice); destructor Destroy; override; function Pair: Boolean; property Address: TBluetoothMacAddress read GetAddress; property DeviceName: string read GetDeviceName; property OnDiscoverService: TDiscoverServiceEvent read GetOnDiscoverService write SetOnDiscoverService; end; // --------------------------------------------------------------------- // // --------------------------------------------------------------------- // TAndroidBluetoothLEDevice = class; TAndroidBluetoothGattCharacteristic = class; TAndroidBluetoothGattDescriptor = class; // --------------------------------------------------------------------- // // --------------------------------------------------------------------- // TAndroidBluetoothLEAdvertiseData = class(TBluetoothLEAdvertiseData) private FBluetoothGattServer: TBluetoothGattServer; FJBluetoothLeAdvertiser: JBluetoothLeAdvertiser; FJAdvertiseData_Builder: JAdvertiseData_Builder; FJScanResponse_Builder: JAdvertiseData_Builder; FJAdvertiseData: JAdvertiseData; FJScanResponse: JAdvertiseData; FJScanResult: Jle_ScanResult; FJAdvertiseSettings_Builder: JAdvertiseSettings_Builder; FJAdvertiseCallback: JRTLAdvertiseCallback; FJAdvertiseListener: JRTLAdvertiseListener; FDevice: TBluetoothLEDevice; FAdapter: TBluetoothLEAdapter; FEvent: TEvent; FServiceUUIDChanged: Boolean; FServiceDataChanged: Boolean; protected FAdvertising: Boolean; FErrorCode: Integer; function GetServiceUUIDs: TArray<TBluetoothUUID>; override; function GetServiceData: TArray<TServiceDataRawData>; override; procedure SetLocalName(const ALocalName: string); override; function GetLocalName: string; override; procedure SetTxPowerLevel(ATxPowerLevel: Integer); override; function GetTxPowerLevel: Integer; override; procedure SetManufacturerSpecificData(const AManufacturerSpecificData: TBytes); override; function GetManufacturerSpecificData: TBytes; override; procedure DoStartAdvertising; procedure DoStopAdvertising; procedure CreateAdvertiseDataJavaObjects; public constructor Create(const ABluetoothGattServer: TBluetoothGattServer; const AnAdapter: TBluetoothLEAdapter; const ADevice: TBluetoothLEDevice = nil); destructor Destroy; override; function DoAddServiceUUID(const AServiceUUID: TBluetoothUUID): Boolean; override; procedure DoRemoveServiceUUID(const AServiceUUID: TBluetoothUUID); override; procedure DoClearServiceUUIDs; override; function ContainsServiceUUID(const AServiceUUID: TBluetoothUUID): Boolean; override; function DoAddServiceData(const AServiceUUID: TBluetoothUUID; const AData: TBytes): Boolean; override; procedure DoRemoveServiceData(const AServiceUUID: TBluetoothUUID); override; function GetDataForService(const AServiceUUID: TBluetoothUUID): TBytes; override; procedure DoClearServiceData; override; end; // --------------------------------------------------------------------- // // --------------------------------------------------------------------- // TAndroidBluetoothGattServer = class(TBluetoothGattServer) private FJGattServer: JBluetoothGattServer; FJGattServerCallback: JRTLBluetoothGattServerCallback; FJGattServerListener: JRTLBluetoothGattServerListener; FLastRWrittenGattCharacteristic: TBluetoothGattCharacteristic; function FindCharacteristic(const AJCharacteristic: JBluetoothGattCharacteristic): TAndroidBluetoothGattCharacteristic; procedure DoDisconnect(const ADevice: TBluetoothLEDevice); procedure DoClientConfigurationWrite(const ADescriptor: TBluetoothGattDescriptor; const OldValue: TArray<Byte>; const AClient: TBluetoothLEDevice); protected // Helper Functions function FindDevice(const AJDevice: JBluetoothDevice): TBluetoothLEDevice; function FindService(const AJService: JBluetoothGattService): TBluetoothGattService; // Service Management. function DoAddService(const AService: TBluetoothGattService): Boolean; override; function DoCreateService(const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType): TBluetoothGattService; override; function DoCreateIncludedService(const AService: TBluetoothGattService; const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType): TBluetoothGattService; override; // Characteristic Management. function DoAddCharacteristic(const AService: TBluetoothGattService; const ACharacteristic: TBluetoothGattCharacteristic): Boolean; override; function DoCreateCharacteristic(const AService: TBluetoothGattService; const AnUUID: TBluetoothUUID; const AProps: TBluetoothPropertyFlags; const ADescription: string = ''): TBluetoothGattCharacteristic; override; // Descriptor Management. function DoCreateDescriptor(const ACharacteristic: TBluetoothGattCharacteristic; const AnUUID: TBluetoothUUID): TBluetoothGattDescriptor; override; function DoCreateAdvertiseData: TBluetoothLEAdvertiseData; override; function DoGetServices: TBluetoothGattServiceList; override; procedure DoClearServices; override; procedure DoClose; override; function DoConnect(const ADevice: TBluetoothLEDevice; AutoConnect: Boolean): Boolean; procedure DoCharacteristicReadRequest(const ADevice: TBluetoothLEDevice; ARequestId: Integer; AnOffset: Integer; const AGattCharacteristic: TBluetoothGattCharacteristic); override; procedure DoCharacteristicWriteRequest(const ADevice: TBluetoothLEDevice; ARequestId: Integer; const AGattCharacteristic: TBluetoothGattCharacteristic; APreparedWrite: Boolean; AResponseNeeded: Boolean; AnOffset: Integer; const AValue: TBytes); override; procedure DoUpdateCharacteristicValue(const ACharacteristic: TBluetoothGattCharacteristic); override; procedure DoDescriptorReadRequest(const ADevice: TBluetoothLEDevice; ARequestId: Integer; AnOffset: Integer; const ADescriptor: TBluetoothGattDescriptor); procedure DoDescriptorWriteRequest(const ADevice: TBluetoothLEDevice; ARequestId: Integer; const ADescriptor: TBluetoothGattDescriptor; APreparedWrite: Boolean; AResponseNeeded: Boolean; AnOffset: Integer; const AValue: TBytes); // procedure DoConnectionStateChange(const ADevice: TBluetoothLEDevice; AStatus: Integer; ANewState: Integer); override; procedure DoServiceAdded(AStatus: TBluetoothGattStatus; const AService: TBluetoothGattService); override; procedure DoStartAdvertising; override; procedure DoStopAdvertising; override; function DoIsAdvertising: Boolean; override; procedure DoExecuteWrite(const ADevice: TBluetoothLEDevice; ARequestId: Integer; Execute: Boolean); procedure DoSendResponse(const ADevice: TBluetoothLEDevice; ARequestId: Integer; AStatus: Integer; AnOffset: Integer; const AValue: TBytes); public constructor Create(const AManager: TAndroidBluetoothLEManager; const AnAdapter: TAndroidBluetoothLEAdapter); destructor Destroy; override; end; // --------------------------------------------------------------------- // TAndroidBluetoothGattServerListener = class(TJavaLocal, JRTLBluetoothGattServerListener) protected [Weak] FGattServer: TAndroidBluetoothGattServer; public constructor Create(const AServer: TAndroidBluetoothGattServer); destructor Destroy; override; procedure onCharacteristicReadRequest(device: JBluetoothDevice; requestId: Integer; offset: Integer; characteristic: JBluetoothGattCharacteristic); cdecl; procedure onCharacteristicWriteRequest(device: JBluetoothDevice; requestId: Integer; characteristic: JBluetoothGattCharacteristic; preparedWrite: Boolean; responseNeeded: Boolean; offset: Integer; value: TJavaArray<Byte>); cdecl; procedure onConnectionStateChange(device: JBluetoothDevice; status: Integer; newState: Integer); cdecl; procedure onDescriptorReadRequest(device: JBluetoothDevice; requestId: Integer; offset: Integer; descriptor: JBluetoothGattDescriptor); cdecl; procedure onDescriptorWriteRequest(device: JBluetoothDevice; requestId: Integer; descriptor: JBluetoothGattDescriptor; preparedWrite: Boolean; responseNeeded: Boolean; offset: Integer; value: TJavaArray<Byte>); cdecl; procedure onExecuteWrite(device: JBluetoothDevice; requestId: Integer; execute: Boolean); cdecl; procedure onServiceAdded(AStatus: Integer; service: JBluetoothGattService); cdecl; end; TAndroidBluetoothAdvertiseListener = class(TJavaLocal, JRTLAdvertiseListener) private FEvent: TEvent; FerrorCode: Integer; public constructor Create(const AEvent: TEvent; AErrorCode: Integer); destructor Destroy; override; procedure onStartFailure(errorCode: Integer); cdecl; procedure onStartSuccess(settingsInEffect: JAdvertiseSettings); cdecl; end; // --------------------------------------------------------------------- // // --------------------------------------------------------------------- // TAndroidBluetoothGattListener = class(TJavaLocal, JRTLBluetoothGattListener) private [Weak] FGatt: TAndroidBluetoothLEDevice; public constructor Create(const ALEDevice: TAndroidBluetoothLEDevice); destructor Destroy; override; procedure onCharacteristicChanged(gatt: JBluetoothGatt; characteristic: JBluetoothGattCharacteristic); cdecl; procedure onCharacteristicRead(gatt: JBluetoothGatt; characteristic: JBluetoothGattCharacteristic; status: Integer); cdecl; procedure onCharacteristicWrite(gatt: JBluetoothGatt; characteristic: JBluetoothGattCharacteristic; status: Integer); cdecl; procedure onConnectionStateChange(gatt: JBluetoothGatt; status: Integer; newState: Integer); cdecl; procedure onDescriptorRead(gatt: JBluetoothGatt; descriptor: JBluetoothGattDescriptor; status: Integer); cdecl; procedure onDescriptorWrite(gatt: JBluetoothGatt; descriptor: JBluetoothGattDescriptor; status: Integer); cdecl; procedure onReadRemoteRssi(gatt: JBluetoothGatt; rssi: Integer; status: Integer); cdecl; procedure onReliableWriteCompleted(gatt: JBluetoothGatt; status: Integer); cdecl; procedure onServicesDiscovered(gatt: JBluetoothGatt; status: Integer); cdecl; end; // --------------------------------------------------------------------- // TAndroidBluetoothLEDevice = class(TBluetoothLEDevice) private class var FRefreshMethod: Boolean; class constructor Create; private const CallbackGattTimeout = 5000; private FServicesEvent: TEvent; FCallbackGattEvents: TEvent; FCallbackGattResult: Boolean; FLastStatus: TBluetoothGattStatus; FConnectionStatus: TBluetoothDeviceState; private FJDevice: JBluetoothDevice; FJGattCallback: JRTLBluetoothGattCallback; FJGattListener: JRTLBluetoothGattListener; FJGatt: JBluetoothGatt; FReconnected: Boolean; FConnecting: Boolean; function InternalGetGattClient: JBluetoothGatt; protected // From TBluetoothCustomDevice function DoCreateAdvertiseData: TBluetoothLEAdvertiseData; override; function GetAddress: TBluetoothMacAddress; override; function GetDeviceName: string; override; function GetBluetoothType: TBluetoothType; override; function GetIdentifier: string; override; function GetIsConnected: Boolean; override; private function FindCharacteristic(const AJCharacteristic: JBluetoothGattCharacteristic): TAndroidBluetoothGattCharacteristic; function FindDescriptor(const AJDescriptor: JBluetoothGattDescriptor): TAndroidBluetoothGattDescriptor; procedure InternalGetServices; function UpdateServicesList: Boolean; protected procedure DoAbortReliableWrite; override; function DoBeginReliableWrite: Boolean; override; function DoExecuteReliableWrite: Boolean; override; function DoDiscoverServices: Boolean; override; function DoReadCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean; override; function DoReadDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean; override; function DoWriteCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean; override; function DoWriteDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean; override; function DoReadRemoteRSSI: Boolean; override; function DoSetCharacteristicNotification(const ACharacteristic: TBluetoothGattCharacteristic; Enable: Boolean): Boolean; override; function DoDisconnect: Boolean; override; function DoConnect: Boolean; override; public constructor Create(const AJDevice: JBluetoothDevice; AutoConnect: Boolean; AForceRefreshCachedServices: Boolean = False); destructor Destroy; override; end; // --------------------------------------------------------------------- // // --------------------------------------------------------------------- // TAndroidBluetoothGattService = class(TBluetoothGattService) private function FindCharacteristic(AJCharacteristic: JBluetoothGattCharacteristic): TAndroidBluetoothGattCharacteristic; function FindDescriptor(AJDescriptor: JBluetoothGattDescriptor): TAndroidBluetoothGattDescriptor; protected FJService: JBluetoothGattService; function GetServiceType: TBluetoothServiceType; override; function GetServiceUUID: TBluetoothUUID; override; function DoGetCharacteristics: TBluetoothGattCharacteristicList; override; function DoAddCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean; override; function DoAddIncludedService(const AService: TBluetoothGattService): Boolean; override; function DoCreateIncludedService(const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType): TBluetoothGattService; override; function DoCreateCharacteristic(const AUuid: TBluetoothUUID; APropertyFlags: TBluetoothPropertyFlags; const ADescription: string): TBluetoothGattCharacteristic; override; function DoGetIncludedServices: TBluetoothGattServiceList; override; public constructor Create(const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType; const AJService: JBluetoothGattService); destructor Destroy; override; end; // --------------------------------------------------------------------- // // --------------------------------------------------------------------- // TAndroidBluetoothGattCharacteristic = class(TBluetoothGattCharacteristic) private function FindDescriptor(const AJDescriptor: JBluetoothGattDescriptor): TAndroidBluetoothGattDescriptor; protected FJCharacteristic: JBluetoothGattCharacteristic; function GetUUID: TBluetoothUUID; override; function GetProperties: TBluetoothPropertyFlags; override; function DoAddDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean; override; function DoCreateDescriptor(const AUUID: TBluetoothUUID): TBluetoothGattDescriptor; override; function DoGetDescriptors: TBluetoothGattDescriptorList; override; function DoGetValue: TBytes; override; procedure DoSetValue(const AValue: TBytes); override; public constructor Create(const AService: TBluetoothGattService; AJCharacteristic: JBluetoothGattCharacteristic); overload; constructor Create(const AService: TBluetoothGattService; const AUUID: TBluetoothUUID; AProperties: TBluetoothPropertyFlags); overload; destructor Destroy; override; end; // --------------------------------------------------------------------- // // --------------------------------------------------------------------- // TAndroidBluetoothGattDescriptor = class(TBluetoothGattDescriptor) protected FJDescriptor: JBluetoothGattDescriptor; function DoGetValue: TBytes; override; procedure DoSetValue(const AValue: TBytes); override; function GetUUID: TBluetoothUUID; override; // Characteristic Extended Properties function DoGetReliableWrite: Boolean; override; function DoGetWritableAuxiliaries: Boolean; override; // Characteristic User Description function DoGetUserDescription: string; override; procedure DoSetUserDescription(const Value: string); override; // Client Characteristic Configuration procedure DoSetNotification(const Value: Boolean); override; function DoGetNotification: Boolean; override; procedure DoSetIndication(const Value: Boolean); override; function DoGetIndication: Boolean; override; // Server Characteristic Configuration function DoGetBroadcasts: Boolean; override; procedure DoSetBroadcasts(const Value: Boolean); override; //Characteristic Presentation Format function DoGetFormat: TBluetoothGattFormatType; override; function DoGetExponent: ShortInt; override; function DoGetFormatUnit: TBluetoothUUID; override; public constructor Create(const ACharacteristic: TBluetoothGattCharacteristic; AJDescriptor: JBluetoothGattDescriptor); destructor Destroy; override; end; // --------------------------------------------------------------------- // // Helper fuctions // --------------------------------------------------------------------- // const PROPERTY_BROADCAST: Integer = $0001; PROPERTY_READ: Integer = $0002; PROPERTY_WRITE_NO_RESPONSE: Integer = $0004; PROPERTY_WRITE: Integer = $0008; PROPERTY_NOTIFY: Integer = $0010; PROPERTY_INDICATE: Integer = $0020; PROPERTY_SIGNED_WRITE: Integer = $0040; PROPERTY_EXTENDED_PROPS: Integer = $0080; REQUEST_DISCOVERABLE = 2001; REQUEST_ENABLE_BT = 2002; CHAR_EXTENDEDPROPERTIES: TBluetoothUUID = '{00002900-0000-1000-8000-00805F9B34FB}'; CHAR_DESCRIPTION: TBluetoothUUID = '{00002901-0000-1000-8000-00805F9B34FB}'; CHAR_CLIENT_CONFIG: TBluetoothUUID = '{00002902-0000-1000-8000-00805F9B34FB}'; CHAR_SERVERCONFIGURATIONFORMAT: TBluetoothUUID = '{00002903-0000-1000-8000-00805F9B34FB}'; function PropertiesToInteger(const AProps: TBluetoothPropertyFlags): Integer; begin Result := 0; if TBluetoothProperty.Broadcast in AProps then Result := Result or PROPERTY_BROADCAST; if TBluetoothProperty.Read in AProps then Result := Result or PROPERTY_READ; if TBluetoothProperty.WriteNoResponse in AProps then Result := Result or PROPERTY_WRITE_NO_RESPONSE; if TBluetoothProperty.Write in AProps then Result := Result or PROPERTY_WRITE; if TBluetoothProperty.Notify in AProps then Result := Result or PROPERTY_NOTIFY; if TBluetoothProperty.Indicate in AProps then Result := Result or PROPERTY_INDICATE; if TBluetoothProperty.SignedWrite in AProps then Result := Result or PROPERTY_SIGNED_WRITE; if TBluetoothProperty.ExtendedProps in AProps then Result := Result or PROPERTY_EXTENDED_PROPS; end; function CheckOSVersionForGattClient: Boolean; begin Result := TOSVersion.Check(4, 3); end; function CheckOSVersionForGattServer: Boolean; begin Result := TOSVersion.Check(5); end; // --------------------------------------------------------------------- // { TBluetoothBroadcastReceiverListener } constructor TBluetoothBroadcastListener.Create(const AnAdapter: TAndroidBluetoothAdapter); begin inherited Create; FAdapter := AnAdapter; end; procedure TBluetoothBroadcastListener.onReceive(context: JContext; intent: JIntent); var LStrAction: string; LJBluetoothDevice: JBluetoothDevice; LDevice: TBluetoothDevice; LBTDevice: TAndroidBluetoothDevice; begin LStrAction := JStringToString(intent.getAction); if LStrAction = JStringToString(TJBluetoothDevice.JavaClass.ACTION_FOUND) then begin LJBluetoothDevice := TJBluetoothDevice.Wrap(intent.getParcelableExtra(TJBluetoothDevice.JavaClass.EXTRA_DEVICE)); LBTDevice := TAndroidBluetoothDevice.Create(LJBluetoothDevice); TAndroidBluetoothManager.AddDeviceToList(LBTDevice, TAndroidBluetoothManager(FAdapter.FManager).FDiscoveredDevices); end else if LStrAction = JStringToString(TJBluetoothAdapter.JavaClass.ACTION_DISCOVERY_STARTED) then begin end else if LStrAction = JStringToString(TJBluetoothAdapter.JavaClass.ACTION_DISCOVERY_FINISHED) then begin if (FAdapter.FDiscoveryThreadTimer <> nil) and FAdapter.FDiscoveryThreadTimer.FDiscovering and not FAdapter.FDiscoveryCancelled then if not FAdapter.FJAdapter.startDiscovery then FAdapter.FDiscoveryThreadTimer.FEvent.SetEvent; end else if LStrAction = JStringToString(TJBluetoothDevice.JavaClass.ACTION_BOND_STATE_CHANGED) then begin //Broadcast Action: Indicates a change in the bond state of a remote device. For example, if a device is bonded (paired). //Always contains the extra fields EXTRA_DEVICE, EXTRA_BOND_STATE and EXTRA_PREVIOUS_BOND_STATE. LJBluetoothDevice := TJBluetoothDevice.Wrap(intent.getParcelableExtra(TJBluetoothDevice.JavaClass.EXTRA_DEVICE)); LBTDevice := TAndroidBluetoothDevice.Create(LJBluetoothDevice); end else if LStrAction = JStringToString(TJBluetoothDevice.JavaClass.ACTION_ACL_CONNECTED) then begin LJBluetoothDevice := TJBluetoothDevice.Wrap(intent.getParcelableExtra(TJBluetoothDevice.JavaClass.EXTRA_DEVICE)); end else if LStrAction = JStringToString(TJBluetoothDevice.JavaClass.ACTION_ACL_DISCONNECTED) then begin LJBluetoothDevice := TJBluetoothDevice.Wrap(intent.getParcelableExtra(TJBluetoothDevice.JavaClass.EXTRA_DEVICE)); end else if LStrAction = JStringToString(TJBluetoothAdapter.JavaClass.ACTION_SCAN_MODE_CHANGED) then begin if FAdapter.FOldScanMode = TJBluetoothAdapter.JavaClass.SCAN_MODE_CONNECTABLE_DISCOVERABLE then FAdapter.DoDiscoverableEnd(FAdapter); FAdapter.FOldScanMode := intent.getIntExtra(TJBluetoothAdapter.JavaClass.EXTRA_SCAN_MODE, TJBluetoothAdapter.JavaClass.ERROR) end else if TOSVersion.Check(4, 0, 3) then // API Level 15 begin if LStrAction = JStringToString(TJBluetoothDevice.JavaClass.ACTION_UUID) then begin LJBluetoothDevice := TJBluetoothDevice.Wrap(intent.getParcelableExtra(TJBluetoothDevice.JavaClass.EXTRA_DEVICE)); for LDevice in TAndroidBluetoothManager(TBlueToothManager.Current).FPairedDevices do begin if TAndroidBluetoothDevice(LDevice).FJDevice.equals(LJBluetoothDevice) then begin LBTDevice := TAndroidBluetoothDevice(LDevice); LBTDevice.FEventUUIDS.SetEvent; break; end; end; end; // API Level 19 if TOSVersion.Check(4, 4) then begin if LStrAction = JStringToString(TJBluetoothDevice.JavaClass.ACTION_PAIRING_REQUEST) then begin // EXTRA_DEVICE LJBluetoothDevice := TJBluetoothDevice.Wrap(intent.getParcelableExtra(TJBluetoothDevice.JavaClass.EXTRA_DEVICE)); LBTDevice := TAndroidBluetoothDevice.Create(LJBluetoothDevice); FAdapter.DoRemoteRequestPair(LBTDevice); end end; end; end; { TPlatformBluetoothClassicManager } class function TPlatformBluetoothClassicManager.GetBluetoothManager: TBluetoothManager; begin Result := TAndroidBluetoothManager.Create; end; { TPlatformBluetoothLEManager } class function TPlatformBluetoothLEManager.GetBluetoothManager: TBluetoothLEManager; begin Result := TAndroidBluetoothLEManager.Create; end; { TAndroidBluetoothAdapter } procedure TAndroidBluetoothAdapter.DoCancelDiscovery; begin FDiscoveryCancelled := True; if (FDiscoveryThreadTimer <> nil) then FDiscoveryThreadTimer.FEvent.SetEvent; FJAdapter.cancelDiscovery; FDiscoveryThreadTimer.Free; end; constructor TAndroidBluetoothAdapter.Create(const AManager: TBluetoothManager; const AJAdapter: JBluetoothAdapter); begin inherited Create(AManager); // Do the magic FJAdapter := AJAdapter; FContext := TAndroidHelper.Context; FBroadcastListener := TBluetoothBroadcastListener.Create(Self); FBroadcastReceiver := TJFMXBroadcastReceiver.JavaClass.init(FBroadcastListener); FIntentFilter := TJIntentFilter.JavaClass.init(TJBluetoothDevice.JavaClass.ACTION_FOUND); FIntentFilter.addAction(TJBluetoothDevice.JavaClass.ACTION_BOND_STATE_CHANGED); FIntentFilter.addAction(TJBluetoothDevice.JavaClass.ACTION_ACL_CONNECTED); FIntentFilter.addAction(TJBluetoothDevice.JavaClass.ACTION_ACL_DISCONNECTED); FIntentFilter.addAction(TJBluetoothDevice.JavaClass.ACTION_ACL_DISCONNECT_REQUESTED); FIntentFilter.addAction(TJBluetoothAdapter.JavaClass.ACTION_DISCOVERY_STARTED); FIntentFilter.addAction(TJBluetoothAdapter.JavaClass.ACTION_DISCOVERY_FINISHED); FIntentFilter.addAction(TJBluetoothAdapter.JavaClass.ACTION_SCAN_MODE_CHANGED); // API Level 15 if TOSVersion.Check(4, 0, 3) then FIntentFilter.addAction(TJBluetoothDevice.JavaClass.ACTION_UUID); // API Level 19 if TOSVersion.Check(4, 4) then FIntentFilter.addAction(TJBluetoothDevice.JavaClass.ACTION_PAIRING_REQUEST); FContext.registerReceiver(FBroadcastReceiver, FIntentFilter); TMessageManager.DefaultManager.SubscribeToMessage(TMessageResultNotification, ResultCallback); FRequestEnableCallback := False; FOldScanMode := TJBluetoothAdapter.JavaClass.ERROR; end; destructor TAndroidBluetoothAdapter.Destroy; begin TMessageManager.DefaultManager.Unsubscribe(TMessageResultNotification, ResultCallback); // First cancel any pending discovery. FJAdapter.cancelDiscovery; // Unregister Receiver. FContext.unregisterReceiver(FBroadcastReceiver); FBroadcastReceiver := nil; FBroadcastListener.Free; FIntentFilter := nil; FJAdapter := nil; FContext := nil; inherited; end; function TAndroidBluetoothAdapter.DoCreateServerSocket(const AName: string; const AUUID: TGUID; Secure: Boolean): TBluetoothServerSocket; var LJServerSocket: JBluetoothServerSocket; LJUUID: JUUID; begin LJUUID := BluetoothUuidToJUuid(AUUID); if Secure then LJServerSocket := FJAdapter.listenUsingRfcommWithServiceRecord(StringToJString(AName), LJUUID) else LJServerSocket := FJAdapter.listenUsingInsecureRfcommWithServiceRecord(StringToJString(AName), LJUUID); Result := TAndroidBluetoothServerSocket.Create(LJServerSocket); end; function TAndroidBluetoothAdapter.GetAdapterName: string; begin Result := JStringToString(FJAdapter.getName); end; function TAndroidBluetoothAdapter.GetAddress: TBluetoothMacAddress; begin Result := JStringToString(FJAdapter.getAddress); end; function TAndroidBluetoothAdapter.GetPairedDevices: TBluetoothDeviceList; var LSetDevices: JSet; LIterator: JIterator; LDevice: JBluetoothDevice; begin TAndroidBluetoothManager(FManager).FPairedDevices.Clear; // Retrieve Paired Devices. LSetDevices := FJAdapter.getBondedDevices; LIterator := LSetDevices.iterator; if not LSetDevices.isEmpty then while LIterator.hasNext do begin LDevice := TJBluetoothDevice.Wrap(LIterator.next); TAndroidBluetoothManager(FManager).FPairedDevices.Add(TAndroidBluetoothDevice.Create(LDevice)); end; Result := TAndroidBluetoothManager(FManager).FPairedDevices; end; function TAndroidBluetoothAdapter.GetRemoteDevice(const AnAddress: TBluetoothMacAddress): TBluetoothDevice; begin Result := TAndroidBluetoothDevice.Create(FJAdapter.getRemoteDevice(StringToJString(AnAddress))); end; function TAndroidBluetoothAdapter.GetScanMode: TBluetoothScanMode; var LScanMode: Integer; begin LScanMode := FJAdapter.getScanMode; case LScanMode of 20: Result := TBluetoothScanMode.None; 21: Result := TBluetoothScanMode.Connectable; 23: Result := TBluetoothScanMode.Discoverable; else raise EBluetoothAdapterException.Create(SBluetoothScanModeError); end; end; function TAndroidBluetoothAdapter.GetState: TBluetoothAdapterState; begin case FJAdapter.getState of // STATE_OFF, STATE_TURNING_ON, STATE_TURNING_OFF. 10, 11, 13: Result := TBluetoothAdapterState.Off; // STATE_ON 12: begin if FJAdapter.isDiscovering then Result := TBluetoothAdapterState.Discovering else Result := TBluetoothAdapterState.&On; end; else raise EBluetoothAdapterException.Create(SBluetoothStateError); end; end; function TAndroidBluetoothAdapter.DoPair(const ADevice: TBluetoothDevice): Boolean; begin // API Level 19 if TOSVersion.Check(4, 4) then Result := TAndroidBluetoothDevice(ADevice).FJDevice.createBond else Result := False; end; procedure TAndroidBluetoothAdapter.SetAdapterName(const Value: string); begin inherited; FJAdapter.setName(StringToJString(Value)); end; procedure TAndroidBluetoothAdapter.DoStartDiscoverable(Timeout: Cardinal); var LIntent: JIntent; begin inherited; if FJAdapter.isEnabled and (FJAdapter.getScanMode <> TJBluetoothAdapter.JavaClass.SCAN_MODE_CONNECTABLE_DISCOVERABLE) then begin FWaitingCallBack := true; LIntent := TJIntent.JavaClass.init(TJBluetoothAdapter.JavaClass.ACTION_REQUEST_DISCOVERABLE); LIntent.putExtra(TJBluetoothAdapter.JavaClass.EXTRA_DISCOVERABLE_DURATION, Integer(Timeout)); TAndroidHelper.Activity.startActivityForResult(LIntent, REQUEST_DISCOVERABLE); { Wait here until adapter becomes discoverable. It happens before the user answers system dialog about permissions } InternalProcessMessages; while FWaitingCallBack and (FJAdapter.getScanMode <> TJBluetoothAdapter.JavaClass.SCAN_MODE_CONNECTABLE_DISCOVERABLE) do InternalProcessMessages; end; end; procedure TAndroidBluetoothAdapter.ResultCallback(const Sender: TObject; const M: TMessage); var LMessage: TMessageResultNotification; begin LMessage := TMessageResultNotification(M); case LMessage.RequestCode of REQUEST_DISCOVERABLE: begin // { Now we can use LMessage.RequestCode, LMessage.ResultCode and LMessage.Value (JIntent object) } // if LMessage.ResultCode <> 0 then // begin // { The user has accepted the Discoverable state. When it finishes show } // end; FWaitingCallback := False; end; REQUEST_ENABLE_BT: FRequestEnableCallback := False; end; end; procedure TAndroidBluetoothAdapter.DoStartDiscovery(Timeout: Cardinal); begin if FJAdapter.isEnabled and not FJAdapter.isDiscovering then begin { Under Android you cannont Set the Timeout value for the Discovery } { Launch the Discovery } if FJAdapter.startDiscovery then begin TAndroidBluetoothManager(FManager).FDiscoveredDevices.Clear; // Start Timer for Discovery process. FDiscoveryCancelled := False; if FDiscoveryThreadTimer <> nil then FDiscoveryThreadTimer.DisposeOf; FDiscoveryThreadTimer := TThreadTimer.Create(Self, Self.DoDiscoveryEnd, Timeout); FDiscoveryThreadTimer.Start; // Ensure that wer are discovering before returning. while not FJAdapter.isDiscovering do Sleep(1); end; end; end; function TAndroidBluetoothAdapter.DoUnPair(const ADevice: TBluetoothDevice): Boolean; begin { Cannot Unpair devices in Android. } raise EBluetoothAdapterException.CreateFmt(SBluetoothNotSupported, ['UnPair', 'Android']); // Do not translate. end; { TAndroidBluetoothAdapter.TThreadTimer } procedure TAndroidBluetoothAdapter.TThreadTimer.Cancel; begin Terminate; FDiscovering := False; FEvent.SetEvent; if Assigned(FOnTimer) then FOnTimer := nil; end; constructor TAndroidBluetoothAdapter.TThreadTimer.Create(const AnAdapter: TBluetoothAdapter; const AEvent: TDiscoveryEndEvent; Timeout: Cardinal); begin inherited Create(True); FAdapter := AnAdapter; FOnTimer := AEvent; FTimeout := Timeout; FEvent := TEvent.Create; end; destructor TAndroidBluetoothAdapter.TThreadTimer.Destroy; begin Cancel; inherited; FEvent.Free; end; procedure TAndroidBluetoothAdapter.TThreadTimer.Execute; var LWaitResult: TWaitResult; begin inherited; FDiscovering := True; LWaitResult := FEvent.WaitFor(FTimeout); if LWaitResult = TWaitResult.wrTimeout then begin FDiscovering := False; end else if LWaitResult = TWaitResult.wrSignaled then begin // There has been a cancelation of the discover process. if TAndroidBluetoothAdapter(FAdapter).FDiscoveryCancelled then Exit; TAndroidBluetoothAdapter(FAdapter).FJAdapter.cancelDiscovery; end; TAndroidBluetoothAdapter(FAdapter).FJAdapter.cancelDiscovery; if not Terminated and not TAndroidBluetoothAdapter(FAdapter).FDiscoveryCancelled and Assigned(FOnTimer) then begin try FOnTimer(FAdapter, TAndroidBluetoothManager(TAndroidBluetoothAdapter(FAdapter).FManager).FDiscoveredDevices); except if Assigned(System.Classes.ApplicationHandleException) then System.Classes.ApplicationHandleException(Self) else raise; end; end; end; { TAndroidBluetoothLEAdapter } constructor TAndroidBluetoothLEAdapter.Create(const AManager: TBluetoothLEManager; const AJAdapter: JBluetoothAdapter); begin inherited Create(AMAnager); FJAdapter := AJAdapter; FContext := TAndroidBluetoothLEManager(AManager).FContext; if TOSVersion.Check(4, 3) then if TOSVersion.Check(5) then begin FJScanListener := TScanCallback.Create(Self); FJScanCallback := TJRTLScanCallback.JavaClass.init(FJScanListener); FEventStartScan := TEvent.Create; end else FLeCallback := TBluetoothLeScanCallback.Create(Self); TMessageManager.DefaultManager.SubscribeToMessage(TMessageResultNotification, ResultCallback); FRequestEnableCallback := False; end; destructor TAndroidBluetoothLEAdapter.Destroy; begin TMessageManager.DefaultManager.Unsubscribe(TMessageResultNotification, ResultCallback); FLeCallback := nil; FJScanCallback := nil; FJScanListener := nil; FJAdapter := nil; FContext := nil; if FEventStartScan <> nil then FEventStartScan.Free; inherited; end; procedure TAndroidBluetoothLEAdapter.DoCancelDiscovery; begin if TOSVersion.Check(5) then begin if (FJScanner <> nil) then FJScanner.stopScan(FJScanCallback) end else FJAdapter.stopLeScan(FLeCallback); if FTimerThread <> nil then begin FTimerThread.Cancel; FTimerThread.Free; end; inherited; FBLEDiscovering := False; end; procedure TAndroidBluetoothLEAdapter.DoDiscoveryEnd(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); begin DoCancelDiscovery; inherited DoDiscoveryEnd(Sender, ADeviceList); end; function TAndroidBluetoothLEAdapter.DoStartDiscovery(Timeout: Cardinal; const FilterUUIDList: TBluetoothUUIDsList; const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList): Boolean; var LServiceUuids: TJavaObjectArray<JUUID>; LBluetoothLEScanFilterList: TBluetoothLEScanFilterList; I: Integer; begin FBluetoothLEScanFilterList := nil; LServiceUUIDs := BluetoothUUIDsListToJavaArrayUUID(FilterUUIDList); if TOSVersion.Check(5) then begin if (FilterUUIDList <> nil) and (FilterUUIDList.Count > 0) then begin LBluetoothLEScanFilterList := TBluetoothLEScanFilterList.Create; for I := 0 to FilterUUIDList.Count - 1 do begin LBluetoothLEScanFilterList.Add(TBluetoothLEScanFilter.Create); LBluetoothLEScanFilterList[I].ServiceUUID := FilterUUIDList[I]; end; Result := DoStartDiscoveryRaw(LBluetoothLEScanFilterList); end else Result := DoStartDiscoveryRaw(ABluetoothLEScanFilterList); end else if LServiceUUIDs <> nil then Result := FJAdapter.startLeScan(LServiceUUIDs, FLeCallback) else begin FBluetoothLEScanFilterList := ABluetoothLEScanFilterList; Result := FJAdapter.startLeScan(FLeCallback); end; if Result then begin FTimerThread := TThreadTimer.Create(Self, Self.DoDiscoveryEnd, Timeout); FTimerThread.Start; FBLEDiscovering := True; end; end; function TAndroidBluetoothLEAdapter.DoStartDiscoveryRaw(const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList; Refresh: Boolean): Boolean; function CreateScanFilters: JArrayList; const MANUFACTURER_IDMASK: Word = $0101; BEACON_MANUFACTURER_ID_POSITION = 0; var LJScanFilter_Builder: JScanFilter_Builder; LManufacturerSpecificData: TBytes; LManufacturerSpecificDataMask: TBytes; LManufacturerId: Word; I: Integer; LHardwareFilter: Boolean; begin LHardwareFilter := True; Result := TJArrayList.JavaClass.init; for I := 0 to ABluetoothLEScanFilterList.Count - 1 do begin if ABluetoothLEScanFilterList[I].ServiceUUID <> TBluetoothUUID.Empty then begin LJScanFilter_Builder := TJScanFilter_Builder.JavaClass.init; if ABluetoothLEScanFilterList[I].ServiceUUIDMask <> TBluetoothUUID.Empty then LJScanFilter_Builder.setServiceUuid(TJParcelUuid.JavaClass.init(BluetoothUuidToJUuid(ABluetoothLEScanFilterList[I].ServiceUUID)), TJParcelUuid.JavaClass.init(BluetoothUuidToJUuid(ABluetoothLEScanFilterList[I].ServiceUUIDMask))) else LJScanFilter_Builder.setServiceUuid(TJParcelUuid.JavaClass.init(BluetoothUuidToJUuid(ABluetoothLEScanFilterList[I].ServiceUUID))); if ABluetoothLEScanFilterList[I].ServiceData.Key <> TBluetoothUUID.Empty then begin if (ABluetoothLEScanFilterList[I].ServiceDataMask <> nil) and (ABluetoothLEScanFilterList[I].ServiceData.Value <> nil) and (Length(ABluetoothLEScanFilterList[I].ServiceDataMask) = Length(ABluetoothLEScanFilterList[I].ServiceData.Value)) then LJScanFilter_Builder.setServiceData(TJParcelUuid.JavaClass.init(BluetoothUuidToJUuid(ABluetoothLEScanFilterList[I].ServiceData.Key)), TBytesToTJavaArray(ABluetoothLEScanFilterList[I].ServiceData.Value), TBytesToTJavaArray(ABluetoothLEScanFilterList[I].ServiceDataMask)) else LJScanFilter_Builder.setServiceData(TJParcelUuid.JavaClass.init(BluetoothUuidToJUuid(ABluetoothLEScanFilterList[I].ServiceData.Key)), TBytesToTJavaArray(ABluetoothLEScanFilterList[I].ServiceData.Value)); ABluetoothLEScanFilterList[I].ServiceData := TServiceDataRawData.Create(TBluetoothUUID.Empty, nil); end else begin if (ABluetoothLEScanFilterList[I].ManufacturerSpecificData <> nil) and (Length(ABluetoothLEScanFilterList[I].ManufacturerSpecificData) > 1) then begin LManufacturerId := PWord(@ABluetoothLEScanFilterList[I].ManufacturerSpecificData[0])^; SetLength(LManufacturerSpecificData, Length(ABluetoothLEScanFilterList[I].ManufacturerSpecificData) - LManufacturerId.Size); Move(ABluetoothLEScanFilterList[I].ManufacturerSpecificData[LManufacturerId.Size], LManufacturerSpecificData[0], Length(LManufacturerSpecificData)); if (ABluetoothLEScanFilterList[I].ManufacturerSpecificDataMask <> nil) and (Length(ABluetoothLEScanFilterList[I].ManufacturerSpecificData) = Length(ABluetoothLEScanFilterList[I].ManufacturerSpecificDataMask)) then begin SetLength(LManufacturerSpecificDataMask, Length(LManufacturerSpecificData)); Move(ABluetoothLEScanFilterList[I].ManufacturerSpecificDataMask[LManufacturerId.Size], LManufacturerSpecificDataMask[0], Length(LManufacturerSpecificDataMask)); LJScanFilter_Builder.setManufacturerData(LManufacturerId, TBytesToTJavaArray(LManufacturerSpecificData), TBytesToTJavaArray(LManufacturerSpecificDataMask)); if PWord(@ABluetoothLEScanFilterList[I].ManufacturerSpecificDataMask[BEACON_MANUFACTURER_ID_POSITION])^ < MANUFACTURER_IDMASK then LHardwareFilter := False end else LJScanFilter_Builder.setManufacturerData(LManufacturerId, TBytesToTJavaArray(LManufacturerSpecificData)); ABluetoothLEScanFilterList[I].ManufacturerSpecificData := nil; end; end; Result.add(LJScanFilter_Builder.build); end; if (ABluetoothLEScanFilterList[I].ManufacturerSpecificData <> nil) and (Length(ABluetoothLEScanFilterList[I].ManufacturerSpecificData) > 1) then begin LJScanFilter_Builder := TJScanFilter_Builder.JavaClass.init; LManufacturerId := PWord(@ABluetoothLEScanFilterList[I].ManufacturerSpecificData[0])^; SetLength(LManufacturerSpecificData, Length(ABluetoothLEScanFilterList[I].ManufacturerSpecificData) - LManufacturerId.Size); Move(ABluetoothLEScanFilterList[I].ManufacturerSpecificData[LManufacturerId.Size], LManufacturerSpecificData[0], Length(LManufacturerSpecificData)); if (ABluetoothLEScanFilterList[I].ManufacturerSpecificDataMask <> nil) and (Length(ABluetoothLEScanFilterList[I].ManufacturerSpecificData) = Length(ABluetoothLEScanFilterList[I].ManufacturerSpecificDataMask)) then begin SetLength(LManufacturerSpecificDataMask, Length(LManufacturerSpecificData)); Move(ABluetoothLEScanFilterList[I].ManufacturerSpecificDataMask[LManufacturerId.Size], LManufacturerSpecificDataMask[0], Length(LManufacturerSpecificDataMask)); LJScanFilter_Builder.setManufacturerData(LManufacturerId, TBytesToTJavaArray(LManufacturerSpecificData), TBytesToTJavaArray(LManufacturerSpecificDataMask)); if PWord(@ABluetoothLEScanFilterList[I].ManufacturerSpecificDataMask[BEACON_MANUFACTURER_ID_POSITION])^ < MANUFACTURER_IDMASK then LHardwareFilter := False end else LJScanFilter_Builder.setManufacturerData(LManufacturerId, TBytesToTJavaArray(LManufacturerSpecificData)); Result.add(LJScanFilter_Builder.build); end; if ABluetoothLEScanFilterList[I].ServiceData.Key <> TBluetoothUUID.Empty then begin LJScanFilter_Builder := TJScanFilter_Builder.JavaClass.init; if (ABluetoothLEScanFilterList[I].ServiceDataMask <> nil) and (ABluetoothLEScanFilterList[I].ServiceData.Value <> nil) and (Length(ABluetoothLEScanFilterList[I].ServiceDataMask) = Length(ABluetoothLEScanFilterList[I].ServiceData.Value)) then LJScanFilter_Builder.setServiceData(TJParcelUuid.JavaClass.init(BluetoothUuidToJUuid(ABluetoothLEScanFilterList[I].ServiceData.Key)), TBytesToTJavaArray(ABluetoothLEScanFilterList[I].ServiceData.Value), TBytesToTJavaArray(ABluetoothLEScanFilterList[I].ServiceDataMask)) else LJScanFilter_Builder.setServiceData(TJParcelUuid.JavaClass.init(BluetoothUuidToJUuid(ABluetoothLEScanFilterList[I].ServiceData.Key)), TBytesToTJavaArray(ABluetoothLEScanFilterList[I].ServiceData.Value)); Result.add(LJScanFilter_Builder.build); end; if ABluetoothLEScanFilterList[I].LocalName <> '' then begin LJScanFilter_Builder := TJScanFilter_Builder.JavaClass.init; LJScanFilter_Builder.setDeviceName(StringToJString(ABluetoothLEScanFilterList[I].LocalName)); Result.add(LJScanFilter_Builder.build); end; if ABluetoothLEScanFilterList[I].DeviceAddress <> '' then begin LJScanFilter_Builder := TJScanFilter_Builder.JavaClass.init; LJScanFilter_Builder.setDeviceAddress(StringToJString(ABluetoothLEScanFilterList[I].DeviceAddress)); Result.add(LJScanFilter_Builder.build); end; end; if not LHardwareFilter then Result := nil; end; var LJScanSettings_Builder: JScanSettings_Builder; LScanSettings: Integer; begin DoCancelDiscovery; if TOSVersion.Check(5) then begin LScanSettings := TAndroidBluetoothLEManager(FManager).ScanSettings; if (FJScanSettings = nil) or (FScanSettings <> LScanSettings) then begin FScanSettings := LScanSettings; LJScanSettings_Builder := TJScanSettings_Builder.JavaClass.init; LJScanSettings_Builder.setScanMode(FScanSettings); FJScanSettings := LJScanSettings_Builder.build; end; if FJScanner = nil then FJScanner := FJAdapter.getBluetoothLeScanner; if ABluetoothLEScanFilterList <> nil then begin if Refresh or (FJArrayListOfAdvertiseData = nil) then FJArrayListOfAdvertiseData := CreateScanFilters; if (FJArrayListOfAdvertiseData <> nil) then begin FBluetoothLEScanFilterList := nil; FJScanner.startScan(TJList.Wrap(FJArrayListOfAdvertiseData), FJScanSettings,FJScanCallback); end else begin FBluetoothLEScanFilterList := ABluetoothLEScanFilterList; FJScanner.startScan(nil, FJScanSettings,FJScanCallback); end; end else FJScanner.startScan(nil, FJScanSettings,FJScanCallback); FEventStartScan.ResetEvent; FEventStartScan.WaitFor(1000); if FStartScanFailed > 1 then // SCAN_FAILED_ALREADY_STARTED $01 Result := False else Result := True; end else begin FBluetoothLEScanFilterList := ABluetoothLEScanFilterList; Result := FJAdapter.startLeScan(FLeCallback); end; FBLEDiscovering := Result; end; function TAndroidBluetoothLEAdapter.GetAdapterName: string; begin Result := JStringToString(FJAdapter.getName); end; function TAndroidBluetoothLEAdapter.GetAddress: TBluetoothMacAddress; begin Result := JStringToString(FJAdapter.getAddress); end; function TAndroidBluetoothLEAdapter.GetRemoteDevice(const AnAddress: TBluetoothMacAddress): TBluetoothLEDevice; begin Result := TAndroidBluetoothLEDevice.Create(FJAdapter.getRemoteDevice(StringToJString(AnAddress)), True); end; function TAndroidBluetoothLEAdapter.GetScanMode: TBluetoothScanMode; var LScanMode: Integer; begin LScanMode := FJAdapter.getScanMode; case LScanMode of 20: Result := TBluetoothScanMode.None; 21: Result := TBluetoothScanMode.Connectable; 23: Result := TBluetoothScanMode.Discoverable; else raise EBluetoothLEAdapterException.Create(SBluetoothScanModeError); end; end; function TAndroidBluetoothLEAdapter.GetState: TBluetoothAdapterState; begin case FJAdapter.getState of // STATE_OFF, STATE_TURNING_ON, STATE_TURNING_OFF. 10, 11, 13: Result := TBluetoothAdapterState.Off; // STATE_ON 12: begin if FBLEDiscovering then Result := TBluetoothAdapterState.Discovering else Result := TBluetoothAdapterState.&On; end; else raise EBluetoothLEAdapterException.Create(SBluetoothStateError); end; end; procedure TAndroidBluetoothLEAdapter.SetAdapterName(const Value: string); begin inherited; FJAdapter.setName(StringToJString(Value)); end; procedure TAndroidBluetoothLEAdapter.ResultCallback(const Sender: TObject; const M: TMessage); begin if TMessageResultNotification(M).RequestCode = REQUEST_ENABLE_BT then FRequestEnableCallback := False; end; { TAndroidBluetoothLEAdapter.TThreadTimer } constructor TAndroidBluetoothLEAdapter.TThreadTimer.Create(const AnAdapter: TBluetoothLEAdapter; const AEvent: TDiscoveryLEEndEvent; Timeout: Cardinal); begin inherited Create(True); FAdapter := AnAdapter; FOnTimer := AEvent; FTimeout := Timeout; FEvent := TEvent.Create; end; destructor TAndroidBluetoothLEAdapter.TThreadTimer.Destroy; begin Cancel; FEvent.Free; inherited; end; procedure TAndroidBluetoothLEAdapter.TThreadTimer.Cancel; begin Terminate; if Assigned(FOnTimer) then begin FOnTimer := nil; FEvent.SetEvent; end; end; procedure TAndroidBluetoothLEAdapter.TThreadTimer.Execute; begin inherited; FEvent.WaitFor(FTimeout); if not Terminated and Assigned(FOnTimer) then begin try FOnTimer(FAdapter, nil); except if Assigned(System.Classes.ApplicationHandleException) then System.Classes.ApplicationHandleException(Self) else raise; end; end; end; { TAndroidBluetoothManager } constructor TAndroidBluetoothManager.Create; var LocalManager: JObject; begin inherited; { This code needs API_18 } if TOsVersion.Check(4, 3) then begin FContext := TAndroidHelper.Context; LocalManager := FContext.getSystemService(TJContext.JavaClass.BLUETOOTH_SERVICE); if LocalManager <> nil then FJManager := TJBluetoothManager.Wrap(LocalManager); end; end; destructor TAndroidBluetoothManager.Destroy; begin FJManager := nil; FContext := nil; inherited; end; function TAndroidBluetoothManager.GetAdapterState: TBluetoothAdapterState; begin if FAdapter = nil then begin { API Level 18; } if TOSVersion.Check(4,3) then FAdapter := TAndroidBluetoothAdapter.Create(Self, FJManager.getAdapter) else FAdapter := TAndroidBluetoothAdapter.Create(Self, TJBluetoothAdapter.JavaClass.getDefaultAdapter); end; Result := FAdapter.State; end; function TAndroidBluetoothManager.DoGetClassicAdapter: TBluetoothAdapter; var LAndroidBluetoothAdapter: TAndroidBluetoothAdapter; begin if GetAdapterState = TBluetoothAdapterState.Off then begin LAndroidBluetoothAdapter := TAndroidBluetoothAdapter(FAdapter); if LAndroidBluetoothAdapter.FRequestEnableCallback then begin InternalProcessMessages; while LAndroidBluetoothAdapter.FRequestEnableCallback do InternalProcessMessages; if GetAdapterState = TBluetoothAdapterState.Off then FAdapter := nil; end else FAdapter := nil; end; Result := FAdapter; end; function TAndroidBluetoothManager.GetConnectionState: TBluetoothConnectionState; begin if GetAdapterState = TBluetoothAdapterState.Off then Result := TBluetoothConnectionState.Disconnected else Result := TBluetoothConnectionState.Connected; end; function TAndroidBluetoothManager.DoEnableBluetooth: Boolean; var LIntent: JIntent; begin if GetConnectionState = TBluetoothConnectionState.Disconnected then begin TAndroidBluetoothAdapter(FAdapter).FRequestEnableCallback := True; TThread.CreateAnonymousThread(procedure begin LIntent := TJIntent.JavaClass.init(TJBluetoothAdapter.JavaClass.ACTION_REQUEST_ENABLE); TAndroidHelper.Activity.startActivityForResult(LIntent, REQUEST_ENABLE_BT); end).Start; end; Result := True; end; { TAndroidBluetoothDevice } constructor TAndroidBluetoothDevice.Create(const AJDevice: JBluetoothDevice); begin inherited Create; FJDevice := AJDevice; FEventUUIDS := TEvent.Create; end; destructor TAndroidBluetoothDevice.Destroy; begin FEventUUIDS.Free; FJDevice := nil; inherited; end; function TAndroidBluetoothDevice.DoCreateClientSocket(const AUUID: TGUID; Secure: Boolean): TBluetoothSocket; var LJUUID: JUUID; LJSocket: JBluetoothSocket; begin Result := nil; LJUUID := BluetoothUuidToJUuid(AUUID); if Secure then LJSocket := FJDevice.createRfcommSocketToServiceRecord(LJUUID) else LJSocket := FJDevice.createInsecureRfcommSocketToServiceRecord(LJUUID); if LJSocket <> nil then Result := TAndroidBluetoothSocket.Create(LJSocket); end; function TAndroidBluetoothDevice.DoGetServices: TBluetoothServiceList; var LJArray: TJavaObjectArray<JParcelUuid>; LParcel: JParcelUuid; I: Integer; LLength: Integer; LService: TBluetoothService; begin FServiceList.Clear; try { API Level 15 } if TOSVersion.Check(4, 0, 2) then begin FEventUUIDS.ResetEvent; if FJDevice.fetchUuidsWithSdp then FEventUUIDS.WaitFor(BluetoothServicesTimeout); LJArray := FJDevice.getUuids; LLength := 0; if LJArray <> nil then LLEngth := LJArray.Length; for I := 0 to LLength - 1 do begin LParcel := TJParcelUuid.Wrap(LJArray.GetRawItem(I)); LService.UUID := JUuidToBluetoothUuid(LParcel.getUuid); LService.Name := TAndroidBluetoothManager.GetKnownServiceName(LService.UUID); FServiceList.Add(LService); end; end; finally Result := FServiceList; end; end; function TAndroidBluetoothDevice.GetAddress: TBluetoothMacAddress; begin Result := JStringToString(FJDevice.getAddress); end; function TAndroidBluetoothDevice.GetBluetoothType: TBluetoothType; begin { Check API Level 18 and ask for BT Type } if TOSVersion.Check(4, 3) then Result := TBluetoothType(FJDevice.getType) else Result := TBluetoothType.Classic; end; function TAndroidBluetoothDevice.GetClassDevice: Integer; begin Result := FJDevice.getBluetoothClass.getDeviceClass; end; function TAndroidBluetoothDevice.GetClassDeviceMajor: Integer; begin Result := FJDevice.getBluetoothClass.getMajorDeviceClass; end; function TAndroidBluetoothDevice.GetDeviceName: string; begin Result := JStringToString(FJDevice.getName); end; function TAndroidBluetoothDevice.GetOnDiscoverService: TDiscoverServiceEvent; begin Result := FDiscoverServiceEvent; end; function TAndroidBluetoothDevice.GetPaired: Boolean; begin Result := FJDevice.getBondState = TJBluetoothDevice.JavaClass.BOND_BONDED; end; function TAndroidBluetoothDevice.GetState: TBluetoothDeviceState; var LBondState: Integer; begin LBondState := FJDevice.getBondState; case LBondState of 10: Result := TBluetoothDeviceState.None; 11: Result := TBluetoothDeviceState.None; //11: Result := TBluetoothDeviceState.Pairing; 12: Result := TBluetoothDeviceState.Paired; else raise EBluetoothAdapterException.CreateFmt(SBluetoothDeviceStateError, [GetDeviceName]); end; end; function TAndroidBluetoothDevice.Pair: Boolean; begin { API Level 19 } if TOSVersion.Check(4, 4) then Result := FJDevice.createBond else Result := False; end; procedure TAndroidBluetoothDevice.SetOnDiscoverService(const Value: TDiscoverServiceEvent); begin FDiscoverServiceEvent := Value; end; { TAndroidBluetoothSocket } procedure TAndroidBluetoothSocket.DoClose; begin FConnected := False; if FJBluetoothSocket.isConnected then begin if FJOStream <> nil then begin FJOStream.close; FJOStream := nil; end; if FJIStream <> nil then begin FJIStream.close; FJIStream := nil; end; FJBluetoothSocket.close; end; end; procedure TAndroidBluetoothSocket.DoConnect; begin //TBluetoothManager.Current.CancelDiscovery; // TODO -cCHECK FJBluetoothSocket.connect; FConnected := True; end; constructor TAndroidBluetoothSocket.Create(const ASocket: JBluetoothSocket); begin inherited Create; FJBluetoothSocket := ASocket; FJBytes := TJavaArray<System.Byte>.Create(BUFFER_SIZE); FSocketEvent := TEvent.Create; FReaderEvent := TEvent.Create; FDestroying := False; FReader := TAndroidBluetoothSocket.TBluetoothSocketReader.Create(Self, BUFFER_SIZE); FReader.Start; FSocketEvent.WaitFor(SocketEventTimeout); FSocketEvent.ResetEvent; end; destructor TAndroidBluetoothSocket.Destroy; begin FDestroying := True; if FJOStream <> nil then FJOStream.close; if FJIStream <> nil then FJIStream.close; if FJBluetoothSocket.isConnected then FJBluetoothSocket.close; FReader.DisposeOf; FReader := nil; FSocketEvent.SetEvent; FReaderEvent.Free; FSocketEvent.Free; FJOStream := nil; FJIStream := nil; FJBluetoothSocket := nil; FJBytes.Free; inherited; end; function TAndroidBluetoothSocket.GetConnected: Boolean; begin if TOsVersion.Check(4) then Result := FConnected and (FJBluetoothSocket <> nil) and FJBluetoothSocket.isConnected else Result := FConnected; end; function TAndroidBluetoothSocket.GetRemoteDevice: TBluetoothDevice; begin Result := TAndroidBluetoothDevice.Create(FJBluetoothSocket.getRemoteDevice); end; function TAndroidBluetoothSocket.DoReceiveData(ATimeout: Cardinal): TBytes; var LReaded: Integer; LCount: Integer; LTime: Cardinal; begin if FJIStream = nil then FJIStream := TJInputStream.Wrap(FJBluetoothSocket.getInputStream); LCount := 0; SetLength(Result, LCount); if (FJIStream <> nil) and (FReader <> nil) then begin // Tell Reader to start reading; FSocketEvent.ResetEvent; FReaderEvent.SetEvent; if Atimeout = 0 then LTime := 1 else LTime := ATimeout; // Wait until Reader reads or timeout or error if FSocketEvent.WaitFor(LTime) <> TWaitResult.wrSignaled then Exit; if FReader <> nil then begin LReaded := FReader.GetBufferedDataSize; if LReaded < 0 then raise EBluetoothSocketException.Create(SBluetoothRFChannelClosed) else begin // Check for already readed data. if LReaded > 0 then begin SetLength(Result, LCount + LReaded); FReader.GetBufferedData(Result, LCount); LCount := LCount + LReaded; end; // Check for available data. repeat try if (FJIStream <> nil) and (FJIStream.available <> 0) then LReaded := FJIStream.read(FJBytes) else Break; except LReaded := -1; end; if LReaded < 0 then raise EBluetoothSocketException.Create(SBluetoothRFChannelClosed); SetLength(Result, LCount + LReaded); Move(PByte(FJBytes.Data)^, Result[LCount], LReaded); LCount := LCount + LReaded; until (LReaded < BUFFER_SIZE) or (FJIStream = nil); end; end; end; end; procedure TAndroidBluetoothSocket.DoSendData(const AData: TBytes); var LJBytes: TJavaArray<System.Byte>; begin inherited; if FJOStream = nil then FJOStream := TJOutputStream.Wrap(FJBluetoothSocket.getOutputStream); if FJOStream <> nil then begin LJBytes := TBytesToTJavaArray(AData); try FJOStream.write(LJBytes); finally LJBytes.Free; end; end else EBluetoothSocketException.Create(SBluetoothSocketOutputStreamError); end; { TAndroidBluetoothServerSocket } function TAndroidBluetoothServerSocket.DoAccept(Timeout: Cardinal): TBluetoothSocket; var LSocket: JBluetoothSocket; begin try LSocket := FJServerSocket.accept(Timeout); Result := TAndroidBluetoothSocket.Create(LSocket); except Result := nil; end; end; procedure TAndroidBluetoothServerSocket.DoClose; begin inherited; FJServerSocket.close; end; constructor TAndroidBluetoothServerSocket.Create(const AServerSocket: JBluetoothServerSocket); begin inherited Create; FJServerSocket := AServerSocket; end; destructor TAndroidBluetoothServerSocket.Destroy; begin FJServerSocket.close; FJServerSocket := nil; inherited; end; { TBluetoothLeScanCallback } function ServiceUUIDToGUID(const AData: TBytes): TGUID; var W: Word; TB: TBytes; I, Z : Integer; begin if Length(AData) = 2 then begin Result := BLUETOOTH_BASE_UUID; WordRec(W).Hi := Adata[0]; WordRec(W).Lo := Adata[1]; Result.D1 := Cardinal(W); end else begin Z := 0; SetLength(TB, Length(AData)); for I := Length(AData) - 1 downto 0 do begin TB[Z] := AData[I]; Inc(Z); end; Result := TGUID.Create(PByte(TB)^, TEndian.Big); end; end; function ScanRecordToTScanResponse(const AScanRecord: TJavaArray<Byte>; const AScanResponse: TScanResponse): TScanResponse; var I:Integer; LDataLength, LTotalLength: Byte; LScanRecord: TBytes; LCurrentData: TBytes; LAdType: Byte; begin if AScanResponse = nil then Result := TScanResponse.Create else Result := AScanResponse; LScanRecord := TJavaArrayToTBytes(AScanRecord); LTotalLength := Length(LScanRecord); I := 0; LDataLength := LScanRecord[I]; while I < LTotalLength do begin Inc(I); if LDataLength > 0 then begin Assert(I < LTotalLength); LAdType := LScanRecord[I]; Setlength(LCurrentData, LDataLength - 1); // Ensure the scan record array is as large as the data block we are about to copy from it Assert(I + LDataLength < LTotalLength); Move(LScanRecord[I+1], LCurrentData[0], LDataLength - 1); Result.AddOrSetValue(TScanResponseKey(LAdType), LCurrentData); end; Inc(I, LDataLength); if I < LTotalLength then LDataLength := LScanRecord[I]; end; end; constructor TBluetoothLeScanCallback.Create(const AnAdapter: TAndroidBluetoothLEAdapter); begin inherited Create; FAdapter := AnAdapter; end; procedure TBluetoothLeScanCallback.onLeScan(device: JBluetoothDevice; rssi: Integer; scanRecord: TJavaArray<Byte>); var LDevice: TAndroidBluetoothLEDevice; LNew: Boolean; begin LNew := False; LDevice := TAndroidBluetoothLEDevice(TAndroidBluetoothLEManager.GetDeviceInList(JStringToString(device.getAddress), FAdapter.FManager.ALLDiscoveredDevices)); if LDevice = nil then begin LDevice := TAndroidBluetoothLEDevice.Create(device, False, FAdapter.FManager.ForceRefreshCachedDevices); LNew := True; end else LDevice.FJDevice := device; LDevice.FAdvertisedData := ScanRecordToTScanResponse(scanRecord, LDevice.FAdvertisedData); LDevice.FLastRSSI := rssi; FAdapter.DoDeviceDiscovered(LDevice, LNew, FAdapter.FBluetoothLEScanFilterList); end; { TAndroidBluetoothGattServer } constructor TAndroidBluetoothGattServer.Create(const AManager: TAndroidBluetoothLEManager; const AnAdapter: TAndroidBluetoothLEAdapter); begin inherited Create(AManager); FJGattServerListener := TAndroidBluetoothGattServerListener.Create(Self); FJGattServerCallback := TJRTLBluetoothGattServerCallback.JavaClass.init(FJGattServerListener); FJGattServer := AManager.FJManager.openGattServer(Amanager.FContext, FJGattServerCallback); end; destructor TAndroidBluetoothGattServer.Destroy; begin FJGattServerCallback := nil; FJGattServerListener := nil; FJGattServer := nil; inherited; end; function TAndroidBluetoothGattServer.DoCreateCharacteristic(const AService: TBluetoothGattService; const AnUUID: TBluetoothUUID; const AProps: TBluetoothPropertyFlags; const ADescription: string): TBluetoothGattCharacteristic; begin Result := TAndroidBluetoothGattService(AService).CreateCharacteristic(AnUUID, AProps, ADescription); end; function TAndroidBluetoothGattServer.DoCreateDescriptor(const ACharacteristic: TBluetoothGattCharacteristic; const AnUUID: TBluetoothUUID): TBluetoothGattDescriptor; begin Result := TAndroidBluetoothGattCharacteristic(ACharacteristic).CreateDescriptor(AnUUID); end; function TAndroidBluetoothGattServer.DoCreateIncludedService(const AService: TBluetoothGattService; const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType): TBluetoothGattService; begin Result := TAndroidBluetoothGattService(AService).CreateIncludedService(AnUUID, AType); end; function TAndroidBluetoothGattServer.DoCreateService(const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType): TBluetoothGattService; var LJService: JBluetoothGattService; begin LJService := TJBluetoothGattService.JavaClass.init(BluetoothUuidToJUuid(AnUUID), Integer(AType)); Result := TAndroidBluetoothGattService.Create(AnUUID, AType, LJService); end; function TAndroidBluetoothGattServer.DoAddCharacteristic(const AService: TBluetoothGattService; const ACharacteristic: TBluetoothGattCharacteristic): Boolean; begin Result := TAndroidBluetoothGattService(AService).DoAddCharacteristic(ACharacteristic); end; function TAndroidBluetoothGattServer.DoAddService(const AService: TBluetoothGattService): Boolean; var LJBluetoothGattService: JBluetoothGattService; begin LJBluetoothGattService := TAndroidBluetoothGattService(AService).FJService; Result := FJGattServer.addService(LJBluetoothGattService); end; procedure TAndroidBluetoothGattServer.DoCharacteristicReadRequest(const ADevice: TBluetoothLEDevice; ARequestId, AnOffset: Integer; const AGattCharacteristic: TBluetoothGattCharacteristic); var LStatus: TBluetoothGattStatus; LOffset: Integer; LValue: TBytes; begin LStatus := TBluetoothGattStatus(TJBluetoothGatt.JavaClass.GATT_SUCCESS); if AnOffset = 0 then DoOnCharacteristicRead(Self, AGattCharacteristic, LStatus); LValue := TAndroidBluetoothGattCharacteristic(AGattCharacteristic).DoGetValue; LOffset := Length(LValue) - AnOffset; if LOffset <= 0 then begin SetLength(LValue, 0); DoSendResponse(ADevice, ARequestId, Integer(LStatus), 0, LValue); end else begin if AnOffset > 0 then begin Move(LValue[AnOffset], LValue[0], LOffset); setLength(LValue, LOffset); end; DoSendResponse(ADevice, ARequestId, Integer(LStatus), AnOffset, LValue); end; end; procedure TAndroidBluetoothGattServer.DoCharacteristicWriteRequest(const ADevice: TBluetoothLEDevice; ARequestId: Integer; const AGattCharacteristic: TBluetoothGattCharacteristic; APreparedWrite, AResponseNeeded: Boolean; AnOffset: Integer; const AValue: TBytes); var LStatus: TBluetoothGattStatus; LOffset: Integer; LValue: TBytes; LTotal: Integer; begin LStatus := TBluetoothGattStatus(TJBluetoothGatt.JavaClass.GATT_SUCCESS); if AnOffset > 0 then begin LTotal := Length(AValue); LOffset := AnOffset + LTotal; LValue := TAndroidBluetoothGattCharacteristic(AGattCharacteristic).DoGetValue; SetLength(LValue, LOffset); Move(AValue[0], LValue[AnOffset], LTotal); TAndroidBluetoothGattCharacteristic(AGattCharacteristic).DoSetValue(LValue); end else TAndroidBluetoothGattCharacteristic(AGattCharacteristic).DoSetValue(AValue); FLastRWrittenGattCharacteristic := AGattCharacteristic; if not APreparedWrite then DoOnCharacteristicWrite(ADevice, AGattCharacteristic, LStatus, AValue); if AResponseNeeded then DoSendResponse(ADevice, ARequestId, Integer(LStatus), AnOffset, AValue); end; procedure TAndroidBluetoothGattServer.DoClearServices; begin inherited; StopAdvertising; FJGattServer.clearServices; FServices.Clear; end; procedure TAndroidBluetoothGattServer.DoClientConfigurationWrite(const ADescriptor: TBluetoothGattDescriptor; const OldValue: TArray<Byte>; const AClient: TBluetoothLEDevice); function IsNotifyDisabled(const AValue: TArray<Byte>): Boolean; begin Result := (Length(AValue) = 2) and (AValue[0] = $00) and (AValue[1] = $00); end; function IsNotifyEnabled(const AValue: TArray<Byte>): Boolean; begin Result := (Length(AValue) = 2) and (AValue[0] = $01) and (AValue[1] = $00); end; function IsIndicateEnabled(const AValue: TArray<Byte>): Boolean; begin Result := (Length(AValue) = 2) and (AValue[0] = $02) and (AValue[1] = $00); end; begin if IsNotifyDisabled(OldValue) and (IsNotifyEnabled(ADescriptor.Value) or IsIndicateEnabled(ADescriptor.Value)) then DoOnClientSubscribed(Self, AClient.Identifier, ADescriptor.GetCharacteristic) else if IsNotifyDisabled(ADescriptor.Value) and (IsNotifyEnabled(OldValue) or IsIndicateEnabled(OldValue)) then DoOnClientUnsubscribed(Self, AClient.Identifier, ADescriptor.GetCharacteristic); end; procedure TAndroidBluetoothGattServer.DoClose; begin FJGattServer.close; end; function TAndroidBluetoothGattServer.DoConnect(const ADevice: TBluetoothLEDevice; AutoConnect: Boolean): Boolean; begin Result := FJGattServer.connect(TAndroidBluetoothDevice(ADevice).FJDevice, AutoConnect); end; procedure TAndroidBluetoothGattServer.DoDescriptorReadRequest(const ADevice: TBluetoothLEDevice; ARequestId, AnOffset: Integer; const ADescriptor: TBluetoothGattDescriptor); var LStatus: TBluetoothGattStatus; LOffset: Integer; LValue: TBytes; begin LStatus := TBluetoothGattStatus(TJBluetoothGatt.JavaClass.GATT_SUCCESS); LValue := TAndroidBluetoothGattDescriptor(ADescriptor).GetValue; LOffset := Length(LValue) - AnOffset; if LOffset <= 0 then begin SetLength(LValue, 0); DoSendResponse(ADevice, ARequestId, Integer(LStatus), 0, LValue); end else begin if AnOffset > 0 then begin Move(LValue[AnOffset], LValue[0], LOffset); setLength(LValue, LOffset); end; DoSendResponse(ADevice, ARequestId, Integer(LStatus), AnOffset, LValue); end; end; procedure TAndroidBluetoothGattServer.DoDescriptorWriteRequest(const ADevice: TBluetoothLEDevice; ARequestId: Integer; const ADescriptor: TBluetoothGattDescriptor; APreparedWrite, AResponseNeeded: Boolean; AnOffset: Integer; const AValue: TBytes); var LStatus: TBluetoothGattStatus; LOffset: Integer; LValue: TBytes; LTotal: Integer; LOldValue: TBytes; begin LStatus := TBluetoothGattStatus(TJBluetoothGatt.JavaClass.GATT_SUCCESS); LOldValue := TAndroidBluetoothGattDescriptor(ADescriptor).Value; if AnOffset > 0 then begin LTotal := Length(AValue); LOffset := AnOffset + LTotal; LValue := TAndroidBluetoothGattDescriptor(ADescriptor).DoGetValue; SetLength(LValue, LOffset); Move(AValue[0], LValue[AnOffset], LTotal); TAndroidBluetoothGattDescriptor(ADescriptor).DoSetValue(LValue); end else TAndroidBluetoothGattDescriptor(ADescriptor).DoSetValue(AValue); if ADescriptor.Kind = TBluetoothDescriptorKind.ClientConfiguration then DoClientConfigurationWrite(ADescriptor, LOldValue, ADevice); if AResponseNeeded then DoSendResponse(ADevice, ARequestId, Integer(LStatus), AnOffset, AValue); end; function TAndroidBluetoothGattServer.FindCharacteristic(const AJCharacteristic: JBluetoothGattCharacteristic): TAndroidBluetoothGattCharacteristic; var I: Integer; begin Result := nil; for I := 0 to FServices.Count - 1 do begin Result := TAndroidBluetoothGattService(FServices[I]).FindCharacteristic(AJCharacteristic); if Result <> nil then Break; end; end; procedure TAndroidBluetoothGattServer.DoDisconnect(const ADevice: TBluetoothLEDevice); begin FJGattServer.cancelConnection(TAndroidBluetoothDevice(ADevice).FJDevice); end; procedure TAndroidBluetoothGattServer.DoExecuteWrite(const ADevice: TBluetoothLEDevice; ARequestId: Integer; Execute: Boolean); var LStatus: TBluetoothGattStatus; LValue: TBytes; begin inherited; if Execute then begin LStatus := TBluetoothGattStatus(TJBluetoothGatt.JavaClass.GATT_SUCCESS); LValue := TAndroidBluetoothGattCharacteristic(FLastRWrittenGattCharacteristic).DoGetValue; DoOnCharacteristicWrite(ADevice, FLastRWrittenGattCharacteristic, LStatus, LValue); DoSendResponse(ADevice, ARequestId, Integer(LStatus), Length(LValue), LValue); end; end; function TAndroidBluetoothGattServer.DoCreateAdvertiseData: TBluetoothLEAdvertiseData; begin Result := TAndroidBluetoothLEAdvertiseData.create(TBluetoothGattServer(Self), FManager.CurrentAdapter, nil); end; function TAndroidBluetoothGattServer.DoGetServices: TBluetoothGattServiceList; var LJList: JList; I: Integer; LJService: JBluetoothGattService; begin if FServices.Count = 0 then begin LJList := FJGattServer.getServices; for I := 0 to LJLIst.size - 1 do begin LJService := TJBluetoothGattService.Wrap(LJList.get(I)); FServices.Add(TAndroidBluetoothGattService.Create(JUuidToBluetoothUuid(LJService.getUuid), TBluetoothServiceType(LJService.getType), LJService)); end; end; Result := FServices; end; function TAndroidBluetoothGattServer.DoIsAdvertising: Boolean; begin if AdvertiseData <> nil then Result := TAndroidBluetoothLEAdvertiseData(AdvertiseData).FAdvertising else Result := False; end; procedure TAndroidBluetoothGattServer.DoSendResponse(const ADevice: TBluetoothLEDevice; ARequestId, AStatus, AnOffset: Integer; const AValue: TBytes); var AResult: Boolean; begin AResult := FJGattServer.sendResponse(TAndroidBluetoothLEDevice(ADevice).FJDevice, ARequestId, AStatus, AnOffset, TBytesToTJavaArray(AValue)); if not AResult then raise EBluetoothDeviceException.CreateFmt('Cannot send response to device "%s" at "%s". %d', [ADevice.DeviceName, ADevice.Address, AStatus]); end; procedure TAndroidBluetoothGattServer.DoServiceAdded(AStatus: TBluetoothGattStatus; const AService: TBluetoothGattService); begin inherited; DoOnServiceAdded(self, AService, TBluetoothGattStatus(AStatus)); end; procedure TAndroidBluetoothGattServer.DoStartAdvertising; begin inherited; if TOSVersion.Check(5) then TAndroidBluetoothLEAdvertiseData(AdvertiseData).DoStartAdvertising; end; procedure TAndroidBluetoothGattServer.DoStopAdvertising; begin inherited; TAndroidBluetoothLEAdvertiseData(AdvertiseData).DoStopAdvertising; end; procedure TAndroidBluetoothGattServer.DoUpdateCharacteristicValue(const ACharacteristic: TBluetoothGattCharacteristic); var I: Integer; DevicesList: JList; begin DevicesList := TAndroidBluetoothLEManager(FManager).FJManager.getConnectedDevices(TJBluetoothProfile.JavaClass.GATT); for I := 0 to DevicesList.size -1 do FJGattServer.notifyCharacteristicChanged(JBluetoothDevice(DevicesList.get(I)),(ACharacteristic as TAndroidBluetoothGattCharacteristic).FJCharacteristic, false); end; function TAndroidBluetoothGattServer.FindDevice(const AJDevice: JBluetoothDevice): TBluetoothLEDevice; begin Result := TAndroidBluetoothLEManager.AddDeviceToList(TAndroidBluetoothLEDevice.Create(AJDevice, True, True), TAndroidBluetoothLEManager(TBluetoothLEManager.Current).AllDiscoveredDevices); end; function TAndroidBluetoothGattServer.FindService(const AJService: JBluetoothGattService): TBluetoothGattService; var LService: TAndroidBluetoothGattService; I: Integer; begin Result := nil; for I := 0 to FServices.Count - 1 do begin LService := TAndroidBluetoothGattService(FServices.Items[I]); if LService.FJService.equals(AJService) then Exit(LService); end; end; { TAndroidBluetoothService } constructor TAndroidBluetoothGattService.Create(const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType; const AJService: JBluetoothGattService); begin inherited Create(AnUUID, AType); if AJService = nil then begin FJService := TJBluetoothGattService.JavaClass.init(BluetoothUuidToJUuid(AnUUID), Integer(AType)); end else FJService := AJService; end; destructor TAndroidBluetoothGattService.Destroy; begin FJService := nil; inherited; end; function TAndroidBluetoothGattService.DoAddCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean; begin Result := FJService.addCharacteristic(TAndroidBluetoothGattCharacteristic(ACharacteristic).FJCharacteristic); end; function TAndroidBluetoothGattService.DoAddIncludedService(const AService: TBluetoothGattService): Boolean; begin Result := FJService.addService(TAndroidBluetoothGattService(AService).FJService); end; function TAndroidBluetoothGattService.DoCreateCharacteristic(const AUuid: TBluetoothUUID; APropertyFlags: TBluetoothPropertyFlags; const ADescription: string): TBluetoothGattCharacteristic; var LDescriptor: TBluetoothGattDescriptor; begin Result := TAndroidBluetoothGattCharacteristic.Create(Self, AUuid, APropertyFlags); if (TBluetoothProperty.Notify in APropertyFlags) or (TBluetoothProperty.Indicate in APropertyFlags) then begin LDescriptor := TAndroidBluetoothGattCharacteristic(Result).DoCreateDescriptor(CHAR_CLIENT_CONFIG); if (TBluetoothProperty.Notify in APropertyFlags) then LDescriptor.Notification := False; if (TBluetoothProperty.Indicate in APropertyFlags) then LDescriptor.Indication := False; TAndroidBluetoothGattCharacteristic(Result).AddDescriptor(LDescriptor); end; if ADescription <> '' then begin LDescriptor := TAndroidBluetoothGattCharacteristic(Result).DoCreateDescriptor(CHAR_DESCRIPTION); LDescriptor.UserDescription := ADescription; TAndroidBluetoothGattCharacteristic(Result).AddDescriptor(LDescriptor); end; end; function TAndroidBluetoothGattService.DoCreateIncludedService(const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType): TBluetoothGattService; var LJService: JBluetoothGattService; begin Result := nil; LJService := TJBluetoothGattService.JavaClass.init(BluetoothUuidToJUuid(AnUUID), Integer(AType)); Result := TAndroidBluetoothGattService.Create(AnUUID, AType, LJService); end; function TAndroidBluetoothGattService.DoGetCharacteristics: TBluetoothGattCharacteristicList; var LJCharList: JList; LJChar: JBluetoothGattCharacteristic; LCharact: TBluetoothGattCharacteristic; I: Integer; begin if FCharacteristics.Count = 0 then begin LJCharList := FJService.getCharacteristics; if LJCharList <> nil then begin for I := 0 to LJCharList.size - 1 do begin LJChar := TJBluetoothGattCharacteristic.Wrap(LJCharList.get(I)); LCharact := TAndroidBluetoothGattCharacteristic.Create(Self, LJChar); FCharacteristics.Add(LCharact); end; end; end; Result := FCharacteristics; end; function TAndroidBluetoothGattService.DoGetIncludedServices: TBluetoothGattServiceList; var LJList: JList; LJItem: JBluetoothGattService; LService: TBluetoothGattService; I: Integer; begin if FIncludedServices.Count = 0 then begin LJList := FJService.getIncludedServices; if LJList <> nil then for I := 0 to LJList.size -1 do begin LJItem := TJBluetoothGattService.Wrap(LJList.get(I)); LService := TAndroidBlueToothGattService.Create(JUuidToBluetoothUuid(LJItem.getUuid), TBluetoothServiceType(LJItem.getType), LJItem); FIncludedServices.Add(LService); end; end; Result := FIncludedServices; end; function TAndroidBluetoothGattService.FindCharacteristic( AJCharacteristic: JBluetoothGattCharacteristic): TAndroidBluetoothGattCharacteristic; var I: Integer; LService: TAndroidBluetoothGattService; LCharact: TAndroidBluetoothGattCharacteristic; begin Result := nil; for I := 0 to FCharacteristics.Count - 1 do begin LCharact := TAndroidBluetoothGattCharacteristic(FCharacteristics.Items[I]); if AJCharacteristic.equals(LCharact.FJCharacteristic) then begin Exit(LCharact); end; end; for I := 0 to FIncludedServices.Count - 1 do begin LService := TAndroidBluetoothGattService(FIncludedServices.Items[I]); Result := LService.FindCharacteristic(AJCharacteristic); if Result <> nil then Break; end; end; function TAndroidBluetoothGattService.FindDescriptor( AJDescriptor: JBluetoothGattDescriptor): TAndroidBluetoothGattDescriptor; var I: Integer; LService: TAndroidBluetoothGattService; LCharact: TAndroidBluetoothGattCharacteristic; begin Result := nil; for I := 0 to FCharacteristics.Count - 1 do begin LCharact := TAndroidBluetoothGattCharacteristic(FCharacteristics.Items[I]); Result := LCharact.FindDescriptor(AJDescriptor); if Result <> nil then Break; end; if Result = nil then for I := 0 to FIncludedServices.Count - 1 do begin LService := TAndroidBluetoothGattService(FIncludedServices.Items[I]); Result := LService.FindDescriptor(AJDescriptor); if Result <> nil then Break; end; end; function TAndroidBluetoothGattService.GetServiceType: TBluetoothServiceType; begin Result := TBluetoothServiceType(FJService.getType); end; function TAndroidBluetoothGattService.GetServiceUUID: TBluetoothUUID; begin Result := JUuidToBluetoothUuid(FJService.getUuid); end; { TAndroidBluetoothGattCharacteristic } constructor TAndroidBluetoothGattCharacteristic.Create(const AService: TBluetoothGattService; AJCharacteristic: JBluetoothGattCharacteristic); begin inherited Create(AService); FJCharacteristic := AJCharacteristic; end; constructor TAndroidBluetoothGattCharacteristic.Create(const AService: TBluetoothGattService; const AUUID: TBluetoothUUID; AProperties: TBluetoothPropertyFlags); begin inherited Create(AService); FJCharacteristic := TJBluetoothGattCharacteristic.JavaClass.init(BluetoothUuidToJUuid(AUUID), PropertiesToInteger(AProperties), TJBluetoothGattCharacteristic.JavaClass.PERMISSION_READ or TJBluetoothGattCharacteristic.JavaClass.PERMISSION_WRITE); end; destructor TAndroidBluetoothGattCharacteristic.Destroy; begin FJCharacteristic := nil; inherited; end; function TAndroidBluetoothGattCharacteristic.DoAddDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean; begin Result := FJCharacteristic.addDescriptor(TAndroidBluetoothGattDescriptor(ADescriptor).FJDescriptor); end; function TAndroidBluetoothGattCharacteristic.DoCreateDescriptor(const AUUID: TBluetoothUUID): TBluetoothGattDescriptor; var LJDesc: JBluetoothGattDescriptor; LPermissions: Integer; begin Result := nil; LPermissions := TJBluetoothGattDescriptor.JavaClass.PERMISSION_READ; if (AUUID = CHAR_EXTENDEDPROPERTIES) or (AUUID = CHAR_DESCRIPTION) or (AUUID = CHAR_CLIENT_CONFIG) or (AUUID = CHAR_SERVERCONFIGURATIONFORMAT) then LPermissions := LPermissions or TJBluetoothGattDescriptor.JavaClass.PERMISSION_WRITE; LJDesc := TJBluetoothGattDescriptor.JavaClass.init(BluetoothUuidToJUuid(AUUID), LPermissions); if LJDesc <> nil then Result := TAndroidBluetoothGattDescriptor.Create(Self, LJDesc); end; function TAndroidBluetoothGattCharacteristic.DoGetDescriptors: TBluetoothGattDescriptorList; var LJDescList: JList; LJDescriptor: JBluetoothGattDescriptor; LDescriptor: TAndroidBluetoothGattDescriptor; I: Integer; begin if FDescriptors.Count = 0 then begin LJDescList := FJCharacteristic.getDescriptors; if LJDescList <> nil then for I := 0 to LJDescList.size - 1 do begin LJDescriptor := TJBluetoothGattDescriptor.Wrap(LJDescList.get(I)); LDescriptor := TAndroidBluetoothGattDescriptor.Create(Self, LJDescriptor); FDescriptors.Add(LDescriptor); end; end; Result := FDescriptors; end; function TAndroidBluetoothGattCharacteristic.DoGetValue: TBytes; begin Result := TJavaArrayToTBytes(FJCharacteristic.getValue); end; function TAndroidBluetoothGattCharacteristic.FindDescriptor( const AJDescriptor: JBluetoothGattDescriptor): TAndroidBluetoothGattDescriptor; var I: Integer; LDescrip: TAndroidBluetoothGattDescriptor; begin Result := nil; for I := 0 to FDescriptors.Count - 1 do begin LDescrip := TAndroidBluetoothGattDescriptor(FDescriptors.Items[I]); if AJDescriptor.equals(LDescrip.FJDescriptor) then begin Exit(LDescrip); end; end; end; procedure TAndroidBluetoothGattCharacteristic.DoSetValue(const AValue: TBytes); begin FJCharacteristic.setValue(TBytesToTJavaArray(AValue)); end; function TAndroidBluetoothGattCharacteristic.GetProperties: TBluetoothPropertyFlags; var LProps: Integer; begin Result := []; LProps := FJCharacteristic.getProperties; if (LProps and PROPERTY_BROADCAST) = PROPERTY_BROADCAST then Include(Result, TBluetoothProperty.Broadcast); if (LProps and PROPERTY_READ) = PROPERTY_READ then Include(Result, TBluetoothProperty.Read); if (LProps and PROPERTY_WRITE_NO_RESPONSE) = PROPERTY_WRITE_NO_RESPONSE then Include(Result, TBluetoothProperty.WriteNoResponse); if (LProps and PROPERTY_WRITE) = PROPERTY_WRITE then Include(Result, TBluetoothProperty.Write); if (LProps and PROPERTY_NOTIFY) = PROPERTY_NOTIFY then Include(Result, TBluetoothProperty.Notify); if (LProps and PROPERTY_INDICATE) = PROPERTY_INDICATE then Include(Result, TBluetoothProperty.Indicate); if (LProps and PROPERTY_SIGNED_WRITE) = PROPERTY_SIGNED_WRITE then Include(Result, TBluetoothProperty.SignedWrite); if (LProps and PROPERTY_EXTENDED_PROPS) = PROPERTY_EXTENDED_PROPS then Include(Result, TBluetoothProperty.ExtendedProps); end; function TAndroidBluetoothGattCharacteristic.GetUUID: TBluetoothUUID; begin Result := JUuidToBluetoothUuid(FJCharacteristic.getUuid); end; { TAndroidBluetoothGattServerListener } constructor TAndroidBluetoothGattServerListener.Create(const AServer: TAndroidBluetoothGattServer); begin inherited Create; FGattServer := AServer; end; destructor TAndroidBluetoothGattServerListener.Destroy; begin inherited; end; procedure TAndroidBluetoothGattServerListener.onCharacteristicReadRequest(device: JBluetoothDevice; requestId, offset: Integer; characteristic: JBluetoothGattCharacteristic); var LGattDevice: TBluetoothLEDevice; begin LGattDevice := FGattServer.FindDevice(device); FGattServer.DoCharacteristicReadRequest(LGattDevice, requestId, offset, FGattServer.FindCharacteristic(characteristic)); end; procedure TAndroidBluetoothGattServerListener.onCharacteristicWriteRequest(device: JBluetoothDevice; requestId: Integer; characteristic: JBluetoothGattCharacteristic; preparedWrite, responseNeeded: Boolean; offset: Integer; value: TJavaArray<Byte>); var LGattDevice: TBluetoothLEDevice; LAndroidBluetoothGattCharacteristic: TAndroidBluetoothGattCharacteristic; begin LGattDevice := FGattServer.FindDevice(device); LAndroidBluetoothGattCharacteristic := FGattServer.FindCharacteristic(characteristic); FGattServer.DoCharacteristicWriteRequest(LGattDevice, requestId, LAndroidBluetoothGattCharacteristic, preparedWrite, responseNeeded, offset, TJavaArrayToTBytes(value)); FGattServer.DoUpdateCharacteristicValue(TBluetoothGattCharacteristic(LAndroidBluetoothGattCharacteristic)); end; procedure TAndroidBluetoothGattServerListener.onConnectionStateChange(device: JBluetoothDevice; status, newState: Integer); const STATE_CONNECTED = 2; STATE_DISCONNECTED = 0; var ABluetoothLEDevice: TBluetoothLEDevice; begin case newState of STATE_CONNECTED: begin ABluetoothLEDevice := FGattServer.FindDevice(device); FGattServer.DoOnConnectedDevice(FGattServer, ABluetoothLEDevice); end; STATE_DISCONNECTED: FGattServer.DoOnDisconnectDevice(FGattServer, FGattServer.FindDevice(device)); else // end; end; procedure TAndroidBluetoothGattServerListener.onDescriptorReadRequest(device: JBluetoothDevice; requestId, offset: Integer; descriptor: JBluetoothGattDescriptor); var LGattDevice: TBluetoothLEDevice; LBluetoothGattServiceList: TBluetoothGattServiceList; LBluetoothGattCharacteristicList: TBluetoothGattCharacteristicList; LBluetoothGattDescriptor: TBluetoothGattDescriptor; I, Z : Integer; LCharactID: TBluetoothUUID; begin LGattDevice := FGattServer.FindDevice(device); LBluetoothGattServiceList := TBluetoothGattServer(FGattServer).GetServices; LCharactID := JUuidToBluetoothUuid(descriptor.getCharacteristic.getUuid); for I := 0 to LBluetoothGattServiceList.Count - 1 do begin LBluetoothGattCharacteristicList := LBluetoothGattServiceList[I].Characteristics; for Z := 0 to LBluetoothGattCharacteristicList.Count - 1 do begin if LBluetoothGattCharacteristicList[Z].UUID = LCharactID then LBluetoothGattDescriptor := LBluetoothGattCharacteristicList[Z].GetDescriptor(JUuidToBluetoothUuid(descriptor.getUuid)); if LBluetoothGattDescriptor <> nil then Break; end; if LBluetoothGattDescriptor <> nil then Break; end; FGattServer.DoDescriptorReadRequest(LGattDevice, requestId, offset,LBluetoothGattDescriptor); end; procedure TAndroidBluetoothGattServerListener.onDescriptorWriteRequest(device: JBluetoothDevice; requestId: Integer; descriptor: JBluetoothGattDescriptor; preparedWrite, responseNeeded: Boolean; offset: Integer; value: TJavaArray<Byte>); var LGattDevice: TBluetoothLEDevice; LBluetoothGattServiceList: TBluetoothGattServiceList; LBluetoothGattCharacteristicList: TBluetoothGattCharacteristicList; LBluetoothGattDescriptor: TBluetoothGattDescriptor; I, Z : Integer; LCharactID: TBluetoothUUID; begin LGattDevice := FGattServer.FindDevice(device); LBluetoothGattServiceList := TBluetoothGattServer(FGattServer).GetServices; LCharactID := JUuidToBluetoothUuid(descriptor.getCharacteristic.getUuid); for I := 0 to LBluetoothGattServiceList.Count - 1 do begin LBluetoothGattCharacteristicList := LBluetoothGattServiceList[I].Characteristics; for Z := 0 to LBluetoothGattCharacteristicList.Count - 1 do begin if LBluetoothGattCharacteristicList[Z].UUID = LCharactID then LBluetoothGattDescriptor := LBluetoothGattCharacteristicList[Z].GetDescriptor(JUuidToBluetoothUuid(descriptor.getUuid)); if LBluetoothGattDescriptor <> nil then Break; end; if LBluetoothGattDescriptor <> nil then Break; end; FGattServer.DoDescriptorWriteRequest(LGattdevice, requestId, LBluetoothGattDescriptor, preparedWrite, responseNeeded, offset, TJavaArrayToTBytes(value)); FGattServer.DoUpdateCharacteristicValue(TBluetoothGattCharacteristic(FGattServer.FindCharacteristic(descriptor.getCharacteristic))); end; procedure TAndroidBluetoothGattServerListener.onExecuteWrite(device: JBluetoothDevice; requestId: Integer; execute: Boolean); var LGattDevice: TBluetoothLEDevice; begin LGattDevice := FGattServer.FindDevice(device); FGattServer.DoExecuteWrite(LGattDevice, requestId, execute); end; procedure TAndroidBluetoothGattServerListener.onServiceAdded(AStatus: Integer; service: JBluetoothGattService); begin FGattServer.DoServiceAdded(TBluetoothGattStatus(AStatus), FGattServer.FindService(service)); end; { TAndroidBluetoothGattListener } constructor TAndroidBluetoothGattListener.Create(const ALEDevice: TAndroidBluetoothLEDevice); begin inherited Create; FGatt := ALEDevice; end; destructor TAndroidBluetoothGattListener.Destroy; begin FGatt := nil; inherited; end; procedure TAndroidBluetoothGattListener.onCharacteristicChanged(gatt: JBluetoothGatt; characteristic: JBluetoothGattCharacteristic); var LGattChar: TBluetoothGattCharacteristic; begin LGattChar := FGatt.FindCharacteristic(characteristic); if LGattChar <> nil then FGatt.DoOnCharacteristicRead(LGattChar, TBluetoothGattStatus.Success) else raise EBluetoothLECharacteristicException.CreateFmt(SBluetoothLECanNotFindCharacteristic, [JUuidToBluetoothUuid(characteristic.getUuid).ToString]); end; procedure TAndroidBluetoothGattListener.onCharacteristicRead(gatt: JBluetoothGatt; characteristic: JBluetoothGattCharacteristic; status: Integer); var LGattChar: TAndroidBluetoothGattCharacteristic; begin LGattChar := FGatt.FindCharacteristic(characteristic); if LGattChar <> nil then FGatt.DoOnCharacteristicRead(LGattChar, TBluetoothGattStatus(status)) else raise EBluetoothLECharacteristicException.CreateFmt(SBluetoothLECanNotFindCharacteristic, [JUuidToBluetoothUuid(characteristic.getUuid).ToString]); end; procedure TAndroidBluetoothGattListener.onCharacteristicWrite(gatt: JBluetoothGatt; characteristic: JBluetoothGattCharacteristic; status: Integer); var LGattChar: TAndroidBluetoothGattCharacteristic; begin LGattChar := FGatt.FindCharacteristic(characteristic); if LGattChar <> nil then begin if TBluetoothGattStatus(status) = TBluetoothGattStatus.Success then FGatt.FCallbackGattResult := True; FGatt.DoOnCharacteristicWrite(LGattChar, TBluetoothGattStatus(status)); FGatt.FCallbackGattEvents.SetEvent; end else raise EBluetoothLECharacteristicException.CreateFmt(SBluetoothLECanNotFindCharacteristic, [JUuidToBluetoothUuid(characteristic.getUuid).ToString]); end; procedure TAndroidBluetoothGattListener.onConnectionStateChange(gatt: JBluetoothGatt; status, newState: Integer); begin FGatt.FConnectionStatus := TBluetoothDeviceState(newState); FGatt.FServicesEvent.SetEvent; case FGatt.FConnectionStatus of TBluetoothDeviceState.None: if Assigned(FGatt.OnDisconnect) then FGatt.OnDisconnect(FGatt); TBluetoothDeviceState.Connected: if (not FGatt.FConnecting) and Assigned(FGatt.OnConnect) then FGatt.OnConnect(FGatt); // TBluetoothDeviceState.Paired:; end; FGatt.FConnecting := False; end; procedure TAndroidBluetoothGattListener.onDescriptorRead(gatt: JBluetoothGatt; descriptor: JBluetoothGattDescriptor; status: Integer); var LGattDesc: TAndroidBluetoothGattDescriptor; begin LGattDesc := FGatt.FindDescriptor(descriptor); if LGattDesc <> nil then FGatt.DoOnDescriptorRead(LGattDesc, TBluetoothGattStatus(status)) else raise EBluetoothLEDescriptorException.CreateFmt(SBluetoothLECanNotFindDescriptor, [JUuidToBluetoothUuid(descriptor.getUuid).ToString]); end; procedure TAndroidBluetoothGattListener.onDescriptorWrite(gatt: JBluetoothGatt; descriptor: JBluetoothGattDescriptor; status: Integer); var LGattDesc: TAndroidBluetoothGattDescriptor; begin LGattDesc := FGatt.FindDescriptor(descriptor); if LGattDesc <> nil then begin if TBluetoothGattStatus(status) = TBluetoothGattStatus.Success then FGatt.FCallbackGattResult := True; FGatt.DoOnDescriptorWrite(LGattDesc, TBluetoothGattStatus(status)); FGatt.FCallbackGattEvents.SetEvent; end else raise EBluetoothLEDescriptorException.CreateFmt(SBluetoothLECanNotFindDescriptor, [JUuidToBluetoothUuid(descriptor.getUuid).ToString]); end; procedure TAndroidBluetoothGattListener.onReadRemoteRssi(gatt: JBluetoothGatt; rssi, status: Integer); begin FGatt.FLastRSSI := rssi; FGatt.DoOnReadRssi(FGatt, rssi, TBluetoothGattStatus(status)) end; procedure TAndroidBluetoothGattListener.onReliableWriteCompleted(gatt: JBluetoothGatt; status: Integer); begin if TBluetoothGattStatus(status) = TBluetoothGattStatus.Success then FGatt.FCallbackGattResult := True; FGatt.DoOnReliableWriteCompleted(TBluetoothGattStatus(status)); FGatt.FCallbackGattEvents.SetEvent; end; procedure TAndroidBluetoothGattListener.onServicesDiscovered(gatt: JBluetoothGatt; status: Integer); begin FGatt.FLastStatus := TBluetoothGattStatus(status); FGatt.FServicesEvent.SetEvent; end; { TAndroidBluetoothGattClient } constructor TAndroidBluetoothLEDevice.Create(const AJDevice: JBluetoothDevice; AutoConnect: Boolean; AForceRefreshCachedServices: Boolean); begin inherited Create(AutoConnect); FJDevice := AJDevice; FServicesEvent := TEvent.Create; FCallbackGattEvents := TEvent.Create; FForceRefreshCachedServices := AForceRefreshCachedServices; FPaired := False; end; class constructor TAndroidBluetoothLEDevice.Create; const ClassName = 'android/bluetooth/BluetoothGatt'; MethodName = 'refresh'; Sig = '()Z'; begin FRefreshMethod := CheckApiMethod(ClassName, MethodName, Sig); end; destructor TAndroidBluetoothLEDevice.Destroy; begin if FJGatt <> nil then FJGatt.close; FJGatt := nil; FJGattCallback := nil; FJGattListener := nil; FServicesEvent.SetEvent; FCallbackGattEvents.SetEvent; inherited; FServicesEvent.Free; FCallbackGattEvents.Free; FJDevice := nil; end; function TAndroidBluetoothLEDevice.InternalGetGattClient: JBluetoothGatt; var LJContext: JContext; LWaitResult: TWaitResult; begin if (not GetIsConnected) and (not FConnecting) then begin FServicesEvent.ResetEvent; LJContext := TAndroidBluetoothLEManager(TBluetoothLEManager.Current).FContext; if FJGatt = nil then begin if FJGattListener = nil then FJGattListener := TAndroidBluetoothGattListener.Create(Self); if FJGattCallback = nil then FJGattCallback := TJRTLBluetoothGattCallback.JavaClass.init(FJGattListener); FJGatt := FJDevice.connectGatt(LJContext, FAutoConnect, FJGattCallback); FReconnected := False; FConnecting := True; end else begin if UpdateOnReconnect then begin FJGatt.close; FJGatt := FJDevice.connectGatt(LJContext, FAutoConnect, FJGattCallback); FReconnected := True; FConnecting := True; end; end; if FConnecting then begin LWaitResult := FServicesEvent.WaitFor(CallbackGattTimeout); if (FConnectionStatus = TBluetoothDeviceState.Connected) and Assigned(OnConnect) then OnConnect(Self); if LWaitResult = TWaitResult.wrTimeout then FConnecting := False; end; end; Result := FJGatt; end; procedure TAndroidBluetoothLEDevice.DoAbortReliableWrite; begin if GetIsConnected then FJGatt.abortReliableWrite; end; function TAndroidBluetoothLEDevice.DoBeginReliableWrite: Boolean; begin InternalGetGattClient; if GetIsConnected then Result := FJGatt.beginReliableWrite else Result := False; end; function TAndroidBluetoothLEDevice.DoDiscoverServices: Boolean; const BLEDiscoverServicesTimeout = 15000; begin InternalGetGattClient; Result := False; if GetIsConnected then begin FServicesEvent.ResetEvent; FServices.Clear; FLastStatus := TBluetoothGattStatus.Failure; if FRefreshMethod and FForceRefreshCachedServices then FJGatt.refresh; Result := FJGatt.discoverServices; if Result then begin FServicesEvent.WaitFor(BLEDiscoverServicesTimeout); Result := FLastStatus = TBluetoothGattStatus.Success; if Result then begin InternalGetServices; FReconnected := False; DoOnServicesDiscovered(Self, FServices); end; end; end; end; function TAndroidBluetoothLEDevice.DoExecuteReliableWrite: Boolean; begin // It should comes after DoBeginReliableWrite FCallbackGattResult := False; if GetIsConnected then begin FCallbackGattEvents.ResetEvent; if FJGatt.executeReliableWrite then FCallbackGattEvents.WaitFor(CallbackGattTimeout); end; Result := FCallbackGattResult; end; function TAndroidBluetoothLEDevice.UpdateServicesList: Boolean; const BLEDiscoverServicesTimeout = 15000; procedure UpdateDescriptors(const AJChar: JBluetoothGattCharacteristic; const ADescriptors: TBluetoothGattDescriptorList); var LJDesList: JList; LJDes: JBluetoothGattDescriptor; LDescriptor: TAndroidBluetoothGattDescriptor; I, B: Integer; begin LJDesList := AJChar.getDescriptors; if LJDesList <> nil then begin for I := 0 to LJDesList.size - 1 do begin LJDes := TJBluetoothGattDescriptor.Wrap(LJDesList.get(I)); for B := 0 to ADescriptors.Count - 1 do begin LDescriptor := TAndroidBluetoothGattDescriptor(ADescriptors[I]); if LJDes.getUuid.compareTo(LDescriptor.FJDescriptor.getUuid) = 0 then begin LDescriptor.FJDescriptor := LJDes; Break; end; end; end; end; end; procedure UpdateCharacteristics(const AJService: JBluetoothGattService; const ACharacteristics: TBluetoothGattCharacteristicList); var LJCharList: JList; LJChar: JBluetoothGattCharacteristic; LCharacteristic: TAndroidBluetoothGattCharacteristic; I, B: Integer; begin LJCharList := AJService.getCharacteristics; if LJCharList <> nil then begin for I := 0 to LJCharList.size - 1 do begin LJChar := TJBluetoothGattCharacteristic.Wrap(LJCharList.get(I)); for B := 0 to ACharacteristics.Count - 1 do begin LCharacteristic := TAndroidBluetoothGattCharacteristic(ACharacteristics[I]); if LJChar.getUuid.compareTo(LCharacteristic.FJCharacteristic.getUuid) = 0 then begin LCharacteristic.FJCharacteristic := LJChar; if LCharacteristic.FDescriptors.Count > 0 then UpdateDescriptors(LJChar, LCharacteristic.FDescriptors); Break; end; end; end; end; end; procedure UpdateServicesList(const AServ: TBluetoothGattServiceList; const LList: JList); var LJService: JBluetoothGattService; LABluetoothGattService: TAndroidBluetoothGattService; I, B: Integer; begin if (LList <> nil) and (AServ <> nil) then begin for I := 0 to LList.size -1 do begin LJService := TJBluetoothGattService.Wrap(LList.get(I)); for B := 0 to AServ.Count -1 do begin LABluetoothGattService := TAndroidBluetoothGattService(AServ[B]); if LABluetoothGattService.FJService.getUuid.compareTo(LJService.getUuid) = 0 then begin if not LJService.getIncludedServices.isEmpty then UpdateServicesList(AServ[B].IncludedServices, LJService.getIncludedServices); LABluetoothGattService.FJService := LJService; if LABluetoothGattService.FCharacteristics.Count > 0 then UpdateCharacteristics(LJService, LABluetoothGattService.FCharacteristics); Break; end; end; end; end; end; begin FServicesEvent.ResetEvent; FLastStatus := TBluetoothGattStatus.Failure; Result := FJGatt.discoverServices; if Result then begin FServicesEvent.WaitFor(BLEDiscoverServicesTimeout); Result := FLastStatus = TBluetoothGattStatus.Success; if Result then begin UpdateServicesList(FServices, FJGatt.getServices); FReconnected := False; end; end; end; function TAndroidBluetoothLEDevice.DoReadCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean; begin InternalGetGattClient; Result := False; if GetIsConnected then begin if FReconnected then UpdateServicesList; Result := FJGatt.readCharacteristic(TAndroidBluetoothGattCharacteristic(ACharacteristic).FJCharacteristic); end; end; function TAndroidBluetoothLEDevice.DoReadDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean; begin InternalGetGattClient; Result := False; if GetIsConnected then begin if FReconnected then UpdateServicesList; Result := FJGatt.readDescriptor(TAndroidBluetoothGattDescriptor(ADescriptor).FJDescriptor) end; end; function TAndroidBluetoothLEDevice.DoReadRemoteRSSI: Boolean; begin InternalGetGattClient; if GetIsConnected then Result := FJGatt.readRemoteRssi else Result := False; end; function TAndroidBluetoothLEDevice.DoSetCharacteristicNotification( const ACharacteristic: TBluetoothGattCharacteristic; Enable: Boolean): Boolean; var LDesc: TBluetoothGattDescriptor; begin InternalGetGattClient; Result := False; if GetIsConnected then begin if FReconnected then UpdateServicesList; if FJGatt.setCharacteristicNotification(TAndroidBluetoothGattCharacteristic(ACharacteristic).FJCharacteristic, Enable) then begin LDesc := ACharacteristic.GetDescriptor(CHAR_CLIENT_CONFIG); if LDesc <> nil then begin if TBluetoothProperty.Notify in ACharacteristic.Properties then LDesc.Notification := Enable else LDesc.Indication := Enable; Result := WriteDescriptor(LDesc); end; end; end; end; function TAndroidBluetoothLEDevice.DoWriteCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean; begin internalGetGattClient; FCallbackGattResult := False; if GetIsConnected then begin if FReconnected then UpdateServicesList; FCallbackGattEvents.ResetEvent; if FJGatt.writeCharacteristic(TAndroidBluetoothGattCharacteristic(ACharacteristic).FJCharacteristic) then FCallbackGattEvents.WaitFor(CallbackGattTimeout); end; Result := FCallbackGattResult; end; function TAndroidBluetoothLEDevice.DoWriteDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean; begin InternalGetGattClient; FCallbackGattResult := False; if GetIsConnected then begin if FReconnected then UpdateServicesList; FCallbackGattEvents.ResetEvent; if FJGatt.writeDescriptor(TAndroidBluetoothGattDescriptor(ADescriptor).FJDescriptor) then FCallbackGattEvents.WaitFor(CallbackGattTimeout); end; Result := FCallbackGattResult; end; function TAndroidBluetoothLEDevice.FindCharacteristic( const AJCharacteristic: JBluetoothGattCharacteristic): TAndroidBluetoothGattCharacteristic; var I: Integer; LService: TAndroidBluetoothGattService; begin for I := 0 to FServices.Count - 1 do begin LService := TAndroidBluetoothGattService(FServices.Items[I]); Result := LService.FindCharacteristic(AJCharacteristic); if Result <> nil then Break; end; end; function TAndroidBluetoothLEDevice.FindDescriptor( const AJDescriptor: JBluetoothGattDescriptor): TAndroidBluetoothGattDescriptor; var I: Integer; LService: TAndroidBluetoothGattService; begin for I := 0 to FServices.Count - 1 do begin LService := TAndroidBluetoothGattService(FServices.Items[I]); Result := LService.FindDescriptor(AJDescriptor); if Result <> nil then Break; end; end; function TAndroidBluetoothLEDevice.DoConnect: Boolean; var LUpdateOnReconnect: Boolean; begin LUpdateOnReconnect := UpdateOnReconnect; UpdateOnReconnect := True; Result := InternalGetGattClient <> nil; UpdateOnReconnect := LUpdateOnReconnect; end; function TAndroidBluetoothLEDevice.DoCreateAdvertiseData: TBluetoothLEAdvertiseData; begin Result := TAndroidBluetoothLEAdvertiseData.Create(nil, nil, TBluetoothLEDevice(Self)); end; function TAndroidBluetoothLEDevice.GetAddress: TBluetoothMacAddress; begin Result := JStringToString(FJDevice.getAddress); end; function TAndroidBluetoothLEDevice.GetBluetoothType: TBluetoothType; begin { Check API Level 18 and ask for BT Type } if TOSVersion.Check(4, 3) then Result := TBluetoothType(FJDevice.getType) else Result := TBluetoothType.Classic; end; function TAndroidBluetoothLEDevice.GetDeviceName: string; begin Result := JStringToString(FJDevice.getName); end; function TAndroidBluetoothLEDevice.GetIdentifier: string; begin Result := GetAddress; end; function TAndroidBluetoothLEDevice.GetIsConnected: Boolean; begin if FJDevice = nil then raise EBluetoothLEDeviceException.Create(SBluetoothLEGetDeviceError); if FJGatt <> nil then Result := FConnectionStatus = TBluetoothDeviceState.Connected else Result := False; end; procedure TAndroidBluetoothLEDevice.InternalGetServices; procedure GetServices(const AServ: TBluetoothGattService; LList: JList); var LServ: TBluetoothGattService; LJService: JBluetoothGattService; I: Integer; begin if LList <> nil then for I := 0 to LList.size -1 do begin LJService := TJBluetoothGattService.Wrap(LList.get(I)); LServ := TAndroidBluetoothGattService.Create(JUuidToBluetoothUuid(LJService.getUuid), TBluetoothServiceType(LJService.getType), LJService); if not LJService.getIncludedServices.isEmpty then GetServices(LServ, LJService.getIncludedServices); if AServ <> nil then AServ.CreateIncludedService(LServ.UUID, LServ.ServiceType) else FServices.Add(LServ); end; end; begin { Fill in the services list } GetServices(nil, FJGatt.getServices); end; function TAndroidBluetoothLEDevice.DoDisconnect: Boolean; begin if FJGatt <> nil then begin FJGatt.disconnect; Result := True; end else Result := False; end; { TAndroidBluetoothGattDescriptor } constructor TAndroidBluetoothGattDescriptor.Create(const ACharacteristic: TBluetoothGattCharacteristic; AJDescriptor: JBluetoothGattDescriptor); begin inherited Create(ACharacteristic); FJDescriptor := AJDescriptor; end; destructor TAndroidBluetoothGattDescriptor.Destroy; begin FJDescriptor := nil; inherited; end; function TAndroidBluetoothGattDescriptor.DoGetBroadcasts: Boolean; var B: TBytes; begin if not (TBluetoothProperty.Broadcast in FCharacteristic.Properties) then raise EBluetoothLEDescriptorException.CreateFmt('Characteristic Error Message: %s, %d', [GetEnumName(TypeInfo(TBluetoothProperty), Ord(TBluetoothProperty.Broadcast))]); B := GetValue; Result := (Length(B) = 2) and (B[0] = $01) and (B[1] = $00); end; function TAndroidBluetoothGattDescriptor.DoGetExponent: ShortInt; begin Result := ShortInt(Value[1]); end; function TAndroidBluetoothGattDescriptor.DoGetFormat: TBluetoothGattFormatType; begin Result := TBluetoothGattFormatType(Value[0]); end; function TAndroidBluetoothGattDescriptor.DoGetFormatUnit: TBluetoothUUID; var B: TBytes; LValue: Word; begin B := GetValue; LValue := B[2] or (B[3] shl 8); Result := BLUETOOTH_BASE_UUID; Result.D1 := Cardinal(LValue); end; function TAndroidBluetoothGattDescriptor.DoGetIndication: Boolean; var B: TBytes; begin if not (TBluetoothProperty.Indicate in FCharacteristic.Properties) then raise EBluetoothLEDescriptorException.CreateFmt(SBluetoothCharacteristicError, [GetEnumName(TypeInfo(TBluetoothProperty), Ord(TBluetoothProperty.Indicate))]); B := GetValue; Result := (Length(B) = 2) and (B[0] = $02) and (B[1] = $00); end; function TAndroidBluetoothGattDescriptor.DoGetNotification: Boolean; var B: TBytes; begin if not (TBluetoothProperty.Notify in FCharacteristic.Properties) then raise EBluetoothLEDescriptorException.CreateFmt(SBluetoothCharacteristicError, [GetEnumName(TypeInfo(TBluetoothProperty), Ord(TBluetoothProperty.Notify))]); B := GetValue; Result := (Length(B) = 2) and (B[0] = $01) and (B[1] = $00); end; function TAndroidBluetoothGattDescriptor.DoGetReliableWrite: Boolean; begin Result := False; end; function TAndroidBluetoothGattDescriptor.DoGetUserDescription: string; begin Result := TEncoding.UTF8.GetString(Value); end; function TAndroidBluetoothGattDescriptor.DoGetValue: TBytes; begin Result := TJavaArrayToTBytes(FJDescriptor.getValue); end; function TAndroidBluetoothGattDescriptor.DoGetWritableAuxiliaries: Boolean; begin Result := False; end; procedure TAndroidBluetoothGattDescriptor.DoSetBroadcasts(const Value: Boolean); var B: TBytes; begin if not (TBluetoothProperty.Broadcast in FCharacteristic.Properties) then raise EBluetoothLEDescriptorException.CreateFmt(SBluetoothCharacteristicError, [GetEnumName(TypeInfo(TBluetoothProperty), Ord(TBluetoothProperty.Broadcast))]); SetLength(B, 2); if Value then B[0] := $01 else B[0] := $00; B[1] := $00; SetValue(B); end; procedure TAndroidBluetoothGattDescriptor.DoSetIndication(const Value: Boolean); var B: TBytes; begin if not (TBluetoothProperty.Indicate in FCharacteristic.Properties) then raise EBluetoothLEDescriptorException.CreateFmt(SBluetoothCharacteristicError, [GetEnumName(TypeInfo(TBluetoothProperty), Ord(TBluetoothProperty.Broadcast))]); SetLength(B, 2); if Value then B[0] := $02 else B[0] := $00; B[1] := $00; SetValue(B); end; procedure TAndroidBluetoothGattDescriptor.DoSetNotification(const Value: Boolean); var B: TBytes; begin if not (TBluetoothProperty.Notify in FCharacteristic.Properties) then raise EBluetoothLEDescriptorException.CreateFmt(SBluetoothCharacteristicError, [GetEnumName(TypeInfo(TBluetoothProperty), Ord(TBluetoothProperty.Notify))]); SetLength(B, 2); if Value then B[0] := $01 else B[0] := $00; B[1] := $00; SetValue(B); end; procedure TAndroidBluetoothGattDescriptor.DoSetUserDescription(const Value: string); begin SetValue(TEncoding.UTF8.GetBytes(Value)); end; procedure TAndroidBluetoothGattDescriptor.DoSetValue(const AValue: TBytes); begin FJDescriptor.setValue(TBytesToTJavaArray(AValue)); end; function TAndroidBluetoothGattDescriptor.GetUUID: TBluetoothUUID; begin Result := JUuidToBluetoothUuid(FJDescriptor.getUuid); end; { TAndroidBluetoothLEManager } constructor TAndroidBluetoothLEManager.Create; var LocalManager: JObject; begin inherited; { This code needs API_18 } if not TOsVersion.Check(4, 3) then raise EBluetoothManagerException.CreateFmt(SBluetoothAndroidVersionError, ['4.3', '18']); FContext := TAndroidHelper.Context; LocalManager := FContext.getSystemService(TJContext.JavaClass.BLUETOOTH_SERVICE); if LocalManager <> nil then FJManager := TJBluetoothManager.Wrap(LocalManager); FScanSettings := TScanSettingsOptions.SCAN_MODE_BALANCED; end; destructor TAndroidBluetoothLEManager.Destroy; begin FJManager := nil; FContext := nil; inherited; end; function TAndroidBluetoothLEManager.DoGetGattServer: TBluetoothGattServer; begin { Android KitKat 4.4.4 doesn't support Gatt servers, we need to wait until next release... } if TOSVersion.Check(5) then begin Result := TAndroidBluetoothGattServer.Create(Self, TAndroidBluetoothLEAdapter(TBluetoothLEManager(Self).CurrentAdapter)); end else raise EBluetoothException.Create(SBluetoothNotImplemented); end; function TAndroidBluetoothLEManager.GetAdapterState: TBluetoothAdapterState; begin if FAdapter = nil then FAdapter := TAndroidBluetoothLEAdapter.Create(Self, FJManager.getAdapter); Result := FAdapter.State; end; function TAndroidBluetoothLEManager.DoGetAdapter: TBluetoothLEAdapter; var LAndroidBluetoothLEAdapter: TAndroidBluetoothLEAdapter; begin if GetAdapterState = TBluetoothAdapterState.Off then begin LAndroidBluetoothLEAdapter := TAndroidBluetoothLEAdapter(FAdapter); if LAndroidBluetoothLEAdapter.FRequestEnableCallback then begin InternalProcessMessages; while LAndroidBluetoothLEAdapter.FRequestEnableCallback do InternalProcessMessages; if GetAdapterState = TBluetoothAdapterState.Off then FAdapter := nil; end else FAdapter := nil; end; Result := FAdapter; end; function TAndroidBluetoothLEManager.DoGetSupportsGattClient: Boolean; begin Result := CheckOSVersionForGattClient; end; function TAndroidBluetoothLEManager.DoGetSupportsGattServer: Boolean; begin Result := CheckOSVersionForGattServer; end; function TAndroidBluetoothLEManager.GetConnectionState: TBluetoothConnectionState; begin if GetAdapterState = TBluetoothAdapterState.Off then Result := TBluetoothConnectionState.Disconnected else Result := TBluetoothConnectionState.Connected; end; function TAndroidBluetoothLEManager.DoEnableBluetooth: Boolean; var LIntent: JIntent; begin if GetConnectionState = TBluetoothConnectionState.Disconnected then begin TAndroidBluetoothLEAdapter(FAdapter).FRequestEnableCallback := True; TThread.CreateAnonymousThread(procedure begin LIntent := TJIntent.JavaClass.init(TJBluetoothAdapter.JavaClass.ACTION_REQUEST_ENABLE); TAndroidHelper.Activity.startActivityForResult(LIntent, REQUEST_ENABLE_BT); end).Start; end; Result := True; end; function TAndroidBluetoothLEManager.GetScanSettingsOptions: IScanSettingsOptions; begin if FIScanSettingsOptions = nil then FIScanSettingsOptions := TScanSettingsOptions.Create; Result := FIScanSettingsOptions; end; function TAndroidBluetoothLEManager.GetScanSettings: Integer; begin Result := FScanSettings; end; procedure TAndroidBluetoothLEManager.SetScanSettings(Value: Integer); begin FScanSettings := Value; end; { TAndroidBluetoothSocket.TAndroidBluetoothSocketReader } constructor TAndroidBluetoothSocket.TBluetoothSocketReader.Create(const ASocket: TAndroidBluetoothSocket; ABuffSize: Integer); begin inherited Create(True); FSocket := ASocket; FJBytes := TJavaArray<System.Byte>.Create(ABuffSize); end; destructor TAndroidBluetoothSocket.TBluetoothSocketReader.Destroy; begin FDestroying := True; FSocket.FReaderEvent.SetEvent; inherited; FSocket := nil; FJBytes.Free; end; procedure TAndroidBluetoothSocket.TBluetoothSocketReader.Execute; begin inherited; FBufferSize := 0; FSocket.FSocketEvent.SetEvent; while not Terminated and not FDestroying do begin FSocket.FReaderEvent.WaitFor(INFINITE); FSocket.FReaderEvent.ResetEvent; // Do Read if not Terminated and not FDestroying and (FBufferSize = 0) then begin try if FSocket.FJIStream <> nil then FBufferSize := FSocket.FJIStream.read(FJBytes); except FBufferSize := -1; end; end; // Inform Socket that there is readed data if not FDestroying then FSocket.FSocketEvent.SetEvent; end; end; procedure TAndroidBluetoothSocket.TBluetoothSocketReader.GetBufferedData(const ABuffer: TBytes; AnOffset: Integer); begin if FBufferSize > 0 then begin Move(PByte(FJBytes.Data)^, ABuffer[AnOffset], FBufferSize); FBufferSize := 0; end; end; function TAndroidBluetoothSocket.TBluetoothSocketReader.GetBufferedDataSize: Integer; begin Result := FBufferSize; end; { TAndroidBluetoothAdvertiseListener } constructor TAndroidBluetoothAdvertiseListener.Create(const AEvent: TEvent; AErrorCode: Integer); begin inherited Create; FEvent := AEvent; FErrorCode := AErrorCode; end; destructor TAndroidBluetoothAdvertiseListener.Destroy; begin inherited; end; procedure TAndroidBluetoothAdvertiseListener.onStartFailure(errorCode: Integer); begin FErrorCode := errorCode; FEvent.SetEvent; end; procedure TAndroidBluetoothAdvertiseListener.onStartSuccess(settingsInEffect: JAdvertiseSettings); begin FEvent.SetEvent; end; { TAndroidBluetoothLEAdvertiseData } constructor TAndroidBluetoothLEAdvertiseData.Create(const ABluetoothGattServer: TBluetoothGattServer; const AnAdapter: TBluetoothLEAdapter; const ADevice: TBluetoothLEDevice); begin inherited Create; FBluetoothGattServer := ABluetoothGattServer; FDevice := ADevice; FAdapter := AnAdapter; CreateAdvertiseDataJavaObjects; end; destructor TAndroidBluetoothLEAdvertiseData.Destroy; begin DoStopAdvertising; FJAdvertiseData_Builder := nil; FJScanResponse_Builder := nil; FJScanResult := nil; FJAdvertiseSettings_Builder := nil; FJAdvertiseCallback := nil; FJAdvertiseListener := nil; inherited; end; procedure TAndroidBluetoothLEAdvertiseData.CreateAdvertiseDataJavaObjects; begin if TOSVersion.Check(5) and (FBluetoothGattServer <> nil) then begin if FJBluetoothLeAdvertiser = nil then FJBluetoothLeAdvertiser := TAndroidBluetoothLEAdapter(FAdapter).FJAdapter.getBluetoothLeAdvertiser(); if FJBluetoothLeAdvertiser = nil then raise EBluetoothLEAdvertiseDataException.Create(ADVERTISE_FAILED_DEVICE_NOT_SUPPORTED); FJAdvertiseData_Builder := TJAdvertiseData_Builder.JavaClass.init; FJAdvertiseData_Builder.setIncludeTxPowerLevel(False); FJAdvertiseData_Builder.setIncludeDeviceName(True); FJScanResponse_Builder := TJAdvertiseData_Builder.JavaClass.init; FJScanResponse_Builder.setIncludeTxPowerLevel(False); FJScanResponse_Builder.setIncludeDeviceName(False); FJAdvertiseSettings_Builder := TJAdvertiseSettings_Builder.JavaClass.init; FJAdvertiseSettings_Builder.setAdvertiseMode(TJAdvertiseSettings.JavaClass.ADVERTISE_MODE_BALANCED); FJAdvertiseSettings_Builder.setTxPowerLevel(TJAdvertiseSettings.JavaClass.ADVERTISE_TX_POWER_HIGH); FJAdvertiseSettings_Builder.setConnectable(True); FEvent := TEvent.Create; FJAdvertiseListener := TAndroidBluetoothAdvertiseListener.Create(FEvent, FErrorCode); FJAdvertiseCallback := TJRTLAdvertiseCallback.JavaClass.init(FJAdvertiseListener); end; end; procedure TAndroidBluetoothLEAdvertiseData.DoStartAdvertising; const FLAGS_FIELD_BYTES = 3; UUID_BYTES_16_BIT = 2; UUID_BYTES_32_BIT = 4; UUID_BYTES_128_BIT = 16; OVERHEAD_BYTES_PER_FIELD = 2; SERVICE_DATA_UUID_LENGTH = 2; MANUFACTURER_SPECIFIC_DATA_LENGTH = 2; MAX_ADVDATA_LENGTH = 31; BEACON_ST_TYPE: Word = $0215; var I: Integer; LAdvertiseService: Boolean; LNameInAdvData: Boolean; AdvertiseDataFull: Boolean; LAdvertiseDataLength: Integer; FScanResponseDataLength: Integer; ItemLength: Integer; OVERHEAD16Bit: Integer; OVERHEAD128Bit: Integer; LManufacturerId: Word; LManufacturerSpecificData: TBytes; Error: string; begin FJBluetoothLeAdvertiser.stopAdvertising(FJAdvertiseCallback); FJAdvertiseCallback.setListener(nil); FJAdvertiseData_Builder := nil; FJScanResponse_Builder := nil; FJAdvertiseSettings_Builder := nil; FJAdvertiseCallback := nil; FJAdvertiseListener := nil; LAdvertiseService := FBluetoothGattServer.AdvertiseService; CreateAdvertiseDataJavaObjects; FBluetoothGattServer.AdvertiseService := False; LAdvertiseDataLength := Length(FManufacturerSpecificData); FScanResponseDataLength := 0; OVERHEAD16Bit := 0; OVERHEAD128Bit := 0; LNameInAdvData := True; if LAdvertiseDataLength > 0 then begin LManufacturerId := PWord(@FManufacturerSpecificData[0])^; SetLength(LManufacturerSpecificData, Length(FManufacturerSpecificData) - LManufacturerId.Size); Move(FManufacturerSpecificData[LManufacturerId.Size], LManufacturerSpecificData[0], Length(LManufacturerSpecificData)); FJAdvertiseData_Builder.addManufacturerData(LManufacturerId, TBytesToTJavaArray(LManufacturerSpecificData)); LAdvertiseDataLength := OVERHEAD_BYTES_PER_FIELD + MANUFACTURER_SPECIFIC_DATA_LENGTH + LAdvertiseDataLength; if LAdvertiseDataLength + FLAGS_FIELD_BYTES + OVERHEAD_BYTES_PER_FIELD + FAdapter.AdapterName.Length > MAX_ADVDATA_LENGTH then begin FJAdvertiseData_Builder.setIncludeDeviceName(False); FJScanResponse_Builder.setIncludeDeviceName(True); FScanResponseDataLength := OVERHEAD_BYTES_PER_FIELD + FAdapter.AdapterName.Length; LNameInAdvData := False; end; end; LAdvertiseDataLength := LAdvertiseDataLength + FLAGS_FIELD_BYTES; for I := 0 to FServiceData.Count - 1 do begin ItemLength := Length(FServiceData.ToArray[I].Value); if LAdvertiseDataLength + ItemLength + OVERHEAD_BYTES_PER_FIELD + SERVICE_DATA_UUID_LENGTH <= MAX_ADVDATA_LENGTH then begin FJAdvertiseData_Builder.addServiceData(TJParcelUuid.JavaClass.init(BluetoothUuidToJUuid(FServiceData.ToArray[I].Key)), TBytesToTJavaArray(FServiceData.ToArray[I].Value)); LAdvertiseDataLength := LAdvertiseDataLength + ItemLength + OVERHEAD_BYTES_PER_FIELD + SERVICE_DATA_UUID_LENGTH; if LNameInAdvData and (LAdvertiseDataLength + OVERHEAD_BYTES_PER_FIELD + FAdapter.AdapterName.Length > MAX_ADVDATA_LENGTH) then begin FJAdvertiseData_Builder.setIncludeDeviceName(False); FJScanResponse_Builder.setIncludeDeviceName(True); FScanResponseDataLength := FScanResponseDataLength + OVERHEAD_BYTES_PER_FIELD + FAdapter.AdapterName.Length; LNameInAdvData := False; end; end else begin if FScanResponseDataLength + ItemLength + OVERHEAD_BYTES_PER_FIELD + SERVICE_DATA_UUID_LENGTH <= MAX_ADVDATA_LENGTH then begin FJScanResponse_Builder.addServiceData(TJParcelUuid.JavaClass.init(BluetoothUuidToJUuid(FServiceData.ToArray[I].Key)), TBytesToTJavaArray(FServiceData.ToArray[I].Value)); FScanResponseDataLength := FScanResponseDataLength + ItemLength + OVERHEAD_BYTES_PER_FIELD + SERVICE_DATA_UUID_LENGTH; end; end; end; AdvertiseDataFull := False; if LNameInAdvData then LAdvertiseDataLength := LAdvertiseDataLength + OVERHEAD_BYTES_PER_FIELD + FAdapter.AdapterName.Length; for I := 0 to FServiceUUIDs.Count - 1 do begin if TBluetoothUUIDHelper.IsBluetoothBaseUUIDBased(FServiceUUIDs.Items[I]) then begin OVERHEAD16Bit := OVERHEAD_BYTES_PER_FIELD; ItemLength := UUID_BYTES_16_BIT; end else begin OVERHEAD128Bit := OVERHEAD_BYTES_PER_FIELD; ItemLength := UUID_BYTES_128_BIT; end; if not AdvertiseDataFull then if (not AdvertiseDataFull) and (LAdvertiseDataLength + ItemLength + OVERHEAD16Bit + OVERHEAD128Bit <= MAX_ADVDATA_LENGTH) then begin FJAdvertiseData_Builder.addServiceUuid(TJParcelUuid.JavaClass.init(BluetoothUuidToJUuid(FServiceUUIDs.Items[I]))); LAdvertiseDataLength := LAdvertiseDataLength + ItemLength; end else begin AdvertiseDataFull := True; if ItemLength = UUID_BYTES_16_BIT then begin OVERHEAD16Bit := OVERHEAD_BYTES_PER_FIELD; OVERHEAD128Bit := 0; end else begin OVERHEAD16Bit := 0; OVERHEAD128Bit := OVERHEAD_BYTES_PER_FIELD; end end; if AdvertiseDataFull then if (FScanResponseDataLength + ItemLength + OVERHEAD16Bit + OVERHEAD128Bit) <= MAX_ADVDATA_LENGTH then begin FJScanResponse_Builder.addServiceUuid(TJParcelUuid.JavaClass.init(BluetoothUuidToJUuid( FServiceUUIDs.Items[I]))); FScanResponseDataLength := FScanResponseDataLength + ItemLength; end; end; FBluetoothGattServer.AdvertiseService := LAdvertiseService; if FJAdvertiseCallback <> nil then begin FJAdvertiseData := FJAdvertiseData_Builder.build; FJScanResponse := FJScanResponse_Builder.build; FErrorCode := 0; FEvent.ResetEvent; FJBluetoothLeAdvertiser.startAdvertising(FJAdvertiseSettings_Builder.build, FJAdvertiseData, FJScanResponse, FJAdvertiseCallback); FEvent.WaitFor(2000); if FErrorCode > 0 then begin FAdvertising := False; if FErrorCode = TJAdvertiseCallback.JavaClass.ADVERTISE_FAILED_DATA_TOO_LARGE then Error := ADVERTISE_FAILED_DATA_TOO_LARGE else if FErrorCode = TJAdvertiseCallback.JavaClass.ADVERTISE_FAILED_TOO_MANY_ADVERTISERS then Error := ADVERTISE_FAILED_TOO_MANY_ADVERTISERS else if FErrorCode = TJAdvertiseCallback.JavaClass.ADVERTISE_FAILED_ALREADY_STARTED then Error := ADVERTISE_FAILED_ALREADY_STARTED else if FErrorCode = TJAdvertiseCallback.JavaClass.ADVERTISE_FAILED_INTERNAL_ERROR then Error := ADVERTISE_FAILED_INTERNAL_ERROR else if FErrorCode = TJAdvertiseCallback.JavaClass.ADVERTISE_FAILED_FEATURE_UNSUPPORTED then Error := ADVERTISE_FAILED_FEATURE_UNSUPPORTED else Error := ADVERTISE_FAILED_UNKNOWN_ERROR; raise EBluetoothLEAdvertiseDataException.Create(Error); end else FAdvertising := True; end; end; procedure TAndroidBluetoothLEAdvertiseData.DoStopAdvertising; begin if FAdvertising then begin FJBluetoothLeAdvertiser.stopAdvertising(FJAdvertiseCallback); FAdvertising := False; end; end; function TAndroidBluetoothLEAdvertiseData.GetDataForService( const AServiceUUID: TBluetoothUUID): TBytes; begin if Length(GetServiceData) > 0 then FServiceData.TryGetValue(AServiceUUID, Result) else Result := nil; end; function TAndroidBluetoothLEAdvertiseData.GetLocalName: string; begin if FDevice = nil then begin if FBluetoothGattServer <> nil then Flocalname := FBluetoothGattServer.GattServerName end else if (FDevice.AdvertisedData <> nil) and (FDevice.AdvertisedData.ContainsKey(TScanResponseKey.CompleteLocalName)) then begin Result := TEncoding.UTF8.GetString(FDevice.AdvertisedData.Items[TScanResponseKey.CompleteLocalName]); if Result <> '' then FLocalName := Result; end else Flocalname := FDevice.DeviceName; Result := Flocalname; end; function TAndroidBluetoothLEAdvertiseData.GetManufacturerSpecificData: TBytes; begin if (FDevice <> nil) and (FDevice.AdvertisedData <> nil) then if FDevice.AdvertisedData.ContainsKey(TScanResponseKey.ManufacturerSpecificData) then FManufacturerSpecificData := FDevice.AdvertisedData.Items[TScanResponseKey.ManufacturerSpecificData]; Result := FManufacturerSpecificData; end; function TAndroidBluetoothLEAdvertiseData.GetServiceData: TArray<TServiceDataRawData>; var LData: TBytes; LServiceTBytes: TBytes; LServiceUUID: TGUID; LSize: Integer; LServiceData: TPair<TBluetoothUUID,TBytes>; begin if (FDevice <> nil) and (FDevice.AdvertisedData <> nil) then if FDevice.AdvertisedData.ContainsKey(TScanResponseKey.ServiceData) then begin LData := FDevice.AdvertisedData.Items[TScanResponseKey.ServiceData]; LServiceUUID := ServiceUUIDToGUID([LData[1], LData[0]]); LSize := Length(LData) - 2; SetLength(LServiceTBytes, LSize); Move(LData[2], LServiceTBytes[0], LSize); FServiceData.AddOrSetValue(LServiceUUID, LServiceTBytes); end; // Prepared to be an array, but it will just own one element for now. SetLength(Result, FServiceData.count); LSize := 0; for LServiceData in FServiceData do begin Result[LSize].create(LServiceData); Inc(LSize); end; end; function TAndroidBluetoothLEAdvertiseData.GetServiceUUIDs: TArray<TBluetoothUUID>; function ScanResponseToAdvertiseData(const ScanResponse: TScanResponse):TArray<TBluetoothUUID>; type TServicesLengthType = (S16B = 2, S32B = 4, S128B = 16); procedure ChekBLEServices(const AData: TBytes; AServicesLengthType: TServicesLengthType); var LDataLength: Integer; I: Integer; Position: Integer; LDeviation: Integer; begin LDeviation := 0; Position := Length(Result); if AServicesLengthType = TServicesLengthType.S128B then begin SetLength(Result, Position + 1); Result[0] := ServiceUUIDToGUID(AData); // we just can have one Service in 128 bits format end else begin LDataLength := Length(AData); I := 0; while I < LDataLength do begin SetLength(Result, Position + 1); Result[Position] := ServiceUUIDToGUID([AData[I + LDeviation + 1], AData[I + LDeviation]]); Inc(I, Integer(AServicesLengthType)); Inc(Position); end; end; end; begin if ScanResponse.ContainsKey(TScanResponseKey.IncompleteList128SCUUID) then ChekBLEServices(ScanResponse.Items[TScanResponseKey.IncompleteList128SCUUID], TServicesLengthType.S128B); if ScanResponse.ContainsKey(TScanResponseKey.CompleteList128SCUUID) then ChekBLEServices(ScanResponse.Items[TScanResponseKey.CompleteList128SCUUID], TServicesLengthType.S128B); if ScanResponse.ContainsKey(TScanResponseKey.IncompleteList16SCUUID) then ChekBLEServices(ScanResponse.Items[TScanResponseKey.IncompleteList16SCUUID], TServicesLengthType.S16B); if ScanResponse.ContainsKey(TScanResponseKey.CompleteList16SCUUID) then ChekBLEServices(ScanResponse.Items[TScanResponseKey.CompleteList16SCUUID], TServicesLengthType.S16B); if ScanResponse.ContainsKey(TScanResponseKey.IncompleteList32SCUUID) then ChekBLEServices(ScanResponse.Items[TScanResponseKey.IncompleteList32SCUUID], TServicesLengthType.S32B); if ScanResponse.ContainsKey(TScanResponseKey.CompleteList32SCUUID) then ChekBLEServices(ScanResponse.Items[TScanResponseKey.CompleteList32SCUUID], TServicesLengthType.S32B); end; begin if FDevice = nil then Result := FServiceUUIDs.ToArray else Result := ScanResponseToAdvertiseData(FDevice.AdvertisedData); end; function TAndroidBluetoothLEAdvertiseData.GetTxPowerLevel: Integer; begin if (FDevice <> nil) and (FDevice.AdvertisedData <> nil) then if FDevice.AdvertisedData.ContainsKey(TScanResponseKey.TxPowerLevel) then FTxPowerLevel := ShortInt(FDevice.AdvertisedData.Items[TScanResponseKey.TxPowerLevel]); Result := FTxPowerLevel; end; procedure TAndroidBluetoothLEAdvertiseData.SetLocalName( const ALocalName: string); begin // In Android we cannot set a GattSerever name that is different from the one of the device. // raise EBluetoothADataException.CreateFmt(SBluetoothNotSupported, ['SetLocalName', 'Android']); // Do not translate. end; procedure TAndroidBluetoothLEAdvertiseData.SetManufacturerSpecificData( const AManufacturerSpecificData: TBytes); begin if TOSVersion.Check(5) then FManufacturerSpecificData := AManufacturerSpecificData else raise EBluetoothLEAdvertiseDataException.CreateFmt(SBluetoothAndroidVersionError, ['5', '21']); // Do not translate. end; procedure TAndroidBluetoothLEAdvertiseData.SetTxPowerLevel( ATxPowerLevel: Integer); begin if TOSVersion.Check(5) then begin FTxPowerLevel := ATxPowerLevel; end else raise EBluetoothLEAdvertiseDataException.CreateFmt(SBluetoothAndroidVersionError, ['5', '21']); // Do not translate. end; function TAndroidBluetoothLEAdvertiseData.DoAddServiceData( const AServiceUUID: TBluetoothUUID; const AData: TBytes): Boolean; begin if TOSVersion.Check(5) then begin Result := True; end else raise EBluetoothLEAdvertiseDataException.CreateFmt(SBluetoothAndroidVersionError, ['5', '21']); // Do not translate. end; function TAndroidBluetoothLEAdvertiseData.DoAddServiceUUID(const AServiceUUID: TBluetoothUUID): Boolean; begin if TOSVersion.Check(5) then Result := True else raise EBluetoothLEAdvertiseDataException.CreateFmt(SBluetoothAndroidVersionError, ['5', '21']); // Do not translate. end; procedure TAndroidBluetoothLEAdvertiseData.DoRemoveServiceUUID( const AServiceUUID: TBluetoothUUID); begin if TOSVersion.Check(5) then FServiceUUIDChanged := True else raise EBluetoothLEAdvertiseDataException.CreateFmt(SBluetoothAndroidVersionError, ['5', '21']); // Do not translate. end; procedure TAndroidBluetoothLEAdvertiseData.DoRemoveServiceData( const AServiceUUID: TBluetoothUUID); begin if TOSVersion.Check(5) then FServiceDataChanged := True else raise EBluetoothLEAdvertiseDataException.CreateFmt(SBluetoothAndroidVersionError, ['5', '21']); // Do not translate. end; procedure TAndroidBluetoothLEAdvertiseData.DoClearServiceData; begin if TOSVersion.Check(5) then FServiceDataChanged := True else raise EBluetoothLEAdvertiseDataException.CreateFmt(SBluetoothAndroidVersionError, ['5', '21']); // Do not translate. end; procedure TAndroidBluetoothLEAdvertiseData.DoClearServiceUUIDs; begin if TOSVersion.Check(5) then FServiceUUIDChanged := True else raise EBluetoothLEAdvertiseDataException.CreateFmt(SBluetoothAndroidVersionError, ['5', '21']); // Do not translate. end; function TAndroidBluetoothLEAdvertiseData.ContainsServiceUUID( const AServiceUUID: TBluetoothUUID): Boolean; var LServiceArray: TArray<TBluetoothUUID>; I: Integer; begin if TOSVersion.Check(5) then begin Result := False; if (FDevice <> nil) and (FDevice.AdvertisedData <> nil) then begin LServiceArray := GetServiceUUIDs; for I := 0 to Length(LServiceArray) - 1 do if LServiceArray[I] = AServiceUUID then Result := True end; end else raise EBluetoothLEAdvertiseDataException.CreateFmt(SBluetoothAndroidVersionError, ['5', '21']); // Do not translate. end; { TScanCallback } constructor TScanCallback.Create( const AnAdapter: TAndroidBluetoothLEAdapter); begin inherited Create; FAdapter := AnAdapter; end; procedure TScanCallback.onBatchScanResults(results: JList); begin // end; procedure TScanCallback.onScanFailed(errorCode: Integer); begin //SCAN_FAILED_ALREADY_STARTED $01 //SCAN_FAILED_APPLICATION_REGISTRATION_FAILED $02 //SCAN_FAILED_INTERNAL_ERROR $03 //SCAN_FAILED_FEATURE_UNSUPPORTED $04 FAdapter.FStartScanFailed := errorCode; FAdapter.FEventStartScan.SetEvent; end; function TBytesToHexString(const AValue: TBytes): string; var I:Integer; begin Result := ''; for I:= 0 to Length(AValue) - 1 do Result := Result + AValue[I].ToHexString(2); end; procedure TScanCallback.onScanResult(callbackType: Integer; result: Jle_ScanResult); var LDevice: TAndroidBluetoothLEDevice; LNew: Boolean; begin FAdapter.FStartScanFailed := 0; FAdapter.FEventStartScan.SetEvent; LNew := False; LDevice := TAndroidBluetoothLEDevice(TAndroidBluetoothLEManager.GetDeviceInList(JStringToString(result.getDevice.getAddress), FAdapter.FManager.AllDiscoveredDevices)); if LDevice = nil then begin LDevice := TAndroidBluetoothLEDevice.Create(result.getDevice, False, FAdapter.FManager.ForceRefreshCachedDevices); LNew := True; end else LDevice.FJDevice := result.getDevice; LDevice.FAdvertisedData := ScanRecordToTScanResponse(result.getScanRecord.getBytes, LDevice.FAdvertisedData); LDevice.FLastRSSI := result.getRssi; FAdapter.DoDeviceDiscovered(LDevice, LNew, FAdapter.FBluetoothLEScanFilterList); end; { ScanSettingsOptions } function TScanSettingsOptions.GetCALLBACK_TYPE_ALL_MATCHES: Integer; begin Result := CALLBACK_TYPE_ALL_MATCHES; end; function TScanSettingsOptions.GetCALLBACK_TYPE_FIRST_MATCH: Integer; begin Result := CALLBACK_TYPE_FIRST_MATCH; end; function TScanSettingsOptions.GetCALLBACK_TYPE_MATCH_LOST: Integer; begin Result := CALLBACK_TYPE_MATCH_LOST; end; function TScanSettingsOptions.GetMATCH_MODE_AGGRESSIVE: Integer; begin Result := MATCH_MODE_AGGRESSIVE; end; function TScanSettingsOptions.GetMATCH_MODE_STICKY: Integer; begin Result := MATCH_MODE_STICKY; end; function TScanSettingsOptions.GetMATCH_NUM_FEW_ADVERTISEMENT: Integer; begin Result := MATCH_NUM_FEW_ADVERTISEMENT; end; function TScanSettingsOptions.GetMATCH_NUM_MAX_ADVERTISEMENT: Integer; begin Result := MATCH_NUM_MAX_ADVERTISEMENT; end; function TScanSettingsOptions.GetMATCH_NUM_ONE_ADVERTISEMENT: Integer; begin Result := MATCH_NUM_ONE_ADVERTISEMENT; end; function TScanSettingsOptions.GetSCAN_MODE_BALANCED: Integer; begin Result := SCAN_MODE_BALANCED; end; function TScanSettingsOptions.GetSCAN_MODE_LOW_LATENCY: Integer; begin Result := SCAN_MODE_LOW_LATENCY; end; function TScanSettingsOptions.GetSCAN_MODE_LOW_POWER: Integer; begin Result := SCAN_MODE_LOW_POWER; end; function TScanSettingsOptions.GetSCAN_MODE_OPPORTUNISTIC: Integer; begin Result := SCAN_MODE_OPPORTUNISTIC; end; end.
// ************************************************************************************************** // Delphi Aio Library. // Unit GInterfaces // https://github.com/Purik/AIO // The contents of this file are subject to the Apache License 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 // // // The Original Code is GInterfaces.pas. // // Contributor(s): // Pavel Minenkov // Purik // https://github.com/Purik // // The Initial Developer of the Original Code is Pavel Minenkov [Purik]. // All Rights Reserved. // // ************************************************************************************************** unit GInterfaces; interface uses SysUtils, GarbageCollector, Classes, Gevent, SyncObjs, PasMP; type {$IFDEF DCC} TSymmetricRoutine = reference to procedure; TSymmetricArgsRoutine = reference to procedure(const Args: array of const); TSymmetricRoutine<T> = reference to procedure(const A: T); TSymmetricRoutine<T1, T2> = reference to procedure(const A1: T1; const A2: T2); TSymmetricRoutine<T1, T2, T3> = reference to procedure(const A1: T1; const A2: T2; const A3: T3); TSymmetricRoutine<T1, T2, T3, T4> = reference to procedure(const A1: T1; const A2: T2; const A3: T3; const A4: T4); TAsymmetricRoutine<RES> = reference to function: RES; TAsymmetricRoutine<T, RES> = reference to function(const A: T): RES; TAsymmetricRoutine<T1, T2, RES> = reference to function(const A1: T1; const A2: T2): RES; TAsymmetricRoutine<T1, T2, T3, RES> = reference to function(const A1: T1; const A2: T2; const A3: T3): RES; TAsymmetricRoutine<T1, T2, T3, T4, RES> = reference to function(const A1: T1; const A2: T2; const A3: T3; const A4: T4): RES; {$ELSE} TSymmetricRoutine = procedure of object; TSymmetricArgsRoutine = procedure(const Args: array of const) of object; TSymmetricRoutine<T> = procedure(const A: T) of object; TSymmetricRoutine<T1, T2> = procedure(const A1: T1; const A2: T2) of object; TSymmetricRoutine<T1, T2, T3> = procedure(const A1: T1; const A2: T2; const A3: T3) of object; TSymmetricRoutine<T1, T2, T3, T4> = procedure(const A1: T1; const A2: T2; const A3: T3; const A4: T4) of object; TAsymmetricRoutine<RES> = function: RES of object; TAsymmetricRoutine<T, RES> = function(const A: T): RES of object; TAsymmetricRoutine<T1, T2, RES> = function(const A1: T1; const A2: T2): RES of object; TAsymmetricRoutine<T1, T2, T3, RES> = function(const A1: T1; const A2: T2; const A3: T3): RES of object; TAsymmetricRoutine<T1, T2, T3, T4, RES> = function(const A1: T1; const A2: T2; const A3: T3; const A4: T4): RES of object; {$ENDIF} TSymmetricRoutineStatic = procedure; TSymmetricArgsStatic = procedure(const Args: array of const); TSymmetricRoutineStatic<T> = procedure(const A: T); TSymmetricRoutineStatic<T1, T2> = procedure(const A1: T1; const A2: T2); TSymmetricRoutineStatic<T1, T2, T3> = procedure(const A1: T1; const A2: T2; const A3: T3); TSymmetricRoutineStatic<T1, T2, T3, T4> = procedure(const A1: T1; const A2: T2; const A3: T3; const A4: T4); TAsymmetricRoutineStatic<RES> = function: RES; TAsymmetricRoutineStatic<T, RES> = function(const A: T): RES; TAsymmetricRoutineStatic<T1, T2, RES> = function(const A1: T1; const A2: T2): RES; TAsymmetricRoutineStatic<T1, T2, T3, RES> = function(const A1: T1; const A2: T2; const A3: T3): RES; TAsymmetricRoutineStatic<T1, T2, T3, T4, RES> = function(const A1: T1; const A2: T2; const A3: T3; const A4: T4): RES; // tuple of parameters tTuple = array of TVarRec; // greenlet state tGreenletState = ( gsReady, // ready for the first launch gsExecute, // is executing gsTerminated, // greenlet is ended on its own gsKilled, // greenlet is killed outside gsException, // greenlet is ended with Exception gsSuspended, // greenlet is suspended gsKilling // greenlet is in killing state ); TEnumerator<T> = class protected function GetCurrent: T; virtual; abstract; public function MoveNext: Boolean; dynamic; abstract; property Current: T read GetCurrent; procedure Reset; dynamic; abstract; end; IGenerator<T> = interface function GetEnumerator: TEnumerator<T>; procedure Setup(const Args: array of const); end; TExceptionClass = class of Exception; TIOOperation = (ioNotSet, ioRead, ioWrite); TIOCallback = procedure(Fd: THandle; const Op: TIOOperation; Data: Pointer; ErrorCode: Integer; NumOfBytes: LongWord); TEventCallback = procedure(Hnd: THandle; Data: Pointer; const Aborted: Boolean); TInervalCallback = procedure(Id: THandle; Data: Pointer); EHubError = class(Exception); TTaskProc = procedure(Arg: Pointer); TExitCondition = function: Boolean of object; TExitConditionStatic = function: Boolean; TAnyAddress = record AddrPtr: Pointer; AddrLen: Integer; end; IIoHandler = interface ['{9FD7E7C2-B328-4F75-9E8F-E3F201B4462A}'] function Emitter: IGevent; procedure Lock; procedure Unlock; function ReallocBuf(Size: LongWord): Pointer; function GetBufSize: LongWord; end; TCustomHub = class strict private FIsSuspended: Boolean; FName: string; public property Name: string read FName write FName; property IsSuspended: Boolean read FIsSuspended write FIsSuspended; function HLS(const Key: string): TObject; overload; dynamic; abstract; procedure HLS(const Key: string; Value: TObject); overload; dynamic; abstract; function GC(A: TObject): IGCObject; dynamic; abstract; // tasks procedure EnqueueTask(const Task: TThreadMethod); overload; dynamic; abstract; procedure EnqueueTask(const Task: TTaskProc; Arg: Pointer); overload; dynamic; abstract; // IO files and sockets procedure Cancel(Fd: THandle); dynamic; abstract; function Write(Fd: THandle; Buf: Pointer; Len: LongWord; const Cb: TIOCallback; Data: Pointer; Offset: Int64 = -1): Boolean; dynamic; abstract; function WriteTo(Fd: THandle; Buf: Pointer; Len: LongWord; const Addr: TAnyAddress; const Cb: TIOCallback; Data: Pointer): Boolean; dynamic; abstract; function Read(Fd: THandle; Buf: Pointer; Len: LongWord; const Cb: TIOCallback; Data: Pointer; Offset: Int64 = -1): Boolean; dynamic; abstract; function ReadFrom(Fd: THandle; Buf: Pointer; Len: LongWord; const Addr: TAnyAddress; const Cb: TIOCallback; Data: Pointer): Boolean; dynamic; abstract; // IO timeouts and timers function CreateTimer(const Cb: TInervalCallback; Data: Pointer; Interval: LongWord): THandle; dynamic; abstract; procedure DestroyTimer(Id: THandle); dynamic; abstract; function CreateTimeout(const Cb: TInervalCallback; Data: Pointer; Interval: LongWord): THandle; dynamic; abstract; procedure DestroyTimeout(Id: THandle); dynamic; abstract; // Event objects function AddEvent(Ev: THandle; const Cb: TEventCallback; Data: Pointer): Boolean; dynamic; abstract; procedure RemEvent(Ev: THandle); dynamic; abstract; // loop function Serve(TimeOut: LongWord): Boolean; dynamic; abstract; // pulse hub procedure Pulse; dynamic; abstract; // Loop procedure LoopExit; dynamic; abstract; procedure Loop(const Cond: TExitCondition; Timeout: LongWord = INFINITE); overload; dynamic; abstract; procedure Loop(const Cond: TExitConditionStatic; Timeout: LongWord = INFINITE); overload; dynamic; abstract; // switch to thread root context procedure Switch; dynamic; abstract; end; IGreenletProxy = interface procedure Pulse; procedure DelayedSwitch; procedure Resume; procedure Suspend; procedure Kill; function GetHub: TCustomHub; function GetState: tGreenletState; function GetException: Exception; function GetOnStateChanged: TGevent; function GetOnTerminate: TGevent; function GetUID: NativeUInt; end; IRawGreenlet = interface function GetUID: NativeUInt; function GetProxy: IGreenletProxy; procedure Switch; procedure Yield; procedure Kill; procedure Suspend; procedure Resume; procedure Inject(E: Exception); overload; procedure Inject(const Routune: TSymmetricRoutine); overload; function GetState: tGreenletState; function GetException: Exception; function GetInstance: TObject; function GetOnStateChanged: TGevent; function GetOnTerminate: TGevent; function GetName: string; procedure SetName(const Value: string); procedure Join(const RaiseErrors: Boolean = False); procedure ReraiseException; {$IFDEF DEBUG} function RefCount: Integer; {$ENDIF} end; IGreenGroup<KEY> = interface procedure SetValue(const Key: KEY; G: IRawGreenlet); function GetValue(const Key: KEY): IRawGreenlet; procedure Clear; procedure KillAll; function IsEmpty: Boolean; function Join(Timeout: LongWord = INFINITE; const RaiseError: Boolean = False): Boolean; function Copy: IGreenGroup<KEY>; function Count: Integer; end; IGreenlet = interface(IRawGreenlet) function Switch: tTuple; overload; function Switch(const Args: array of const): tTuple; overload; function Yield: tTuple; overload; function Yield(const A: array of const): tTuple; overload; end; IAsymmetric<T> = interface(IRawGreenlet) function GetResult(const Block: Boolean = True): T; end; IGCondVariable = interface ['{BB479A02-A201-4339-B600-26043F523FDB}'] procedure SetSync(const Value: Boolean); function GetSync: Boolean; property Sync: Boolean read GetSync write SetSync; procedure Wait(aUnlocking: TCriticalSection = nil); overload; procedure Wait(aSpinUnlocking: TPasMPSpinLock); overload; procedure Signal; procedure Broadcast; end; IGSemaphore = interface ['{098C6819-DE79-4A7D-9840-DB4747C581AC}'] procedure Acquire; procedure Release; function Limit: LongWord; function Value: LongWord; end; IGMutex = interface ['{2CD93CD7-E3B6-4DB5-ABBC-9D764EC2D82E}'] procedure Acquire; procedure Release; end; IGQueue<T> = interface ['{28CABD15-521C-4BE0-AC2A-031BA29C2FDF}'] procedure Enqueue(A: T); procedure Dequeue(out A: T); procedure Clear; function Count: Integer; end; IAbstractChannel = interface ['{4BA64DCF-5E5F-46D0-B74C-8F8A6F370917}'] procedure AccumRefs(ReadRefCount, WriteRefCount: Integer); procedure ReleaseRefs(ReadRefCount, WriteRefCount: Integer); procedure SetDeadlockExceptionClass(Cls: TExceptionClass); function GetDeadlockExceptionClass: TExceptionClass; end; EResultIsEmpty = class(Exception); // channel allows you to catch DeadLock EChannelDeadLock = class(Exception); EChannelLeaveLock = class(Exception); EChannelClosed = class(Exception); IErrorHolder<ERROR> = interface ['{252FD6CA-D691-4D45-BDFB-FC3C769D7EE0}'] function GetErrorCode: ERROR; function GetErrorStr: string; end; IFuture<RESULT, ERROR> = interface(IErrorHolder<ERROR>) ['{00A2154A-0B80-4267-9E44-1E68430E48A6}'] function OnFullFilled: TGevent; function OnRejected: TGevent; function GetResult: RESULT; end; IPromise<RESULT, STATUS> = interface ['{33FF6CE8-4B84-4911-A7A5-FEB67C646C25}'] procedure SetResult(const A: RESULT); procedure SetErrorCode(Value: STATUS; const ErrorStr: string = ''); end; TPendingError = (psUnknown, psClosed, psDeadlock, psTimeout, psException, psSuccess); IReadOnly<T> = interface(IAbstractChannel) ['{ACD057AD-B28A-4232-98D9-6ABC0732A732}'] function Read(out A: T): Boolean; function ReadPending: IFuture<T, TPendingError>; procedure Close; function IsClosed: Boolean; function GetEnumerator: TEnumerator<T>; function Get: T; function GetBufSize: LongWord; end; IWriteOnly<T> = interface(IAbstractChannel) ['{2CD85C7A-6BDB-454F-BF54-9F260DA237B4}'] function Write(const A: T): Boolean; function WritePending(const A: T): IFuture<T, TPendingError>; procedure Close; function IsClosed: Boolean; function GetBufSize: LongWord; end; IChannel<T> = interface(IAbstractChannel) ['{275B1ED7-0927-497C-8689-5030AAE94341}'] function Read(out A: T): Boolean; function Write(const A: T): Boolean; function ReadOnly: IReadOnly<T>; function WriteOnly: IWriteOnly<T>; procedure Close; function IsClosed: Boolean; function GetEnumerator: TEnumerator<T>; function Get: T; function GetBufSize: LongWord; function ReadPending: IFuture<T, TPendingError>; function WritePending(const A: T): IFuture<T, TPendingError>; end; IFanOut<T> = interface function Inflate(const BufSize: Integer=-1): IReadOnly<T>; end; ICase = interface ['{20C53130-1104-4644-BE7B-C06249FC0631}'] function GetOperation: TIOOperation; procedure SetOperation(const Value: TIOOperation); function GetOnSuccess: TGevent; procedure SetOnSuccess(Value: TGevent); function GetOnError: TGevent; procedure SetOnError(Value: TGevent); function GetErrorHolder: IErrorHolder<TPendingError>; procedure SetErrorHolder(Value: IErrorHolder<TPendingError>); function GetWriteValueExists: Boolean; procedure SetWriteValueExists(const Value: Boolean); // props property Operation: TIOOperation read GetOperation write SetOperation; property OnSuccess: TGevent read GetOnSuccess write SetOnSuccess; property OnError: TGevent read GetOnError write SetOnError; property ErrorHolder: IErrorHolder<TPendingError> read GetErrorHolder write SetErrorHolder; property WriteValueExists: Boolean read GetWriteValueExists write SetWriteValueExists; end; ICollection<T> = interface ['{8C5840E8-A67D-40A6-9733-62087EAAE8D6}'] procedure Append(const A: T; const IgnoreDuplicates: Boolean); overload; procedure Append(const Other: ICollection<T>; const IgnoreDuplicates: Boolean); overload; procedure Remove(const A: T); function Count: Integer; function Get(Index: Integer): T; function Copy: ICollection<T>; procedure Clear; function GetEnumerator: TEnumerator<T>; end; implementation end.
(* ** $Id: lualib.h,v 1.28 2003/03/18 12:24:26 roberto Exp $ ** Lua standard libraries ** See Copyright Notice in lua.h *) (* ** Translated to pascal by Lavergne Thomas ** Bug reports : ** - thomas.lavergne@laposte.net ** In french or in english *) (* $Updated by foofighter69@gmail.com -> 5.1.1 2008-03-26 $ *) unit lualib; interface uses Lua; const LUA_COLIBNAME = 'coroutine'; function luaopen_base(L: Plua_State): LongBool; cdecl; const LUA_TABLIBNAME = 'table'; function luaopen_table(L: Plua_State): LongBool; cdecl; const LUA_IOLIBNAME = 'io'; function luaopen_io(L: Plua_State): LongBool; cdecl; const LUA_OSLIBNAME = 'os'; function luaopen_os(L: Plua_State): LongBool; cdecl; (* new *) const LUA_STRLIBNAME = 'string'; function luaopen_string(L: Plua_State): LongBool; cdecl; const LUA_MATHLIBNAME = 'math'; function luaopen_math(L: Plua_State): LongBool; cdecl; const LUA_DBLIBNAME = 'debug'; function luaopen_debug(L: Plua_State): LongBool; cdecl; const LUA_PACKAGENAME = 'package'; function luaopen_package(L: Plua_State): LongBool; cdecl; (* function luaopen_loadlib(L: Plua_State): LongWord; cdecl; *) procedure luaL_openlibs(L: Plua_State);cdecl; (* LUALIB_API void luaL_openlibs (lua_State *L) { const luaL_Reg *lib = lualibs; for (; lib->func; lib++) { lua_pushcfunction(L, lib->func); lua_pushstring(L, lib->name); lua_call(L, 1, 0); } } *) (* compatibility code *) function lua_baselibopen(L: Plua_State): LongBool; function lua_tablibopen(L: Plua_State): LongBool; function lua_iolibopen(L: Plua_State): LongBool; function lua_strlibopen(L: Plua_State): LongBool; function lua_mathlibopen(L: Plua_State): LongBool; function lua_dblibopen(L: Plua_State): LongBool; implementation function luaopen_base(L: Plua_State): LongBool; cdecl; external LUA_LIB_NAME; function luaopen_table(L: Plua_State): LongBool; cdecl; external LUA_LIB_NAME; function luaopen_io(L: Plua_State): LongBool; cdecl; external LUA_LIB_NAME; function luaopen_os(L: Plua_State): LongBool; cdecl; external LUA_LIB_NAME; function luaopen_string(L: Plua_State): LongBool; cdecl; external LUA_LIB_NAME; function luaopen_math(L: Plua_State): LongBool; cdecl; external LUA_LIB_NAME; function luaopen_debug(L: Plua_State): LongBool; cdecl; external LUA_LIB_NAME; function luaopen_package(L: Plua_State): LongBool; cdecl; external LUA_LIB_NAME; (* new *) (* function luaopen_loadlib(L: Plua_State): LongWord; cdecl; external LUA_LIB_NAME;*) procedure luaL_openlibs(L: Plua_State);cdecl; external LUA_LIB_NAME;(* new *) function lua_baselibopen(L: Plua_State): LongBool; begin Result := luaopen_base(L); end; function lua_tablibopen(L: Plua_State): LongBool; begin Result := luaopen_table(L); end; function lua_iolibopen(L: Plua_State): LongBool; begin Result := luaopen_io(L); end; function lua_strlibopen(L: Plua_State): LongBool; begin Result := luaopen_string(L); end; function lua_mathlibopen(L: Plua_State): LongBool; begin Result := luaopen_math(L); end; function lua_dblibopen(L: Plua_State): LongBool; begin Result := luaopen_debug(L); end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2015-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit EMSHosting.RequestHandler; interface uses System.SysUtils, System.Classes, System.Generics.Collections, EMSHosting.RequestTypes, EMS.ResourceAPI, EMSHosting.Endpoints; type TEMSHostRequestProps = record public type THeaderNames = record public const ApiVersion = 'X-Embarcadero-Api-Version'; ApplicationId = 'X-Embarcadero-Application-Id'; SessionToken = 'X-Embarcadero-Session-Token'; MasterSecret = 'X-Embarcadero-Master-Secret'; AppSecret = 'X-Embarcadero-App-Secret'; TenantId = 'X-Embarcadero-Tenant-Id'; TenantSecret = 'X-Embarcadero-Tenant-Secret'; end; private FApplicationId: string; FApiVersion: string; FApiMajorVersion: string; FApiMinorVersion: string; FSessionToken: string; FResourceURL: string; FAppSecret: string; FMasterSecret: string; FTenantId: string; FTenantSecret: string; public property ApiVersion: string read FApiVersion; property ApiMajorVersion: string read FApiMajorVersion; property ApiMinorVersion: string read FApiMinorVersion; property ApplicationID: string read FApplicationID; property ResourceURL: string read FResourceURL; property SessionToken: string read FSessionToken; property AppSecret: string read FAppSecret; property MasterSecret: string read FMasterSecret; property TenantId: string read FTenantId; property TenantSecret: string read FTenantSecret; end; TEMSHostRequestHandler = class abstract private function GetRequestProps( const Request: IEMSHostRequest): TEMSHostRequestProps; function GetGroups(const AContext: IEMSHostContext; const AUserID, ATenantId: string; var AGroups: TEndpointContext.TGroups): TEndpointContext.TGroups; function GetUserID(const AContext: IEMSHostContext; const ASessionToken, ATenantId: string; var AUserID: string): string; function GetUserName(const AContext: IEMSHostContext; const AUserID, ATenantId: string; var AUserName: string): string; protected function UserIDOfSession(const AContext: IEMSHostContext; const ASessionToken, ATenantId: string; out AUserID: string): Boolean; virtual; abstract; function UserNameOfID(const AContext: IEMSHostContext; const AUserID, ATenantId: string; out AUserName: string): Boolean; virtual; abstract; function GetGroupsByUser(const AContext: IEMSHostContext; const AUserID, ATenantId: string): TArray<string>; virtual; procedure CheckForbiddenRequest(const AResourceName, AOriginalResourceName: string); virtual; abstract; procedure AuthenticateRequest(const AResources: TArray<TEMSResource>; const AResourceRequest: TEMSHostRequestProps; var AAuthenticated: TEndpointContext.TAuthenticated); virtual; abstract; procedure LogEndpoint(const AResource, AEndpointName, AMethod, AUserID, ACustom, ATenantId: string); virtual; abstract; procedure RedirectResource(const AContext: TEndpointContext; var AResource: TEMSResource; var AEndpointName: string); virtual; abstract; function ResourcesPath: string; virtual; //Tenants function IsUserBelongsToTenant(const AUserId, ATenantId: string): Boolean; virtual; abstract; function GetTenantNameByTenantId(const ATenantId: string; const AContext: IEMSHostContext = nil): string; virtual; abstract; function GetDefaultTenantId: string; virtual; abstract; public { Public declarations } procedure HandleRequest(const Context: IEMSHostContext; const Request: IEMSHostRequest; const Response: IEMSHostResponse; var Handled: Boolean); procedure HandleException(const E: Exception; const Response: IEMSHostResponse; var Handled: Boolean); end; implementation uses System.JSON, EMSHosting.Utility, EMSHosting.Helpers, EMSHosting.ResourceManager, EMSHosting.Consts, System.Character, System.NetEncoding; type TUser = class(TEndpointContextImpl.TUser) private type TGroups = TEndpointContext.TGroups; private FContext: IEMSHostContext; FRequestHandler: TEMSHostRequestHandler; [weak] FEndpointContext: TEndpointContextImpl; FUserID: string; FUserName: string; FSessionToken: string; FGroups: TGroups; protected function GetUserName: string; override; function GetUserID: string; override; function GetSessionToken: string; override; function GetGroups: TEndpointContext.TGroups; override; public constructor Create(const AContext: IEMSHostContext; const ARequestHandler: TEMSHostRequestHandler; const AEndpointContext: TEndpointContextImpl; const AUserID, ASessionToken: string); end; TEdgemodule = class(TEndpointContextImpl.TEdgemodule) private FContext: IEMSEdgeHostContext; protected function GetModuleName: string; override; function GetModuleVersion: string; override; public constructor Create(const AContext: IEMSEdgeHostContext); end; TGroups = class(TEndpointContextImpl.TGroups) private FContext: IEMSHostContext; FRequestHandler: TEMSHostRequestHandler; FUserID: string; FTenantId: string; FGroups: TList<string>; procedure CheckGroups; protected function GetCount: Integer; override; public constructor Create(const AContext: IEMSHostContext; const ARequestHandler: TEMSHostRequestHandler; const AUserID, ATenantId: string); destructor Destroy; override; function Contains(const AGroup: string): Boolean; override; end; TTenant = class(TEndpointContextImpl.TTenant) private FContext: IEMSHostContext; FRequestHandler: TEMSHostRequestHandler; FTenantId: string; protected function GetTenantId: string; override; function GetTenantName: string; override; public constructor Create(const AContext: IEMSHostContext; const ARequestHandler: TEMSHostRequestHandler; const ATenantId: string); end; { TUser } constructor TUser.Create(const AContext: IEMSHostContext; const ARequestHandler: TEMSHostRequestHandler; const AEndpointContext: TEndpointContextImpl; const AUserID, ASessionToken: string); begin inherited Create; FContext := AContext; FRequestHandler := ARequestHandler; FEndpointContext := AEndpointContext; FUserID := AUserID; FSessionToken := ASessionToken; end; function TUser.GetUserName: string; begin Result := FRequestHandler.GetUserName(FContext, FUserID, FEndpointContext.Tenant.Id, FUserName); end; function TUser.GetUserID: string; begin Result := FUserID; end; function TUser.GetSessionToken: string; begin Result := FSessionToken; end; function TUser.GetGroups: TEndpointContext.TGroups; begin Result := FRequestHandler.GetGroups(FContext, FUserID, FEndpointContext.Tenant.Id, FGroups); end; { TEdgemodule } constructor TEdgemodule.Create(const AContext: IEMSEdgeHostContext); begin inherited Create; FContext := AContext; end; function TEdgemodule.GetModuleName: string; begin Result := FContext.ModuleName; end; function TEdgemodule.GetModuleVersion: string; begin Result := FContext.ModuleVersion; end; { TGroups } constructor TGroups.Create(const AContext: IEMSHostContext; const ARequestHandler: TEMSHostRequestHandler; const AUserID, ATenantId: string); begin inherited Create; FContext := AContext; FRequestHandler := ARequestHandler; FUserID := AUserID; FTenantId := ATenantId; end; destructor TGroups.Destroy; begin FGroups.Free; inherited Destroy; end; procedure TGroups.CheckGroups; begin if FGroups = nil then begin FGroups := TList<string>.Create; FGroups.AddRange(FRequestHandler.GetGroupsByUser(FContext, FUserID, FTenantId)); end; end; function TGroups.Contains(const AGroup: string): Boolean; begin CheckGroups; Result := FGroups.Contains(AGroup); end; function TGroups.GetCount: Integer; begin CheckGroups; Result := FGroups.Count; end; { TTenant } constructor TTenant.Create(const AContext: IEMSHostContext; const ARequestHandler: TEMSHostRequestHandler; const ATenantId: string); begin inherited Create; FContext := AContext; FRequestHandler := ARequestHandler; FTenantId := ATenantId; end; function TTenant.GetTenantId: string; begin Result := FTenantId; end; function TTenant.GetTenantName: string; begin Result := FRequestHandler.GetTenantNameByTenantId(FTenantId, FContext); end; { TEMSHostRequestHandler } function TEMSHostRequestHandler.GetRequestProps(const Request: IEMSHostRequest): TEMSHostRequestProps; function GetField(const AName: string; const ADefault: string = ''): string; begin Result := Request.Headers[AName]; if Result = '' then Result := ADefault; end; function RemoveGuidBrackets(const AValue: string): string; begin Result := AValue; if not Result.IsEmpty and (Result.Length > 32) and Result.StartsWith('{') and Result.EndsWith('}') then Result := Result.Substring(1, Result.Length - 2); end; var LPathInfo: string; LStrings: TStrings; I: Integer; begin LPathInfo := String(Request.PathInfo); LStrings := ParseURLPath(LPathInfo); try if LStrings.Count > 0 then begin if LStrings[0] = '/' then if LStrings.Count > 1 then Result.FResourceURL := '/' + LStrings[1] else Result.FResourceURL := LStrings[0] else Result.FResourceURL := LStrings[0]; end; Result.FApplicationId := GetField(TEMSHostRequestProps.THeaderNames.ApplicationId); Result.FApiVersion := GetField(TEMSHostRequestProps.THeaderNames.ApiVersion); I := Result.FApiVersion.IndexOf('.'); if I > 0 then begin Result.FApiMinorVersion := Result.FApiVersion.Substring(I+1); Result.FApiMajorVersion := Result.FApiVersion.Substring(0, I); end else Result.FApiMajorVersion := Result.FApiVersion; Result.FMasterSecret := GetField(TEMSHostRequestProps.THeaderNames.MasterSecret); Result.FAppSecret := GetField(TEMSHostRequestProps.THeaderNames.AppSecret); Result.FSessionToken := GetField(TEMSHostRequestProps.THeaderNames.SessionToken); Result.FTenantId := RemoveGuidBrackets(TNetEncoding.URL.Decode(GetField(TEMSHostRequestProps.THeaderNames.TenantId), [])); Result.FTenantSecret := TNetEncoding.URL.Decode(GetField(TEMSHostRequestProps.THeaderNames.TenantSecret), []); if Result.FResourceURL = '' then Result.FResourceURL := '/'; finally LStrings.Free; end; end; function TEMSHostRequestHandler.GetUserID(const AContext: IEMSHostContext; const ASessionToken, ATenantId: string; var AUserID: string): string; begin Result := AUserID; if Result = '' then begin if not Self.UserIDOfSession(AContext, ASessionToken, ATenantId, Result) then EEMSHTTPError.RaiseUnauthorized; // No user end; AUserID := Result; end; function TEMSHostRequestHandler.GetGroups(const AContext: IEMSHostContext; const AUserID, ATenantId: string; var AGroups: TEndpointContext.TGroups): TEndpointContext.TGroups; begin Result := AGroups; if Result = nil then Result := TGroups.Create(AContext, Self, AUserID, ATenantId); AGroups := Result; end; function TEMSHostRequestHandler.GetUserName(const AContext: IEMSHostContext; const AUserID, ATenantId: string; var AUserName: string): string; begin Result := AUserName; if Result = '' then begin if not Self.UserNameOfID(AContext, AUserID, ATenantId, Result) then EEMSHTTPError.RaiseNotFound; end; AUserName := Result; end; function TEMSHostRequestHandler.GetGroupsByUser(const AContext: IEMSHostContext; const AUserID, ATenantId: string): TArray<string>; begin Result := nil; end; type TEMSHostRequestWrapper = class(TInterfacedObject, IEMSHostRequest) private FPathInfo: string; FOriginalRequest: IEMSHostRequest; function GetContentType: string; function GetMethodType: TEMSHostMethodType; function GetPathInfo: string; function GetQueryFields: TStringKeyValues; function GetRawContent: TBytes; function GetMethod: string; function GetContentLength: Integer; function GetHeader(const AName: string): string; function GetBasePath: string; function GetServerHost: string; public constructor Create(const AOriginalRequest: IEMSHostRequest; const APathInfo: string); end; constructor TEMSHostRequestWrapper.Create(const AOriginalRequest: IEMSHostRequest; const APathInfo: string); begin FPathInfo := APathInfo; FOriginalRequest := AOriginalRequest; end; function TEMSHostRequestWrapper.GetBasePath: string; begin Result := FOriginalRequest.GetBasePath; end; function TEMSHostRequestWrapper.GetContentLength: Integer; begin Result := FOriginalRequest.GetContentLength; end; function TEMSHostRequestWrapper.GetContentType: string; begin Result := FOriginalRequest.GetContentType; end; function TEMSHostRequestWrapper.GetHeader(const AName: string): string; begin Result := FOriginalRequest.GetHeader(AName); end; function TEMSHostRequestWrapper.GetMethod: string; begin Result := FOriginalRequest.GetMethod; end; function TEMSHostRequestWrapper.GetMethodType: TEMSHostMethodType; begin Result := FOriginalRequest.GetMethodType; end; function TEMSHostRequestWrapper.GetPathInfo: string; begin Result := FPathInfo; // FOriginalRequest.GetPathInfo; end; function TEMSHostRequestWrapper.GetQueryFields: TStringKeyValues; begin Result := FOriginalRequest.GetQueryFields; end; function TEMSHostRequestWrapper.GetRawContent: TBytes; begin Result := FOriginalRequest.GetRawContent; end; function TEMSHostRequestWrapper.GetServerHost: string; begin Result := FOriginalRequest.GetServerHost; end; procedure TEMSHostRequestHandler.HandleRequest(const Context: IEMSHostContext; const Request: IEMSHostRequest; const Response: IEMSHostResponse; var Handled: Boolean); var LResources: TArray<TEMSResource>; function IsVersionResource: Boolean; begin Result := (Length(LResources) = 1) and SameText(LResources[0].Name, 'version'); end; type TUserGroups = TUser.TGroups; var LPathInfo: string; LResource: TEMSResource; R: TEMSResource; LContext: TEndpointContextImpl; LRequest: TEndpointRequest; LResponse: TEndpointResponseImpl; LAuthenticated: TEndpointContext.TAuthenticated; LEndpointName: string; LCustom: string; LResourceRequest: TEMSHostRequestProps; LUserID: string; LOriginalResourceName: string; LOriginalEndpointName: string; LHostRequest: IEMSHostRequest; LTemp: string; LIsResourceRequest: Boolean; begin LAuthenticated := []; LRequest := nil; LResponse := nil; LIsResourceRequest := True; try LPathInfo := String(Request.PathInfo); if (LPathInfo.Length > 0) and (Self.ResourcesPath <> '') then begin LTemp := Self.ResourcesPath; if (LTemp.Chars[0] <> '/') and (LPathInfo.Chars[0] = '/') then LTemp := '/' + LTemp; LTemp.TrimRight(['/']); if LPathInfo.StartsWith(LTemp, True) then LPathInfo := LPathInfo.Substring(LTemp.Length) else LIsResourceRequest := False; end; LHostRequest := TEMSHostRequestWrapper.Create(Request, LPathInfo); LResourceRequest := GetRequestProps(LHostRequest); if LIsResourceRequest then begin LResources := TEMSEndpointManagerImpl.Instance.FindByBaseURL(LResourceRequest.ResourceURL); Self.AuthenticateRequest(LResources, LResourceRequest, LAuthenticated); end else LResources := nil; if LResources = nil then begin if LResourceRequest.ResourceURL = '/' then begin // Blank page Response.StatusCode := 200; Exit; // EXIT end else if SameText(LResourceRequest.ResourceURL, '/favicon.ico') then begin // Silent failure Response.StatusCode := EEMSHTTPError.TCodes.NotFound; Exit; // EXIT end; EEMSHTTPError.RaiseNotFound(Format(sResourceNotFound, [LPathInfo])); end; LRequest := TEndpointRequestImpl.Create(LHostRequest); LContext := TEndpointContextImpl.Create; LContext.OnGetAuthenticated := function: TEndpointContext.TAuthenticated begin Result := LAuthenticated; if LContext.User <> nil then Include(Result, TEndpointContext.TAuthenticate.User); end; LContext.OnGetEndpointName := function: string begin Result := LEndpointName; end; LContext.OnGetRequest := function: TEndpointRequest begin Result := LRequest; end; LContext.OnGetResponse := function: TEndpointResponse begin Result := LResponse; end; LContext.OnCreateUser := procedure(const AContext: TEndpointContextImpl; out AUser: TEndpointContextImpl.TUser) var LUserId: string; begin AUser := nil; if (LResourceRequest.SessionToken <> '') and (AContext.Tenant <> nil) then begin GetUserID(Context, LResourceRequest.SessionToken, LContext.Tenant.Id, LUserID); if IsUserBelongsToTenant(LUserId, AContext.Tenant.Id) then AUser := TUser.Create(Context, Self, LContext, LUserID, LResourceRequest.SessionToken); end; end; LContext.OnCreateEdgemodule := procedure(const AContext: TEndpointContextImpl; out AEdgemodule: TEndpointContextImpl.TEdgemodule) var LIntf: IEMSEdgeHostContext; begin AEdgemodule := nil; if Supports(Context, IEMSEdgeHostContext, LIntf) then AEdgemodule := TEdgemodule.Create(LIntf); end; LContext.OnGetTenant := function: TEndpointContextImpl.TTenant begin Result := nil; if LResourceRequest.TenantId = '' then LResourceRequest.FTenantId := Self.GetDefaultTenantId; if LResourceRequest.TenantId <> '' then Result := TTenant.Create(Context, Self, LResourceRequest.TenantId); end; LResource := nil; for R in LResources do if R.CanHandleRequest(LContext, LEndpointName) then begin if LResource = nil then LResource := R else EEMSHTTPError.RaiseError(500, sResourceErrorMessage, Format(sResourceMultipleEndpoints, [LEndpointName])); end; if LResource <> nil then begin LOriginalResourceName := LResource.Name; LOriginalEndpointName := LEndpointName; RedirectResource(LContext, LResource, LEndpointName); end; if LResource <> nil then begin CheckForbiddenRequest(LResource.Name, LOriginalResourceName); if LContext.User <> nil then LUserID := LContext.User.UserID else LUserID := ''; if TLogHelpers.LoggingEnabled then TLogHelpers.LogRequest(LResource.Name, LEndpointName, LRequest.MethodString, LUserID); LResponse := TEndpointResponseImpl.Create(Response); Handled := True; LResource.HandleRequest(LContext); LResponse.Write; case LContext.EndpointDataType of // In the case of AddUser/DeleteUser, the userid being added or deleted should be passed to ACustom TEndpointContextImpl.TEndpointDataType.AddUser, TEndpointContextImpl.TEndpointDataType.DeletedUser: LCustom := LContext.EndpointDataValue; end; case LContext.EndpointDataType of // In the case of AddUser/Login, log the userid TEndpointContextImpl.TEndpointDataType.AddUser, TEndpointContextImpl.TEndpointDataType.LoginUser: if LUserID = '' then LUserID := LContext.EndpointDataValue; end; // Analytics log Self.LogEndpoint(LResource.Name, LEndpointName, LRequest.MethodString, LUserID, LCustom, LResourceRequest.TenantId); end else EEMSHTTPError.RaiseNotFound('', Format(sResourceNotFound, [LPathInfo])); finally LRequest.Free; LResponse.Free; LContext.Free; end; end; function TEMSHostRequestHandler.ResourcesPath: string; begin Result := ''; end; procedure TEMSHostRequestHandler.HandleException(const E: Exception; const Response: IEMSHostResponse; var Handled: Boolean); var LHTTPError: EEMSHTTPError; LJSONObject: TJSONObject; LBody: TEndpointResponseBodyImpl; LError: string; LDescription: string; begin Handled := True; if E is EEMSHTTPError then begin LHTTPError := EEMSHTTPError(E); Response.StatusCode := LHTTPError.Code; if LHTTPError.Error <> '' then LError := LHTTPError.Error; if LHTTPError.Description <> '' then LDescription := LHTTPError.Description; end else begin Response.StatusCode := 500; LDescription := E.Message; end; // Write JSONObject with error description LJSONObject := TErrorHelpers.CreateJSONError(string(Response.ReasonString), LError, LDescription); try if TLogHelpers.LoggingEnabled then TLogHelpers.LogHTTPError(REsponse.StatusCode, String(Response.ReasonString), LError, LDescription); LBody := TEndpointResponseBodyImpl.Create(Response); try // Write to response LBody.SetValue(LJSONObject, False); finally LBody.Free; end; finally LJSONObject.Free; end; end; end.
unit AioIndyTests; interface uses Greenlets, IdHTTP, AioIndy, TestFramework; type TAioIndyTests = class(TTestCase) published procedure HttpGet; end; implementation { TAioIndyTests } procedure TAioIndyTests.HttpGet; var Client: TIdHTTP; Response: string; begin Client := TIdHTTP.Create(nil); try Client.IOHandler := AioIndy.TAioIdIOHandlerSocket.Create(Client); Client.HandleRedirects := True; Response := Client.Get('http://uit.fun/aio'); CheckEquals('Hello!!!', Response); finally Client.Free end; end; initialization RegisterTest('AioIndyTests', TAioIndyTests.Suite); end.
unit Player; {$mode objfpc}{$H+} interface uses Classes, SysUtils, SDL2, Utility, Options; type rPlayerAction = record MousePressed, Left, Right, Forwards, Backwards, Up, Down, PitchDown, PitchUp, YawLeft, YawRight, RollLeft, RollRight, WireFrame, DrawFrame, Paused: Boolean; mx, my: single; end; { tPlayer } tPlayer = class private Event: tSDL_Event; public Options: tOptions; Name: string; Action: rPlayerAction; constructor Create(Opts: tOptions); destructor Destroy; override; procedure LoadProfile(FileName: string); //character? procedure ProcessInput; end; const DefaultProfileName = 'DefaultProfile'; ProfileExt = '.xml'; implementation uses app; { tPlayer } constructor tPlayer.Create(Opts: tOptions); begin Options:= Opts; //this could create problems; is in todo end; destructor tPlayer.Destroy; begin Options.Free; inherited Destroy; end; procedure tPlayer.LoadProfile(FileName: string); { TODO 1 -cimprovement : change into a func } begin if FileExists(FileName) then begin //Options.Free; { TODO : Possible overlap from different profiles: needs reset } //Options:= tOptions.Create; WriteLog('Loading player profile ' + FileName); Options.Load(FileName); //Secondary, overriding primary end else begin { TODO : warn about missing profile } WriteLog('Player profile is missing'); Options.WriteDefault(FileName); end; end; procedure tPlayer.ProcessInput; begin with Action do begin mx:= 0; my:= 0; while SDL_PollEvent(@Event) = 1 do with Event do begin case type_ of SDL_MOUSEBUTTONDOWN: MousePressed:= true; // Mouse button pressed SDL_MOUSEBUTTONUP: MousePressed:= false; SDL_MouseMotion: begin mx:= motion.xrel; my:= motion.yrel; end; SDL_KeyDown: case Options.cs[eScanCode(key.keysym.scancode)] of aLeft: Left:= true; aRight: Right:= true; aForward: Forwards:= true; aBackward: Backwards:= true; aUpward: Up:= true; aDownward: Down:= true; aPitchDown: PitchDown:= true; aPitchUp: PitchUp:= true; aYawLeft: YawLeft:= true; aYawRight: YawRight:= true; aRollLeft: RollLeft:= true; aRollRight: RollRight:= true; aEsc: Paused:= true; end; SDL_KeyUp: case Options.cs[eScanCode(key.keysym.scancode)] of aLeft: Left:= false; aRight: Right:= false; aForward: Forwards:= false; aBackward: Backwards:= false; aUpward: Up:= false; aDownward: Down:= false; aPitchDown: PitchDown:= false; aPitchUp: PitchUp:= false; aYawLeft: YawLeft:= false; aYawRight: YawRight:= false; aRollLeft: RollLeft:= false; aRollRight: RollRight:= false; end; SDL_QuitEv: GameApp.State:= sShutDown; else WriteLog(strf(Event.key.keysym.scancode)); end; end; end; end; end.
unit Scripts; interface uses Values, Codes, Variables, Functions, ClassDefs, Strings; type TScript = class private FVariables: TVariables; FFunctions: TFunctions; FClassDefs: TClassDefs; FOnVariable: TVariableFunc; FOnFunction: TFunctionFunc; procedure DoDefine(const AID: TID; AType_: TType_; AExts: TType_Exts = []); function DoVariable(const AID: TID): TValue; function DoFunction(const AID: TID; const AArguments: TValues; AClass: TValue = nil): TValue; function DoMethod(const AID: TID; const AArguments: TValues; AClass: TValue = nil): TValue; function DoCompile(const AText: String): Boolean; public constructor Create(); destructor Destroy(); override; function Include(const AFileName: String): Boolean; function Compile(const AText: String): Boolean; procedure Attach(ACode: TCode); procedure Clear(); property Variables: TVariables read FVariables; property Functions: TFunctions read FFunctions; property ClassDefs: TClassDefs read FClassDefs; property OnVariable: TVariableFunc read FOnVariable write FOnVariable; property OnFunction: TFunctionFunc read FOnFunction write FOnFunction; end; implementation uses Classes, SysUtils; { TScript } { private } procedure TScript.DoDefine(const AID: TID; AType_: TType_; AExts: TType_Exts); begin FVariables.Define(AID, AType_, AExts); end; function TScript.DoVariable(const AID: TID): TValue; var lVariable: TVariable; begin lVariable := FVariables.VariableByID(AID); if Assigned(lVariable) then Result := lVariable.Value else if Assigned(FOnVariable) then Result := FOnVariable(AID) else Result := nil; end; function TScript.DoFunction(const AID: TID; const AArguments: TValues; AClass: TValue): TValue; var lFunction: TFunction; lClassDef: TClassDef; I: Integer; begin lFunction := FFunctions.FunctionByID(AID); if Assigned(lFunction) then Result := lFunction.Run(AArguments) else if Assigned(FOnFunction) then Result := FOnFunction(AID, AArguments, AClass) else Result := nil; if not Assigned(Result) then // void include(str AFileName1, ..., str AFileNameN) if AID = 'include' then begin for I := 0 to High(AArguments) do Include(AArguments[I].S); Result := TValue.Create(); end else if AID = 'class' then begin lClassDef := FClassDefs.ClassDefByID(AArguments[0].S); if Assigned(lClassDef) then begin Result := TValue.Create(TYPE_CLASS); Result.CreateClass(lClassDef.CID, lClassDef.Fields); end else Result := TValue.Create(); end end; function TScript.DoMethod(const AID: TID; const AArguments: TValues; AClass: TValue): TValue; var lClassDef: TClassDef; begin if Assigned(AClass) then begin lClassDef := FClassDefs.ClassDefByCID(AClass.CID); if Assigned(lClassDef) then Result := lClassDef.Method(AID, AArguments, AClass) else Result := nil; end else Result := nil; end; function TScript.DoCompile(const AText: String): Boolean; var lText, lItem: String; begin Result := False; lText := AText; Prepare(lText); while lText <> '' do begin lItem := ReadCompileItem(lText); if FirstItem(lItem, ' ') = STR_CLASSDEF then with TClassDef.Create(FClassDefs) do if Compile(lItem) then Result := True else begin Free(); Result := False; Break; end else with TFunction.Create(FFunctions) do if Compile(lItem) then Result := True else begin Free(); Result := False; Break; end; end; end; { public } constructor TScript.Create; begin inherited Create(); FVariables := TVariables.Create(); FFunctions := TFunctions.Create(); FFunctions.OnDefine := DoDefine; FFunctions.OnVariable := DoVariable; FFunctions.OnFunction := DoFunction; FFunctions.OnMethod := DoMethod; FClassDefs := TClassDefs.Create(); FClassDefs.OnDefine := DoDefine; FClassDefs.OnVariable := DoVariable; FClassDefs.OnFunction := DoFunction; FClassDefs.OnMethod := DoMethod; FOnVariable := nil; FOnFunction := nil; end; destructor TScript.Destroy; begin FClassDefs.Free(); FFunctions.Free(); FVariables.Free(); inherited; end; function TScript.Include(const AFileName: String): Boolean; var lFile: TStringList; begin Result := FileExists(AFileName); if Result then begin lFile := TStringList.Create(); lFile.LoadFromFile(AFileName); Result := Compile(lFile.Text); lFile.Free; end; end; function TScript.Compile(const AText: String): Boolean; begin Result := DoCompile(AText); end; procedure TScript.Attach(ACode: TCode); begin if Assigned(ACode) then begin ACode.OnDefine := DoDefine; ACode.OnVariable := DoVariable; ACode.OnFunction := DoFunction; end; end; procedure TScript.Clear(); begin FClassDefs.Clear(); FFunctions.Clear(); FVariables.Clear(); end; end.
unit uDependente; interface uses System.Classes; type TDependente = class private FIsCalculaINSS: Boolean; FNome: String; FIsCalculaIR: Boolean; FId_Funcionario: integer; public property Nome: String read FNome write FNome; property IsCalculaIR: Boolean read FIsCalculaIR write FIsCalculaIR; property IsCalculaINSS: Boolean read FIsCalculaINSS write FIsCalculaINSS; property Id_Funcionario: Integer read FId_Funcionario write FId_Funcionario; end; implementation end.
{**********************************************************************} {* Иллюстрация к книге "OpenGL в проектах Delphi" *} {* Краснов М.В. softgl@chat.ru *} {**********************************************************************} unit frmMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OpenGL; type TfrmGL = class(TForm) procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormResize(Sender: TObject); private DC: HDC; hrc: HGLRC; procedure SetDCPixelFormat; procedure DrawFloor; procedure DrawObjects; protected procedure WMPaint(var Msg: TWMPaint); message WM_PAINT; end; var frmGL: TfrmGL; Angle: GLint = 0; implementation uses DGLUT; {$R *.DFM} procedure TfrmGL.DrawFloor; begin glPushMatrix; glColor4f(0.5, 0.5, 0.5, 0.8); glBegin(GL_QUADS); glTexCoord2f(0, 1); glVertex3f(-2, 0, 2); glTexCoord2f(1, 1); glVertex3f(2, 0, 2); glTexCoord2f(1, 0); glVertex3f(2, 0, -2); glTexCoord2f(0, 0); glVertex3f(-2, 0, -2); glEnd; glPopMatrix; end; procedure TfrmGL.DrawObjects; begin glPushMatrix; glColor3f(1, 0, 0); glTranslatef(0, 0.5, 0); glRotatef(Angle, 1, 0.5, 0); glutSolidTorus(0.1, 0.3, 16, 32); glTranslatef(0, 0, -0.25); glColor3f(0, 0.5, 0); glPushMatrix; glScalef (0.05, 0.05, 0.05); glutSolidDodecahedron; glPopMatrix; glPushMatrix; glTranslatef(0, 0, 0.5); glColor3f(0, 0, 1); glScalef (0.05, 0.05, 0.05); glutSolidDodecahedron; glPopMatrix; glPopMatrix; end; {======================================================================= Рисование картинки} procedure TfrmGL.WMPaint(var Msg: TWMPaint); var ps : TPaintStruct; begin BeginPaint(Handle, ps); glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); glLoadIdentity; glTranslatef(0, -0.5, -4); glEnable(GL_STENCIL_TEST); glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE); glStencilFunc(GL_ALWAYS, 1, $FFFF); glColorMask(FALSE, FALSE, FALSE, FALSE); glDisable(GL_DEPTH_TEST); DrawFloor; glColorMask(TRUE, TRUE, TRUE, TRUE); glEnable(GL_DEPTH_TEST); glStencilFunc(GL_EQUAL, 1, $FFFF); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); glPushMatrix; glScalef(1, -1, 1); DrawObjects; glPopMatrix; glDepthMask(FALSE); DrawFloor; glDepthMask(TRUE); glDisable(GL_STENCIL_TEST); DrawObjects; glFinish; SwapBuffers(DC); // конец работы EndPaint(Handle, ps); Angle := (Angle + 2) mod 360; InvalidateRect(Handle, nil, False); end; {======================================================================= Создание окна} procedure TfrmGL.FormCreate(Sender: TObject); begin DC := GetDC(Handle); SetDCPixelFormat; hrc := wglCreateContext(DC); wglMakeCurrent(DC, hrc); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_COLOR_MATERIAL); glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE); glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_NORMALIZE); glClearColor (0.25, 0.1, 0.25, 0.0); glClearStencil(0); end; {======================================================================= Устанавливаем формат пикселей} procedure TfrmGL.SetDCPixelFormat; var nPixelFormat: Integer; pfd: TPixelFormatDescriptor; begin FillChar(pfd, SizeOf(pfd), 0); pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; nPixelFormat := ChoosePixelFormat(DC, @pfd); SetPixelFormat(DC, nPixelFormat, @pfd); end; {======================================================================= Конец работы программы} procedure TfrmGL.FormDestroy(Sender: TObject); begin wglMakeCurrent(0, 0); wglDeleteContext(hrc); ReleaseDC(Handle, DC); DeleteDC (DC); end; procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_ESCAPE then Close end; procedure TfrmGL.FormResize(Sender: TObject); begin glViewport(0, 0, ClientWidth, ClientHeight ); glMatrixMode(GL_PROJECTION); glLoadIdentity; gluPerspective(35, 1, 2, 6); glMatrixMode(GL_MODELVIEW); InvalidateRect(Handle, nil, False); end; end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit ExpertsIntf; interface uses ToolsAPI; type IExpertsProjectAccessor = interface ['{5758F0ED-8CE5-48C1-B772-739005977158}'] function GetCreatorType: string; function NewProjectSource(const ProjectName: string): IOTAFile; procedure NewDefaultModule; function GetFileName: string; function GetDirectory: string; function GetUnnamed: Boolean; end; IExpertsModuleAccessor = interface ['{1452FEA7-4A4A-4A34-B7E3-CCB3A6604EDE}'] function Designing: Boolean; function NewSourceFile(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; function NewInterfaceFile(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; function NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile; function GetAncestorName: string; function GetFileName: string; function GetFileNameExt: string; function GetUnnamed: Boolean; function GetFormName: string; end; implementation end.
{ Skyrim: Display Model 2 Speed up the process of creating Idles with Packages that use them. } Unit UserScript; Const TemplateIdle = $1d97; TemplatePkg = $1d98; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// Function DccCreateForm(TemplateID: Integer; Plugin: IInterface): IInterface; Var FormID: Integer; Begin AddMessage('Load Order ' + IntToStr(GetLoadOrder(Plugin))); FormID := (GetLoadOrder(Plugin) shl 24) + TemplateID; AddMessage('Creating Form From Template: ' + IntToHex(FormID,8)); Result := wbCopyElementToFile( DccGetForm(FormID), Plugin, True, True ); End; Function DccGetForm(FormID: Integer): IInterface; Begin Result := RecordByFormID( FileByLoadOrder(FormID shr 24), LoadOrderFormIDtoFileFormID( FileByLoadOrder(FormID shr 24), FormID ), True ); End; Procedure DccSetEditorID(Form: IInterface; EditorID: String); Begin SetElementEditValues(Form,'EDID - Editor ID',EditorID); End; Procedure DccSetAnimationEvent(Form: IInterface; EventName: String); Begin SetElementEditValues(Form,'ENAM - Animation Event',EventName); End; Procedure DccSetIdleAnimation(Form: IInterface; IdleForm: IInterface); Begin SetNativeValue(ElementByIndex(ElementByPath(Form,'Idle Animations\IDLA - Animations'),0),FormID(IdleForm)); End; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// Procedure DccCreateNewIdle(Plugin: IInterface); Var IdleEditorID: String; // input IdleEventName: String; // input FormNewIdle: IInterface; FormNewPkg: IInterface; InputResult: Boolean; Begin AddMessage('Creating a new Idle and Package in ' + Name(Plugin)); //////// //////// InputResult := TRUE; While InputResult Do Begin IdleEditorID := NULL; IdleEventName := NULL; InputResult := InputQuery( 'Enter Editor ID', 'Value will be prefixed with "dcc_dm_Idle" and "dcc_dm_PackageIdle" (Ex: Hogtie1)', IdleEditorID ); If(InputResult = FALSE) Then Begin Exit; End; InputResult := InputQuery( 'Enter Animation Event Name', 'Enter the value given to SAE to trigger the animation.', IdleEventName ); If(InputResult = FALSE) Then Begin Exit; End; //////// //////// FormNewIdle := DccCreateForm(TemplateIdle,Plugin); DccSetEditorID(FormNewIdle,('dcc_dm_Idle' + IdleEditorID)); DccSetAnimationEvent(FormNewIdle,IdleEventName); AddMessage('Created ' + Name(FormNewIdle)); FormNewPkg := DccCreateForm(TemplatePkg,Plugin); DccSetEditorId(FormNewPkg,('dcc_dm_PackageIdle' + IdleEditorID)); DccSetIdleAnimation(FormNewPkg,FormNewIdle); AddMessage('Created ' + Name(FormNewPkg)); End; End; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// Function Initialize: Integer; Var Iter: Integer; Plugin: IInterface; Begin For Iter := 0 To FileCount - 1 Do Begin Plugin := FileByIndex(Iter); AddMessage('-- ' + IntToStr(Iter) + ' ' + Name(Plugin)); If(CompareText(GetFileName(Plugin),'dcc-dm2.esp') = 0) Then Begin DccCreateNewIdle(Plugin); End; End; End; End.
unit RepositoryDataModule; interface uses System.SysUtils, System.Classes, cxEditRepositoryItems, cxExtEditRepositoryItems, cxEdit, cxClasses, cxLocalization, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, Data.DB, FireDAC.Comp.Client, Vcl.ImgList, Vcl.Controls, cxGraphics, cxStyles, System.ImageList, NotifyEvents, FireDAC.VCLUI.Wait, FireDAC.Moni.Base, FireDAC.Moni.FlatFile, cxImageList; type TDMRepository = class(TDataModule) cerMain: TcxEditRepository; cxFieldValueWithExpand: TcxEditRepositoryButtonItem; cxFieldLabel: TcxEditRepositoryLabel; cxFieldMemo: TcxEditRepositoryMemoItem; cxFieldDateTime: TcxEditRepositoryDateItem; cxFieldBlobEdit: TcxEditRepositoryBlobItem; cxFieldCheckBox: TcxEditRepositoryCheckBoxItem; cxFieldComponentExternalId: TcxEditRepositoryMaskItem; cerMainCalcItem1: TcxEditRepositoryCalcItem; cxFieldNumber: TcxEditRepositoryCalcItem; cxFieldText: TcxEditRepositoryTextItem; clRus: TcxLocalizer; dbConnection: TFDConnection; cxImageList: TcxImageList; cxStyleRepository: TcxStyleRepository; cxHeaderStyle: TcxStyle; cxInactiveStyle: TcxStyle; cxStyleNotFound: TcxStyle; procedure DataModuleDestroy(Sender: TObject); procedure dbConnectionAfterCommit(Sender: TObject); procedure dbConnectionAfterConnect(Sender: TObject); procedure dbConnectionAfterRollback(Sender: TObject); procedure dbConnectionBeforeCommit(Sender: TObject); procedure dbConnectionBeforeDisconnect(Sender: TObject); private FAfterCommit: TNotifyEventsEx; FBeforeCommit: TNotifyEventsEx; FAfterConnect: TNotifyEventsEx; FAfterRollback: TNotifyEventsEx; FAfterRollback1: TNotifyEventsEx; FBeforeDisconnect: TNotifyEventsEx; FBeforeDestroy: TNotifyEventsEx; procedure LocalizeDevExpress; { Private declarations } public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property AfterCommit: TNotifyEventsEx read FAfterCommit; property BeforeCommit: TNotifyEventsEx read FBeforeCommit; property AfterConnect: TNotifyEventsEx read FAfterConnect; property AfterRollback: TNotifyEventsEx read FAfterRollback; property AfterRollback1: TNotifyEventsEx read FAfterRollback1; property BeforeDisconnect: TNotifyEventsEx read FBeforeDisconnect; property BeforeDestroy: TNotifyEventsEx read FBeforeDestroy; { Public declarations } end; var DMRepository: TDMRepository; implementation uses System.IOUtils, cxGridCustomView, cxGridTableView, ProjectConst; { %CLASSGROUP 'Vcl.Controls.TControl' } {$R *.dfm} constructor TDMRepository.Create(AOwner: TComponent); begin inherited Create(AOwner); FAfterCommit := TNotifyEventsEx.Create(Self); FBeforeCommit := TNotifyEventsEx.Create(Self); FAfterRollback := TNotifyEventsEx.Create(Self); FAfterConnect := TNotifyEventsEx.Create(Self); FBeforeDisconnect := TNotifyEventsEx.Create(Self); FBeforeDestroy := TNotifyEventsEx.Create(Self); // локализуем девэкспресс LocalizeDevExpress(); end; procedure TDMRepository.DataModuleDestroy(Sender: TObject); begin FBeforeDestroy.CallEventHandlers(Self); end; destructor TDMRepository.Destroy; begin FreeAndNil(FAfterCommit); FreeAndNil(FBeforeCommit); FreeAndNil(FAfterRollback); FreeAndNil(FAfterConnect); FreeAndNil(FBeforeDisconnect); FreeAndNil(FBeforeDestroy); inherited; end; procedure TDMRepository.dbConnectionAfterCommit(Sender: TObject); begin // Извещаем всех о коммите if FAfterCommit <> nil then FAfterCommit.CallEventHandlers(Sender); end; procedure TDMRepository.dbConnectionAfterConnect(Sender: TObject); begin // Извещаем всех, что соединение с БД установлено if FAfterConnect <> nil then FAfterConnect.CallEventHandlers(Sender); end; procedure TDMRepository.dbConnectionAfterRollback(Sender: TObject); begin // Извещаем всех о роллбэке if FAfterRollback <> nil then FAfterRollback.CallEventHandlers(Sender); end; procedure TDMRepository.dbConnectionBeforeCommit(Sender: TObject); begin // Извещаем всех о предстоящем коммите if FBeforeCommit <> nil then FBeforeCommit.CallEventHandlers(Sender); end; procedure TDMRepository.dbConnectionBeforeDisconnect(Sender: TObject); begin FBeforeDisconnect.CallEventHandlers(Self); end; procedure TDMRepository.LocalizeDevExpress; var AFileName: string; begin // локализуем девэкспресс AFileName := TPath.Combine(ExtractFilePath(ParamStr(0)), sLocalizationFileName); if FileExists(AFileName) then begin clRus.FileName := AFileName; clRus.Active := True; clRus.Locale := 1049; end; end; end.
{----------------------------------------------------------------------------- Unit Name: SettingTemplate This software and source code are distributed on an as is basis, without warranty of any kind, either express or implied. This file can be redistributed, modified if you keep this header. Copyright © Erwien Saputra 2005 All Rights Reserved. Author: Erwien Saputra Purpose: Interfaces and classes to save and restore registry template for Delphi Setting Manager. To use, an XML file with valid template must exist. The main form or main object must create the TemplateCollection using CreateTemplateCollection. The loaded template collection can be accessed through GetTemplateCollection. History: 06/18/2005 - Initial version. 06/25/2005 - Fixed bug with comments. Added check for comments. Updated code that writes the default value. -----------------------------------------------------------------------------} unit SettingTemplate; interface uses Classes, SettingCollection, XMLDoc, XMLIntf; type //Interface that represent a registry key. IRegistryKey = interface ['{4D37A8EE-9A3E-42D9-9B37-C0E06A4626C7}'] function GetDefaultValue: string; function GetDeleteTree: boolean; function GetEmptyTree: boolean; function GetItemCount: integer; function GetNames(Index: integer): string; function GetTreeName: string; function GetValues(Index: integer): string; procedure Assign (Source : IRegistryKey); procedure Merge (Source : IRegistryKey); property TreeName : string read GetTreeName; property DeleteTree : boolean read GetDeleteTree; property EmptyTree : boolean read GetEmptyTree; property ItemCount : integer read GetItemCount; property Names[Index : integer]: string read GetNames; property Values[Index : integer]: string read GetValues; property DefaultValue : string read GetDefaultValue; end; ISettingTemplate = interface ['{C3219481-A8CE-4D8D-B32F-FF8D9FA655F2}'] function GetTemplateName : string; function GetRegistryKeyCount : integer; function GetRegistryKey(index : integer) : IRegistryKey; function GetIDEVersion: TIDEVersion; procedure LoadTemplate (const AFileName : string; const AIDEVersion : TIDEVersion; const ATemplateName : string); procedure MergeTemplate (const OtherTemplate : ISettingTemplate); property TemplateName : string read GetTemplateName; property RegistryKeyCount : integer read GetRegistryKeyCount; property RegistryKey[Index : integer] : IRegistryKey read GetRegistryKey; property IDEVersion : TIDEVersion read GetIDEVersion;// = (Delphi6, Delphi7, BDS1, BDS2, BDS3); end; //Registry key class represents all values under a certain tree. This class //holds information about what values under a certain tree. TRegistryKey = class (TInterfacedObject, IRegistryKey) private FDefaultValue : string; FDeleteTree : boolean; FEmptyTree : boolean; FTreeName : string; FValues : TStringList; function GetDefaultValue: string; function GetDeleteTree: boolean; function GetEmptyTree: boolean; function GetItemCount: integer; function GetNames(Index: integer): string; function GetTreeName: string; function GetValues(Index: integer): string; procedure Assign (Source : IRegistryKey); procedure Merge (Source : IRegistryKey); protected property TreeName : string read GetTreeName; property DeleteTree : boolean read GetDeleteTree; property EmptyTree : boolean read GetEmptyTree; property ItemCount : integer read GetItemCount; property Names[Index : integer]: string read GetNames; property Values[Index : integer]: string read GetValues; property DefaultValue : string read GetDefaultValue; public constructor Create; overload; constructor Create (const ANode : IXMLNode); overload; destructor Destroy; override; procedure LoadRegistryKey (const ANode : IXMLNode); end; //This class contains all trees and values for a specific configuration. TSettingTemplate = class (TInterfacedObject, ISettingTemplate) private FTemplateName: string; FRegistryKeys : IInterfaceList; FIDEVersion : TIDEVersion; protected function GetTemplateName : string; function GetRegistryKeyCount : integer; function GetRegistryKey(index : integer) : IRegistryKey; function GetIDEVersion: TIDEVersion; function GetTargetNode (const XMLDoc : IXMLDocument; const AIDEVersion : TIDEVersion; const ATemplateName : string): IXMLNode; procedure LoadTemplate (const AFileName : string; const AIDEVersion : TIDEVersion; const ATemplateName : string); procedure MergeTemplate (const OtherTemplate : ISettingTemplate); public constructor Create; destructor Destroy; override; end; //ITemplateCollection provides the ability to get and access the Delphi //Setting Manager templates. This interface allows easy retrieval for the //templates. ITemplateCollection = interface ['{51278FEE-BBD5-48D1-A1E9-CA93E272CD36}'] function TemplateCount (const AIDEVersion : TIDEVersion) : integer; function GetTemplate (const AIDEVersion : TIDEVersion; const TemplateName : string) : ISettingTemplate; procedure GetTemplateNames (const AIDEVersion : TIDEVersion; Strings : TStrings); procedure ApplyTemplate (Root : string; const ASettingTemplate : ISettingTemplate); end; TTemplateCollection = class (TInterfacedObject, ITemplateCollection) private FDelphi6, FDelphi7, FBDS1, FBDS2, FBDS3 : TStringList; FFileName : string; protected function GetStringList (const IDEVersion : string) : TStrings; overload; function GetStringList (const IDEVersion : TIDEVersion) : TStrings; overload; function TemplateCount (const AIDEVersion : TIDEVersion) : integer; function GetTemplate (const AIDEVersion : TIDEVersion; const TemplateName : string) : ISettingTemplate; procedure GetTemplateNames (const AIDEVersion : TIDEVersion; Strings : TStrings); procedure LoadTemplateNames (const FileName : string); procedure ApplyTemplate (Root : string; const ASettingTemplate : ISettingTemplate); public constructor Create (const TemplateFileName : string); destructor Destroy; override; end; //This function and procedure allow a centralized access for the //ITemplateCollection object. function GetTemplateCollection : ITemplateCollection; procedure CreateTemplateCollection (const TemplateFileName : string); implementation uses SysUtils, Registry, Dialogs; const //These strings are the node in the XML file. Each string represents a Delphi //version. NODE_DELPHI6 = 'DELPHI6'; NODE_DELPHI7 = 'DELPHI7'; NODE_BDS1 = 'BDS1'; NODE_BDS2 = 'BDS2'; NODE_BDS3 = 'BDS3'; ERR_LOAD_TEMPLATE_FAILED = 'Error loading Template file. Template is ' + 'not available.' + sLineBreak; var TemplateCollection : ITemplateCollection; function GetTemplateCollection : ITemplateCollection; begin Result := TemplateCollection; end; //If the Template does not exist, or the XML is invalid, the exception will be //supressed and the user will be notified with an error message. This is //important. If the object is create in the main form constructor and this //procedure failed, the application would die. procedure CreateTemplateCollection (const TemplateFileName : string); begin if FileExists (TemplateFileName) = true then try TemplateCollection := TTemplateCollection.Create (TemplateFileName); except on E : Exception do begin MessageDlg (ERR_LOAD_TEMPLATE_FAILED + E.Message, mtError, [mbOK], 0); end; end; end; { TRegistryKey } function TRegistryKey.GetDefaultValue: string; begin Result := self.FDefaultValue; end; function TRegistryKey.GetDeleteTree: boolean; begin Result := self.FDeleteTree; end; function TRegistryKey.GetEmptyTree: boolean; begin Result := self.FEmptyTree; end; function TRegistryKey.GetTreeName: string; begin Result := self.FTreeName; end; function TRegistryKey.GetNames(Index: integer): string; begin Result := self.FValues.Names [Index]; end; function TRegistryKey.GetItemCount: integer; begin Result := self.FValues.Count; end; constructor TRegistryKey.Create; begin inherited Create; self.FValues := TStringList.Create; end; function TRegistryKey.GetValues(Index: integer): string; begin Result := self.FValues.ValueFromIndex[Index]; end; procedure TRegistryKey.Assign(Source: IRegistryKey); var Loop : integer; begin if Assigned (Source) then begin FDefaultValue := Source.DefaultValue; FDeleteTree := Source.DeleteTree; FEmptyTree := Source.EmptyTree; FTreeName := Source.TreeName; FValues.Clear; for Loop := 0 to Source.ItemCount - 1 do FValues.Add (Source.Names[Loop] + '=' + Source.Values[Loop]); end; end; procedure TRegistryKey.Merge (Source : IRegistryKey); var Loop : integer; begin if Assigned (Source) then begin if SameText (self.FTreeName, EmptyStr) then Assign (Source) else begin if SameText (FTreeName, Source.TreeName) = false then raise Exception.Create ('Cannot merge keys with different TreeName.'); if Source.DeleteTree <> self.FDeleteTree then begin FDeleteTree := false; FEmptyTree := true; end; if Source.EmptyTree <> self.FEmptyTree then self.FEmptyTree := true; for Loop := 0 to Source.ItemCount - 1 do if self.FValues.IndexOfName(Source.Names[Loop]) = -1 then FValues.Add (Source.Names[Loop] + '=' + Source.Values[Loop]) else if SameText (FValues.Values[Source.Names[Loop]], Source.Values [Loop]) = false then FValues.Values[Source.Names[Loop]] := Source.Values[Loop]; end; end; end; destructor TRegistryKey.Destroy; begin if Assigned (FValues) then FreeAndNil (FValues); inherited; end; //Load the registry key and values from ANode. ANode must must be the Template //Node. procedure TRegistryKey.LoadRegistryKey(const ANode: IXMLNode); var Node : IXMLNode; Name, Value : string; begin if ANode.NodeType = ntComment then Exit; //Get the name of the node. This is the relative tree name. if ANode.HasAttribute ('name') then FTreeName := ANode.Attributes ['name']; //Is this tree must be deleted? FDeleteTree := (ANode.HasAttribute ('delete_tree') = true) and (ANode.Attributes ['delete_tree'] = true); //Is this key must be emptied first? FEmptyTree := (ANode.HasAttribute ('empty_tree') = true) and (ANode.Attributes ['empty_tree']); //Iterate the name values for this key. if ANode.HasChildNodes = true then begin Node := ANode.ChildNodes.First; while Node <> nil do begin if Node.NodeType <> ntComment then begin Name := Node.Attributes['name']; Value := Node.Attributes['value']; if SameText (Name, 'default') then FDefaultValue := Value else FValues.Add (Name + '=' + Value); end; Node := Node.NextSibling; end; end; end; constructor TRegistryKey.Create(const ANode: IXMLNode); begin inherited Create; self.FValues := TStringList.Create; LoadRegistryKey (ANode); end; { TSettingTemplate } //This method loads the text file, looks for a specific template by name for a //specific Delphi version. The registry keys under that tempate is stored as a //list of IRegistryKey. procedure TSettingTemplate.LoadTemplate(const AFileName : string; const AIDEVersion : TIDEVersion; const ATemplateName : string); var XML : IXMLDocument; TreeNode, TargetNode : IXMLNode; TreeLoop : integer; RegKey : IRegistryKey; begin XML := TXMLDocument.Create (nil); XML.LoadFromFile (AFileName); //Get the Node of the Template Name. TargetNode := GetTargetNode(XML, AIDEVersion, ATemplateName); //Each children of the Template Node are an instance of IRegistryKey. Load //each children node to a list of IRegistryKey. for TreeLoop := 0 to TargetNode.ChildNodes.Count - 1 do begin TreeNode := TargetNode.ChildNodes.Get (TreeLoop); RegKey := TRegistryKey.Create (TreeNode); FRegistryKeys.Add (RegKey); end; end; procedure TSettingTemplate.MergeTemplate(const OtherTemplate: ISettingTemplate); var Index, Loop : integer; NewKey, RegKey : IRegistryKey; Names : TStringList; begin Names := TStringList.Create; try for Loop := 0 to self.FRegistryKeys.Count - 1 do begin RegKey := IRegistryKey (FRegistryKeys.Items[Loop]); Names.Add (RegKey.TreeName); end; for Loop := 0 to OtherTemplate.RegistryKeyCount - 1 do begin RegKey := OtherTemplate.RegistryKey [Loop]; Index := Names.IndexOf(RegKey.TreeName); if (Index = -1) then begin NewKey := TRegistryKey.Create; NewKey.Assign (RegKey); self.FRegistryKeys.Add (NewKey); Names.Add (NewKey.TreeName); end else begin NewKey := (FRegistryKeys[Index]) as IRegistryKey; NewKey.Merge (RegKey); end; end; finally Names.Free; end; end; function TSettingTemplate.GetRegistryKey(index: integer): IRegistryKey; begin Result := FRegistryKeys[index] as IRegistryKey; end; function TSettingTemplate.GetRegistryKeyCount: integer; begin Result := self.FRegistryKeys.Count; end; function TSettingTemplate.GetTemplateName: string; begin Result := self.FTemplateName; end; constructor TSettingTemplate.Create; begin self.FRegistryKeys := TInterfaceList.Create; end; destructor TSettingTemplate.Destroy; begin FRegistryKeys := nil; inherited; end; //Returns the root node of the template name on the IXMLDocument. In a XML file //there can be more than one template with same name that belongs to different //IDE version. function TSettingTemplate.GetTargetNode(const XMLDoc : IXMLDocument; const AIDEVersion: TIDEVersion; const ATemplateName: string): IXMLNode; var Node : IXMLNode; NodeName : string; ANode : IXMLNode; Loop : integer; begin Result := nil; Node := XMLDoc.Node; FIDEVersion := AIDEVersion; //Get the node named ROOT. while SameText (Node.NodeName, 'ROOT') = false do Node := Node.ChildNodes.First; //Get the string representation of the desired IDE version and get that node. case AIDEVersion of Delphi6 : NodeName := NODE_DELPHI6; Delphi7 : NodeName := NODE_DELPHI7; BDS1 : NodeName := NODE_BDS1; BDS2 : NodeName := NODE_BDS2; BDS3 : NodeName := NODE_BDS3; end; Node := Node.ChildNodes.FindNode (NodeName); //Iterate through the node, stop when it finds the desired node. if Assigned (Node) = true then begin for Loop := 0 to Node.ChildNodes.Count - 1 do begin ANode := Node.ChildNodes.Get(Loop); if (ANode.NodeType = ntComment) then Continue; if (ANode.HasAttribute ('name') and (ANode.Attributes ['name'] = ATemplateName)) then begin Result := ANode; Break; end; end; end; end; //Returns the IDE Version of the Template. function TSettingTemplate.GetIDEVersion: TIDEVersion; begin Result := self.FIDEVersion; end; { TTemplateCollection } //Create the TemplateCollection and load the Templates. constructor TTemplateCollection.Create (const TemplateFileName : string); begin FFileName := TemplateFileName; //The StringList that hold the Template Name. FDelphi6 := TStringList.Create; FDelphi7 := TStringList.Create; FBDS1 := TStringList.Create; FBDS2 := TStringList.Create; FBDS3 := TStringList.Create; LoadTemplateNames(FFileName); end; //Load the Template names from the XML file to the string lists. procedure TTemplateCollection.LoadTemplateNames(const FileName: string); var XML : IXMLDocument; TemplateNode, Node : IXMLNode; List : TStrings; begin XML := TXMLDocument.Create (nil); XML.LoadFromFile (FileName); Node := XML.ChildNodes.First; //Get the root. while SameText (Node.NodeName, 'ROOT') = false do Node := Node.ChildNodes.First; //Does the root has ide tmplate? if Node.HasChildNodes = true then begin //Get the IDE Version root. Node := Node.ChildNodes.First; while Node <> nil do begin //The IDE Version root has templates in it. if Node.HasChildNodes = true then begin List := self.GetStringList(Node.NodeName); if Assigned (List) = true then begin //Move pointer to the children node, the template names, and iterate //each template names. TemplateNode := Node.ChildNodes.First; while TemplateNode <> nil do begin if TemplateNode.NodeType <> ntComment then List.Add (TemplateNode.Attributes ['name']); TemplateNode := TemplateNode.NextSibling; end; end; end; Node := Node.NextSibling; end; end; end; //Returns the number of template for a Delphi IDE version. function TTemplateCollection.TemplateCount( const AIDEVersion: TIDEVersion): integer; var List : TStrings; begin List := GetStringList (AIDEVersion); if Assigned (List) then Result := List.Count else Result := 0; end; //Returns all templates for a specific IDE. procedure TTemplateCollection.GetTemplateNames(const AIDEVersion : TIDEVersion; Strings: TStrings); var List : TStrings; begin Strings.Clear; List := GetStringList (AIDEVersion); if Assigned (List) then Strings.Assign (List); end; destructor TTemplateCollection.Destroy; begin FDelphi6.Free; FDelphi7.Free; FBDS1.Free; FBDS2.Free; FBDS3.Free; inherited; end; //Given a template name and an IDE version, this method returns an instance of //ISettingTemplate. function TTemplateCollection.GetTemplate(const AIDEVersion: TIDEVersion; const TemplateName: string): ISettingTemplate; begin Result := TSettingTemplate.Create; Result.LoadTemplate(self.FFileName, AIDEVersion, TemplateName); end; //A helper function, returns the TStrings that is associated with the expected //IDEVersion in string. function TTemplateCollection.GetStringList(const IDEVersion: string): TStrings; begin if SameText (IDEVersion, NODE_DELPHI6) then Result := FDelphi6 else if SameText (IDEVersion, NODE_DELPHI7) then Result := FDelphi7 else if SameText (IDEVersion, NODE_BDS1) then Result := FBDS1 else if SameText (IDEVersion, NODE_BDS2) then Result := FBDS2 else if SameText (IDEVersion, NODE_BDS3) then Result := FBDS3 else Result := nil; end; function TTemplateCollection.GetStringList( const IDEVersion: TIDEVersion): TStrings; begin case IDEVersion of Delphi6 : Result := FDelphi6; Delphi7 : Result := FDelphi7; BDS1 : Result := FBDS1; BDS2 : Result := FBDS2; BDS3 : Result := FBDS3; else Result := nil; end; end; //Apply the Template to a registry key (Root). If Root is a valid Delphi Setting //Manager key, this will update that registry key to match the rules in the //Template. Root must be an absolute registry key under HKEY_CURRENT_USER. procedure TTemplateCollection.ApplyTemplate(Root: string; const ASettingTemplate: ISettingTemplate); var Reg : TRegistry; RegKeyLoop, ValueLoop : integer; RegKey : IRegistryKey; begin //Make sure that Root has backslash. if (Root[1] <> '\') then Root := '\' + Root; Reg := TRegistry.Create; try if Reg.OpenKey(Root, false) = false then raise Exception.CreateFmt ('%s does not exist.', [Root]); //Loop through the registry key in the template. for RegKeyLoop := 0 to ASettingTemplate.RegistryKeyCount - 1 do begin //Create the key Reg.OpenKey (Root, false); RegKey := ASettingTemplate.RegistryKey[RegKeyLoop]; //Delete the tree. if RegKey.DeleteTree = true then Reg.DeleteKey (RegKey.TreeName) else begin //Empty the tree, if the tree exist. if (RegKey.EmptyTree = true) and (Reg.KeyExists (RegKey.TreeName) = true) then begin Reg.DeleteKey (RegKey.TreeName); Reg.CreateKey (RegKey.TreeName); end; //Recreate the key. Reg.OpenKey (RegKey.TreeName, true); //Write the default value. if SameText (RegKey.DefaultValue, EmptyStr) = false then Reg.WriteString('', RegKey.DefaultValue); //Write each values. for ValueLoop := 0 to RegKey.ItemCount - 1 do Reg.WriteString (RegKey.Names[ValueLoop], RegKey.Values[ValueLoop]); end; end; finally Reg.Free; end; end; end.
unit FC.StockData.StockTempValueCollection; interface uses SysUtils,Classes, Contnrs, FC.Definitions,Collections.List; type TStockTempValue = class public DateTime : TDateTime; Value : TStockRealNumber; BarNo : integer; Comment: string; constructor Create(const aDateTime : TDateTime; const aValue : TStockRealNumber; const aBarNo : integer; const aComment: string); end; TStockTempValueCollection = class(TInterfacedObject,IStockTempValueCollection) private FData : TOwnedOjectList<TStockTempValue>; public procedure Add(const aDateTime : TDateTime; const aValue : TStockRealNumber; const aBarNo : integer; const aComment: string); //from IStockTempValueCollection function Count: integer; function GetDateTime(index: integer): TDateTime; function GetValue(index: integer): TStockRealNumber; function GetBarNo(index: integer): integer; function GetComment(index: integer): string; // function GetItem(index: integer) : TStockTempValue; inline; constructor Create; destructor Destroy; override; end; implementation { TStockTempValue } constructor TStockTempValue.Create(const aDateTime : TDateTime; const aValue : TStockRealNumber; const aBarNo : integer; const aComment: string); begin DateTime:=aDateTime; Value:=aValue; BarNo:=aBarNo; Comment:=aComment; end; { TStockTempValueCollection } procedure TStockTempValueCollection.Add(const aDateTime : TDateTime; const aValue : TStockRealNumber; const aBarNo : integer; const aComment: string); var aItem : TStockTempValue; begin aItem:=TStockTempValue.Create(aDateTime,aValue,aBarNo,aComment); FData.Add(aItem); end; function TStockTempValueCollection.Count: integer; begin result:=FData.Count; end; constructor TStockTempValueCollection.Create; begin FData:=TOwnedOjectList<TStockTempValue>.Create; end; destructor TStockTempValueCollection.Destroy; begin FreeAndNil(FData); inherited; end; function TStockTempValueCollection.GetBarNo(index: integer): integer; begin result:=GetItem(index).BarNo; end; function TStockTempValueCollection.GetComment(index: integer): string; begin result:=GetItem(index).Comment; end; function TStockTempValueCollection.GetDateTime(index: integer): TDateTime; begin result:=GetItem(index).DateTime; end; function TStockTempValueCollection.GetValue(index: integer): TStockRealNumber; begin result:=GetItem(index).Value; end; function TStockTempValueCollection.GetItem(index: integer): TStockTempValue; begin result:=FData[index]; end; end.
unit ServiceManager; interface uses SysUtils, Windows, WinSvc; type TInstallType = ( Install, Uninstall ); TServiceManager = class private { Private declarations } ServiceControlManager: SC_Handle; ServiceHandle: SC_Handle; protected function DoStartService(NumberOfArgument: DWORD; ServiceArgVectors: PChar): Boolean; public { Public declarations } function Connect(MachineName: PChar = nil; DatabaseName: PChar = nil; Access: DWORD = SC_MANAGER_ALL_ACCESS): Boolean; // Access may be SC_MANAGER_ALL_ACCESS function OpenServiceConnection(ServiceName: PChar): Boolean; function StartService: Boolean; overload; // Simple start function StartService(NumberOfArgument: DWORD; ServiceArgVectors: PChar): Boolean; overload; // More complex start function StopService: Boolean; procedure PauseService; procedure ContinueService; procedure ShutdownService; procedure DisableService; function GetStatus: DWORD; function ServiceRunning: Boolean; function ServiceStopped: Boolean; Class Function Singleton : TServiceManager; Class Procedure Libera; end; implementation uses FPrincipal; var ServiceMng : TServiceManager; { TServiceManager } function TServiceManager.Connect(MachineName, DatabaseName: PChar; Access: DWORD): Boolean; begin Result := False; { open a connection to the windows service manager } ServiceControlManager := OpenSCManager(MachineName, DatabaseName, Access); Result := (ServiceControlManager <> 0); end; function TServiceManager.OpenServiceConnection(ServiceName: PChar): Boolean; begin Result := False; { open a connetcion to a specific service } ServiceHandle := OpenService(ServiceControlManager, ServiceName, SERVICE_ALL_ACCESS); Result := (ServiceHandle <> 0); end; procedure TServiceManager.PauseService; var ServiceStatus: TServiceStatus; begin { Pause the service: attention not supported by all services } ControlService(ServiceHandle, SERVICE_CONTROL_PAUSE, ServiceStatus); end; function TServiceManager.StopService: Boolean; var ServiceStatus: TServiceStatus; begin { Stop the service } Result := ControlService(ServiceHandle, SERVICE_CONTROL_STOP, ServiceStatus); end; procedure TServiceManager.ContinueService; var ServiceStatus: TServiceStatus; begin { Continue the service after a pause: attention not supported by all services } ControlService(ServiceHandle, SERVICE_CONTROL_CONTINUE, ServiceStatus); end; procedure TServiceManager.ShutdownService; var ServiceStatus: TServiceStatus; begin { Shut service down: attention not supported by all services } ControlService(ServiceHandle, SERVICE_CONTROL_SHUTDOWN, ServiceStatus); end; function TServiceManager.StartService: Boolean; begin Result := DoStartService(0, ''); end; function TServiceManager.StartService(NumberOfArgument: DWORD; ServiceArgVectors: PChar): Boolean; begin Result := DoStartService(NumberOfArgument, ServiceArgVectors); end; function TServiceManager.GetStatus: DWORD; var ServiceStatus: TServiceStatus; begin { Returns the status of the service. Maybe you want to check this more than once, so just call this function again. Results may be: SERVICE_STOPPED SERVICE_START_PENDING SERVICE_STOP_PENDING SERVICE_RUNNING SERVICE_CONTINUE_PENDING SERVICE_PAUSE_PENDING SERVICE_PAUSED } Result := 0; QueryServiceStatus(ServiceHandle, ServiceStatus); Result := ServiceStatus.dwCurrentState; end; procedure TServiceManager.DisableService; begin { Implementation is following... } end; function TServiceManager.ServiceRunning: Boolean; begin Result := (GetStatus = SERVICE_RUNNING); end; function TServiceManager.ServiceStopped: Boolean; begin Result := (GetStatus = SERVICE_STOPPED); end; function TServiceManager.DoStartService(NumberOfArgument: DWORD; ServiceArgVectors: PChar): Boolean; var err: integer; begin Result := WinSvc.StartService(ServiceHandle, NumberOfArgument, ServiceArgVectors); end; class function TServiceManager.Singleton: TServiceManager; begin if not ( Assigned( ServiceMng ) ) then begin ServiceMng := TServiceManager.Create; ServiceMng.Connect( '', Nil, SC_MANAGER_CONNECT ); ServiceMng.OpenServiceConnection( PChar ( SERVICE_NAME ) ); end; Result := ServiceMng; end; class procedure TServiceManager.Libera; begin TServiceManager.Singleton.Free; ServiceMng := Nil; end; end.
unit JAPolygon; {$mode objfpc}{$H+} {$PACKRECORDS 2} {required for compatibility with various amiga APIs} {$i JA.inc} {Polygons wrap up the storage of Vertex data along with with the polygon style. Shadow Hull data is stored here as polygons can be shadow casters, so it's a good spot for now.} interface uses JATypes, JAGlobal, JAMath; type {Polygon vertex type} TJAVertex = record Position : TVec2; Normal : TVec2; end; PJAVertex = ^TJAVertex; {Polygon Style} TJAPolygonStyle = record Visible : boolean; Fill : TJColourUInt8; Stroke : TJColourUInt8; PenIndex : SInt32; end; PJAPolygonStyle = ^TJAPolygonStyle; TJAVertexPool = record Vertex : PVec2SInt16; VertexCapacity : SInt32; VertexCount : sInt32; end; PJAVertexPool = ^TJAVertexPool; TJAPolygonShadow = record {Umbra} ShadowVertex : PVec2SInt16; {Shadow Vertices are in Screen Space} ShadowVertexCapacity : SInt32; ShadowVertexCount : SInt32; ShadowVertexStart : SInt32; {First vertex of first back facing face} ShadowVertexEnd : SInt32; {Last vertex of last back facing face} {Penumbra (always solid)} StartUmbra,StartPenumbra : TVec2; EndUmbra,EndPenumbra : TVec2; ShadowPenumbra0Index : SInt32; ShadowPenumbra1Index : SInt32; {'Solid' Penumbras} ShadowPenumbra0Vertex : PVec2SInt16; ShadowPenumbra0VertexCapacity : SInt32; ShadowPenumbra0VertexCount : SInt32; ShadowPenumbra1Vertex : PVec2SInt16; ShadowPenumbra1VertexCapacity : SInt32; ShadowPenumbra1VertexCount : SInt32; {Penumbra Bands} ShadowPenumbra0Fins : PJAVertexPool; ShadowPenumbra0FinsCapacity : SInt32; ShadowPenumbra0FinsCount : SInt32; ShadowPenumbra1Fins : PJAVertexPool; ShadowPenumbra1FinsCapacity : SInt32; ShadowPenumbra1FinsCount : SInt32; end; PJAPolygonShadow = ^TJAPolygonShadow; {2D Polygon} TJAPolygon = record {Polygon Data} {Local Space Vertices} Vertex : PJAVertex; VertexCapacity : SInt32; VertexCount : SInt32; {World Space Vertices} WorldVertex : PVec2; {Screen Space vertices} WorldVertexI : PVec2SInt16; {Vertex Indicies} Index : PUInt32; IndexCapacity : SInt32; IndexCount : SInt32; {Polygon Fill/Stroke Colors} Style : TJAPolygonStyle; {Enable/Disable Shadow volume construction for this polygon} ShadowCast : boolean; {Shadow Volumes Per Light} Shadows : PJAPolygonShadow; ShadowsCount : SInt16; {Umbras (always solid)} ShadowVertex : PVec2SInt16; {Shadow Vertices are in Screen Space} ShadowVertexCapacity : SInt32; ShadowVertexCount : SInt32; {Umbra Variables} ShadowVertexStart : SInt32; {First vertex of first back facing face} ShadowVertexEnd : SInt32; {Last vertex of last back facing face} {Penumbra Variables} ShadowPenumbra0Index : SInt32; ShadowPenumbra1Index : SInt32; StartUmbra,StartPenumbra : TVec2; EndUmbra,EndPenumbra : TVec2; ShadowPenumbra0CrossEdgeFinIndex : SInt16; ShadowPenumbra1CrossEdgeFinIndex : SInt16; {'Solid' Penumbra Geometry} ShadowPenumbra0Vertex : PVec2SInt16; ShadowPenumbra0VertexCapacity : SInt32; ShadowPenumbra0VertexCount : SInt32; ShadowPenumbra1Vertex : PVec2SInt16; ShadowPenumbra1VertexCapacity : SInt32; ShadowPenumbra1VertexCount : SInt32; {'Blended' Shadow Fin Geometry} ShadowPenumbra0Fins : PJAVertexPool; ShadowPenumbra0FinsCapacity : SInt32; ShadowPenumbra0FinsCount : SInt32; ShadowPenumbra1Fins : PJAVertexPool; ShadowPenumbra1FinsCapacity : SInt32; ShadowPenumbra1FinsCount : SInt32; end; PJAPolygon = ^TJAPolygon; function JAVertexPoolVertexAdd(AVertexPool : PJAVertexPool) : PVec2SInt16; function JAVertexPoolClear(AVertexPool : PJAVertexPool) : PJAVertexPool; function JAPolygonVertexCreate(APolygon : PJAPolygon) : PJAVertex; function JAPolygonIndexCreate(APolygon : PJAPolygon) : PUInt32; function JAPolygonClear(APolygon : PJAPolygon) : PJAPolygon; function JAPolygonIntersectVertex(APolygon : PJAPolygon; AVertex : TVec2) : boolean; procedure JAShadowFinsCountSet(AShadow: PJAPolygonShadow; AFinsCount : SInt16); function JAShadowVertexAdd(AShadow : PJAPolygonShadow) : PVec2SInt16; function JAShadowPenumbra0Add(AShadow : PJAPolygonShadow) : PVec2SInt16; function JAShadowPenumbra1Add(AShadow : PJAPolygonShadow) : PVec2SInt16; function JAShadowClear(AShadow : PJAPolygonShadow) : PJAPolygonShadow; implementation function JAVertexPoolVertexAdd(AVertexPool: PJAVertexPool) : PVec2SInt16; var NewCapacity : SInt32; begin NewCapacity := AVertexPool^.VertexCapacity; if (NewCapacity=0) then NewCapacity := JAPool_BlockSize else if (AVertexPool^.VertexCount+1) > NewCapacity then NewCapacity += JAPool_BlockSize; if NewCapacity<>AVertexPool^.VertexCapacity then begin if AVertexPool^.VertexCapacity=0 then AVertexPool^.Vertex := JAMemGet(SizeOf(UInt32)*NewCapacity) else AVertexPool^.Vertex := reallocmem(AVertexPool^.Vertex, SizeOf(UInt32)*NewCapacity); AVertexPool^.VertexCapacity := NewCapacity; end; {return pointer to Vertexed element} Result := @AVertexPool^.Vertex[AVertexPool^.VertexCount]; AVertexPool^.VertexCount += 1; end; function JAVertexPoolClear(AVertexPool: PJAVertexPool) : PJAVertexPool; begin {Leave Memory and Capacity intact ready for reuse} AVertexPool^.VertexCount := 0; end; function JAPolygonVertexCreate(APolygon : PJAPolygon) : PJAVertex; var NewCapacity : SInt32; begin NewCapacity := APolygon^.VertexCapacity; if (NewCapacity=0) then NewCapacity := JAPool_BlockSize else if (APolygon^.VertexCount+1) > NewCapacity then NewCapacity += JAPool_BlockSize; if NewCapacity<>APolygon^.VertexCapacity then begin if APolygon^.VertexCapacity=0 then begin APolygon^.Vertex := JAMemGet(SizeOf(TJAVertex)*NewCapacity); APolygon^.WorldVertex := JAMemGet(SizeOf(TVec2)*NewCapacity); APolygon^.WorldVertexI := JAMemGet(SizeOf(TVec2SInt16)*NewCapacity); end else begin APolygon^.Vertex := reallocmem(APolygon^.Vertex, SizeOf(TJAVertex)*NewCapacity); APolygon^.WorldVertex := reallocmem(APolygon^.WorldVertex, SizeOf(TVec2)*NewCapacity); APolygon^.WorldVertexI := reallocmem(APolygon^.WorldVertexI, SizeOf(TVec2SInt16)*NewCapacity); end; APolygon^.VertexCapacity := NewCapacity; end; {return pointer to Vertex structure} Result := @APolygon^.Vertex[APolygon^.VertexCount]; {set defaults} Result^.Position := vec2zero; Result^.Normal := vec2zero; APolygon^.WorldVertex[APolygon^.VertexCount] := Vec2(0,0); APolygon^.WorldVertexI[APolygon^.VertexCount] := Vec2SInt16(0,0); APolygon^.VertexCount += 1; end; function JAPolygonIndexCreate(APolygon : PJAPolygon) : PUInt32; var NewCapacity : SInt32; begin NewCapacity := APolygon^.IndexCapacity; if (NewCapacity=0) then NewCapacity := JAPool_BlockSize else if (APolygon^.IndexCount+1) > NewCapacity then NewCapacity += JAPool_BlockSize; if NewCapacity<>APolygon^.IndexCapacity then begin if APolygon^.IndexCapacity=0 then APolygon^.Index := JAMemGet(SizeOf(UInt32)*NewCapacity) else APolygon^.Index := reallocmem(APolygon^.Index, SizeOf(UInt32)*NewCapacity); APolygon^.IndexCapacity := NewCapacity; end; {return pointer to indexed element} Result := @APolygon^.Index[APolygon^.IndexCount]; APolygon^.IndexCount += 1; end; function JAPolygonClear(APolygon : PJAPolygon) : PJAPolygon; var I : SInt16; begin APolygon^.VertexCount := 0; APolygon^.IndexCount := 0; APolygon^.Style.Visible := true; APolygon^.Style.Fill := JColourUInt8(255,0,255,255); APolygon^.Style.Stroke := JColourUInt8(0,0,0,255); APolygon^.Style.PenIndex := -1; {$IFDEF JA_ENABLE_SHADOW} APolygon^.ShadowCast := false; {Setup Shadow Array} if (APolygon^.Shadows=nil) then begin APolygon^.ShadowsCount := JAShadowsPerPolygon; APolygon^.Shadows := JAMemGet(SizeOf(TJAPolygonShadow)*APolygon^.ShadowsCount); end; {Reset Shadows} if (APolygon^.Shadows<>nil) then for I := 0 to APolygon^.ShadowsCount-1 do begin {Umbras (always solid)} APolygon^.Shadows[I].ShadowVertexCount := 0; APolygon^.Shadows[I].ShadowVertexCapacity := 0; APolygon^.Shadows[I].ShadowVertex := nil; {'Solid' Penumbras} APolygon^.Shadows[I].ShadowPenumbra0Vertex := nil; APolygon^.Shadows[I].ShadowPenumbra0VertexCapacity := 0; APolygon^.Shadows[I].ShadowPenumbra0VertexCount := 0; APolygon^.Shadows[I].ShadowPenumbra1Vertex := nil; APolygon^.Shadows[I].ShadowPenumbra1VertexCapacity := 0; APolygon^.Shadows[I].ShadowPenumbra1VertexCount := 0; {'Blended' Shadow Fins} APolygon^.Shadows[I].ShadowPenumbra0Fins := nil; APolygon^.Shadows[I].ShadowPenumbra0FinsCount := 0; APolygon^.Shadows[I].ShadowPenumbra0FinsCapacity := 0; APolygon^.Shadows[I].ShadowPenumbra1Fins := nil; APolygon^.Shadows[I].ShadowPenumbra1FinsCount := 0; APolygon^.Shadows[I].ShadowPenumbra1FinsCapacity := 0; JAShadowClear(@APolygon^.Shadows[I]); JAShadowFinsCountSet(@APolygon^.Shadows[I], 3); end; {$ENDIF} Result := APolygon; end; function JAPolygonIntersectVertex(APolygon: PJAPolygon; AVertex: TVec2): boolean; var I, J, NVert : SInt32; C : Boolean; begin NVert := APolygon^.VertexCount; C := false; I := 0; J := NVert-1; with APolygon^ do for I := 0 to APolygon^.VertexCount-1 do begin if ((WorldVertex[I].Y >= AVertex.Y) <> (WorldVertex[J].Y >= AVertex.Y)) and (AVertex.X <= (WorldVertex[J].X - WorldVertex[I].X) * (AVertex.Y - WorldVertex[I].Y) / (WorldVertex[J].Y - WorldVertex[I].Y) + WorldVertex[I].X) then C := not C; J := I; end; Result := C; end; procedure JAShadowFinsCountSet(AShadow: PJAPolygonShadow; AFinsCount : SInt16); var NewCapacity : SInt32; I : SInt16; begin NewCapacity := AShadow^.ShadowPenumbra0FinsCapacity; if (NewCapacity=0) then NewCapacity := JAPool_BlockSize else if (AFinsCount) > NewCapacity then NewCapacity += JAPool_BlockSize; if NewCapacity<>AShadow^.ShadowPenumbra0FinsCapacity then begin if AShadow^.ShadowPenumbra0FinsCapacity=0 then begin AShadow^.ShadowPenumbra0Fins := JAMemGet(SizeOf(TJAVertexPool)*NewCapacity); end else begin AShadow^.ShadowPenumbra0Fins := reallocmem(AShadow^.ShadowPenumbra0Fins, SizeOf(TJAVertexPool)*NewCapacity); end; end; if NewCapacity<>AShadow^.ShadowPenumbra1FinsCapacity then begin if AShadow^.ShadowPenumbra1FinsCapacity=0 then begin AShadow^.ShadowPenumbra1Fins := JAMemGet(SizeOf(TJAVertexPool)*NewCapacity); end else begin AShadow^.ShadowPenumbra1Fins := reallocmem(AShadow^.ShadowPenumbra1Fins, SizeOf(TJAVertexPool)*NewCapacity); end; end; if NewCapacity>AShadow^.ShadowPenumbra0FinsCapacity then for I := AShadow^.ShadowPenumbra0FinsCapacity to NewCapacity-1 do begin AShadow^.ShadowPenumbra0Fins[I].Vertex := nil; AShadow^.ShadowPenumbra0Fins[I].VertexCapacity := 0; AShadow^.ShadowPenumbra0Fins[I].VertexCount := 0; end; if NewCapacity>AShadow^.ShadowPenumbra1FinsCapacity then for I := AShadow^.ShadowPenumbra1FinsCapacity to NewCapacity-1 do begin AShadow^.ShadowPenumbra1Fins[I].Vertex := nil; AShadow^.ShadowPenumbra1Fins[I].VertexCapacity := 0; AShadow^.ShadowPenumbra1Fins[I].VertexCount := 0; end; AShadow^.ShadowPenumbra0FinsCapacity := NewCapacity; AShadow^.ShadowPenumbra0FinsCount := AFinsCount; AShadow^.ShadowPenumbra1FinsCapacity := NewCapacity; AShadow^.ShadowPenumbra1FinsCount := AFinsCount; end; function JAShadowVertexAdd(AShadow : PJAPolygonShadow) : PVec2SInt16; var NewCapacity : SInt32; begin NewCapacity := AShadow^.ShadowVertexCapacity; if (NewCapacity=0) then NewCapacity := JAPool_BlockSize else if (AShadow^.ShadowVertexCount+1) > NewCapacity then NewCapacity += JAPool_BlockSize; if NewCapacity<>AShadow^.ShadowVertexCapacity then begin if AShadow^.ShadowVertexCapacity=0 then begin AShadow^.ShadowVertex := JAMemGet(SizeOf(TVec2SInt16)*NewCapacity); end else begin AShadow^.ShadowVertex := reallocmem(AShadow^.ShadowVertex, SizeOf(TVec2SInt16)*NewCapacity); end; AShadow^.ShadowVertexCapacity := NewCapacity; end; Result := @AShadow^.ShadowVertex[AShadow^.ShadowVertexCount]; AShadow^.ShadowVertexCount += 1; end; function JAShadowPenumbra0Add(AShadow: PJAPolygonShadow): PVec2SInt16; begin end; function JAShadowPenumbra1Add(AShadow: PJAPolygonShadow): PVec2SInt16; begin end; function JAShadowClear(AShadow: PJAPolygonShadow): PJAPolygonShadow; begin {Leave Memory and Capacity intact ready for reuse} AShadow^.ShadowVertexCount := 0; AShadow^.ShadowVertexStart := -1; AShadow^.ShadowVertexEnd := -1; AShadow^.ShadowPenumbra0FinsCount := 0; AShadow^.ShadowPenumbra1FinsCount := 0; AShadow^.ShadowPenumbra0Index := 0; AShadow^.ShadowPenumbra1Index := 0; AShadow^.ShadowPenumbra0FinsCapacity := 0; AShadow^.ShadowPenumbra1FinsCapacity := 0; end; end.
unit Jet.CommandLine; { Command line parsing home. } interface uses SysUtils, UniStrUtils; type EUsage = class(Exception); procedure BadUsage(msg: UniString=''); procedure Redefined(term: string; old, new: UniString); procedure Define(var Term: UniString; TermName: string; Value: UniString); type { Command line parsing context. For now its a record because it's easier to track its lifetime. We may later make this a virtual class and overrides will pull params from different sources: string, TStringList, ParamStr() As far as this module is concerned: argument == any continuous element in the command line option == argument starting with - or -- param == any element in the command line which serves as a parameter for the preceding argument } TParsingContext = record i: integer; procedure Reset; function TryNextArg(out value: UniString): boolean; function NextParam(key, param: UniString): UniString; function TryNextParam(key, param: UniString; out value: UniString): boolean; end; PParsingContext = ^TParsingContext; TCommandLineParser = class public procedure PrintUsage; virtual; procedure Reset; virtual; function HandleOption(ctx: PParsingContext; const s: UniString): boolean; virtual; procedure Finalize; virtual; end; implementation procedure BadUsage(msg: UniString=''); begin raise EUsage.Create(msg); end; procedure Redefined(term: string; old, new: UniString); begin raise EUsage.Create(term+' already specified: '+old+'. Cannot process command "'+new+'".'); end; procedure Define(var Term: UniString; TermName: string; Value: UniString); begin if Term <> '' then Redefined(TermName, Term, Value); Term := Value; end; procedure TParsingContext.Reset; begin i := 0; end; //Tries to consume one more argument from the command line or returns false function TParsingContext.TryNextArg(out value: UniString): boolean; begin Result := (i < ParamCount); if Result then begin Inc(i); value := ParamStr(i); end; end; //Tries to consume one more _parameter_ for the current _argument_ from the command line. //Parameters can't start with - or --, this is considered the beginning of the next option. //If you need this format, use TryNextArg. function TParsingContext.TryNextParam(key, param: UniString; out value: UniString): boolean; begin if i >= ParamCount then begin Result := false; exit; end; value := ParamStr(i+1); Result := not value.StartsWith('-'); if Result then Inc(i) else value := ''; end; function TParsingContext.NextParam(key, param: UniString): UniString; begin Inc(i); if i > ParamCount then BadUsage(Key+' requires specifying the '+param); Result := ParamStr(i); end; procedure TCommandLineParser.PrintUsage; begin //Override to output help for the options covered end; procedure TCommandLineParser.Reset; begin //Override to reset any configurable values to their default state end; function TCommandLineParser.HandleOption(ctx: PParsingContext; const s: string): boolean; begin //Override to handle some options and return true Result := false; end; procedure TCommandLineParser.Finalize; begin //Override to perform any post-processing and consistency checks after parsing //the available parameters. end; end.
{*******************************************************} { } { Windows Firewall example } { } { Copyright © 2014 } { } { Journeyman Consultancy & Services } { } {*******************************************************} {$WARN GARBAGE OFF} {$WEAKLINKRTTI OFF} unit System.Win.Firewall; interface uses NetFwTypeLib_TLB, System.Classes, Winapi.ActiveX, System.Generics.Collections; type {$M+} TWindowsFirewall = class public type TWindowsFirewallRule = class protected FRule: INetFwRule; constructor CreateEmptyRule; public type TWindowsFirewallRuleAction = (Block, Allow); TWindowsFirewallRuleActionHelper = record helper for TWindowsFirewallRuleAction function ToString: string; end; TWindowsFirewallRuleDirection = (&In, &Out, Both); TWindowsFirewallRuleDirectionHelper = record helper for TWindowsFirewallRuleDirection function ToString: string; end; TWindowsFirewallProfile = (PUBLIC, PRIVATE, DOMAIN, ALL); TWindowsFirewallProfileHelper = record helper for TWindowsFirewallProfile function ToString: string; end; TWindowsFirewallProfiles = set of TWindowsFirewallProfile; TWindowsFirewallProfilesHelper = record helper for TWindowsFirewallProfiles function ToString: string; end; TWindowsFirewallRuleProtocol = (TCP, UDP, ANY); TWindowsFirewallRuleProtocolHelper = record helper for TWindowsFirewallRuleProtocol function ToString: string; end; TWindowsFirewallRuleInterfaceType = (LAN, Wireless, RemoteAccess); TWindowsFirewallRuleInterfaceTypeHelper = record helper for TWindowsFirewallRuleInterfaceType function ToString: string; end; TWindowsFirewallRuleInterfaceTypes = set of TWindowsFirewallRuleInterfaceType; TWindowsFirewallRuleInterfaceTypesHelper = record helper for TWindowsFirewallRuleInterfaceTypes function ToString: string; end; private function getAction: TWindowsFirewallRuleAction; procedure setAction(const Value: TWindowsFirewallRuleAction); function getApplicationName: string; procedure setApplicationName(const Value: string); function getDescription: string; procedure setDescription(const Value: string); function getDirection: TWindowsFirewallRuleDirection; procedure setDirection(const Value: TWindowsFirewallRuleDirection); function getEdgeTraversal: Boolean; procedure setEdgeTraversal(const Value: Boolean); function getEnabled: Boolean; procedure setEnabled(const Value: Boolean); function getGrouping: string; procedure setGrouping(const Value: string); function getIcmpTypesAndCodes: string; procedure setIcmpTypesAndCodes(const Value: string); function getInterfaces: TArray<string>; procedure setInterfaces(const Values: TArray<string>); function getInterfaceTypes: TWindowsFirewallRuleInterfaceTypes; procedure setInterfaceTypes(const Values: TWindowsFirewallRuleInterfaceTypes); function getLocalAddresses: string; procedure setLocalAddresses(const Value: string); function getLocalPorts: string; procedure setLocalPorts(const Value: string); function getName: string; procedure setName(const Value: string); function getProfile: TWindowsFirewallProfiles; procedure setProfile(const Values: TWindowsFirewallProfiles); function getProtocol: TWindowsFirewallRuleProtocol; procedure setProtocol(const Value: TWindowsFirewallRuleProtocol); function getRemoteAddresses: string; procedure setRemoteAddresses(const Value: string); function getRemotePorts: string; procedure setRemotePorts(const Value: string); function getServiceName: string; procedure setServiceName(const Value: string); public constructor Create; ///<summary>Adds an IPv4 address to the list of IPv4 addresses to block.</summary> procedure AddIP(const IP: string); ///<summary>Adds a list of IPv4 addresses to the list of IPv4 addresses to block.</summary> procedure AddIPs(const SL: TStringList); overload; ///<summary>Adds a list of IPv4 addresses to the list of IPv4 addresses to block.</summary> ///<param name="IPs">List of IPs to block.</param> procedure AddIPs(const IPs: TArray<string>); overload; destructor Destroy; override; ///<summary>Specifies whether to block or allow connections.</summary> property Action: TWindowsFirewallRuleAction read getAction write setAction; ///<summary>Specifies the application to which this rule applies.</summary> property ApplicationName: string read getApplicationName write setApplicationName; property EdgeTraversal: Boolean read getEdgeTraversal write setEdgeTraversal; ///<summary>Specifies if this rule is enabled or disabled.</summary> property Enabled: Boolean read getEnabled write setEnabled; ///<summary>Specifies what this rule do.</summary> property Description: string read getDescription write setDescription; property Direction: TWindowsFirewallRuleDirection read getDirection write setDirection; property Grouping: string read getGrouping write setGrouping; property IcmpTypesAndCodes: string read getIcmpTypesAndCodes write setIcmpTypesAndCodes; property Interfaces: TArray<string> read getInterfaces write setInterfaces; property InterfaceTypes: TWindowsFirewallRuleInterfaceTypes read getInterfaceTypes write setInterfaceTypes; property LocalAddresses: string read getLocalAddresses write setLocalAddresses; property LocalPorts: string read getLocalPorts write setLocalPorts; ///<summary>Specifies name of this rule.</summary> property Name: string read getName write setName; ///<summary>Specifies which profiles to apply this rule to.</summary> property Profile: TWindowsFirewallProfiles read getProfile write setProfile; property Protocol: TWindowsFirewallRuleProtocol read getProtocol write setProtocol; ///<summary>Specifies the remote addresses which this rule applies to.</summary> property RemoteAddresses: string read getRemoteAddresses write setRemoteAddresses; property RemotePorts: string read getRemotePorts write setRemotePorts; property ServiceName: string read getServiceName write setServiceName; end; TWindowsFirewallRules = class protected FPolicy: INetFwPolicy2; ///<remarks>Call EnsureRulesExist before accessing FRules.</remarks> FRules: INetFwRules; FRuleList: TObjectList<TWindowsFirewallRule>; procedure EnsureRulesExist; function getCount: Integer; function getRule(const AName: string): TWindowsFirewallRule; type TFirewallRuleEnumerator = class protected FRules: INetFwRules; FIndex, FCount: Integer; FVar: OleVariant; FFetched: Cardinal; FEnumVARIANT: IEnumVARIANT; FRuleList: TObjectList<TWindowsFirewallRule>; procedure EnsureCount; constructor Create(const ARules: INetFwRules); function getCurrent: TWindowsFirewallRule; public property Current: TWindowsFirewallRule read getCurrent; destructor Destroy; override; function MoveNext: Boolean; end; public procedure AddRule(const ARule: TWindowsFirewallRule); /// <remarks>The TWindowsFirewallRule created by this method must be freed manually.</remarks> function CreateRule: TWindowsFirewallRule; /// <param name="AName">Name of rule to find</param> /// <remarks>Returns True/False depending on if rule is found.</remarks> function FindRule(const AName: string): Boolean; destructor Destroy; override; function GetEnumerator: TFirewallRuleEnumerator; ///<param name="AName">Name of rule to remove.</param> ///<summary>Removes a rule by its name.</summary> procedure RemoveRule(const AName: string); ///<remarks>Returns number of rules</remarks> property Count: Integer read getCount; ///<summary>Gets a rule given its name.</summary> ///<remarks>raises an exception if rule doesn't exist.</remarks> property Rules[const AName: string]: TWindowsFirewallRule read getRule; default; end; protected FFirewall: INetFwMgr; class threadvar FInitialized: Boolean; class var FRules: TWindowsFirewallRules; class procedure Initialize; class function getWindowsFirewallRules: TWindowsFirewallRules; static; procedure EnsureFirewallAvailable; function getEnabled: Boolean; procedure setEnabled(const Value: Boolean); public constructor Create; destructor Destroy; override; class function CreateRule: INetFwRule; class function CreateAllowingRule: INetFwRule; class function CreateBlockingRule: INetFwRule; class function CreatePolicy: INetFwPolicy2; /// <summary>Allows access to a firewall rule given its name.</summary> /// <remarks>Rules returned from here are tracked, and will be freed automatically.</remarks> class property Rules: TWindowsFirewallRules read getWindowsFirewallRules; /// <summary>Check if the firewall is enabled or not.</summary> /// <remarks>Returns if the firewall is enabled.</remarks> property Enabled: Boolean read getEnabled write setEnabled; end; implementation uses System.Win.ComObj, System.SysUtils, System.TypInfo, System.Variants, System.SysConst, System.Rtti; { TWindowsFirewall } constructor TWindowsFirewall.Create; begin inherited; FInitialized := CoInitialize(nil) = S_OK; end; class function TWindowsFirewall.CreateAllowingRule: INetFwRule; begin Result := CreateRule; Result.Action := NET_FW_ACTION_ALLOW; end; class function TWindowsFirewall.CreateBlockingRule: INetFwRule; begin Result := CreateRule; Result.Action := NET_FW_ACTION_BLOCK; end; class function TWindowsFirewall.CreatePolicy: INetFwPolicy2; begin Initialize; Result := CreateComObject(ProgIDToClassID('HNetCfg.FwPolicy2')) as INetFwPolicy2; end; class function TWindowsFirewall.CreateRule: INetFwRule; begin Initialize; Result := CreateComObject(ProgIDToClassID('HNetCfg.FWRule')) as INetFwRule; end; destructor TWindowsFirewall.Destroy; begin FRules.Free; if FInitialized then CoUninitialize; inherited; end; procedure TWindowsFirewall.EnsureFirewallAvailable; begin if not Assigned(FFirewall) then FFirewall := CreateComObject(ProgIDToClassID('HNetCfg.FwMgr')) as INetFwMgr; end; function TWindowsFirewall.getEnabled: Boolean; begin Result := FFirewall.LocalPolicy.CurrentProfile.FirewallEnabled; end; class function TWindowsFirewall.getWindowsFirewallRules: TWindowsFirewallRules; begin if not Assigned(FRules) then FRules := TWindowsFirewallRules.Create; Result := FRules; end; class procedure TWindowsFirewall.Initialize; begin if not FInitialized then begin CoInitialize(nil); FInitialized := True; end; end; procedure TWindowsFirewall.setEnabled(const Value: Boolean); begin EnsureFirewallAvailable; FFirewall.LocalPolicy.CurrentProfile.FirewallEnabled := Value; end; { TWindowsFirewallRule } procedure TWindowsFirewall.TWindowsFirewallRule.AddIP(const IP: string); var LRemoteAddresses, LPad: string; begin LRemoteAddresses := FRule.RemoteAddresses; if (LRemoteAddresses = '') or (LRemoteAddresses = '*') then begin LPad := ''; if LRemoteAddresses = '*' then LRemoteAddresses := ''; end else LPad := ','; FRule.RemoteAddresses := LRemoteAddresses + LPad + IP + '/255.255.255.255'; end; procedure TWindowsFirewall.TWindowsFirewallRule.AddIPs(const SL: TStringList); var IP: string; begin for IP in SL do AddIP(IP); end; procedure TWindowsFirewall.TWindowsFirewallRule.AddIPs(const IPs: TArray<string>); var IP: string; begin for IP in IPs do AddIP(IP); end; constructor TWindowsFirewall.TWindowsFirewallRule.Create; begin CreateEmptyRule; FRule := TWindowsFirewall.CreateRule; end; constructor TWindowsFirewall.TWindowsFirewallRule.CreateEmptyRule; begin inherited; end; destructor TWindowsFirewall.TWindowsFirewallRule.Destroy; begin FRule := nil; inherited; end; function TWindowsFirewall.TWindowsFirewallRule.getAction: TWindowsFirewallRuleAction; begin case FRule.Action of NET_FW_ACTION_BLOCK: Result := TWindowsFirewallRuleAction.Block; else Result := TWindowsFirewallRuleAction.Allow; end; end; function TWindowsFirewall.TWindowsFirewallRule.getApplicationName: string; begin Result := FRule.ApplicationName; end; function TWindowsFirewall.TWindowsFirewallRule.getLocalAddresses: string; begin Result := FRule.LocalAddresses; end; function TWindowsFirewall.TWindowsFirewallRule.getLocalPorts: string; begin Result := FRule.LocalPorts; end; function TWindowsFirewall.TWindowsFirewallRule.getDescription: string; begin Result := FRule.Description; end; function TWindowsFirewall.TWindowsFirewallRule.getDirection: TWindowsFirewallRuleDirection; begin case FRule.Direction of NET_FW_RULE_DIR_IN: Result := &In; else Result := Out; end; end; function TWindowsFirewall.TWindowsFirewallRule.getEdgeTraversal: Boolean; begin Result := FRule.EdgeTraversal; end; function TWindowsFirewall.TWindowsFirewallRule.getEnabled: Boolean; begin Result := FRule.Enabled; end; function TWindowsFirewall.TWindowsFirewallRule.getGrouping: string; begin Result := FRule.Grouping; end; function TWindowsFirewall.TWindowsFirewallRule.getIcmpTypesAndCodes: string; begin Result := FRule.IcmpTypesAndCodes; end; function TWindowsFirewall.TWindowsFirewallRule.getInterfaces: TArray<string>; var V: Variant; P: Pointer; Count: Integer; begin V := FRule.Interfaces; Result := nil; if not VarIsArray(V) or (VarType(V) and varTypeMask <> varString) or (VarArrayDimCount(V) <> 1) then Exit; Count := VarArrayHighBound(V, 1) - VarArrayLowBound(V, 1) + 1; if Count = 0 then Exit; P := VarArrayLock(V); try SetLength(Result, Count); Move(P^, Result[0], Count * SizeOf(Double)); finally VarArrayUnlock(V); end; end; function TWindowsFirewall.TWindowsFirewallRule.getInterfaceTypes: TWindowsFirewallRuleInterfaceTypes; var LTypes: string; begin Result := []; LTypes := UpperCase(FRule.InterfaceTypes); if (Pos('LAN', LTypes)<>0) or (Pos('ALL', LTypes)<>0) then Result := Result + [LAN]; if (Pos('WIRELESS', LTypes)<>0) or (Pos('ALL', LTypes)<>0) then Result := Result + [Wireless]; if (Pos('REMOTEACCESS', LTypes)<>0) or (Pos('ALL', LTypes)<>0) then Result := Result + [RemoteAccess]; end; function TWindowsFirewall.TWindowsFirewallRule.getName: string; begin Result := FRule.Name; end; function TWindowsFirewall.TWindowsFirewallRule.getProfile: TWindowsFirewallProfiles; const cProfile: array[TWindowsFirewallProfile] of TOleEnum = ( NET_FW_PROFILE2_DOMAIN, NET_FW_PROFILE2_PRIVATE, NET_FW_PROFILE2_PUBLIC, NET_FW_PROFILE2_ALL ); type TType = (X, Y, Z); TTypes = set of TType; var LProfile: TWindowsFirewallProfile; LProfiles: Integer; begin Result := []; LProfiles := FRule.Profiles; for LProfile in [Low(TWindowsFirewallProfile)..High(TWindowsFirewallProfile)] do begin case LProfiles and cProfile[LProfile] of NET_FW_PROFILE2_DOMAIN: Result := Result + [DOMAIN]; NET_FW_PROFILE2_PRIVATE: Result := Result + [&PRIVATE]; NET_FW_PROFILE2_PUBLIC: Result := Result + [&PUBLIC]; else Result := [DOMAIN, &PRIVATE, &PUBLIC, ALL]; Break; end; end; end; function TWindowsFirewall.TWindowsFirewallRule.getProtocol: TWindowsFirewallRuleProtocol; begin case FRule.Protocol of NET_FW_IP_PROTOCOL_TCP: Result := TCP; NET_FW_IP_PROTOCOL_UDP: Result := UDP; else Result := ANY; end; end; function TWindowsFirewall.TWindowsFirewallRule.getRemoteAddresses: string; begin Result := FRule.RemoteAddresses; end; function TWindowsFirewall.TWindowsFirewallRule.getRemotePorts: string; begin Result := FRule.RemotePorts; end; function TWindowsFirewall.TWindowsFirewallRule.getServiceName: string; begin Result := FRule.serviceName; end; procedure TWindowsFirewall.TWindowsFirewallRule.setAction( const Value: TWindowsFirewallRuleAction); const cAction: array[TWindowsFirewallRuleAction] of TOleEnum = ( NET_FW_ACTION_BLOCK, NET_FW_ACTION_ALLOW ); begin FRule.Action := cAction[Value]; end; procedure TWindowsFirewall.TWindowsFirewallRule.setApplicationName( const Value: string); begin FRule.ApplicationName := Value; end; procedure TWindowsFirewall.TWindowsFirewallRule.setLocalAddresses( const Value: string); begin FRule.LocalAddresses := Value; end; procedure TWindowsFirewall.TWindowsFirewallRule.setLocalPorts( const Value: string); begin FRule.LocalPorts := Value; end; procedure TWindowsFirewall.TWindowsFirewallRule.setDescription( const Value: string); begin FRule.Description := Value; end; procedure TWindowsFirewall.TWindowsFirewallRule.setDirection( const Value: TWindowsFirewallRuleDirection); const cDirection: array[TWindowsFirewallRuleDirection] of TOleEnum = ( NET_FW_RULE_DIR_IN, NET_FW_RULE_DIR_OUT, NET_FW_RULE_DIR_MAX ); begin FRule.Direction := cDirection[Value]; end; procedure TWindowsFirewall.TWindowsFirewallRule.setEdgeTraversal( const Value: Boolean); begin FRule.EdgeTraversal := Value; end; procedure TWindowsFirewall.TWindowsFirewallRule.setEnabled( const Value: Boolean); begin FRule.Enabled := Value; end; procedure TWindowsFirewall.TWindowsFirewallRule.setGrouping( const Value: string); begin FRule.Grouping := Value; end; procedure TWindowsFirewall.TWindowsFirewallRule.setIcmpTypesAndCodes( const Value: string); begin FRule.IcmpTypesAndCodes := Value; end; procedure TWindowsFirewall.TWindowsFirewallRule.setInterfaces( const Values: TArray<string>); var LVariant: Variant; begin LVariant := Values; FRule.Interfaces := LVariant; end; procedure TWindowsFirewall.TWindowsFirewallRule.setInterfaceTypes( const Values: TWindowsFirewallRuleInterfaceTypes); var LTypes: string; LType: TWindowsFirewallRuleInterfaceType; const cType: array[TWindowsFirewallRuleInterfaceType] of string = ( 'Lan', 'Wireless', 'RemoteAccess' ); begin LTypes := ''; for LType in Values do begin if LTypes = '' then LTypes := cType[LType] else LTypes := LTypes + ',' + cType[LType]; end; FRule.InterfaceTypes := LTypes; end; procedure TWindowsFirewall.TWindowsFirewallRule.setName(const Value: string); begin FRule.Name := Value; end; procedure TWindowsFirewall.TWindowsFirewallRule.setProfile( const Values: TWindowsFirewallProfiles); const cProfile: array[TWindowsFirewallProfile] of TOleEnum = ( NET_FW_PROFILE2_DOMAIN, NET_FW_PROFILE2_PRIVATE, NET_FW_PROFILE2_PUBLIC, NET_FW_PROFILE2_ALL ); var LProfile: TWindowsFirewallProfile; LProfiles: TOleEnum; begin // FRule.Profiles := cProfile[Value]; LProfiles := 0; for LProfile in [Low(TWindowsFirewallProfile)..High(TWindowsFirewallProfile)] do if LProfile in Values then LProfiles := LProfiles or cProfile[LProfile]; FRule.Profiles := LProfiles; end; procedure TWindowsFirewall.TWindowsFirewallRule.setProtocol( const Value: TWindowsFirewallRuleProtocol); const cProtocol: array[TWindowsFirewallRuleProtocol] of TOleEnum = ( NET_FW_IP_PROTOCOL_TCP, NET_FW_IP_PROTOCOL_UDP, NET_FW_IP_PROTOCOL_ANY); begin FRule.Protocol := cProtocol[Value]; end; procedure TWindowsFirewall.TWindowsFirewallRule.setRemoteAddresses( const Value: string); begin FRule.RemoteAddresses := Value; end; procedure TWindowsFirewall.TWindowsFirewallRule.setRemotePorts( const Value: string); begin FRule.RemotePorts := Value; end; procedure TWindowsFirewall.TWindowsFirewallRule.setServiceName( const Value: string); begin FRule.serviceName := Value; end; { TWindowsFirewallRules } procedure TWindowsFirewall.TWindowsFirewallRules.AddRule( const ARule: TWindowsFirewallRule); begin EnsureRulesExist; FRules.Add(ARule.FRule); end; function TWindowsFirewall.TWindowsFirewallRules.CreateRule: TWindowsFirewallRule; begin EnsureRulesExist; Result := TWindowsFirewallRule.Create; end; destructor TWindowsFirewall.TWindowsFirewallRules.Destroy; begin FRuleList.Free; FRules := nil; FPolicy := nil; inherited; end; procedure TWindowsFirewall.TWindowsFirewallRules.EnsureRulesExist; var LClassID: string; LGUID: TGUID; begin if not Assigned(FPolicy) then begin LGUID := ProgIDToClassID('HNetCfg.FwPolicy2'); LClassID := LGUID.ToString; FPolicy := CreateComObject(LGUID) as INetFwPolicy2; FRules := FPolicy.Rules; end; end; function TWindowsFirewall.TWindowsFirewallRules.FindRule(const AName: string): Boolean; begin EnsureRulesExist; try Result := Assigned(FRules.Item(AName)); except on E: EOleException do Result := False; end; end; function TWindowsFirewall.TWindowsFirewallRules.getCount: Integer; begin EnsureRulesExist; Result := FRules.Count; end; function TWindowsFirewall.TWindowsFirewallRules.GetEnumerator: TFirewallRuleEnumerator; begin EnsureRulesExist; Result := TFirewallRuleEnumerator.Create(FRules); end; function TWindowsFirewall.TWindowsFirewallRules.getRule( const AName: string): TWindowsFirewallRule; var LRule: INetFwRule; begin EnsureRulesExist; LRule := FRules.Item(AName); Result := TWindowsFirewall.TWindowsFirewallRule.CreateEmptyRule; Result.FRule := LRule; end; procedure TWindowsFirewall.TWindowsFirewallRules.RemoveRule( const AName: string); begin EnsureRulesExist; FRules.Remove(AName); end; { TWindowsFirewall.TWindowsFirewallRules.TFirewallRuleEnumerator } constructor TWindowsFirewall.TWindowsFirewallRules.TFirewallRuleEnumerator.Create( const ARules: INetFwRules); begin inherited Create; FRules := ARules; VarClear(FVar); FCount := -1; Supports(FRules._NewEnum, IEnumVARIANT, FEnumVARIANT); FRuleList := TObjectList<TWindowsFirewallRule>.Create; end; destructor TWindowsFirewall.TWindowsFirewallRules.TFirewallRuleEnumerator.Destroy; begin FRuleList.Free; FEnumVARIANT := nil; FRules := nil; inherited; end; procedure TWindowsFirewall.TWindowsFirewallRules.TFirewallRuleEnumerator.EnsureCount; begin if FCount = -1 then FCount := FRules.Count; end; function TWindowsFirewall.TWindowsFirewallRules.TFirewallRuleEnumerator.getCurrent: TWindowsFirewallRule; var LRule: INetFwRule; begin Result := TWindowsFirewallRule.CreateEmptyRule; FRuleList.Add(Result); if FEnumVARIANT.Next(1, FVar, FFetched) = S_OK then begin Supports(FVar, INetFwRule, LRule); Result.FRule := LRule; if Pos('File Transfer', Result.Name)<>0 then asm nop end; end; end; function TWindowsFirewall.TWindowsFirewallRules.TFirewallRuleEnumerator.MoveNext: Boolean; begin EnsureCount; Result := FIndex < FCount; if Result then Inc(FIndex); end; { TWindowsFirewall.TWindowsFirewallRule.TWindowsFirewallRuleProtocolHelper } function TWindowsFirewall.TWindowsFirewallRule.TWindowsFirewallRuleProtocolHelper.ToString: string; begin Result := GetEnumName(TypeInfo(TWindowsFirewall.TWindowsFirewallRule.TWindowsFirewallRuleProtocol), Ord(Self)); end; { TWindowsFirewall.TWindowsFirewallRule.TWindowsFirewallRuleActionHelper } function TWindowsFirewall.TWindowsFirewallRule.TWindowsFirewallRuleActionHelper.ToString: string; begin Result := GetEnumName(TypeInfo(TWindowsFirewall.TWindowsFirewallRule.TWindowsFirewallRuleAction), Ord(Self)); end; { TWindowsFirewall.TWindowsFirewallRule.TWindowsFirewallProfileHelper } function TWindowsFirewall.TWindowsFirewallRule.TWindowsFirewallProfileHelper.ToString: string; begin Result := GetEnumName(TypeInfo(TWindowsFirewall.TWindowsFirewallRule.TWindowsFirewallProfile), Ord(Self)); end; function TWindowsFirewall.TWindowsFirewallRule.TWindowsFirewallProfilesHelper.ToString: string; var LType: TWindowsFirewall.TWindowsFirewallRule.TWindowsFirewallProfile; LSet: string; begin LSet := ''; for LType in Self do if LSet = '' then LSet := LType.ToString else LSet := LSet + ',' + LType.ToString; Result := '[' + LSet + ']'; end; { TWindowsFirewall.TWindowsFirewallRule.TWindowsFirewallRuleDirectionHelper } function TWindowsFirewall.TWindowsFirewallRule.TWindowsFirewallRuleDirectionHelper.ToString: string; begin Result := GetEnumName(TypeInfo(TWindowsFirewall.TWindowsFirewallRule.TWindowsFirewallRuleDirection), Ord(Self)); end; { TWindowsFirewall.TWindowsFirewallRule.TWindowsFirewallRuleInterfaceTypesHelper } function TWindowsFirewall.TWindowsFirewallRule.TWindowsFirewallRuleInterfaceTypeHelper.ToString: string; begin Result := GetEnumName(TypeInfo(TWindowsFirewall.TWindowsFirewallRule.TWindowsFirewallRuleInterfaceType), Ord(Self)); end; { TWindowsFirewall.TWindowsFirewallRule.TWindowsFirewallRuleInterfaceTypesHelper } function TWindowsFirewall.TWindowsFirewallRule.TWindowsFirewallRuleInterfaceTypesHelper.ToString: string; var LType: TWindowsFirewall.TWindowsFirewallRule.TWindowsFirewallRuleInterfaceType; LSet: string; begin LSet := ''; for LType in Self do if LSet = '' then LSet := LType.ToString else LSet := LSet + ',' + LType.ToString; Result := '[' + LSet + ']'; end; end. {*******************************************************} { } { Windows Firewall example } { } { Journeyman Consultancy & Services } { } {*******************************************************}
{----------------------------------------------------------------------------} { Written by Nguyen Le Quang Duy } { Nguyen Quang Dieu High School, An Giang } {----------------------------------------------------------------------------} Program DTDOI; Uses Math; Const maxN =100; maxValue =1000000000; Var n,s,m,res :LongInt; A :Array[1..maxN] of LongInt; F :Array[1..1000000] of LongInt; procedure Enter; var i :LongInt; begin Read(n,s); m:=0; for i:=1 to n do begin Read(A[i]); m:=Max(m,A[i]); end; end; procedure Greedy; begin res:=0; while (s>1000000) do begin Inc(res); Dec(s,m); end; end; procedure Optimize; var i,j :LongInt; begin F[0]:=0; for i:=1 to s do begin F[i]:=maxValue; for j:=1 to n do if (i>=A[j]) and ((F[i]>F[i-A[j]]+1)) then F[i]:=F[i-A[j]]+1; end; end; Begin Assign(Input,''); Reset(Input); Assign(Output,''); Rewrite(Output); Enter; Greedy; Optimize; Write(F[s]+res); Close(Input); Close(Output); End.
unit ContactBox; {$mode objfpc}{$H+} interface uses Classes, SysUtils, StdCtrls, Controls, Graphics, LCLType; type { TContactBox } TContactBox = class(TListBox) private fMsgCount: array of integer; procedure ResizeArray; public constructor Create(TheOwner: TComponent); override; procedure ListBoxDrawItem(Control: TWinControl; Index: integer; ARect: TRect; State: TOwnerDrawState); virtual; public procedure NewMessage(fItem: integer); procedure ClearMessage(fItem: integer); end; implementation { TContactBox } procedure TContactBox.ResizeArray; var OldLen: integer; i: integer; begin OldLen := High(fMsgCount) + 1; if OldLen <> Items.Count then begin SetLength(fMsgCount, Items.Count); for i := OldLen to High(fMsgCount) do fMsgCount[i] := 0; end; end; constructor TContactBox.Create(TheOwner: TComponent); begin inherited Create(TheOwner); Style := lbVirtual; OnDrawItem := @ListBoxDrawItem; SetLength(fMsgCount, 1); end; procedure TContactBox.ListBoxDrawItem(Control: TWinControl; Index: integer; ARect: TRect; State: TOwnerDrawState); var BufStr: string; begin with (Control as TContactBox).Canvas do begin { Color:= clWhite; if (odSelected in State) then begin Brush.Color:=clBlack; Font.Color := clWhite end else Font.Color := clBlack; } FillRect(aRect); Pen.Style := psClear; Brush.Style := bsClear; BufStr := ''; if fMsgCount[Index] <> 0 then BufStr := '(' + IntToStr(fMsgCount[Index]) + ') '; BufStr += (Control as TListBox).Items[Index]; TextOut(aRect.Left + 2, aRect.Top + 2, BufStr); if (odFocused in State) then DrawFocusRect(aRect); end; end; procedure TContactBox.NewMessage(fItem: integer); begin ResizeArray; fMsgCount[fItem] += 1; end; procedure TContactBox.ClearMessage(fItem: integer); begin ResizeArray; fMsgCount[fItem] := 0; end; end.
unit ATipoCorte; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, Componentes1, ExtCtrls, PainelGradiente, BotaoCadastro, StdCtrls, Buttons, Db, DBTables, Tabela, CBancoDados, Mask, DBCtrls, DBKeyViolation, Grids, DBGrids, Localizacao, DBClient; type TFTipoCorte = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; PanelColor2: TPanelColor; TipoCorte: TRBSQL; MoveBasico1: TMoveBasico; BotaoCadastrar1: TBotaoCadastrar; BotaoAlterar1: TBotaoAlterar; BotaoExcluir1: TBotaoExcluir; BotaoGravar1: TBotaoGravar; BotaoCancelar1: TBotaoCancelar; BFechar: TBitBtn; TipoCorteCODCORTE: TFMTBCDField; TipoCorteNOMCORTE: TWideStringField; ECodigo: TDBKeyViolation; DBEditColor1: TDBEditColor; BaseTipoCorte: TDataSource; Label1: TLabel; Label2: TLabel; Label3: TLabel; Bevel1: TBevel; EConsulta: TLocalizaEdit; GridIndice1: TGridIndice; TipoCorteDATALT: TSQLTimeStampField; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BFecharClick(Sender: TObject); procedure GridIndice1Ordem(Ordem: String); procedure TipoCorteAfterInsert(DataSet: TDataSet); procedure TipoCorteAfterEdit(DataSet: TDataSet); procedure TipoCorteAfterPost(DataSet: TDataSet); procedure TipoCorteBeforePost(DataSet: TDataSet); private { Private declarations } public { Public declarations } end; var FTipoCorte: TFTipoCorte; implementation uses APrincipal, UnSistema; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFTipoCorte.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } EConsulta.AtualizaConsulta; end; { ******************* Quando o formulario e fechado ************************** } procedure TFTipoCorte.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} procedure TFTipoCorte.BFecharClick(Sender: TObject); begin close; end; {******************************************************************************} procedure TFTipoCorte.GridIndice1Ordem(Ordem: String); begin EConsulta.AOrdem := Ordem; end; {******************************************************************************} procedure TFTipoCorte.TipoCorteAfterInsert(DataSet: TDataSet); begin ECodigo.ReadOnly := false; ECodigo.ProximoCodigo; end; {******************************************************************************} procedure TFTipoCorte.TipoCorteAfterEdit(DataSet: TDataSet); begin ECodigo.ReadOnly := true; end; {******************************************************************************} procedure TFTipoCorte.TipoCorteAfterPost(DataSet: TDataSet); begin Sistema.MarcaTabelaParaImportar('TIPOCORTE'); EConsulta.AtualizaConsulta; end; {******************************************************************************} procedure TFTipoCorte.TipoCorteBeforePost(DataSet: TDataSet); begin if TipoCorte.State = dsinsert then ECodigo.VerificaCodigoUtilizado; TipoCorteDATALT.AsDateTime := Sistema.RDataServidor; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFTipoCorte]); end.
PROGRAM WorkWithQueryString(INPUT, OUTPUT); USES GPC; FUNCTION GetQueryStringParameter(Key: STRING): STRING; VAR KeyCheck, QueryString : STRING; BEGIN KeyCheck := ''; QueryString := GetEnv('QUERY_STRING'); KeyCheck := Copy(QueryString, pos(key, QueryString), length(key)); IF Key = KeyCheck THEN BEGIN Delete(QueryString, 1, pos(key, QueryString) + length(key)); IF (pos('&', QueryString) > 1) THEN Delete(QueryString, pos('&', QueryString), length(QueryString)); GetQueryStringParameter := QueryString; END ELSE GetQueryStringParameter := 'No Request' END; BEGIN {WorkWithQueryString} WRITELN; WRITELN('First Name: ', GetQueryStringParameter('first_name')); WRITELN('Last Name: ', GetQueryStringParameter('last_name')); WRITELN('Age: ', GetQueryStringParameter('age')) END. {WorkWithQueryString}
unit FormClientMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.TabControl, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Gestures, System.Actions, FMX.ActnList, FMX.ScrollBox, FMX.Memo, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, FMX.Edit, FMX.Layouts, FMX.ListBox, System.Rtti, FMX.Grid, System.ImageList, FMX.ImgList, YahtzeeClasses; type TClientMainForm = class(TForm) TabControl1: TTabControl; TabItem1: TTabItem; TabControl2: TTabControl; TabItem5: TTabItem; ToolBar1: TToolBar; lblTitle1: TLabel; btnNext: TSpeedButton; TabItem6: TTabItem; ToolBar2: TToolBar; lblTitle2: TLabel; btnBack: TSpeedButton; TabItem2: TTabItem; TabItem3: TTabItem; TabItem4: TTabItem; ToolBar5: TToolBar; lblTitle5: TLabel; GestureManager1: TGestureManager; ActionList1: TActionList; NextTabAction1: TNextTabAction; PreviousTabAction1: TPreviousTabAction; Timer1: TTimer; Panel1: TPanel; Label1: TLabel; Edit1: TEdit; Label2: TLabel; Edit2: TEdit; Button1: TButton; Label3: TLabel; Edit3: TEdit; Memo2: TMemo; actConnectConnect: TAction; actConnectSetName: TAction; actUpdateName: TAction; actUpdateServer: TAction; Button2: TButton; TabControl3: TTabControl; TabItem7: TTabItem; ToolBar3: TToolBar; Label4: TLabel; SpeedButton1: TSpeedButton; Panel2: TPanel; TabItem8: TTabItem; ToolBar6: TToolBar; Label8: TLabel; SpeedButton2: TSpeedButton; NextTabAction2: TNextTabAction; PreviousTabAction2: TPreviousTabAction; Label5: TLabel; Edit4: TEdit; Button3: TButton; Button4: TButton; Memo3: TMemo; actRoomJoin: TAction; Panel3: TPanel; Memo4: TMemo; Edit5: TEdit; actRoomSend: TAction; actUpdateRoomLog: TAction; actUpdateRoomJoin: TAction; actUpdateRoomPart: TAction; actRoomList: TAction; SpeedButton3: TSpeedButton; Panel4: TPanel; ListBox1: TListBox; actRoomToggleMembers: TAction; TabControl4: TTabControl; TabItem9: TTabItem; ToolBar4: TToolBar; Label6: TLabel; Panel5: TPanel; Memo5: TMemo; TabItem10: TTabItem; ToolBar7: TToolBar; Label9: TLabel; SpeedButton5: TSpeedButton; Panel6: TPanel; Panel7: TPanel; ListBox2: TListBox; TabItem11: TTabItem; ToolBar8: TToolBar; Label10: TLabel; SpeedButton7: TSpeedButton; Panel8: TPanel; Panel9: TPanel; ListBox3: TListBox; Edit7: TEdit; Label11: TLabel; Panel10: TPanel; Memo1: TMemo; ListBox4: TListBox; Label13: TLabel; Memo6: TMemo; Label14: TLabel; Label15: TLabel; Edit9: TEdit; Label16: TLabel; Label17: TLabel; Button7: TButton; Label18: TLabel; GridPanelLayout1: TGridPanelLayout; SpeedButton6: TSpeedButton; Glyph1: TGlyph; SpeedButton8: TSpeedButton; Glyph2: TGlyph; SpeedButton9: TSpeedButton; Glyph3: TGlyph; SpeedButton10: TSpeedButton; Glyph4: TGlyph; SpeedButton11: TSpeedButton; Glyph5: TGlyph; Button8: TButton; imgLstDie: TImageList; StringGrid1: TStringGrid; StringColumn1: TStringColumn; StringColumn2: TStringColumn; StringColumn3: TStringColumn; StringColumn4: TStringColumn; Label19: TLabel; Label20: TLabel; GridPanelLayout2: TGridPanelLayout; Button9: TButton; Label21: TLabel; Label22: TLabel; ListBoxItem1: TListBoxItem; ListBoxItem2: TListBoxItem; ListBoxItem3: TListBoxItem; ListBoxItem4: TListBoxItem; ListBoxItem5: TListBoxItem; ListBoxItem6: TListBoxItem; imgLstGamePlayer: TImageList; imgListZones: TImageList; StyleBook1: TStyleBook; GridPanelLayout3: TGridPanelLayout; GridPanelLayout4: TGridPanelLayout; GridPanelLayout5: TGridPanelLayout; Label7: TLabel; Edit6: TEdit; Label12: TLabel; Edit8: TEdit; Button5: TButton; Button6: TButton; PreviousTabAction3: TPreviousTabAction; NextTabAction3: TNextTabAction; CheckBox1: TCheckBox; actGameJoin: TAction; actGameList: TAction; actUpdateGameJoin: TAction; actUpdateGamePart: TAction; actUpdateGameLog: TAction; actGameControl: TAction; actUpdateGameDetail: TAction; actGameRoll: TAction; actGameScore: TAction; SpeedButton4: TSpeedButton; procedure GestureDone(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean); procedure FormCreate(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure Timer1Timer(Sender: TObject); procedure IdTCPClient1Connected(Sender: TObject); procedure IdTCPClient1Disconnected(Sender: TObject); procedure actConnectConnectExecute(Sender: TObject); procedure actConnectSetNameExecute(Sender: TObject); procedure actConnectSetNameUpdate(Sender: TObject); procedure actUpdateNameExecute(Sender: TObject); procedure actUpdateServerExecute(Sender: TObject); procedure actRoomJoinExecute(Sender: TObject); procedure actRoomJoinUpdate(Sender: TObject); procedure Edit5KeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure actRoomSendExecute(Sender: TObject); procedure actUpdateRoomLogExecute(Sender: TObject); procedure Edit4KeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure actUpdateRoomPartExecute(Sender: TObject); procedure actUpdateRoomJoinExecute(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure actRoomListExecute(Sender: TObject); procedure actRoomListUpdate(Sender: TObject); procedure actRoomToggleMembersExecute(Sender: TObject); procedure ToolBar3KeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure Edit7KeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure SpeedButton10Click(Sender: TObject); procedure actGameJoinExecute(Sender: TObject); procedure actGameJoinUpdate(Sender: TObject); procedure actGameListExecute(Sender: TObject); procedure actGameListUpdate(Sender: TObject); procedure actUpdateGameJoinExecute(Sender: TObject); procedure actUpdateGamePartExecute(Sender: TObject); procedure actUpdateGameLogExecute(Sender: TObject); procedure actGameControlUpdate(Sender: TObject); procedure actGameControlExecute(Sender: TObject); procedure actUpdateGameDetailExecute(Sender: TObject); procedure actGameRollExecute(Sender: TObject); procedure ListBoxItem1Click(Sender: TObject); procedure StringGrid1SelectCell(Sender: TObject; const ACol, ARow: Integer; var CanSelect: Boolean); procedure StringGrid1DrawColumnCell(Sender: TObject; const Canvas: TCanvas; const Column: TColumn; const Bounds: TRectF; const Row: Integer; const Value: TValue; const State: TGridDrawStates); procedure StringGrid1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); procedure actGameScoreExecute(Sender: TObject); procedure actGameScoreUpdate(Sender: TObject); procedure actGameRollUpdate(Sender: TObject); procedure StringGrid1Tap(Sender: TObject; const Point: TPointF); procedure TabControl4Change(Sender: TObject); private procedure DoConnect; procedure DoDisconnect; public procedure UpdateGameSlotState(AGameState: TGameState; ASlot: Integer); procedure UpdateOurState; end; var ClientMainForm: TClientMainForm; implementation {$R *.fmx} uses {$IFDEF ANDROID} ORawByteString, {$ENDIF} YahtzeeClient; procedure TClientMainForm.actConnectConnectExecute(Sender: TObject); begin PushDebugMsg(AnsiString('actConnectConnectExecute.')); Client.Game.Lock.Acquire; try if not Client.Connection.Connected then DoConnect else DoDisconnect; finally Client.Game.Lock.Release; end; end; procedure TClientMainForm.actConnectSetNameExecute(Sender: TObject); begin PushDebugMsg(AnsiString('actConnectSetNameExecute.')); Client.SendConnctIdent(AnsiString(Edit2.Text)); end; procedure TClientMainForm.actConnectSetNameUpdate(Sender: TObject); begin Client.Game.Lock.Acquire; try actConnectSetName.Enabled:= Client.Game.WasConnected; finally Client.Game.Lock.Release; end; end; procedure TClientMainForm.actGameControlExecute(Sender: TObject); var m: TMessage; begin PushDebugMsg(AnsiString('actGameControlExecute.')); Client.Game.Lock.Acquire; try if actGameControl.Tag = 1 then begin m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $07; // m.Params.Add(AnsiChar(Client.Game.OurSlot)); // m.Params.Add(AnsiChar(psReady)); SetLength(m.Data, 2); m.Data[0]:= Client.Game.OurSlot; m.Data[1]:= Ord(psReady); // m.DataFromParams; // MessageLock.Acquire; // try SendMessages.PushItem(m) // finally // MessageLock.Release; // end; end else if actGameControl.Tag = 2 then begin m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $07; // m.Params.Add(AnsiChar(Client.Game.OurSlot)); // m.Params.Add(AnsiChar(psIdle)); SetLength(m.Data, 2); m.Data[0]:= Client.Game.OurSlot; m.Data[1]:= Ord(psIdle); // m.DataFromParams; // MessageLock.Acquire; // try SendMessages.PushItem(m) // finally // MessageLock.Release; // end; end else if actGameControl.Tag = 3 then begin m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $08; // m.Params.Add(AnsiChar(Client.Game.OurSlot)); // m.Params.Add(AnsiChar(DieSetToByte(VAL_SET_DICEALL))); SetLength(m.Data, 2); m.Data[0]:= Client.Game.OurSlot; m.Data[1]:= DieSetToByte(VAL_SET_DICEALL); // m.DataFromParams; // MessageLock.Acquire; // try SendMessages.PushItem(m) // finally // MessageLock.Release; // end; end; finally Client.Game.Lock.Release; end; end; procedure TClientMainForm.actGameControlUpdate(Sender: TObject); begin actGameControl.Enabled:= actGameControl.Tag > 0; end; procedure TClientMainForm.actGameJoinExecute(Sender: TObject); var m: TMessage; {$IFDEF ANDROID} i: Integer; {$ENDIF} begin PushDebugMsg(AnsiString('actGameJoinExecute.')); if actGameJoin.Tag = 0 then begin if Length(Edit6.Text) > 0 then begin m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $01; m.Params.Add(AnsiString(Copy(Edit6.Text, Low(string), 8))); if Length(Edit8.Text) > 0 then m.Params.Add(AnsiString(Copy(Edit8.Text, Low(string), 8))); m.DataFromParams; // MessageLock.Acquire; // try SendMessages.PushItem(m); // finally // MessageLock.Release; // end; end; end else begin {$IFDEF ANDROID} if AnsiLength(Client.Game.Desc) > 0 then {$ELSE} if Length(Client.Game.Desc) > 0 then {$ENDIF} begin m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $02; {$IFDEF ANDROID} i:= AnsiLength(Client.Game.Desc); if AnsiLength(Client.Game.Desc) > 8 then i:= 8; m.Params.Add(AnsiString(AnsiCopy(Client.Game.Desc, 1, i))); {$ELSE} m.Params.Add(AnsiString(Copy(Client.Game.Desc, Low(AnsiString), 8))); {$ENDIF} m.DataFromParams; // MessageLock.Acquire; // try SendMessages.PushItem(m); // finally // MessageLock.Release; // end; end; end; end; procedure TClientMainForm.actGameJoinUpdate(Sender: TObject); begin Client.Game.Lock.Acquire; try actGameJoin.Enabled:= Client.Game.WasConnected; finally Client.Game.Lock.Release; end; end; procedure TClientMainForm.actGameListExecute(Sender: TObject); var m: TMessage; begin PushDebugMsg(AnsiString('actGameListExecute.')); m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $03; // MessageLock.Acquire; // try SendMessages.PushItem(m); // finally // MessageLock.Release; // end; end; procedure TClientMainForm.actGameListUpdate(Sender: TObject); begin Client.Game.Lock.Acquire; try actGameList.Enabled:= Client.Game.WasConnected; finally Client.Game.Lock.Release; end; end; procedure TClientMainForm.actGameRollExecute(Sender: TObject); var m: TMessage; begin PushDebugMsg(AnsiString('actGameRollExecute.')); actGameRoll.Tag:= 1; Client.Game.Lock.Acquire; try Client.Game.RollNo:= Client.Game.RollNo + 1; Client.Game.PreviewLoc:= []; FillChar(Client.Game.Preview, SizeOf(TScoreSheet), $FF); m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $08; SetLength(m.Data, 2); m.Data[0]:= Client.Game.OurSlot; m.Data[1]:= DieSetToByte(VAL_SET_DICEALL - Client.Game.Slots[Client.Game.OurSlot].Keepers); finally Client.Game.Lock.Release; end; // MessageLock.Acquire; // try SendMessages.PushItem(m); // finally // MessageLock.Release; // end; StringGrid1.Repaint; end; procedure TClientMainForm.actGameRollUpdate(Sender: TObject); begin Client.Game.Lock.Acquire; try actGameRoll.Enabled:= Client.Game.WasConnected and (Client.Game.OurSlot = Client.Game.VisibleSlot) and (Client.Game.Slots[Client.Game.OurSlot].State = psPlaying) and (Client.Game.RollNo < 3) and (actGameRoll.Tag = 0); finally Client.Game.Lock.Release; end; end; procedure TClientMainForm.actGameScoreExecute(Sender: TObject); var m: TMessage; begin PushDebugMsg(AnsiString('actGameScoreExecute.')); Client.Game.Lock.Acquire; try if Client.Game.SelScore then begin FillChar(Client.Game.Preview, SizeOf(TScoreSheet), $FF); Client.Game.PreviewLoc:= []; m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $0B; SetLength(m.Data, 2); m.Data[0]:= Client.Game.OurSlot; m.Data[1]:= Ord(Client.Game.SelScoreLoc); // MessageLock.Acquire; // try SendMessages.PushItem(m); // finally // MessageLock.Release; // end; end; finally Client.Game.Lock.Release; end; end; procedure TClientMainForm.actGameScoreUpdate(Sender: TObject); begin Client.Game.Lock.Acquire; try actGameScore.Enabled:= Client.Game.WasConnected and (Client.Game.OurSlot = Client.Game.VisibleSlot) and (Client.Game.Slots[Client.Game.OurSlot].State = psPlaying) and Client.Game.SelScore; finally Client.Game.Lock.Release; end; end; procedure TClientMainForm.actRoomJoinExecute(Sender: TObject); var m: TMessage; {$IFDEF ANDROID} i: Integer; {$ENDIF} begin PushDebugMsg(AnsiString('actRoomJoinExecute.')); if actRoomJoin.Tag = 0 then begin if Length(Edit4.Text) > 0 then begin m:= TMessage.Create; m.Category:= mcLobby; m.Method:= $01; m.Params.Add(AnsiString(Copy(Edit4.Text, Low(string), 8))); if Length(Edit7.Text) > 0 then m.Params.Add(AnsiString(Copy(Edit7.Text, Low(string), 8))); m.DataFromParams; // MessageLock.Acquire; // try SendMessages.PushItem(m); // finally // MessageLock.Release; // end; end; end else begin {$IFDEF ANDROID} if AnsiLength(Client.Room) > 0 then {$ELSE} if Length(Client.Room) > 0 then {$ENDIF} begin m:= TMessage.Create; m.Category:= mcLobby; m.Method:= $02; {$IFDEF ANDROID} i:= AnsiLength(Client.Game.Desc); if AnsiLength(Client.Game.Desc) > 8 then i:= 8; m.Params.Add(AnsiString(AnsiCopy(Client.Room, 1, i))); {$ELSE} m.Params.Add(AnsiString(Copy(Client.Room, Low(string), 8))); {$ENDIF} m.DataFromParams; // MessageLock.Acquire; // try SendMessages.PushItem(m); // finally // MessageLock.Release; // end; end; end; end; procedure TClientMainForm.actRoomJoinUpdate(Sender: TObject); begin Client.Game.Lock.Acquire; try actRoomJoin.Enabled:= Client.Game.WasConnected; finally Client.Game.Lock.Release; end; end; procedure TClientMainForm.actRoomListExecute(Sender: TObject); var m: TMessage; begin PushDebugMsg(AnsiString('actRoomListExecute.')); m:= TMessage.Create; m.Category:= mcLobby; m.Method:= $03; // MessageLock.Acquire; // try SendMessages.PushItem(m); // finally // MessageLock.Release; // end; end; procedure TClientMainForm.actRoomListUpdate(Sender: TObject); begin Client.Game.Lock.Acquire; try actRoomList.Enabled:= Client.Game.WasConnected; finally Client.Game.Lock.Release; end; end; procedure TClientMainForm.actRoomSendExecute(Sender: TObject); var m: TMessage; c: TMsgCategory; s: string; n: AnsiString; p: Integer; begin PushDebugMsg(AnsiString('actRoomSendExecute.')); s:= Edit5.Text; if CompareText(Copy(s, Low(string), 3), '/w ') = 0 then begin c:= mcText; s:= Copy(s, Low(string) + 3, MaxInt); p:= Pos(' ', s); if p < 2 then Exit else begin n:= AnsiString(Copy(s, Low(string), p - Low(string))); s:= Copy(s, p + 1, MaxInt); end; end else begin c:= mcLobby; n:= Client.Name; end; if Length(s) > 0 then begin m:= TMessage.Create; m.Category:= c; m.Method:= $04; if c = mcLobby then m.Params.Add(Client.Room); m.Params.Add(n); m.Params.Add(AnsiString(Copy(s, Low(string), 40))); m.DataFromParams; // MessageLock.Acquire; // try SendMessages.PushItem(m); // finally // MessageLock.Release; // end; end; Edit5.Text:= ''; end; procedure TClientMainForm.actRoomToggleMembersExecute(Sender: TObject); begin Panel4.Visible:= not Panel4.Visible; end; procedure TClientMainForm.actUpdateGameDetailExecute(Sender: TObject); var s: Integer; f: Boolean; i: Integer; begin PushDebugMsg(AnsiString('actUpdateGameDetailExecute.')); Client.Game.Lock.Acquire; try s:= Client.Game.VisibleSlot; if s < 0 then Exit; f:= s = Client.Game.OurSlot; Label22.Text:= string(Client.Game.Slots[s].Name); Glyph1.ImageIndex:= Client.Game.Slots[s].Dice[0]; Glyph2.ImageIndex:= Client.Game.Slots[s].Dice[1]; Glyph3.ImageIndex:= Client.Game.Slots[s].Dice[2]; Glyph4.ImageIndex:= Client.Game.Slots[s].Dice[3]; Glyph5.ImageIndex:= Client.Game.Slots[s].Dice[4]; for i:= 1 to 5 do if i in Client.Game.Slots[s].Keepers then GridPanelLayout1.ControlCollection.Items[i - 1].Row:= 1 else GridPanelLayout1.ControlCollection.Items[i - 1].Row:= 0; if f then if Client.Game.RollNo = 3 then actGameRoll.Text:= 'Can''t Roll' else actGameRoll.Text:= 'Roll ' + IntToStr(Client.Game.RollNo + 1) + '/3' else actGameRoll.Text:= 'Rolling'; Label20.Text:= IntToStr(Client.Game.Slots[s].Score); GridPanelLayout1.Enabled:= f; StringGrid1.Enabled:= f; Button9.Enabled:= f; actGameRoll.Enabled:= f and not (Client.Game.RollNo = 3); finally Client.Game.Lock.Release; end; end; procedure TClientMainForm.actUpdateGameJoinExecute(Sender: TObject); begin PushDebugMsg(AnsiString('actUpdateGameJoinExecute.')); actGameJoin.Text:= 'Part'; actGameJoin.Tag:= 1; Edit6.Enabled:= False; Edit8.Enabled:= False; Memo6.Lines.Clear; Client.Game.Lock.Acquire; try Client.Game.GameHaveSpc:= True; finally Client.Game.Lock.Release; end; end; procedure TClientMainForm.actUpdateGameLogExecute(Sender: TObject); var p: Integer; s, u, r: string; f: Boolean; // w: Boolean; begin f:= GameLog.QueueSize > 0; Client.Game.Lock.Acquire; try while GameLog.QueueSize > 0 do begin s:= string(GameLog.PopItem); if (s[Low(string)] = '<') or (s[Low(string)] = '>') then begin if not Client.Game.GameHaveSpc then Memo6.Lines.Add(''); Memo6.Lines.Add(s); Memo6.Lines.Add(''); Client.Game.GameLastSpeak:= ''; Client.Game.GameHaveSpc:= True; end else begin s:= Copy(s, Low(string) + 1, MaxInt); p:= Pos(' ', s); r:= Copy(s, Low(string), p - Low(string)); s:= Copy(s, p + 1, MaxInt); p:= Pos(' ', s); u:= Copy(s, Low(string), p - Low(string)); s:= Copy(s, p + 1, MaxInt); if CompareText(u, Client.Game.GameLastSpeak) <> 0 then begin Client.Game.GameLastSpeak:= u; Memo6.Lines.Add(u + ':'); end; Memo6.Lines.Add(#9 + s); Client.Game.GameHaveSpc:= False; end; end; finally Client.Game.Lock.Release; end; if f then Memo6.ScrollBy(0, MaxInt); end; procedure TClientMainForm.actUpdateGamePartExecute(Sender: TObject); begin PushDebugMsg(AnsiString('actUpdateGamePartExecute.')); actGameJoin.Text:= 'Join'; actGameJoin.Tag:= 0; Edit6.Enabled:= True; Edit8.Enabled:= True; Edit8.Text:= ''; TabControl4.ActiveTab:= TabItem9; end; procedure TClientMainForm.actUpdateNameExecute(Sender: TObject); begin Edit2.Text:= string(Client.Name); end; procedure TClientMainForm.actUpdateRoomJoinExecute(Sender: TObject); begin PushDebugMsg(AnsiString('actUpdateRoomJoinExecute.')); actRoomJoin.Text:= 'Part'; actRoomJoin.Tag:= 1; Edit4.Enabled:= False; Edit7.Enabled:= False; end; procedure TClientMainForm.actUpdateRoomLogExecute(Sender: TObject); var p: Integer; s, u, r: string; f: Boolean; w: Boolean; begin f:= RoomLog.QueueSize > 0; Client.Game.Lock.Acquire; try while RoomLog.QueueSize > 0 do begin s:= string(RoomLog.PopItem); if (s[Low(string)] = '<') or (s[Low(string)] = '>') then begin if not Client.Game.RoomHaveSpc then Memo4.Lines.Add(''); Memo4.Lines.Add(s); Memo4.Lines.Add(''); Client.Game.LastSpeak:= ''; Client.Game.RoomHaveSpc:= True; end else begin w:= s[Low(string)] = '!'; s:= Copy(s, Low(string) + 1, MaxInt); if not w then begin p:= Pos(' ', s); r:= Copy(s, Low(string), p - Low(string)); s:= Copy(s, p + 1, MaxInt); end; p:= Pos(' ', s); u:= Copy(s, Low(string), p - Low(string)); s:= Copy(s, p + 1, MaxInt); if w then u:= u + ' whispers'; if CompareText(u, Client.Game.LastSpeak) <> 0 then begin Client.Game.LastSpeak:= u; Memo4.Lines.Add(u + ':'); end; Memo4.Lines.Add(#9 + s); Client.Game.RoomHaveSpc:= False; end; end; finally Client.Game.Lock.Release; end; if f then Memo4.ScrollBy(0, MaxInt); end; procedure TClientMainForm.actUpdateRoomPartExecute(Sender: TObject); begin PushDebugMsg(AnsiString('actUpdateRoomPartExecute.')); actRoomJoin.Text:= 'Join'; actRoomJoin.Tag:= 0; Edit4.Enabled:= True; Edit7.Enabled:= True; Edit7.Text:= ''; end; procedure TClientMainForm.actUpdateServerExecute(Sender: TObject); begin PushDebugMsg(AnsiString('actUpdateServerExecute.')); Edit3.Text:= string(Client.Server.Name + AnsiString(' ') + Client.Server.Host + AnsiString(' ') + Client.Server.version); end; procedure TClientMainForm.DoConnect; begin {$IFNDEF ANDROID} DebugLock.Acquire; try if Assigned(DebugFile) then DebugFile.Destroy; DebugFile:= TFileStream.Create(Edit2.Text + '.log', fmCreate); finally DebugLock.Release; end; {$ENDIF} PushDebugMsg(AnsiString('DoConnect.')); Client.Connection.OnConnected:= IdTCPClient1Connected; Client.Connection.OnDisconnected:= IdTCPClient1Disconnected; Client.Connection.Host:= Edit1.Text; Client.Connection.Port:= 7632; actConnectConnect.Text:= 'Disconnect'; Client.Connection.Connect; actUpdateRoomPartExecute(Self); actUpdateGamePartExecute(Self); end; procedure TClientMainForm.DoDisconnect; begin PushDebugMsg(AnsiString('DoDisconnect.')); Client.Game.Lock.Acquire; try // Client.Connection:= nil; SetLength(Client.InputBuffer, 0); finally Client.Game.Lock.Release; end; Client.Connection.OnDisconnected:= nil; Client.Connection.Disconnect; PushDebugMsg(AnsiString('Discarding read message queue.')); // MessageLock.Acquire; // try while ReadMessages.QueueSize > 0 do ReadMessages.PopItem.Free; // finally // MessageLock.Release; // end; ListMessages.Clear; actConnectConnect.Text:= 'Connect'; Edit3.Text:= ''; Client.Game.Lock.Acquire; try Client.Game.WasConnected:= False; Client.Game.LostConnection:= False; finally Client.Game.Lock.Release; end; end; procedure TClientMainForm.Edit4KeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if key = vkReturn then begin Key:= 0; actRoomJoin.Execute; end; end; procedure TClientMainForm.Edit5KeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if Key = vkReturn then begin Key:= 0; actRoomSend.Execute; end; end; procedure TClientMainForm.Edit7KeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if key = vkReturn then begin Key:= 0; actRoomJoin.Execute; end; end; procedure TClientMainForm.FormCreate(Sender: TObject); var i: TScoreLocation; procedure CorrectRowSize(AGridPanel: TGridPanelLayout; ASize: Integer); var i: Integer; begin for i:= 0 to AGridPanel.RowCollection.Count - 1 do AGridPanel.RowCollection[i].Value:= ASize; AGridPanel.Height:= AGridPanel.RowCollection.Count * ASize + 2; end; begin { This defines the default active tab at runtime } TabControl1.ActiveTab := TabItem1; // Client.Connection:= IdTCPClient1; Client.Game.RoomHaveSpc:= True; Client.Game.GameHaveSpc:= True; Client.Game.ConnHaveSpc:= True; for i:= slAces to slSixes do StringGrid1.Cells[0, Ord(i)]:= ARR_LIT_NAME_SCORELOC[i] + ':'; StringGrid1.Cells[0, 9]:= ARR_LIT_NAME_SCORELOC[slUpperBonus] + ':'; for i:= slThreeKind to slChance do StringGrid1.Cells[2, Ord(i) - Ord(slThreeKind)]:= ARR_LIT_NAME_SCORELOC[i] + ':'; StringGrid1.Cells[2, 8]:= ARR_LIT_NAME_SCORELOC[slYahtzeeBonus1] + ':'; StringGrid1.Cells[2, 9]:= 'Bonus Score:'; GridPanelLayout3.ControlCollection[1].ColumnSpan:= 3; GridPanelLayout3.ControlCollection[3].ColumnSpan:= 2; GridPanelLayout3.ControlCollection[7].ColumnSpan:= 3; {$IFDEF ANDROID} // CorrectRowSize(GridPanelLayout1, 40); CorrectRowSize(GridPanelLayout2, 32); CorrectRowSize(GridPanelLayout3, 40); CorrectRowSize(GridPanelLayout4, 40); CorrectRowSize(GridPanelLayout5, 40); Button1.Height:= 32; Button2.Height:= 32; Button3.Height:= 32; Button4.Height:= 32; Button5.Height:= 32; Button6.Height:= 32; Button7.Height:= 32; Button8.Height:= 32; Button9.Height:= 32; Label1.Height:= 32; Label2.Height:= 32; Label3.Height:= 32; Label4.Height:= 32; Label5.Height:= 32; Label6.Height:= 32; Label7.Height:= 32; Label8.Height:= 32; Label9.Height:= 32; Label10.Height:= 32; Label11.Height:= 32; Label12.Height:= 32; Label13.Height:= 32; Label14.Height:= 32; Label15.Height:= 32; Label16.Height:= 32; Label17.Height:= 32; Label18.Height:= 32; Label19.Height:= 32; Label20.Height:= 32; Label21.Height:= 32; Label22.Height:= 32; StringGrid1.OnMouseUp:= nil; StringGrid1.RowHeight:= 32; StringGrid1.Height:= StringGrid1.RowCount * 32; {$ELSE} TabItem1.StyleLookup:= 'TabItem1Style1'; TabItem2.StyleLookup:= 'TabItem1Style1'; TabItem3.StyleLookup:= 'TabItem1Style1'; TabItem4.StyleLookup:= 'TabItem1Style1'; {$ENDIF} end; procedure TClientMainForm.FormDestroy(Sender: TObject); begin Client.Game.Lock.Acquire; try if Client.Game.WasConnected then Client.Connection.Disconnect; finally Client.Game.Lock.Release; end; end; procedure TClientMainForm.FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if Key = vkHardwareBack then begin if (TabControl1.ActiveTab = TabItem1) and (TabControl2.ActiveTab = TabItem6) then begin TabControl2.Previous; Key := 0; end; end; end; procedure TClientMainForm.GestureDone(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean); begin case EventInfo.GestureID of sgiLeft: begin if TabControl1.ActiveTab <> TabControl1.Tabs[TabControl1.TabCount - 1] then TabControl1.ActiveTab := TabControl1.Tabs[TabControl1.TabIndex + 1]; Handled := True; end; sgiRight: begin if TabControl1.ActiveTab <> TabControl1.Tabs[0] then TabControl1.ActiveTab := TabControl1.Tabs[TabControl1.TabIndex - 1]; Handled := True; end; end; end; procedure TClientMainForm.IdTCPClient1Connected(Sender: TObject); begin PushDebugMsg(AnsiString('Connected to server.')); Client.Game.Lock.Acquire; try Client.Game.WasConnected:= Client.Connection.Connected; Client.Game.LostConnection:= False; // MessageLock.Acquire; // try // Client.Connection:= Client.Connection; Client.Name:= AnsiString(Edit2.Text); // finally // MessageLock.Release; // end; finally Client.Game.Lock.Release; end; end; procedure TClientMainForm.IdTCPClient1Disconnected(Sender: TObject); begin PushDebugMsg(AnsiString('Disconnected from server.')); DoDisconnect; end; procedure TClientMainForm.ListBoxItem1Click(Sender: TObject); var s: Integer; f: Boolean; begin PushDebugMsg(AnsiString('ListBoxItem1Click.')); f:= False; s:= (Sender as TListBoxItem).Tag; Client.Game.Lock.Acquire; try if (Client.Game.State > gsPreparing) and (Client.Game.Slots[s].State > psPreparing) then begin f:= True; Client.Game.VisibleSlot:= s; end; finally Client.Game.Lock.Release; end; if f then begin actUpdateGameDetail.Execute; if TabControl4.ActiveTab <> TabControl4.Tabs[TabControl4.TabCount - 1] then TabControl4.Next; end; end; procedure TClientMainForm.SpeedButton10Click(Sender: TObject); var b: TSpeedButton; r: Integer; m: TMessage; d: TDieSet; begin PushDebugMsg(AnsiString('SpeedButton10Click.')); // if WaitKeeper then // Exit; // // WaitKeeper:= True; b:= Sender as TSpeedButton; r:= GridPanelLayout1.ControlCollection.Items[b.Tag].Row; r:= (r + 1) mod 2; // GridPanelLayout1.ControlCollection.Items[b.Tag].Row:= r; Client.Game.Lock.Acquire; try if Client.Game.VisibleSlot = Client.Game.OurSlot then begin d:= Client.Game.Slots[Client.Game.OurSlot].Keepers; if r = 0 then Exclude(d, b.Tag + 1) else Include(d, b.Tag + 1); m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $09; SetLength(m.Data, 3); m.Data[0]:= Client.Game.OurSlot; m.Data[1]:= b.Tag + 1; m.Data[2]:= r; // MessageLock.Acquire; // try SendMessages.PushItem(m); // finally // MessageLock.Release; // end; end finally Client.Game.Lock.Release; end; end; procedure TClientMainForm.StringGrid1DrawColumnCell(Sender: TObject; const Canvas: TCanvas; const Column: TColumn; const Bounds: TRectF; const Row: Integer; const Value: TValue; const State: TGridDrawStates); var r: Word; s: string; n: TScoreLocation; f: Boolean; p: Boolean; b: TRectF; begin if (Column = StringColumn1) or (Column = StringColumn3) then begin Canvas.Fill.Color:= TAlphaColorRec.MedGray; Canvas.Fill.Kind:= TBrushKind.Solid; Canvas.FillRect(Bounds, 0, 0, AllCorners, 1, TCornerType.Round); Canvas.Fill.Color:= TAlphaColorRec.White; Canvas.FillText(Bounds, StringGrid1.Cells[Column.Index, Row], False, 1, [], TTextAlign.Leading, TTextAlign.Center); end else begin b:= Bounds; if State <> [] then Canvas.Fill.Color:= TAlphaColorRec.Lightblue else Canvas.Fill.Color:= TAlphaColorRec.White; Canvas.StrokeThickness:= 1; Canvas.Stroke.Thickness:= 1; Canvas.Stroke.Kind:= TBrushKind.Solid; Canvas.Stroke.Color:= TAlphaColorRec.Lightgray; Canvas.Fill.Kind:= TBrushKind.Solid; Canvas.FillRect(b, 0, 0, AllCorners, 1, TCornerType.Round); Canvas.DrawRect(b, 0, 0, AllCorners, 1, TCornerType.Round); b.Inflate(-1, -1); Canvas.StrokeThickness:= 0; Canvas.Stroke.Thickness:= 0; f:= False; n:= slAces; if Column = StringColumn2 then begin if Row = 9 then begin n:= slUpperBonus; f:= True; end else if Row < 6 then begin n:= TScoreLocation(Row); f:= True; end; end; if Column = StringColumn4 then if Row < 7 then begin n:= TScoreLocation(Ord(slThreeKind) + Row); f:= True end else if Row in [8, 9] then begin n:= slYahtzeeBonus1; f:= True; end; r:= VAL_KND_SCOREINVALID; p:= False; if f then begin Client.Game.Lock.Acquire; try if n = slYahtzeeBonus1 then begin r:= VAL_KND_SCOREINVALID; s:= ''; if Client.Game.Slots[Client.Game.VisibleSlot].Sheet[n] <> VAL_KND_SCOREINVALID then begin if Row = 8 then s:= 'X ' else r:= Client.Game.Slots[Client.Game.VisibleSlot].Sheet[n]; if Client.Game.Slots[Client.Game.VisibleSlot].Sheet[slYahtzeeBonus2] <> VAL_KND_SCOREINVALID then if Row = 8 then s:= s + 'X ' else r:= r + Client.Game.Slots[Client.Game.VisibleSlot].Sheet[n]; if Client.Game.Slots[Client.Game.VisibleSlot].Sheet[slYahtzeeBonus3] <> VAL_KND_SCOREINVALID then if Row = 8 then s:= s + 'X ' else r:= r + Client.Game.Slots[Client.Game.VisibleSlot].Sheet[n]; end; if [slYahtzeeBonus1..slYahtzeeBonus3] * Client.Game.PreviewLoc <> [] then begin p:= True; if r = VAL_KND_SCOREINVALID then begin r:= 100; s:= s + 'X '; end else begin Inc(r, 100); s:= s + 'X '; end; end; if Row = 9 then if r = VAL_KND_SCOREINVALID then s:= '' else s:= IntToStr(r); end else begin r:= Client.Game.Slots[Client.Game.VisibleSlot].Sheet[n]; if Client.Game.VisibleSlot = Client.Game.OurSlot then if n in Client.Game.PreviewLoc then begin r:= Client.Game.Preview[n]; p:= True; end; end; finally Client.Game.Lock.Release; end; end; if n <> slYahtzeeBonus1 then if r = VAL_KND_SCOREINVALID then s:= '' else s:= IntToStr(r); if p then Canvas.Fill.Color:= TAlphaColorRec.Red else Canvas.Fill.Color:= TAlphaColorRec.Black; Canvas.FillText(b, s, False, 1, [], TTextAlign.Trailing, TTextAlign.Center); end; end; procedure TClientMainForm.StringGrid1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); var m: TMessage; begin PushDebugMsg(AnsiString('StringGrid1MouseUp.')); if Button = TMouseButton.mbLeft then begin Client.Game.Lock.Acquire; try if Client.Game.SelScore then begin FillChar(Client.Game.Preview, SizeOf(TScoreSheet), $FF); Client.Game.PreviewLoc:= []; m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $0A; SetLength(m.Data, 2); m.Data[0]:= Client.Game.OurSlot; m.Data[1]:= Ord(Client.Game.SelScoreLoc); // MessageLock.Acquire; // try SendMessages.PushItem(m); // finally // MessageLock.Release; // end; end; finally Client.Game.Lock.Release; end; end; end; procedure TClientMainForm.StringGrid1SelectCell(Sender: TObject; const ACol, ARow: Integer; var CanSelect: Boolean); begin PushDebugMsg(AnsiString('StringGrid1SelectCell.')); Client.Game.Lock.Acquire; try if ACol in [0, 2] then CanSelect:= False else if ACol = 1 then begin CanSelect:= ARow < 6; if CanSelect then Client.Game.SelScoreLoc:= TScoreLocation(ARow); end else begin CanSelect:= ARow < 7; if CanSelect then Client.Game.SelScoreLoc:= TScoreLocation(Ord(slThreeKind) + ARow); end; Client.Game.SelScore:= CanSelect; finally Client.Game.Lock.Release; end; {$IFDEF ANDROID} StringGrid1Tap(Sender, PointF(0, 0)); {$ENDIF} end; procedure TClientMainForm.StringGrid1Tap(Sender: TObject; const Point: TPointF); var m: TMessage; begin Client.Game.Lock.Acquire; try if Client.Game.SelScore then begin FillChar(Client.Game.Preview, SizeOf(TScoreSheet), $FF); Client.Game.PreviewLoc:= []; m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $0A; SetLength(m.Data, 2); m.Data[0]:= Client.Game.OurSlot; m.Data[1]:= Ord(Client.Game.SelScoreLoc); // MessageLock.Acquire; // try SendMessages.PushItem(m); // finally // MessageLock.Release; // end; end; finally Client.Game.Lock.Release; end; end; procedure TClientMainForm.TabControl4Change(Sender: TObject); begin if TabControl4.ActiveTab <> TabItem11 then begin CheckBox1.IsChecked:= False; end; end; procedure TClientMainForm.Timer1Timer(Sender: TObject); begin while DebugMsgs.QueueSize > 0 do Memo1.Lines.Add(string(DebugMsgs.PopItem)); while ClientLog.QueueSize > 0 do Memo2.Lines.Add(string(ClientLog.PopItem)); actUpdateRoomLog.Execute; actUpdateGameLog.Execute; Client.Game.Lock.Acquire; try finally Client.Game.Lock.Release; end; Client.Game.Lock.Acquire; try if ReadMessages.QueueSize > 0 then if Client.Game.WasConnected then Client.ExecuteMessages; // else // begin // PushDebugMsg(AnsiString('Discarding read message queue.')); // // while ReadMessages.QueueSize > 0 do // ReadMessages.PopItem.Free; // end; finally Client.Game.Lock.Release; end; Client.Game.Lock.Acquire; try if Client.Game.WasConnected and Client.Game.LostConnection then begin PushDebugMsg(AnsiString('Caught server disconnect.')); DoDisconnect; end; finally Client.Game.Lock.Release; end; end; procedure TClientMainForm.ToolBar3KeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if Key = vkRight then begin Key:= 0; TabControl3.Next; end else if Key = vkLeft then begin Key:= 0; TabControl3.Previous; end; end; procedure TClientMainForm.UpdateGameSlotState(AGameState: TGameState; ASlot: Integer); var l: TListBoxItem; begin PushDebugMsg(AnsiString('UpdateGameSlotState.')); case ASlot of 0: l:= ListBoxItem1; 1: l:= ListBoxItem2; 2: l:= ListBoxItem3; 3: l:= ListBoxItem4; 4: l:= ListBoxItem5; 5: l:= ListBoxItem6; else l:= nil; end; Assert(Assigned(l), 'Failure in Update Game Slot State logic'); l.ImageIndex:= Ord(Client.Game.Slots[ASlot].State); if Client.Game.Slots[ASlot].State > psNone then l.Text:= string(Client.Game.Slots[ASlot].Name) else l.Text:= ''; case Client.Game.Slots[ASlot].State of psNone: if AGameState >= gsPreparing then l.ItemData.Detail:= '' else l.ItemData.Detail:= 'Available for Player'; psIdle: l.ItemData.Detail:= 'Not Yet Ready'; psReady: l.ItemData.Detail:= 'Waiting for all Players'; psPreparing: l.ItemData.Detail:= 'Waiting for First Roll'; psWaiting..psWinner: if (Client.Game.Slots[ASlot].State = psWaiting) and (Client.Game.Round = 0) then l.ItemData.Detail:= 'Rolled: ' + IntToStr(Client.Game.Slots[ASlot].FirstRoll) else l.ItemData.Detail:= 'Score: ' + IntToStr(Client.Game.Slots[ASlot].Score); else l.ItemData.Detail:= ''; end; end; procedure TClientMainForm.UpdateOurState; begin PushDebugMsg(AnsiString('UpdateOurState.')); if Client.Game.State > gsPreparing then Label15.Text:= IntToSTr(Client.Game.Round) else Label15.Text:= 'Game Not Started'; if (Client.Game.OurSlot = -1) or (Client.Game.Slots[Client.Game.OurSlot].State in [psNone, psWaiting]) then begin actGameControl.Tag:= 0; actGameControl.Text:= 'Waiting'; end else if Client.Game.Slots[Client.Game.OurSlot].State = psIdle then begin actGameControl.Tag:= 1; actGameControl.Text:= 'Ready'; end else if Client.Game.Slots[Client.Game.OurSlot].State = psReady then begin actGameControl.Tag:= 2; actGameControl.Text:= 'Not Ready'; end else if Client.Game.Slots[Client.Game.OurSlot].State = psPreparing then begin actGameControl.Tag:= 3; actGameControl.Text:= 'Roll for First'; end end; end.
{ Some routines for string handling on a higher level than those provided by the RTS. Copyright (C) 1999-2005 Free Software Foundation, Inc. Author: Frank Heckenbach <frank@pascal.gnu.de> This file is part of GNU Pascal. GNU Pascal 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, or (at your option) any later version. GNU Pascal 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 GNU Pascal; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, if you link this file with files compiled with a GNU compiler to produce an executable, this does not cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. } {$gnu-pascal,I-} {$if __GPC_RELEASE__ < 20030303} {$error This unit requires GPC release 20030303 or newer.} {$endif} unit StringUtils; interface uses GPC; { Various routines } { Appends Source to s, truncating the result if necessary. } procedure AppendStr (var s: String; const Source: String); { Cuts s to MaxLength characters. If s is already MaxLength characters or shorter, it doesn't change anything. } procedure StrCut (var s: String; MaxLength: Integer); { Returns the number of disjoint occurences of SubStr in s. Returns 0 if SubStr is empty. } function StrCount (const SubStr: String; s: String): Integer; { Returns s, with all disjoint occurences of Source replaced by Dest. } function StrReplace (const s, Source, Dest: String) = Result: TString; { Sets of characters accepted for `True' and `False' by Char2Boolean and StrReadBoolean. } var CharactersTrue : CharSet = ['Y', 'y']; CharactersFalse: CharSet = ['N', 'n']; { If ch is an element of CharactersTrue, Dest is set to True, otherwise if it is an element of CharactersFalse, Dest is set to False. In both cases True is returned. If ch is not an element of either set, Dest is set to False and False is returned. } function Char2Boolean (ch: Char; var Dest: Boolean): Boolean; attribute (ignorable); { Converts a digit character to its numeric value. Handles every base up to 36 (0 .. 9, a .. z, upper and lower case recognized). Returns -1 if the character is not a digit at all. If you want to use it for a base < 36, you have to check if the result is smaller than the base and not equal to -1. } function Char2Digit (ch: Char): Integer; { Encode a string in a printable format (quoted printable). All occurences of EscapeChar within the string are encoded. If QuoteHigh is True, all characters above the ASCII range are encoded as well (required in "7 bit" environments, as per several RFCs). `=' is always encoded, as required for proper decoding, as are all characters below space (control characters), so if you don't need an escape char yourself, you can pass #0 for EscapeChar. } function QuoteStringEscape (const s: String; EscapeChar: Char; QuoteHigh: Boolean): TString; { Encode a string in a printable format (quoted printable and surrounded with `"'). All occurences of `"' within the string are encoded, so the result string contains exactly two `"' characters (at the beginning and ending). This is useful to store arbitrary strings in text files while keeping them as readable as possible (which is the goal of the quoted printable encoding in general, see RFC 1521, section 5.1) and being able to read them back losslessly (with UnQuoteString). } function QuoteString (const s: String): TString; { Encode a string in a printable format suitable for StrReadEnum. All occurences of `,' within the string are encoded. } function QuoteEnum (const s: String): TString; { Decode a string encoded by QuoteString (removing the `"' and expanding quoted printable encoded characters). Returns True if successful and False if the string has an invalid form. A string returned by QuoteString is always valid. } function UnQuoteString (var s: String): Boolean; attribute (ignorable); { Decode a quoted-printable string (not enclosed in `"', unlike for UnQuoteString). Returns True if successful and False if the string has an invalid form. In the latter case, it still decodes as much as is valid, even after the error position. } function UnQPString (var s: String): Boolean; attribute (ignorable); { Quotes a string as done in shells, i.e. all special characters are enclosed in either `"' or `'', where `"', `$' and ``' are always enclosed in `'' and `'' is always enclosed in `"'. } function ShellQuoteString (const s: String) = Res: TString; { Replaces all tab characters in s with the appropriate amount of spaces, assuming tab stops at every TabSize columns. Returns True if successful and False if the expanded string would exceed the capacity of s. In the latter case, some, but not all of the tabs in s may have been expanded. } function ExpandTabs (var s: String; TabSize: Integer): Boolean; attribute (ignorable); { Returns s, with all occurences of C style escape sequences (e.g. `\n') replaced by the characters they mean. If AllowOctal is True, also octal character specifications (e.g. `\007') are replaced. If RemoveQuoteChars is True, any other backslashes are removed (e.g. `\*' -> `*' and `\\' -> `\'), otherwise they are kept, and also `\\' is left as two backslashes then. } function ExpandCEscapeSequences (const s: String; RemoveQuoteChars, AllowOctal: Boolean) = r: TString; { Routines for TPStrings } { Initialise a TPStrings variable, allocate Size characters for each element. This procedure does not dispose of any previously allocated storage, so if you use it on a previously used variable without freeing the storage yourself, this might cause memory leaks. } procedure AllocateTPStrings (var Strings: TPStrings; Size: Integer); { Clear all elements (set them to empty strings), does not free any storage. } procedure ClearTPStrings (var Strings: TPStrings); { Divide a string into substrings, using Separators as separator. A single trailing separator is ignored. Further trailing separators as well as any leading separators and multiple separators in a row produce empty substrings. } function TokenizeString (const Source: String; Separators: CharSet) = Res: PPStrings; { Divide a string into substrings, using SpaceCharacters as separators. The splitting is done according the usual rules of shells, using (and removing) single and double quotes and QuotingCharacter. Multiple, leading, and trailing separators are ignored. If there is an error, a message is stored in ErrMsg (if not Null), and nil is returned. nil is also returned (without an error message) if s is empty. } function ShellTokenizeString (const s: String; var ErrMsg: String) = Tokens: PPStrings; { String parsing routines } { All the following StrReadFoo functions behave similarly. They read items from a string s, starting at index i, to a variable Dest. They skip any space characters (spaces and tabs) by incrementing i first. They return True if successful, False otherwise. i is incremented accordingly if successful, otherwise i is left unchanged, apart from the skipping of space characters, and Dest is undefined. This behaviour makes it easy to use the functions in a row like this: i := 1; if StrReadInt (s, i, Size) and StrReadComma (s, i) and StrReadQuoted (s, i, Name) and StrReadComma (s, i) and ... StrReadReal (s, i, Angle) and (i > Length (s)) then ... (The check `i > Length (s)' is in case you don't want to accept trailing "garbage".) } { Just skip any space characters as described above. } procedure StrSkipSpaces (const s: String; var i: Integer); { Read a quoted string (as produced by QuoteString) from a string and unquote the result using UnQuoteString. It is considered failure if the result (unquoted) would be longer than the capacity of Dest. } function StrReadQuoted (const s: String; var i: Integer; var Dest: String): Boolean; attribute (ignorable); { Read a string delimited with Delimiter from a string and return the result with the delimiters removed. It is considered failure if the result (without delimiters) would be longer than the capacity of Dest. } function StrReadDelimited (const s: String; var i: Integer; var Dest: String; Delimiter: Char): Boolean; attribute (ignorable); { Read a word (consisting of anything but space characters and commas) from a string. It is considered failure if the result would be longer than the capacity of Dest. } function StrReadWord (const s: String; var i: Integer; var Dest: String): Boolean; attribute (ignorable); { Check that a certain string is contained in s (after possible space characters). } function StrReadConst (const s: String; var i: Integer; const Expected: String) = Res: Boolean; attribute (ignorable); { A simpler to use version of StrReadConst that expects a `,'. } function StrReadComma (const s: String; var i: Integer) = Res: Boolean; attribute (ignorable); { Read an integer number from a string. } function StrReadInt (const s: String; var i: Integer; var Dest: Integer): Boolean; attribute (ignorable); { Read a real number from a string. } function StrReadReal (const s: String; var i: Integer; var Dest: Real): Boolean; attribute (ignorable); { Read a Boolean value, represented by a single character from CharactersTrue or CharactersFalse (cf. Char2Boolean), from a string. } function StrReadBoolean (const s: String; var i: Integer; var Dest: Boolean): Boolean; attribute (ignorable); { Read an enumerated value, i.e., one of the entries of IDs, from a string, and stores the ordinal value, i.e., the index in IDs (always zero-based) in Dest. } function StrReadEnum (const s: String; var i: Integer; var Dest: Integer; const IDs: array of PString): Boolean; attribute (ignorable); { String hash table } const DefaultHashSize = 1403; type THash = Cardinal; PStrHashList = ^TStrHashList; TStrHashList = record Next: PStrHashList; s: PString; i: Integer; p: Pointer end; PStrHashTable = ^TStrHashTable; TStrHashTable (Size: Cardinal) = record CaseSensitive: Boolean; Table: array [0 .. Size - 1] of PStrHashList end; function HashString (const s: String): THash; function NewStrHashTable (Size: Cardinal; CaseSensitive: Boolean) = HashTable: PStrHashTable; procedure AddStrHashTable (HashTable: PStrHashTable; s: String; i: Integer; p: Pointer); procedure DeleteStrHashTable (HashTable: PStrHashTable; s: String); function SearchStrHashTable (HashTable: PStrHashTable; const s: String; var p: Pointer): Integer; { p may be Null } procedure StrHashTableUsage (HashTable: PStrHashTable; var Entries, Slots: Integer); procedure DisposeStrHashTable (HashTable: PStrHashTable); implementation procedure AppendStr (var s: String; const Source: String); begin Insert (Source, s, Length (s) + 1) end; procedure StrCut (var s: String; MaxLength: Integer); begin if Length (s) > MaxLength then Delete (s, MaxLength + 1) end; function StrCount (const SubStr: String; s: String): Integer; var c, p: Integer; begin if SubStr = '' then StrCount := 0 else begin c := 0; p := 1; repeat p := PosFrom (SubStr, s, p); if p <> 0 then begin Inc (c); Inc (p, Length (SubStr)) end until p = 0; StrCount := c end end; function StrReplace (const s, Source, Dest: String) = Result: TString; var c: Integer; begin Result := s; for c := Length (Result) - Length (Source) + 1 downto 1 do if Copy (Result, c, Length (Source)) = Source then begin Delete (Result, c, Length (Source)); Insert (Dest, Result, c) end end; function Char2Boolean (ch: Char; var Dest: Boolean): Boolean; begin Char2Boolean := True; Dest := False; if ch in CharactersTrue then Dest := True else if not (ch in CharactersFalse) then Char2Boolean := False end; function Char2Digit (ch: Char): Integer; begin case ch of '0' .. '9': Char2Digit := Ord (ch) - Ord ('0'); 'A' .. 'Z': Char2Digit := Ord (ch) - Ord ('A') + $a; 'a' .. 'z': Char2Digit := Ord (ch) - Ord ('a') + $a; else Char2Digit := -1 end end; function QuoteStringEscape (const s: String; EscapeChar: Char; QuoteHigh: Boolean): TString; var q, t: TString; i, n: Integer; Chars: set of Char; begin Chars := [#0 .. Pred (' '), EscapeChar, '=']; if QuoteHigh then Chars := Chars + [#127 .. High (Char)]; q := s; i := 0; repeat i := CharPosFrom (Chars, q, i + 1); if i = 0 then Break; n := Ord (q[i]); t := NumericBaseDigitsUpper[n div $10] + NumericBaseDigitsUpper[n mod $10]; Insert (t, q, i + 1); q[i] := '='; Inc (i, Length (t)) until False; QuoteStringEscape := q end; function QuoteString (const s: String): TString; begin QuoteString := '"' + QuoteStringEscape (s, '"', True) + '"' end; function QuoteEnum (const s: String): TString; begin QuoteEnum := QuoteStringEscape (s, ',', True) end; function UnQPString (var s: String): Boolean; var i, j: Integer; begin UnQPString := True; repeat i := Pos (' ' + NewLine, s); if i = 0 then Break; j := i; while (j > 1) and (s[j - 1] = ' ') do Dec (j); Delete (s, j, i - j + 1) until False; i := 0; repeat i := PosFrom ('=', s, i + 1); if i = 0 then Break; if (i <= Length (s) - 2) and (s[i + 1] in ['0' .. '9', 'A' .. 'F', 'a' .. 'f']) and (s[i + 2] in ['0' .. '9', 'A' .. 'F', 'a' .. 'f']) then begin s[i] := Chr ($10 * Char2Digit (s[i + 1]) + Char2Digit (s[i + 2])); Delete (s, i + 1, 2) end else if (i <= Length (s) - 1) and (s[i + 1] = NewLine) then begin Delete (s, i, 2); Dec (i) end else UnQPString := False until False end; function ShellQuoteString (const s: String) = Res: TString; var i: Integer; ch: Char; begin if (s <> '') and (s[1] = '''') then ch := '"' else ch := ''''; Res := ch; for i := 1 to Length (s) do begin if (s[i] = ch) or ((ch = '"') and (s[i] in ['$', '`'])) then begin Res := Res + ch; if ch = '''' then ch := '"' else ch := ''''; Res := Res + ch end; Res := Res + s[i] end; Res := Res + ch end; function UnQuoteString (var s: String): Boolean; begin UnQuoteString := False; if (Length (s) < 2) or (s[1] <> '"') or (s[Length (s)] <> '"') then Exit; Delete (s, 1, 1); Delete (s, Length (s)); UnQuoteString := UnQPString (s) end; function ExpandTabs (var s: String; TabSize: Integer): Boolean; const chTab = #9; var i, TabSpaces: Integer; begin ExpandTabs := True; repeat i := Pos (chTab, s); if i = 0 then Break; TabSpaces := TabSize - (i - 1) mod TabSize; if Length (s) + TabSpaces - 1 > High (s) then begin ExpandTabs := False; Break end; Delete (s, i, 1); Insert (StringOfChar (' ', TabSpaces), s, i) until False end; function ExpandCEscapeSequences (const s: String; RemoveQuoteChars, AllowOctal: Boolean) = r: TString; const chEsc = #27; var i, c, Digit, v: Integer; DelFlag: Boolean; begin r := s; i := 1; while i < Length (r) do begin if r[i] = '\' then begin DelFlag := True; case r[i + 1] of 'n': r[i + 1] := "\n"; 't': r[i + 1] := "\t"; 'r': r[i + 1] := "\r"; 'f': r[i + 1] := "\f"; 'b': r[i + 1] := "\b"; 'v': r[i + 1] := "\v"; 'a': r[i + 1] := "\a"; 'e', 'E': r[i + 1] := chEsc; 'x': begin v := 0; c := 2; while i + c <= Length (r) do begin Digit := Char2Digit (r[i + c]); if (Digit < 0) or (Digit >= $10) then Break; v := $10 * v + Digit; Inc (c) end; Delete (r, i + 1, c - 2); r[i + 1] := Chr (v) end; '0' .. '7' : if AllowOctal then begin v := 0; c := 1; repeat v := 8 * v + Ord (r[i + c]) - Ord ('0'); Inc (c) until (i + c > Length (r)) or (c > 3) or not (r[i + c] in ['0' .. '7']); Delete (r, i + 1, c - 2); r[i + 1] := Chr (v) end else DelFlag := False; else DelFlag := False end; if DelFlag or RemoveQuoteChars then Delete (r, i, 1) else Inc (i) end; Inc (i) end end; procedure AllocateTPStrings (var Strings: TPStrings; Size: Integer); var i: Cardinal; begin for i := 1 to Strings.Count do begin New (Strings[i], Max (1, Size)); Strings[i]^ := '' end end; procedure ClearTPStrings (var Strings: TPStrings); var i: Cardinal; begin for i := 1 to Strings.Count do Strings[i]^ := '' end; function TokenizeString (const Source: String; Separators: CharSet) = Res: PPStrings; var n: Integer; procedure ScanString; var i, TokenStart: Integer; begin n := 0; TokenStart := 1; for i := 1 to Length (Source) do if Source[i] in Separators then begin Inc (n); if Res <> nil then Res^[n] := NewString (Copy (Source, TokenStart, i - TokenStart)); TokenStart := i + 1 end; if TokenStart <= Length (Source) then { ignore trailing separator } begin Inc (n); if Res <> nil then Res^[n] := NewString (Copy (Source, TokenStart)) end end; begin Res := nil; ScanString; { count tokens } New (Res, n); if n <> 0 then ScanString { assign tokens } end; function ShellTokenizeString (const s: String; var ErrMsg: String) = Tokens: PPStrings; var TokenCount, i: Integer; Quoting: Char; SuppressEmptyToken, AddChar: Boolean; r: TString; procedure NextToken; var c: Integer; NewTokens: PPStrings; begin if (r = '') and SuppressEmptyToken then Exit; New (NewTokens, TokenCount + 1); for c := 1 to TokenCount do NewTokens^[c] := Tokens^[c]; NewTokens^[TokenCount + 1] := NewString (r); Dispose (Tokens); Tokens := NewTokens; Inc (TokenCount); r := ''; SuppressEmptyToken := True end; begin if @ErrMsg <> nil then ErrMsg := ''; Tokens := nil; TokenCount := 0; r := ''; SuppressEmptyToken := True; Quoting := #0; for i := 1 to Length (s) do begin AddChar := True; case s[i] of '"', '''': if Quoting = #0 then begin Quoting := s[i]; SuppressEmptyToken := False; AddChar := False end else if Quoting = s[i] then begin Quoting := #0; AddChar := False end; ' ' : if Quoting = #0 then begin NextToken; AddChar := False end; end; if AddChar then r := r + s[i] end; NextToken; if Quoting <> #0 then begin if @ErrMsg <> nil then ErrMsg := 'Missing ' + Quoting; DisposePPStrings (Tokens); Tokens := nil end end; procedure StrSkipSpaces (const s: String; var i: Integer); begin while (i >= 1) and (i <= Length (s)) and (s[i] in SpaceCharacters) do Inc (i) end; function StrReadQuoted (const s: String; var i: Integer; var Dest: String): Boolean; var j: Integer; s1: TString; begin StrReadQuoted := False; StrSkipSpaces (s, i); if (i < 1) or (i >= Length (s)) or (s[i] <> '"') then Exit; j := PosFrom ('"', s, i + 1); if j = 0 then Exit; s1 := s[i .. j]; i := j + 1; if not UnQuoteString (s1) or (Length (s1) > Dest.Capacity) then Exit; Dest := s1; StrReadQuoted := True end; function StrReadDelimited (const s: String; var i: Integer; var Dest: String; Delimiter: Char): Boolean; var j: Integer; begin StrReadDelimited := False; StrSkipSpaces (s, i); if (i < 1) or (i >= Length (s)) or (s[i] <> Delimiter) then Exit; j := PosFrom (Delimiter, s, i + 1); if (j = 0) or (j - i - 1 > Dest.Capacity) then Exit; Dest := Copy (s, i + 1, j - i - 1); i := j + 1; StrReadDelimited := True end; function StrReadWord (const s: String; var i: Integer; var Dest: String): Boolean; var j: Integer; begin StrReadWord := False; StrSkipSpaces (s, i); if (i < 1) or (i > Length (s)) then Exit; j := CharPosFrom (SpaceCharacters + [','], s, i + 1); if j = 0 then j := Length (s) + 1; if j - i > Dest.Capacity then Exit; Dest := Copy (s, i, j - i); i := j; StrReadWord := True end; function StrReadConst (const s: String; var i: Integer; const Expected: String) = Res: Boolean; begin StrSkipSpaces (s, i); Res := (i >= 1) and (Copy (s, i, Length (Expected)) = Expected); if Res then Inc (i, Length (Expected)) end; function StrReadComma (const s: String; var i: Integer) = Res: Boolean; begin StrSkipSpaces (s, i); Res := (i >= 1) and (i <= Length (s)) and (s[i] = ','); if Res then Inc (i) end; function StrReadInt (const s: String; var i: Integer; var Dest: Integer): Boolean; var j, e: Integer; begin StrReadInt := False; StrSkipSpaces (s, i); if (i < 1) or (i > Length (s)) then Exit; j := i + 1; { This is so Val gets at least one character. Also, a possible `-' sign is covered here, and does not have to be included in the set in the following statement. } while (j <= Length (s)) and (s[j] in ['0' .. '9']) do Inc (j); Val (s[i .. j - 1], Dest, e); if e <> 0 then Exit; i := j; StrReadInt := True end; function StrReadReal (const s: String; var i: Integer; var Dest: Real): Boolean; var j, e: Integer; begin StrReadReal := False; StrSkipSpaces (s, i); if (i < 1) or (i > Length (s)) then Exit; j := i + 1; { This is so Val gets at least one character. Also, a possible `-' sign is covered here, and does not have to be included in the set in the following statement. } while (j <= Length (s)) and (s[j] in ['0' .. '9', '+', '-', '.', 'E', 'e']) do Inc (j); Val (s[i .. j - 1], Dest, e); if e <> 0 then Exit; i := j; StrReadReal := True end; function StrReadBoolean (const s: String; var i: Integer; var Dest: Boolean): Boolean; begin StrReadBoolean := False; StrSkipSpaces (s, i); if (i < 1) or (i > Length (s)) or not Char2Boolean (s[i], Dest) then Exit; Inc (i); StrReadBoolean := True end; function StrReadEnum (const s: String; var i: Integer; var Dest: Integer; const IDs: array of PString): Boolean; var c, j: Integer; s1: TString; begin StrReadEnum := False; StrSkipSpaces (s, i); if (i < 1) or (i > Length (s)) then Exit; j := PosFrom (',', s, i); if j = 0 then j := Length (s) + 1; s1 := Copy (s, i, j - i); if not UnQPString (s1) then Exit; c := 0; while (c <= High (IDs)) and (s1 <> IDs[c]^) do Inc (c); if c > High (IDs) then Exit; Dest := c; i := j; StrReadEnum := True end; function HashString (const s: String): THash; var Hash, i: THash; begin Hash := Length (s); for i := 1 to Length (s) do {$local R-} Hash := Hash shl 2 + Ord (s[i]); {$endlocal} HashString := Hash end; function NewStrHashTable (Size: Cardinal; CaseSensitive: Boolean) = HashTable: PStrHashTable; var i: Cardinal; begin SetReturnAddress (ReturnAddress (0)); New (HashTable, Max (1, Size)); RestoreReturnAddress; HashTable^.CaseSensitive := CaseSensitive; for i := 0 to HashTable^.Size - 1 do HashTable^.Table[i] := nil end; procedure AddStrHashTable (HashTable: PStrHashTable; s: String; i: Integer; p: Pointer); var Hash: THash; pl: PStrHashList; begin if not HashTable^.CaseSensitive then LoCaseString (s); Hash := HashString (s) mod HashTable^.Size; SetReturnAddress (ReturnAddress (0)); New (pl); pl^.s := NewString (s); pl^.i := i; pl^.p := p; pl^.Next := HashTable^.Table[Hash]; HashTable^.Table[Hash] := pl; RestoreReturnAddress end; procedure DeleteStrHashTable (HashTable: PStrHashTable; s: String); var Hash: THash; pl: PStrHashList; ppl: ^PStrHashList; begin if not HashTable^.CaseSensitive then LoCaseString (s); Hash := HashString (s) mod HashTable^.Size; ppl := @HashTable^.Table[Hash]; while (ppl^ <> nil) and (ppl^^.s^ <> s) do ppl := @ppl^^.Next; if ppl^ <> nil then begin pl := ppl^; ppl^ := pl^.Next; Dispose (pl^.s); Dispose (pl) end end; function SearchStrHashTable (HashTable: PStrHashTable; const s: String; var p: Pointer): Integer; var Hash: THash; pl: PStrHashList; ps: ^const String; sl: String (Length (s)); begin if HashTable^.CaseSensitive then ps := @s else begin sl := LoCaseStr (s); ps := @sl end; Hash := HashString (ps^) mod HashTable^.Size; pl := HashTable^.Table[Hash]; while (pl <> nil) and (pl^.s^ <> ps^) do pl := pl^.Next; if pl = nil then begin if @p <> nil then p := nil; SearchStrHashTable := 0 end else begin if @p <> nil then p := pl^.p; SearchStrHashTable := pl^.i end end; procedure StrHashTableUsage (HashTable: PStrHashTable; var Entries, Slots: Integer); var i: Integer; pl: PStrHashList; begin Entries := 0; Slots := 0; for i := 0 to HashTable^.Size - 1 do begin pl := HashTable^.Table[i]; if pl <> nil then begin Inc (Slots); while pl <> nil do begin Inc (Entries); pl := pl^.Next end end end end; procedure DisposeStrHashTable (HashTable: PStrHashTable); var i: Cardinal; pl, pt: PStrHashList; begin for i := 0 to HashTable^.Size - 1 do begin pl := HashTable^.Table[i]; HashTable^.Table[i] := nil; while pl <> nil do begin pt := pl; pl := pl^.Next; Dispose (pt^.s); Dispose (pt) end end; Dispose (HashTable) end; end.
unit BootloaderDialog; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, Internal, Dialogs, JvDialogs, QTypes; ResourceString rsSelectBootloader = '-- Select Bootloader --'; rsConfigNone = '-- None --'; rsConfigBoot = '-- Configuration from Bootloader --'; rsConfigApp = '-- Configuration from Application --'; rsLoadFromFile = 'Load from file...'; type TBootloaderDlg = class(TForm) OKBtn: TButton; CancelBtn: TButton; OpenDialog: TJvOpenDialog; RadioGroup1: TRadioGroup; MCHPUSB: TRadioButton; HID: TRadioButton; VASCO: TRadioButton; FileSelectCB: TComboBox; RadioGroup2: TRadioGroup; AppSelectCB: TComboBox; RadioGroup3: TRadioGroup; ConfigSelectCB: TComboBox; GroupBox1: TGroupBox; RelocSelectCB: TComboBox; procedure BootloaderCheckClick(Sender: TObject); procedure SelectCBChange(Sender: TObject); procedure FormCreate(Sender: TObject); private FBootloaderType : string; function GetConfigIndex : integer; function GetFileName(Index : integer) : string; function GetIsResourceFile(Index : integer) : boolean; public property BootloaderType : string read FBootloaderType; property ConfigIndex : integer read GetConfigIndex; property FileName[Index : integer] : string read GetFileName; property IsResourceFile[Index : integer] : boolean read GetIsResourceFile; end; var BootloaderDlg: TBootloaderDlg; implementation {$R *.dfm} procedure TBootloaderDlg.BootloaderCheckClick(Sender: TObject); begin with FileSelectCB do begin Text := rsSelectBootloader; ItemIndex := -1; Items.Clear; end; with AppSelectCB do begin Text := ''; ItemIndex := -1; Items.Clear; Enabled := false; end; with ConfigSelectCB do begin Text := ''; ItemIndex := -1; Items.Clear; Enabled := false; end; if MCHPUSB.Checked then FBootloaderType := 'MCHPUSB' else if HID.Checked then FBootloaderType := 'HID' else if VASCO.Checked then FBootloaderType := 'VASCO' else exit; with FileSelectCB do begin InternalFAT.GetDirectoryInfo('BOOTLOADER.'+FBootloaderType, Items, true); Items.Add(rsLoadFromFile); end; with AppSelectCB do begin InternalFAT.GetDirectoryInfo('APPLICATION.'+FBootloaderType, Items, true); Items.Add(rsLoadFromFile); ItemIndex := 0; Enabled := true; end; with ConfigSelectCB do begin Items.Add(rsConfigNone); Items.Add(rsConfigBoot); Items.Add(rsConfigApp); InternalFAT.GetDirectoryInfo('CONFIG', Items, true); Items.Add(rsLoadFromFile); ItemIndex := 1; // Config from bootloader by default Enabled := true; end; end; procedure TBootloaderDlg.SelectCBChange(Sender: TObject); begin if not (Sender is TComboBox) then exit; with Sender as TComboBox do begin if (ItemIndex<>-1) and (ItemIndex = Items.Count-1) then begin if OpenDialog.Execute then with Items do begin if IndexOf(OpenDialog.FileName) = -1 then Insert(Items.Count-1, OpenDialog.FileName); ItemIndex := IndexOf(OpenDialog.FileName); end; end; end; OKBtn.Enabled := (FileSelectCB.ItemIndex >= 0); end; function TBootloaderDlg.GetConfigIndex : integer; begin result := ConfigSelectCB.ItemIndex; end; function TBootloaderDlg.GetFileName(Index : integer) : string; begin result := ''; case Index of 0 : with RelocSelectCB do begin result := Text; if IsResourceFile[Index] then result := PFileInfo(Items.Objects[ItemIndex]).SR.Name; end; 1 : with FileSelectCB do begin result := Text; if IsResourceFile[Index] then result := PFileInfo(Items.Objects[ItemIndex]).SR.Name; end; 2 : with AppSelectCB do begin result := Text; if IsResourceFile[Index] then result := PFileInfo(Items.Objects[ItemIndex]).SR.Name; end; 3 : with ConfigSelectCB do begin result := Text; if IsResourceFile[Index] then result := PFileInfo(Items.Objects[ItemIndex]).SR.Name; end; end; end; function TBootloaderDlg.GetIsResourceFile(Index : integer) : boolean; begin result := false; case Index of 0 : With RelocSelectCB do result := (ItemIndex >= 0) and (Items.Objects[ItemIndex] <> nil); 1 : With FileSelectCB do result := (ItemIndex >= 0) and (Items.Objects[ItemIndex] <> nil); 2 : With AppSelectCB do result := (ItemIndex >= 0) and (Items.Objects[ItemIndex] <> nil); 3 : With ConfigSelectCB do result := (ItemIndex >= 0) and (Items.Objects[ItemIndex] <> nil); end; end; procedure TBootloaderDlg.FormCreate(Sender: TObject); begin with RelocSelectCB do begin Items.Clear; InternalFAT.GetDirectoryInfo('RELOCATE', Items, true); Items.Add(rsLoadFromFile); ItemIndex := 0; end; end; end.
unit TraceportCodeToName; interface uses ExtCtrls, Classes, SysUtils; type TTrancportCode = class private StringList : TStringList; public Constructor Create; Function ConversionCodeToName(Value : String) : String; Class Function GetObject: TTrancportCode; end; implementation uses uDMclient; var TrancprotCode : TTrancportCode = nil; { TTrancportCode } function TTrancportCode.ConversionCodeToName(Value: String): String; var i : Integer; begin try for i := 0 to StringList.Count-1 do begin if StringList.Find(Value, i) = True then begin Result := StringList.Strings[i+1]; end; end; except Result := ''; end; end; constructor TTrancportCode.Create; begin StringList := TStringList.Create; with DMClient.ClientDataSet_EmpInfo do begin Close; Open; First; while not eof do begin StringList.Add(FieldByName('CODE').AsString); StringList.Add(FieldByName('NAME').AsString); Next; end; end; end; class function TTrancportCode.GetObject: TTrancportCode; begin if not Assigned(TrancprotCode) then TrancprotCode := TTrancportCode.Create; Result := TrancprotCode; end; end.
(** This module contains a class to manage the global options of the application. @Author David Hoyle @Version 1.0 @Date 05 Jan 2018 **) Unit ITHelper.GlobalOptions; Interface Uses Graphics, Classes, IniFiles, ToolsAPI, ITHelper.Interfaces, ITHelper.Types; Type (** A class to manage the gloabl options of the application. **) TITHGlobalOptions = Class(TInterfacedObject, IITHGlobalOptions) Strict Private FINIFileName : String; FFontName : Array [Low(TITHFontNames) .. High(TITHFontNames)] Of String; FFontColour : Array [Low(TITHFonts) .. High(TITHFonts)] Of TColor; FFontStyle : Array [Low(TITHFonts) .. High(TITHFonts)] Of TFontStyles; FSwitchToMessages : Boolean; FProjectGroupOps : TStringList; FZipEXE : String; FZipParameters : String; FGroupMessages : Boolean; FAutoScrollMessages: Boolean; FClearMessages : Integer; Strict Protected Procedure LoadSettings; Procedure SaveSettings; Function GetFontName(Const iFont: TITHFontNames): String; Procedure SetFontName(Const iFont: TITHFontNames; Const strValue: String); Function GetFontColour(Const iFont: TITHFonts): TColor; Procedure SetFontColour(Const iFont: TITHFonts; Const iValue: TColor); Function GetFontStyles(Const iFont: TITHFonts): TFontStyles; Procedure SetFontStyles(Const iFont: TITHFonts; Const iValue: TFontStyles); Function GetProjectGroupOps: TITHEnabledOptions; Procedure SetProjectGroupOps(Const Ops: TITHEnabledOptions); Function GetINIFileName : String; Function GetSwitchToMessages : Boolean; Procedure SetSwitchToMessages(Const boolValue : Boolean); Function GetZipEXE : String; Procedure SetZipEXE(Const strValue : String); Function GetZipParameters : String; Procedure SetZipParameters(Const strValue : String); Function GetGroupMessages : Boolean; Procedure SetGroupMessages(Const boolValue : Boolean); Function GetAutoScrollMessages : Boolean; Procedure SetAutoScrollMessages(Const boolValue : Boolean); Function GetClearMessages : Integer; Procedure SetClearMessages(Const iValue : Integer); Procedure ExceptionsMgs(Const strExceptionMsg: String); Procedure Save; Function ProjectOptions(Const Project: IOTAProject): IITHProjectOptions; Public Constructor Create; Destructor Destroy; Override; End; Implementation Uses Dialogs, ITHelper.TestingHelperUtils, SysUtils, ActnList, Windows, ITHelper.CommonFunctions, UITypes, Contnrs, ITHelper.ProjectOptions; Const (** A constant array of INI name prefixes for font information. **) strFontINIPrefixes: Array [Low(TITHFonts) .. High(TITHFonts)] Of String = ( 'MsgHeaderFont', 'MsgDefault', 'MsgSuccess', 'MsgFailure', 'MsgWarning' ); (** A constant array of INI font name prefixes for font information. **) strFontNameINIPrefixes: Array [Low(TITHFontNames) .. High(TITHFontNames)] Of String = ( 'HeaderFontName', 'ToolFontName' ); (** An INI Section name for general information. **) strSetupSection = 'Setup'; (** An INI Section name for message information. **) strMessagesSection = 'Messages'; (** An INI Section name for new project group information. **) strNewProjectGroupOptionsSection = 'NewProjectGroupOptions'; (** An INI Section name for project group information. **) strProjectGroupOptionsSection = 'ProjectGroupOptions'; (** An INI Section name for shortcut information. **) strShortcutsSection = 'Shortcuts'; (** An INI Key for the ZIP EXE **) strZIPEXEKey = 'ZIPEXE'; (** An INI Key for the ZIP Parmeters **) strZIPParametersKey = 'ZIPParameters'; (** An INI Key for the group messages **) strGroupMessagesKey = 'GroupMessages'; (** An INI Key for the auto scroll messages **) strAutoScrollMessagesKey = 'AutoScrollMessages'; (** An INI Key for the clear messages **) strClearMessagesKey = 'ClearMessages'; (** An INI Key for the colours **) strColourKey = 'Colour'; (** An INI Key for the font styles **) strStyleKey = 'Style'; (** An INI Key for the switch to message **) strSwitchToMessagesKey = 'SwitchToMessages'; (** An INI Key for the Enalbed **) strEnabledKey = 'Enabled'; (** An INI Key for the ITHelper extension **) strITHelperExt = '.ithelper'; { TGlobalOptions } (** A constructor for the TGlobalOptions class. @precon None. @postcon Loads the global settings from an INI file. **) Constructor TITHGlobalOptions.Create; Begin FINIFileName := BuildRootKey; FProjectGroupOps := TStringList.Create; LoadSettings; End; (** A destructor for the TGlobalOptions class. @precon None. @postcon Saves the global settings to an INI file. **) Destructor TITHGlobalOptions.Destroy; Begin SaveSettings; FProjectGroupOps.Free; Inherited Destroy; End; (** This method displays an exception message on the screen. @precon None. @postcon Displays an exception message on the screen. @param strExceptionMsg as a String as a constant **) Procedure TITHGlobalOptions.ExceptionsMgs(Const strExceptionMsg: String); Begin MessageDlg(strExceptionMsg, mtError, [mbOK], 0); End; (** This is a getter method for the AutoScrollMessages property. @precon None. @postcon Returns whether new messages should be scrolled to in the message window. @return a Boolean **) Function TITHGlobalOptions.GetAutoScrollMessages: Boolean; Begin Result := FAutoScrollMessages; End; (** This is a getter method for the ClearMessages property. @precon None. @postcon Returns the period in seconds after which whether messages should be cleared. @return an Integer **) Function TITHGlobalOptions.GetClearMessages: Integer; Begin Result := FClearMessages; End; (** This is a getter method for the FontColour property. @precon None. @postcon Returns the enumerated font colour. @param iFont as a TITHFonts as a constant @return a TColor **) Function TITHGlobalOptions.GetFontColour(Const iFont: TITHFonts): TColor; Begin Result := FFontColour[iFont]; End; (** This is a getter method for the FontName property. @precon None. @postcon Returns the enumerated font name. @param iFont as a TITHFontNames as a constant @return a String **) Function TITHGlobalOptions.GetFontName(Const iFont: TITHFontNames): String; Begin Result := FFontName[iFont]; End; (** This is a getter method for the FontStyles property. @precon None. @postcon Returns the enumerated font styles. @param iFont as a TITHFonts as a constant @return a TFontStyles **) Function TITHGlobalOptions.GetFontStyles(Const iFont: TITHFonts): TFontStyles; Begin Result := FFontStyle[iFont]; End; (** This is a getter method for the GroupMessages property. @precon None. @postcon Returns whether messages should be grouped. @return a Boolean **) Function TITHGlobalOptions.GetGroupMessages: Boolean; Begin Result := FGroupMessages; End; (** This is a getter method for the INIFileName property. @precon None. @postcon Returns the internal INI Filename. @return a String **) Function TITHGlobalOptions.GetINIFileName: String; Begin Result := FINIFileName; End; (** This is a getter method for the ProjectGroupOps property. @precon None. @postcon Returns the projectc group options. @return a TITHEnabledOptions **) Function TITHGlobalOptions.GetProjectGroupOps: TITHEnabledOptions; Const strSetupIniSubSection = '%s.Setup'; strEnabledOptionsKey = 'EnabledOptions'; Var PG : IOTAProjectGroup; strProjectGroup: String; INIFile : TMemIniFile; strSection : String; Ops : TITHEnabledOptions; iIndex : Integer; boolNeedSave : Boolean; Begin Result := []; PG := ProjectGroup; If PG = Nil Then Exit; strProjectGroup := ExtractFileName(PG.FileName); iIndex := FProjectGroupOps.IndexOf(strProjectGroup); If iIndex = -1 Then Begin // Migrate old settings INIFile := TMemIniFile.Create(FINIFileName); Try boolNeedSave := False; strSection := Format(strSetupIniSubSection, [strProjectGroup]); If INIFile.ValueExists(strSection, strEnabledKey) Then Begin If INIFile.ReadBool(strSection, strEnabledKey, True) Then Include(Result, eoGroupEnabled); INIFile.DeleteKey(strSection, strEnabledKey); boolNeedSave := True; End Else Include(Result, eoGroupEnabled); If INIFile.ValueExists(strSection, strEnabledOptionsKey) Then Begin Ops := [eoBefore, eoAfter, eoZip]; Result := Result + TITHEnabledOptions(Byte(INIFile.ReadInteger(strSection, strEnabledOptionsKey, Byte(Ops)))); FProjectGroupOps.AddObject(strProjectGroup, TObject(Byte(Result))); INIFile.DeleteKey(strSection, strEnabledOptionsKey); INIFile.EraseSection(strSection); boolNeedSave := True; End Else Begin Include(Result, eoBefore); Include(Result, eoAfter); Include(Result, eoZip); End; Include(Result, eoBuildVersionResource); Include(Result, eoCopyVersionInfo); Include(Result, eoIncrementBuild); If boolNeedSave Then INIFile.UpdateFile; Finally INIFile.Free; End; End Else Result := TITHEnabledOptions(Byte(FProjectGroupOps.Objects[iIndex])); End; (** This is a getter method for the SwitchToMessages property. @precon None. @postcon Returns whether the IDE should switch to the ITHelper messages after a successful compile. @return a Boolean **) Function TITHGlobalOptions.GetSwitchToMessages: Boolean; Begin Result := FSwitchToMessages; End; (** This is a getter method for the ZipEXE property. @precon None. @postcon Returns the ZipEXE filename. @return a String **) Function TITHGlobalOptions.GetZipEXE: String; Begin Result := FZipEXE; End; (** This is a getter method for the ZipParameters property. @precon None. @postcon Returns the Zip Parameters. @return a String **) Function TITHGlobalOptions.GetZipParameters: String; Begin Result := FZipParameters; End; (** This method loads the applications global settings from the main INI file. @precon None. @postcon Loads the applications global settings from the main INI file. **) Procedure TITHGlobalOptions.LoadSettings; Const strDefaultZipEXE = 'C:\Program Files\7-Zip\7Z.EXE'; iDefaultClearMsgInterval = 30; strDefaultZIPParamsKey = '-ouexrPyb @"$RESPONSEFILE$" "$ZIPFILE$"'; strDefaultFontName = 'Tahoma'; strDefaultFontColour = 'clBlack'; Var iFont : TITHFonts; iFontName: TITHFontNames; sl : TStringList; i : Integer; Ops : TITHEnabledOptions; A : TAction; iIndex : Integer; boolNeedsSaving : Boolean; iniFile : TMemIniFile; Begin boolNeedsSaving := False; iniFile := TMemIniFile.Create(FINIFileName); Try FZipEXE := iniFile.ReadString(strSetupSection, strZIPEXEKey, strDefaultZipEXE); FZipParameters := iniFile.ReadString(strSetupSection, strZIPParametersKey, strDefaultZIPParamsKey); FGroupMessages := iniFile.ReadBool(strSetupSection, strGroupMessagesKey, False); FAutoScrollMessages := iniFile.ReadBool(strSetupSection, strAutoScrollMessagesKey, True); FClearMessages := iniFile.ReadInteger(strSetupSection, strClearMessagesKey, iDefaultClearMsgInterval); For iFontName := Low(TITHFontNames) To High(TITHFontNames) Do FFontName[iFontName] := iniFile.ReadString(strMessagesSection, strFontNameINIPrefixes[iFontName], strDefaultFontName); For iFont := Low(TITHFonts) To High(TITHFonts) Do Begin FFontColour[iFont] := StringToColor(iniFile.ReadString(strMessagesSection, strFontINIPrefixes[iFont] + strColourKey, strDefaultFontColour)); FFontStyle[iFont] := TFontStyles(Byte(iniFile.ReadInteger(strMessagesSection, strFontINIPrefixes[iFont] + strStyleKey, 0))); End; FSwitchToMessages := iniFile.ReadBool(strMessagesSection, strSwitchToMessagesKey, True); // Project Group Options sl := TStringList.Create; Try iniFile.ReadSection(strNewProjectGroupOptionsSection, sl); For i := 0 To sl.Count - 1 Do Begin Ops := [eoAfter..eoIncrementBuild]; Ops := TITHEnabledOptions(Byte(iniFile.ReadInteger(strNewProjectGroupOptionsSection, sl[i], Byte(Ops)))); FProjectGroupOps.AddObject(sl[i], TObject(Byte(Ops))); End; iniFile.ReadSection(strProjectGroupOptionsSection, sl); For i := 0 To sl.Count - 1 Do Begin Ops := [eoBefore .. eoGroupEnabled]; Ops := TITHEnabledOptions(Byte(iniFile.ReadInteger(strProjectGroupOptionsSection, sl[i], Byte(Ops)))); Ops := Ops + [eoBuildVersionResource, eoCopyVersionInfo, eoIncrementBuild]; iIndex := FProjectGroupOps.IndexOf(sl[i]); If iIndex = -1 Then FProjectGroupOps.AddObject(sl[i], TObject(Byte(Ops))) Else FProjectGroupOps.Objects[iIndex] := TObject(Byte(Ops)); iniFile.DeleteKey(strProjectGroupOptionsSection, sl[i]); boolNeedsSaving := True; End; Finally sl.Free; End; // Action Shortcuts For i := 0 To Actions.Count - 1 Do If Actions[i] Is TAction Then Begin A := Actions[i] As TAction; A.ShortCut := iniFile.ReadInteger(strShortcutsSection, A.Name, A.ShortCut); End; If boolNeedsSaving Then iniFile.UpdateFile; Finally iniFile.Free; End; End; (** This method returns an ini file for the local project settings. If this file does not exist any settings from the main ini files are migrated to a new local project settings file. @precon Project must be a valid instance. @postcon Returns an ini file for the local project settings. If this file does not exist any settings from the main ini files are migrated to a new local project settings file. Reference returned needs to be freed by the caller. @param Project as an IOTAProject as a constant @return an IITHProjectOptions **) Function TITHGlobalOptions.ProjectOptions(Const Project: IOTAProject): IITHProjectOptions; Const strSections: Array [1 .. 5] Of String = (strSetupSection, 'Pre-Compilation', 'Post-Compilation', 'Zipping', 'Additional Zip Files'); Var strINIFileName : String; iniMain, iniProject: TMemIniFile; strProjectName : String; iSection : Integer; strSection : String; sl : TStringList; i : Integer; Begin strINIFileName := ChangeFileExt(Project.FileName, strITHelperExt); strProjectName := GetProjectName(Project); If Not FileExists(strINIFileName) Then Begin // Migrate settings from the main INI file to a local one iniMain := TMemIniFile.Create(GetINIFileName); Try iniProject := TMemIniFile.Create(strINIFileName); Try For iSection := Low(strSections) To High(strSections) Do Begin strSection := Format('%s.%s', [strProjectName, strSections[iSection]]); If iniMain.SectionExists(strSection) Then Begin sl := TStringList.Create; Try iniMain.ReadSection(strSection, sl); For i := 0 To sl.Count - 1 Do iniProject.WriteString(strSections[iSection], sl[i], iniMain.ReadString(strSection, sl[i], '')); Finally sl.Free; End; iniMain.EraseSection(strSection); End; End; iniProject.UpdateFile; Finally iniProject.Free; End; iniMain.UpdateFile; Finally iniMain.Free; End; End; Result := TITHProjectOptions.Create(strINIFileName, Project); End; (** A public method of the class to allow callers to save the global settings. @precon None. @postcon Saves the global settings. **) Procedure TITHGlobalOptions.Save; Begin SaveSettings; End; (** This method saves the applications global settings to the main INI file. @precon None. @postcon Saves the applications global settings to the main INI file. **) Procedure TITHGlobalOptions.SaveSettings; Var iFont : TITHFonts; iFontName: TITHFontNames; i : Integer; A : TAction; iniFile : TMemIniFile; Begin iniFile := TMemIniFile.Create(FINIFileName); Try iniFile.WriteString(strSetupSection, strZIPEXEKey, FZipEXE); iniFile.WriteString(strSetupSection, strZIPParametersKey, FZipParameters); iniFile.WriteBool(strSetupSection, strGroupMessagesKey, FGroupMessages); iniFile.WriteBool(strSetupSection, strAutoScrollMessagesKey, FAutoScrollMessages); iniFile.WriteInteger(strSetupSection, strClearMessagesKey, FClearMessages); For iFontName := Low(TITHFontNames) To High(TITHFontNames) Do iniFile.WriteString(strMessagesSection, strFontNameINIPrefixes[iFontName], FFontName[iFontName]); For iFont := Low(TITHFonts) To High(TITHFonts) Do Begin iniFile.WriteString(strMessagesSection, strFontINIPrefixes[iFont] + strColourKey, ColorToString(FFontColour[iFont])); iniFile.WriteInteger(strMessagesSection, strFontINIPrefixes[iFont] + strStyleKey, Byte(FFontStyle[iFont])); End; iniFile.WriteBool(strMessagesSection, strSwitchToMessagesKey, FSwitchToMessages); iniFile.EraseSection(strNewProjectGroupOptionsSection); For i := 0 To FProjectGroupOps.Count - 1 Do iniFile.WriteInteger(strNewProjectGroupOptionsSection, FProjectGroupOps[i], Integer(FProjectGroupOps.Objects[i])); For i := 0 To Actions.Count - 1 Do If Actions[i] Is TAction Then Begin A := Actions[i] As TAction; iniFile.WriteInteger(strSetupSection, A.Name, A.ShortCut); End; iniFile.UpdateFile; Finally iniFile.Free; End; End; (** This is a setter method for the AutoScrollMessages property. @precon None. @postcon Sets whether the message view should automatically scroll to the last message. @param boolValue as a Boolean as a constant **) Procedure TITHGlobalOptions.SetAutoScrollMessages(Const boolValue: Boolean); Begin If FAutoScrollMessages <> boolValue Then FAutoScrollMessages := boolValue; End; (** This is a setter method for the ClearMessages property. @precon None. @postcon Sets the number of seconds after which the message view can be cleared of existing ITHelper messages. @param iValue as an Integer as a constant **) Procedure TITHGlobalOptions.SetClearMessages(Const iValue: Integer); Begin If FClearMessages <> iValue Then FClearMessages := iValue; End; (** This is a setter method for the FontColour property. @precon None. @postcon Sets the font colour of the enumerated font. @param iFont as a TITHFonts as a constant @param iValue as a TColor as a constant **) Procedure TITHGlobalOptions.SetFontColour(Const iFont: TITHFonts; Const iValue: TColor); Begin FFontColour[iFont] := iValue; End; (** This is a setter method for the FontName property. @precon None. @postcon Sets the font name of the enumerated font. @param iFont as a TITHFontNames as a constant @param strValue as a String as a constant **) Procedure TITHGlobalOptions.SetFontName(Const iFont: TITHFontNames; Const strValue: String); Begin FFontName[iFont] := strValue; End; (** This is a setter method for the FontStyles property. @precon None. @postcon Sets the font styles of the enumerated font. @param iFont as a TITHFonts as a constant @param iValue as a TFontStyles as a constant **) Procedure TITHGlobalOptions.SetFontStyles(Const iFont: TITHFonts; Const iValue: TFontStyles); Begin FFontStyle[iFont] := iValue; End; (** This is a setter method for the GroupMessages property. @precon None. @postcon Sets whether the ITHelper messages should be grouped into their own message pane. @param boolValue as a Boolean as a constant **) Procedure TITHGlobalOptions.SetGroupMessages(Const boolValue: Boolean); Begin If FGroupMessages <> boolValue Then FGroupMessages := boolValue; End; (** This is a setter method for the ProjectGroupOps property. @precon None. @postcon Sets the project group options. @param Ops as a TITHEnabledOptions as a constant **) Procedure TITHGlobalOptions.SetProjectGroupOps(Const Ops: TITHEnabledOptions); Var PG : IOTAProjectGroup; strProjectGroup: String; iIndex : Integer; Begin PG := ProjectGroup; If PG = Nil Then Exit; strProjectGroup := ExtractFileName(PG.FileName); iIndex := FProjectGroupOps.IndexOf(strProjectGroup); If iIndex = -1 Then FProjectGroupOps.AddObject(strProjectGroup, TObject(Byte(Ops))) Else FProjectGroupOps.Objects[iIndex] := TObject(Byte(Ops)); End; (** This is a setter method for the SwitchToMessages property. @precon None. @postcon Sets whetherm after a successful compilation, the messages view with the ITHelper messages should be displayed. @param boolValue as a Boolean as a constant **) Procedure TITHGlobalOptions.SetSwitchToMessages(Const boolValue: Boolean); Begin If FSwitchToMessages <> boolValue Then FSwitchToMessages := boolValue; End; (** This is a setter method for the ZipEXE property. @precon None. @postcon Sets the Zip EXE Filename. @param strValue as a String as a constant **) Procedure TITHGlobalOptions.SetZipEXE(Const strValue: String); Begin If FZipEXE <> strValue Then FZipEXE := strValue; End; (** This is a setter method for the ZipParameters property. @precon None. @postcon Sets the Zip parameters. @param strValue as a String as a constant **) Procedure TITHGlobalOptions.SetZipParameters(Const strValue: String); Begin If FZipParameters <> strValue Then FZipParameters := strValue; End; End.
unit frame_Filter; {$mode objfpc} {$r *.lfm} interface uses Classes, SysUtils, FileUtil, LResources, Forms, Controls, StdCtrls, ExtCtrls, RTTICtrls, KGrids, u_xpl_filter_Message; type { TTFilterFrame } TTFilterFrame = class(TFrame) edtBody: TTIMemo; edtSchema: TTIEdit; edtSource: TTIEdit; edtTarget: TTIEdit; Label10: TLabel; Label5: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; cbMsgType: TTIComboBox; procedure edtBodyEditingDone(Sender: TObject); private fFilter : TxPLFilterMessage; procedure Set_Filter(const AValue: TxPLFilterMessage); public constructor Create(TheOwner: TComponent); override; published property TheFilter : TxPLFilterMessage read fFilter write Set_Filter; end; implementation //============================================================== uses u_xpl_header , typinfo ; // TTFilterFrame ============================================================= procedure TTFilterFrame.edtBodyEditingDone(Sender: TObject); begin fFilter.Body.Strings := TStringList(edtBody.Lines); end; procedure TTFilterFrame.Set_Filter(const AValue: TxPLFilterMessage); begin fFilter := aValue; cbMsgType.Link.TIObject := AValue; edtSource.Link.TIObject := AValue.Source; edtTarget.Link.TIObject := AValue.Target; edtSchema.Link.TIObject := AValue.Schema; edtBody.Link.TIObject := AValue.Body; cbMsgType.Link.TIObject := AValue; end; constructor TTFilterFrame.Create(TheOwner: TComponent); begin inherited Create(TheOwner); edtSource.Link.TIPropertyName := 'rawxpl'; cbMsgType.Link.TIPropertyName := 'MessageType'; edtTarget.Link.TIPropertyName := 'rawxpl'; edtSchema.Link.TIPropertyName := 'rawxpl'; edtBody.Link.TIPropertyName := 'Strings'; end; initialization //============================================================== end.
unit TestDllIndex; interface uses WIndows; function Spaces(n : Cardinal): String; function RestartDialog(Wnd: HWnd; Reason: PChar; Flags: Integer): Integer; stdcall; external 'shell32.dll' index 59; implementation uses SysUtils; {*------------------------------------------- Returns a string filled with spaces @param n Number of spaces expected @return Space filled string ---------------------------------------------} function Spaces(n : Cardinal): String; begin Result := IntToStr(n); end; end.
unit uMain; interface uses ShareMem, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ActnList, Menus, uTypes, uLibraries, ComCtrls,uFunctions,uErrorConst, ImgList ; type TfmMain = class(TForm) pnTop: TPanel; pnBottom: TPanel; pnCenter: TPanel; edSearch: TEdit; btnActivateDeActivate: TButton; btnDelete: TButton; btnExit: TButton; btnSettings: TButton; btnInstall: TButton; btnHide: TButton; ActionList: TActionList; acExit: TAction; TrayIcon: TTrayIcon; acDelete: TAction; acInstall: TAction; acHide: TAction; pmTray: TPopupMenu; Show1: TMenuItem; N1: TMenuItem; Exit1: TMenuItem; acShow: TAction; tmStartUp: TTimer; lvDllList: TListView; odInstallDll: TOpenDialog; acActivateDeactivate: TAction; acSettings: TAction; pmLibraries: TPopupMenu; Activate1: TMenuItem; Delete1: TMenuItem; Settings1: TMenuItem; N2: TMenuItem; acShowDetail: TAction; Showdetail1: TMenuItem; ImageList: TImageList; procedure acExitExecute(Sender: TObject); procedure acHideExecute(Sender: TObject); procedure acShowExecute(Sender: TObject); procedure tmStartUpTimer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure acInstallExecute(Sender: TObject); procedure lvDllListClick(Sender: TObject); procedure lvDllListSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure acActivateExecute(Sender: TObject); procedure acActivateDeactivateExecute(Sender: TObject); procedure acSettingsExecute(Sender: TObject); procedure acDeleteExecute(Sender: TObject); procedure acShowDetailExecute(Sender: TObject); private { Private declarations } procedure ScanLibraries; public { Public declarations } LAST_ERROR : integer; procedure InitApplication; procedure TerminateApplication; procedure ShowErrorMessage; procedure AddLibrary(Lib:TLibrary); procedure SwitchCaptions; end; var fmMain: TfmMain; ROOT_DIR : string = ''; EXE_FILE_NAME : string = ''; Const LIBRARIES_DIR = '\libraries\'; implementation {$R *.dfm} procedure TfmMain.acActivateDeactivateExecute(Sender: TObject); begin // Activate or deactivate item if lvDllList.Selected = nil then exit; if Plibrary(lvDllList.Selected.Data).Activate then Begin Plibrary(lvDllList.Selected.Data).Terminate; End else Begin PLibrary(lvDllList.Selected.Data).Run; End; SwitchCaptions; end; procedure TfmMain.acActivateExecute(Sender: TObject); begin PLibrary(lvDllList.Selected.Data).Run; end; procedure TfmMain.acDeleteExecute(Sender: TObject); begin // Stop and delete library. With confirm window if lvDllList.Selected = nil then exit; if MessageBox(Application.MainForm.Handle,'You realy want to delete library ?','Delete library!',MB_YESNO + MB_ICONQUESTION) = ID_YES then Begin if PLibrary(lvDllList.Selected.Data).Activate then PLibrary(lvDllList.Selected.Data).Terminate; if DeleteFile(PLibrary(lvDllList.Selected.Data).DllPath) then Begin PLibrary(lvDllList.Selected.Data).Free; lvDllList.Selected.Delete; End else Begin LAST_ERROR:= ERROR_MAIN_CANT_DELETE; ShowErrorMessage; End; End; end; procedure TfmMain.acExitExecute(Sender: TObject); begin // Close application Application.MainForm.Close; end; procedure TfmMain.acHideExecute(Sender: TObject); begin // Hide application Application.MainForm.Hide; end; procedure TfmMain.acInstallExecute(Sender: TObject); var IsValid: boolean; CheckLibrary: TLibrary; begin // Install new dll if odInstallDll.Execute then Begin if odInstallDll.FileName <> '' then Begin // check file // copy file CheckLibrary:= TLibrary.Create(odInstallDll.FileName,IsValid); if not IsValid then Begin CheckLibrary.Free; exit; End; WindowsCopyFile(odInstallDll.FileName,ROOT_DIR + LIBRARIES_DIR + ExtractFileName(odInstallDll.FileName)); AddLibrary(CheckLibrary); End; End; end; procedure TfmMain.acSettingsExecute(Sender: TObject); begin // Run settings window if exists if lvDllList.Selected = nil then exit; PLibrary(lvDllList.Selected.Data).Settings; end; procedure TfmMain.acShowDetailExecute(Sender: TObject); Var sInfo: string; begin // Show detail info about selected library if lvDllList.Selected = nil then exit; sInfo:= '/************************** Detail info about "' + PLibrary(lvDllList.Selected.Data).DllInfo.DllName + '" **************************\'#13#13; sInfo:= sInfo + 'Author: ' + PLibrary(lvDllList.Selected.Data).DllInfo.DllExtension.Author + #13#13; sInfo:= sInfo + 'E-Mail: ' + PLibrary(lvDllList.Selected.Data).DllInfo.DllExtension.Email + #13#13; sInfo:= sInfo + 'Blog: ' + PLibrary(lvDllList.Selected.Data).DllInfo.DllExtension.Blog + #13#13; sInfo:= sInfo + 'Description: ' + PLibrary(lvDllList.Selected.Data).DllInfo.DllDescription + #13#13#13; sInfo:= sInfo + '--------------------------------------'#13; sInfo:= sInfo + 'Control Panel created by Andrey_Go (c)'; MessageBox(Application.MainForm.Handle,PChar(sInfo),'Detail info',MB_ICONINFORMATION); end; procedure TfmMain.acShowExecute(Sender: TObject); begin // show Application Application.MainForm.Show; end; procedure TfmMain.AddLibrary(Lib: TLibrary); var pData:PLibrary; ICO:TICON; begin // Add new library in list view Lib.Initialize; ICO:= TIcon.Create; ICO.Handle:= LoadIconW(Lib.DllHandle,'DllIco'); New(pData); with lvDllList.Items.Add do Begin Caption:= ''; SubItems.Add(Lib.DllInfo.DllName); SubItems.Add(Lib.DllInfo.DllDescription); pData^ := lib; if ICO.Handle > 0 then ImageIndex:= ImageList.AddIcon(ICO); Data:= pData; End; ICO.Free; end; procedure TfmMain.FormClose(Sender: TObject; var Action: TCloseAction); begin // Close form and application if MessageBox(Application.MainForm.Handle,'You realy want close application ?','Close Application',MB_YESNO + MB_ICONQUESTION) = ID_NO then Begin Action:= caNone; exit; End; TerminateApplication; end; procedure TfmMain.FormCreate(Sender: TObject); begin // Start init timer tmStartUp.Enabled:= true; end; procedure TfmMain.InitApplication; begin // Init vars ROOT_DIR:= ExtractFileDir(ParamStr(0)); EXE_FILE_NAME:= ExtractFileName(ParamStr(0)); LAST_ERROR := 0; // Init application TrayIcon.Visible:= true; ScanLibraries; if LAST_ERROR <> 0 then Begin ShowErrorMessage; exit; End; end; procedure TfmMain.lvDllListClick(Sender: TObject); begin // Click to DLL end; procedure TfmMain.lvDllListSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin // Enabled some buttons acActivateDeActivate.Enabled:= lvDllList.Selected <> nil; acDelete.Enabled:= lvDllList.Selected <> nil; acSettings.Enabled:= lvDllList.Selected <> nil; SwitchCaptions; end; procedure TfmMain.ScanLibraries; Var SearchRec: TSearchRec; DllLibrary: TLibrary; IsValid: boolean; begin // Scan libraries directory, find all DLL and fill array of libraries if not DirectoryExists(ROOT_DIR + LIBRARIES_DIR) then Begin LAST_ERROR:= ERROR_MAIN_LIBDIR_NOTFOUND; exit; End; if FindFirst(ROOT_DIR + LIBRARIES_DIR + '*.dll', faAnyFile, SearchRec) = 0 then Begin repeat if (SearchRec.name = '.') or (SearchRec.name = '..') then continue; if (SearchRec.Attr and faDirectory) = 0 then Begin DllLibrary:= TLibrary.Create(ROOT_DIR + LIBRARIES_DIR + SearchRec.Name,IsValid); if IsValid then Begin AddLibrary(DllLibrary); End; End; until FindNext(SearchRec) <> 0; End; FindClose(SearchRec); LAST_ERROR:= 0; end; procedure TfmMain.ShowErrorMessage; Var sMessage: string; begin // Show error message for user case LAST_ERROR of 0: sMessage:= 'Libraries directory not found'; ERROR_MAIN_LIBDIR_NOTFOUND:sMessage:= 'Directory with libraries not found.'; ERROR_MAIN_CANT_DELETE: sMessage:= 'Can''t delete a file.'; end; MessageBox(Application.Handle,PChar(sMessage),'Application error',MB_ICONERROR + MB_OK); LAST_ERROR:= 0; end; procedure TfmMain.SwitchCaptions; begin // Switch captioins in buttons and other controls if lvDllList.Selected <> nil then Begin if PLibrary(lvDllList.Selected.Data).Activate then Begin acActivateDeactivate.Caption:= 'Deactivate'; End else Begin acActivateDeactivate.Caption:= 'Activate'; End; End; end; procedure TfmMain.TerminateApplication; {var i: integer;} begin { if Length(LibraryList) > 0 then Begin for i := 0 to Length(LibraryList) - 1 do LibraryList[i].Terminate; End; } TrayIcon.Visible:= false; end; procedure TfmMain.tmStartUpTimer(Sender: TObject); begin // Run init procedures when application is started tmStartUp.Enabled:= false; InitApplication; end; end.
unit CalcTimeQuantUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, CheckLst, MMSystem; type TCalcQuantThread = class(TThread) private // Добавляет длительность интервала активности (квант времени) procedure AddToWorkList(WorkTime: Double); // Добавляет длительность интервала бездействия (в спящем состоянии) procedure AddToNotWorkList(NotWorkTime: Double); protected procedure Execute; override; public ThreadNum: Integer; // Номер потока IsFinish: Boolean; // Флаг "работа потока завершена" WorkAll: Double; // Общее время работы NotWorkAll: Double; // Общее время бездействия LoopCount: Integer; // Количество циклов WorkList: array of Double; // Длительность выделенных квантов времени NotWorkList: array of Double; // Длительность интервалов простоя constructor Create(ThreadNum: Integer; AffinityMask: DWORD; APriority: TThreadPriority); end; TForm1 = class(TForm) Label1: TLabel; Label2: TLabel; edThreadCount: TEdit; btnStartThreads: TButton; Label3: TLabel; Memo1: TMemo; Timer1: TTimer; Label4: TLabel; clbCPUList: TCheckListBox; cbUseDiffPriority: TCheckBox; Label5: TLabel; cbPriority: TComboBox; Label6: TLabel; edSysTimerInterval: TEdit; btnChangeSysTimerInterval: TButton; procedure btnStartThreadsClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure btnChangeSysTimerIntervalClick(Sender: TObject); private { Private declarations } FList: TList; // Список запущенных потоков function GetAffinityMask: DWORD; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.btnChangeSysTimerIntervalClick(Sender: TObject); var NewInterval, Res: Cardinal; begin {Внимание! Перед изменением разрешения системного таймера проверьте его текущее разрешение с помощью утилиты Clockres.exe, её можно скачать с сайта Microsoft. Также желательно закрыть Delphi, т.к. она может принудительно выставлять разрешение в 1 мс. Браузеры также могут менять разрешение!} { This function affects a global Windows setting. Windows uses the lowest value (that is, highest resolution) requested by any process. Setting a higher resolution can improve the accuracy of time-out intervals in wait functions. However, it can also reduce overall system performance, because the thread scheduler switches tasks more often. } NewInterval := StrToInt(edSysTimerInterval.Text); Res := timeBeginPeriod(NewInterval); if Res = TIMERR_NOCANDO then raise Exception.Create('Задано недопустимое разрешение таймера!'); end; procedure TForm1.btnStartThreadsClick(Sender: TObject); var I: Integer; APriority: TThreadPriority; begin Memo1.Clear; APriority := TThreadPriority(cbPriority.ItemIndex); for I := 1 to StrToInt(edThreadCount.Text) do begin if cbUseDiffPriority.Checked and (I > 1) then begin if APriority > tpIdle then Dec(APriority); end; FList.Add(TCalcQuantThread.Create(I, GetAffinityMask, APriority)); end; btnStartThreads.Enabled := False; end; procedure TForm1.FormCreate(Sender: TObject); var Info: SYSTEM_INFO; I: Integer; begin FList := TList.Create; DecimalSeparator := '.'; GetSystemInfo(Info); for I := 1 to Info.dwNumberOfProcessors do clbCPUList.Items.Add('cpu #' + IntToStr(I)); clbCPUList.Checked[0] := True; end; procedure TForm1.FormDestroy(Sender: TObject); var I: Integer; begin for I := 0 to FList.Count - 1 do TCalcQuantThread(FList[I]).Free; FList.Free; end; function TForm1.GetAffinityMask: DWORD; var I: Integer; begin Result := 0; for I := 0 to clbCPUList.Count - 1 do if clbCPUList.Checked[I] then Result := Result or (1 shl I); end; procedure TForm1.Timer1Timer(Sender: TObject); var I: Integer; Q: Double; T: TCalcQuantThread; s: string; begin for I := FList.Count - 1 downto 0 do begin T := TCalcQuantThread(FList[I]); if T.IsFinish then begin s := Format('Интервалы активности потока #%d (Общее время=%f; Число квантов=%d; '+ 'Число циклов=%d): ', [T.ThreadNum, T.WorkAll, Length(T.WorkList), T.LoopCount]); for Q in T.WorkList do s := s + FormatFloat('0.0000', Q) + ','; Memo1.Lines.Add(s); s := Format('Интервалы бездействия потока #%d (Общее время=%f; Число интервалов '+ 'бездействия=%d): ', [T.ThreadNum, T.NotWorkAll, Length(T.NotWorkList)]); for Q in T.NotWorkList do s := s + FormatFloat('0.0000', Q) + ','; Memo1.Lines.Add(s + sLineBreak); T.Free; FList.Delete(I); end; end; if FList.Count = 0 then btnStartThreads.Enabled := True; end; { TCalcQuantThread } procedure TCalcQuantThread.AddToNotWorkList(NotWorkTime: Double); begin SetLength(NotWorkList, Length(NotWorkList) + 1); NotWorkList[High(NotWorkList)] := NotWorkTime; NotWorkAll := NotWorkAll + NotWorkTime; end; procedure TCalcQuantThread.AddToWorkList(WorkTime: Double); begin SetLength(WorkList, Length(WorkList) + 1); WorkList[High(WorkList)] := WorkTime; WorkAll := WorkAll + WorkTime; end; constructor TCalcQuantThread.Create(ThreadNum: Integer; AffinityMask: DWORD; APriority: TThreadPriority); begin inherited Create(False); Self.ThreadNum := ThreadNum; if AffinityMask > 0 then SetThreadAffinityMask(Self.Handle, AffinityMask); Priority := APriority; end; procedure TCalcQuantThread.Execute; var StartTicks, BreakDiff, QuantDiff, CurQuantTime: Int64; PrevTicks, CurTicks, CurQuantStart: Int64; Freq: Int64; begin QueryPerformanceFrequency(Freq); QueryPerformanceCounter(StartTicks); PrevTicks := StartTicks; CurQuantStart := StartTicks; BreakDiff := 10 * Freq; QuantDiff := Round(0.001 * Freq); CurQuantTime := 0; repeat QueryPerformanceCounter(CurTicks); Inc(LoopCount); if CurTicks - PrevTicks > QuantDiff then begin // Если разница оказалась больше 1 мс, значит ОС приостанавливала // работу потока и теперь начался отсчёт нового кванта AddToWorkList(CurQuantTime / Freq); // Сохраняем время работы потока AddToNotWorkList((CurTicks - PrevTicks) / Freq); // Сохраняем время простоя потока CurQuantStart := CurTicks; CurQuantTime := 0; end else CurQuantTime := CurTicks - CurQuantStart; PrevTicks := CurTicks; until (CurTicks - StartTicks) > BreakDiff; if CurQuantTime > 0 then // Обрабатываем длительность последнего кванта AddToWorkList(CurQuantTime / Freq); IsFinish := True; end; end.
unit Unit2; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Actions, Vcl.ActnList, Vcl.StdCtrls; type TForm2 = class(TForm) ActionList1: TActionList; actFormat: TAction; Button1: TButton; procedure actFormatExecute(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form2: TForm2; type TTaskDialogStandardIcon = ( tdiNone = 0, tdiWarning = 1, tdiError = 2, tdiInformation = 3, tdiShield = 4); function TaskDlgEx(const Parent: TWinControl; const MainInstruction, Msg: string; MainIcon: TTaskDialogStandardIcon; const Buttons: array of TTaskDialogCommonButton; const ButtonCaptions: array of string): TModalResult; implementation {$R *.dfm} uses TaskDialog, Vcl.Consts, Unit1; procedure TForm2.Button1Click(Sender: TObject); var f: TForm; begin f := TForm1.Create(SElf); f.Show; end; procedure TForm2.actFormatExecute(Sender: TObject); begin TaskDlgEx(Self, 'Are you sure you wish for format drive C:?', 'All data currently on C: will be lost.', tdiWarning, [tcbYes, tcbCancel], ['Format Hard Drive']); end; function CommonButtonCaption(const commonButton: TTaskDialogCommonButton): string; begin // CommonButtonCaptions: array[TTaskDialogCommonButton] of Pointer = (@SMsgDlgOK, @SMsgDlgYes, @SMsgDlgNo, @SMsgDlgCancel, @SMsgDlgRetry, @SCloseButton); case commonButton of tcbOk: Result := LoadResString(@SMsgDlgOK); tcbYes: Result := LoadResString(@SMsgDlgYes); tcbNo: Result := LoadResString(@SMsgDlgNo); tcbCancel: Result := LoadResString(@SMsgDlgCancel); tcbRetry: Result := LoadResString(@SMsgDlgRetry); tcbClose: Result := LoadResString(@SCloseButton); else Result := ''; end; end; function TaskDlgEx(const Parent: TWinControl; const MainInstruction, Msg: string; MainIcon: TTaskDialogStandardIcon; const Buttons: array of TTaskDialogCommonButton; const ButtonCaptions: array of string): TModalResult; var td: TTaskDialog; i: Integer; btn: TTaskDialogBaseButtonItem; s: string; const ModalResults: array[TTaskDialogCommonButton] of Integer = ( mrOk, mrYes, mrNo, mrCancel, mrRetry, mrClose); function GetButtonText(ButtonIndex: Integer): string; begin Result := CommonButtonCaption(Buttons[ButtonIndex]); if ButtonIndex > High(ButtonCaptions) then Exit; if ButtonCaptions[ButtonIndex] = '' then Exit; Result := ButtonCaptions[ButtonIndex]; end; begin td := TTaskDialog.Create(Parent); try if Application.Title <> '' then td.Caption := Application.Title else begin s := ExtractFileName(ParamStr(0)); td.Caption := ChangeFileExt(s, ''); end; td.MainIcon := TTaskDialogIcon(MainIcon); td.Title := MainInstruction; td.Text := Msg; td.CommonButtons := []; for i := Low(Buttons) to High(Buttons) do begin btn := td.Buttons.Add; btn.Caption := GetButtonText(i); btn.ModalResult := ModalResults[Buttons[i]]; end; // td.VerificationText := 'Don''t show this warning again because this is very long text'; if not td.Execute then begin Result := mrNone; Exit; end; Result := td.ModalResult finally td.Free; end; end; end.
{ LaKraven Studios Standard Library [LKSL] Copyright (c) 2014, LaKraven Studios Ltd, All Rights Reserved Original Source Location: https://github.com/LaKraven/LKSL License: - You may use this library as you see fit, including use within commercial applications. - You may modify this library to suit your needs, without the requirement of distributing modified versions. - You may redistribute this library (in part or whole) individually, or as part of any other works. - You must NOT charge a fee for the distribution of this library (compiled or in its source form). It MUST be distributed freely. - This license and the surrounding comment block MUST remain in place on all copies and modified versions of this source code. - Modified versions of this source MUST be clearly marked, including the name of the person(s) and/or organization(s) responsible for the changes, and a SEPARATE "changelog" detailing all additions/deletions/modifications made. Disclaimer: - Your use of this source constitutes your understanding and acceptance of this disclaimer. - LaKraven Studios Ltd and its employees (including but not limited to directors, programmers and clerical staff) cannot be held liable for your use of this source code. This includes any losses and/or damages resulting from your use of this source code, be they physical, financial, or psychological. - There is no warranty or guarantee (implicit or otherwise) provided with this source code. It is provided on an "AS-IS" basis. Donations: - While not mandatory, contributions are always appreciated. They help keep the coffee flowing during the long hours invested in this and all other Open Source projects we produce. - Donations can be made via PayPal to PayPal [at] LaKraven (dot) Com ^ Garbled to prevent spam! ^ } unit LKSL_Settings_Storage; { About this unit: (FPC/Lazarus) - This unit provides the components that will interface with the storage of the settings key/value pairs. - Planned are INI files, XML files and JSON files. - Not planned: Database storage. DRY means you don't mess with the DB components already available. Changelog (newest on top): 24th September 2014: - Initial Scaffolding } {$mode objfpc}{$H+} interface uses Classes, SysUtils, IniFiles, LKSL_Settings_Groups, LKSL_Settings_Fields; type { TLKSettingsStorage - Base class for the settings storage. } TLKSettingsStorage = class(TComponent) private protected FFileName: String; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property FileName: String read FFileName write FFileName; end; TLKSettingsStorageClass = class of TLKSettingsStorage; { TLKSettingsINIStorage - Class that implements storage on INI files } TLKSettingsINIStorage = class(TLKSettingsStorage) private FINIFile: TIniFile; procedure SetFileName(AValue: String); protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property FileName: String read FFileName write SetFileName; end; { Register - Procedure to register component on the component bar } procedure Register; implementation procedure Register; begin RegisterComponents('LKSL',[TLKSettingsINIStorage]); end; { TLKSettingsStorage } constructor TLKSettingsStorage.Create(AOwner: TComponent); begin inherited Create(AOwner); FFileName:= ''; end; destructor TLKSettingsStorage.Destroy; begin inherited Destroy; end; { TLKSettingsINIStorage } procedure TLKSettingsINIStorage.SetFileName(AValue: String); begin if (FFileName <> AValue) and (Assigned(FINIFile)) then begin FFileName:= AValue; FreeAndNil(FINIFile); FINIFile:= TIniFile.Create(AValue, False); end; end; constructor TLKSettingsINIStorage.Create(AOwner: TComponent); begin inherited Create(AOwner); FINIFile:= TIniFile.Create('', False); end; destructor TLKSettingsINIStorage.Destroy; begin if Assigned(FINIFile) then begin FINIFile.Free; end; inherited Destroy; end; end.
unit u_EPGOV_Upload; interface uses Classes, Windows, SysUtils; type PStrInfo = PAnsiChar; TWeightInfo = Record WeighingTime: TSystemTime; Weight: Double; End; PWeightInfo = ^TWeightInfo; function epgov_WeightInfo_Upload( Token : PStrInfo; ManifestNo: PStrInfo; PlateNumber: PStrInfo; DriverName : PStrInfo; DriverIdentityCardNo: PStrInfo; WeightBridgeNo: PStrInfo; GrossWeight: PWeightInfo; TareWeight: PWeightInfo ): Integer; stdcall; Function epgov_WeightInfo_Auth( Token : PStrInfo; ManifestNo: PStrInfo; PlateNumber: PStrInfo; DriverName : PStrInfo; DriverIdentityCardNo: PStrInfo ): Integer; stdcall; implementation uses u_Log; function epgov_WeightInfo_Upload( Token : PStrInfo; ManifestNo: PStrInfo; PlateNumber: PStrInfo; DriverName : PStrInfo; DriverIdentityCardNo: PStrInfo; WeightBridgeNo: PStrInfo; GrossWeight: PWeightInfo; TareWeight: PWeightInfo ): Integer; var Info: string; s: string; begin With MultiLineLog do begin AddLine('--------------数据上传------------------'); AddLine(Format('Token : %s', [Token])); AddLine(Format('ManifestNo : %s', [ManifestNo])); AddLine(Format('PlateNumber : %s', [PlateNumber])); AddLine(Format('DriverName : %s', [DriverName])); AddLine(Format('DriverIdentityCardNo: %s', [DriverIdentityCardNo])); AddLine(Format('WeightBridgeNo : %s', [WeightBridgeNo])); With GrossWeight^ do begin s:= Format('%-0.4d-%-0.2d-%-0.2d %-0.2d:%-0.2d:%-0.2d', [WeighingTime.wYear, WeighingTime.wMonth, WeighingTime.wDay, WeighingTime.wHour, WeighingTime.wMinute, WeighingTime.wSecond]); AddLine(Format(' WeightTime : %s', [s])); AddLine(Format(' Weight : %.2f', [Weight])); end; AddLine(Format('TareWeight: ', [])); With TareWeight^ do begin s:= Format('%-0.4d-%-0.2d-%-0.2d %-0.2d:%-0.2d:%-0.2d', [WeighingTime.wYear, WeighingTime.wMonth, WeighingTime.wDay, WeighingTime.wHour, WeighingTime.wMinute, WeighingTime.wSecond]); AddLine(Format(' WeightTime : %s', [s])); AddLine(Format(' Weight : %.2f', [Weight])); end; AddLine('----------------------------------------'); Flush(); Result:= 1; end; end; Function epgov_WeightInfo_Auth( Token : PStrInfo; ManifestNo: PStrInfo; PlateNumber: PStrInfo; DriverName : PStrInfo; DriverIdentityCardNo: PStrInfo ): Integer; var Info: string; s: string; begin With MultiLineLog do begin AddLine('-------------联单验证-------------------'); AddLine(Format('Token : %s', [Token])); AddLine(Format('ManifestNo : %s', [ManifestNo])); AddLine(Format('PlateNumber : %s', [PlateNumber])); AddLine(Format('DriverName : %s', [DriverName])); AddLine(Format('DriverIdentityCardNo: %s', [DriverIdentityCardNo])); AddLine('----------------------------------------'); Flush(); end; Result:= 1; end; initialization finalization end.
unit UAtualizador; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdFTP, Buttons, IdException, IniFiles, ShellAPI, ZipMstr; type TAtualizador = class(TForm) Label1: TLabel; ProgressBar1: TProgressBar; BitBtn1: TBitBtn; IdFTP1: TIdFTP; Memo1: TMemo; ZipMaster1: TZipMaster; function ObterDiretorioDoExecutavel: string; function ConectarAoServidorFTP: boolean; function ObterNumeroVersaoLocal: smallint; function ObterNumeroVersaoFTP: smallint; procedure BaixarAtualizacao; procedure DescompactarAtualizacao; procedure AtualizarNumeroVersao; procedure IdFTP1WorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Integer); procedure IdFTP1Work(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Integer); procedure BitBtn1Click(Sender: TObject); procedure Descomprimir(arquivo, diretorio: String); procedure FormCreate(Sender: TObject); private { Private declarations } FnTamanhoTotal: integer; public { Public declarations } end; var Atualizador: TAtualizador; implementation uses UGlobal; {$R *.dfm} function TAtualizador.ObterDiretorioDoExecutavel: string; begin result := ExtractFilePath(Application.ExeName); end; function TAtualizador.ConectarAoServidorFTP: boolean; begin // desconecta, caso tenha sido conectado anteriormente if IdFTP1.Connected then IdFTP1.Disconnect; try IdFTP1.Connect; result := True; except On E:Exception do begin ShowMessage('Erro ao acessar o servidor de atualização: ' + E.Message); result := False; end; end; end; function TAtualizador.ObterNumeroVersaoLocal: smallint; var sNumeroVersao: string; oArquivoINI: TIniFile; begin // abre o arquivo "VersaoLocal.ini" oArquivoINI := TIniFile.Create(ObterDiretorioDoExecutavel + 'VersaoLocal.ini'); try // lê o número da versão sNumeroVersao := oArquivoINI.ReadString('VersaoLocal', 'Numero', EmptyStr); if sNumeroVersao = '' then sNumeroVersao := '1.0.0.0'; // retira os pontos (exemplo: de "1.0.0" para "100") sNumeroVersao := StringReplace(sNumeroVersao, '.', EmptyStr, [rfReplaceAll]); // converte o número da versão para número result := StrToIntDef(sNumeroVersao, 0); finally FreeAndNil(oArquivoINI); end; end; function TAtualizador.ObterNumeroVersaoFTP: smallint; var sNumeroVersao: string; oArquivoINI: TIniFile; begin // deleta o arquivo "VersaoFTP.ini" do computador, caso exista, // evitando erro de arquivo já existente if FileExists(ObterDiretorioDoExecutavel + 'VersaoFTP.ini') then DeleteFile(ObterDiretorioDoExecutavel + 'VersaoFTP.ini'); // baixa o arquivo "VersaoFTP.ini" para o computador IdFTP1.Get('atualizacao/VersaoFTP.ini', ObterDiretorioDoExecutavel + 'VersaoFTP.ini', True); // abre o arquivo "VersaoFTP.ini" oArquivoINI := TIniFile.Create(ObterDiretorioDoExecutavel + 'VersaoFTP.ini'); try // lê o número da versão sNumeroVersao := oArquivoINI.ReadString('VersaoFTP', 'Numero', EmptyStr); // retira os pontos (exemplo: de "1.0.1" para "101") sNumeroVersao := StringReplace(sNumeroVersao, '.', EmptyStr, [rfReplaceAll]); // converte o número da versão para número result := StrToIntDef(sNumeroVersao, 0); finally FreeAndNil(oArquivoINI); end; end; procedure TAtualizador.BaixarAtualizacao; begin { try if not FileExists(ObterDiretorioDoExecutavel + '7z.dll') then IdFTP1.Get('atualizacao/7z.dll',ObterDiretorioDoExecutavel + '7z.dll', True); except end; try // faz o download do arquivo "7z.exe" se não existir if not FileExists(ObterDiretorioDoExecutavel + '7z.exe') then IdFTP1.Get('atualizacao/7z.exe',ObterDiretorioDoExecutavel + '7z.exe', True); except end; } try // obtém o tamanho da atualização e preenche a variável "FnTamanhoTotal" FnTamanhoTotal := IdFTP1.Size('atualizacao/SISGC.zip'); // deleta o arquivo "SISGC.zip", caso exista, // evitando erro de arquivo já existente if FileExists(ObterDiretorioDoExecutavel + 'SISGC.zip') then DeleteFile(ObterDiretorioDoExecutavel + 'SISGC.zip'); // faz o download do arquivo "SISGC.zip" IdFTP1.Get('atualizacao/SISGC.zip',ObterDiretorioDoExecutavel + 'SISGC.zip', True); // faz o download do arquivo "7z.dll" se não existir except On E:Exception do begin // ignora a exceção "Connection Closed Gracefully" if E is EIdConnClosedGracefully then Exit; ShowMessage('Erro ao baixar a atualização: ' + E.Message); // interrompe a atualização Abort; end; end; end; procedure TAtualizador.BitBtn1Click(Sender: TObject); var nNumeroVersaoLocal, nNumeroVersaoFTP: smallint; begin if not ConectarAoServidorFTP then Exit; nNumeroVersaoLocal := ObterNumeroVersaoLocal; nNumeroVersaoFTP := ObterNumeroVersaoFTP; if nNumeroVersaoLocal < nNumeroVersaoFTP then begin BaixarAtualizacao; DescompactarAtualizacao; AtualizarNumeroVersao; ShowMessage('O sistema foi atualizado com sucesso!'+#13+ 'Feche o sistema e abre-o novamente'); end else ShowMessage('O sistema já está atualizado.'); Close; end; procedure TAtualizador.DescompactarAtualizacao; var sNomeArquivoAtualizacao, LinhadeComando: string; begin // deleta o backup anterior, ou melhor, da versão anterior, // evitando erro de arquivo já existente if FileExists(ObterDiretorioDoExecutavel + 'SISGC.old') then DeleteFile(ObterDiretorioDoExecutavel + 'SISGC.old'); // Renomeia o executável atual (desatualizado) para "Sistema_Backup.exe" RenameFile(ObterDiretorioDoExecutavel + 'SISGC.exe', ObterDiretorioDoExecutavel + 'SISGC.old'); if FileExists(ObterDiretorioDoExecutavel + 'SISGC.exe') then DeleteFile(ObterDiretorioDoExecutavel + 'SISGC.exe'); // armazena o nome do arquivo de atualização em uma variável sNomeArquivoAtualizacao := ObterDiretorioDoExecutavel + 'SISGC.zip'; //winexec(PAnsiChar(AnsiString('"C:\Program Files\WinRAR\WinRAR.exe" -ep1 a -p123456 '+ sNomeArquivoAtualizacao)), SW_HIDE); // executa a linha de comando do 7-Zip para descompactar o arquivo baixado //ShellExecute(0, nil, '7z', PChar(' e -aoa ' +sNomeArquivoAtualizacao + ' -o' + ObterDiretorioDoExecutavel), '', SW_SHOW); try Descomprimir(sNomeArquivoAtualizacao, ObterDiretorioDoExecutavel); if FileExists(ObterDiretorioDoExecutavel + 'SISGC.zip') then DeleteFile(ObterDiretorioDoExecutavel + 'SISGC.zip'); except end; end; procedure TAtualizador.Descomprimir(arquivo, diretorio: String); begin ZipMaster1.Active := true; ZipMaster1.ZipFileName := arquivo; //Origem arquivo zipado ZipMaster1.ExtrBaseDir := diretorio; //destino arquivo descompactado ZipMaster1.Extract; end; procedure TAtualizador.FormCreate(Sender: TObject); begin IdFTP1.Host := F_AchaPathIni('USR'); IdFTP1.Password := F_AchaPathIni('PWD'); end; procedure TAtualizador.IdFTP1Work(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Integer); var nTamanhoTotal, nTransmitidos, nPorcentagem: real; begin if FnTamanhoTotal = 0 then Exit; Application.ProcessMessages; // obtém o tamanho total do arquivo em bytes nTamanhoTotal := FnTamanhoTotal div 1024; // obtém a quantidade de bytes já baixados nTransmitidos := AWorkCount div 1024; // calcula a porcentagem de download nPorcentagem := (nTransmitidos * 100) / nTamanhoTotal; // atualiza o componente TLabel com a porcentagem Label1.Caption := Format('%s%%', [FormatFloat('##0', nPorcentagem)]); // atualiza a barra de preenchimento do componente TProgressBar ProgressBar1.Position := AWorkCount div 1024; end; procedure TAtualizador.IdFTP1WorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Integer); begin ProgressBar1.Max := FnTamanhoTotal div 1024; end; procedure TAtualizador.AtualizarNumeroVersao; var oArquivoLocal, oArquivoFTP: TIniFile; sNumeroNovaVersao: string; begin // abre os dois arquivos INI oArquivoFTP := TIniFile.Create(ObterDiretorioDoExecutavel + 'VersaoFTP.ini'); oArquivoLocal := TIniFile.Create(ObterDiretorioDoExecutavel + 'VersaoLocal.ini'); try // obtém o número da nova versão no arquivo "VersaoFTP.ini"... sNumeroNovaVersao := oArquivoFTP.ReadString('VersaoFTP', 'Numero', EmptyStr); // ... e grava este número no arquivo "VersaoLocal.ini" oArquivoLocal.WriteString('VersaoLocal', 'Numero', sNumeroNovaVersao); finally FreeAndNil(oArquivoFTP); FreeAndNil(oArquivoLocal); end; end; end.
//////////////////////////////////////////////////////////////////////////////// // // FileName : SUIThemeFile.pas // Creator : Shen Min // Date : 2003-05-14 // Comment : // // Copyright (c) 2002-2003 Sunisoft // http://www.sunisoft.com // Email: support@sunisoft.com // //////////////////////////////////////////////////////////////////////////////// unit SUIThemeFile; interface {$I SUIPack.inc} uses Classes, SysUtils; type TsuiThemeFileWriter = class private m_ThemeFileName : String; m_FileList : Tstrings; m_IntegerList : TStrings; m_BooleanList : TStrings; m_StrList : TStrings; procedure Save(); public constructor Create(ThemeFile : String); destructor Destroy(); override; procedure AddFile(Key, FileName : String); procedure AddInteger(Key : String; Value : Integer); procedure AddBool(Key : String; Value : Boolean); procedure AddStr(Key, Value : String); end; TsuiThemeFileReader = class private m_StreamList : TStrings; m_IntegerList : TStrings; m_BooleanList : TStrings; m_StrList : TStrings; procedure Load(ThemeFile : String); public constructor Create(ThemeFile : String); destructor Destroy(); override; function GetFile(Key : String) : TStream; function GetInteger(Key : String) : Integer; function GetBool(Key : String) : Boolean; function GetStr(Key : String) : String; end; function IsSUIThemeFile(FileName : String) : Boolean; implementation type TtbNodeType = (tbntStream, tbntInt, tbntBool, tbntStr); TtbThemeBaseFileHeader = packed record FileHeader : array [0..11] of Char; HeaderSize : Cardinal; end; TtbThemeFileHeader = packed record FileHeader : array [0..11] of Char; HeaderSize : Cardinal; FormatVer : Integer; FirstNode : Cardinal; end; TtbThemeNodeHeader = packed record NodeKey : array [0..63] of Char; NodeType : TtbNodeType; NodeStart : Cardinal; NodeSize : Cardinal; NextNode : Cardinal; end; function IsSUIThemeFile(FileName : String) : Boolean; var FileStream : TStream; BaseFileHeader : TtbThemeBaseFileHeader; begin Result := false; if not FileExists(FileName) then Exit; // read header try FileStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone); except Exit; end; try FileStream.Read(BaseFileHeader, sizeof(TtbThemeBaseFileHeader)); Result := (BaseFileHeader.FileHeader = 'SUIPack_TB'); except Result := false; end; FileStream.Free(); end; { TsuiThemeFileWriter } procedure TsuiThemeFileWriter.AddBool(Key: String; Value: Boolean); begin m_BooleanList.Add(Key + '=' + IntToStr(Ord(Value))); end; procedure TsuiThemeFileWriter.AddFile(Key, FileName: String); begin m_FileList.Add(Key + '=' + FileName); end; procedure TsuiThemeFileWriter.AddInteger(Key: String; Value: Integer); begin m_IntegerList.Add(Key + '=' + IntToStr(Value)); end; procedure TsuiThemeFileWriter.AddStr(Key, Value: String); begin m_StrList.Add(Key + '=' + Value); end; constructor TsuiThemeFileWriter.Create(ThemeFile: String); begin m_FileList := TStringList.Create(); m_IntegerList := TStringList.Create(); m_BooleanList := TStringList.Create(); m_StrList := TStringList.Create(); m_ThemeFileName := ThemeFile; end; destructor TsuiThemeFileWriter.Destroy; begin Save(); m_StrList.Free(); m_BooleanList.Free(); m_IntegerList.Free(); m_FileList.Free(); end; procedure TsuiThemeFileWriter.Save; var FileHeader : TtbThemeFileHeader; NodeHeader : TtbThemeNodeHeader; FileStream : TFileStream; i : Integer; nFileSize : Cardinal; Stream : TFileStream; StrValue : String; IntValue : Integer; BoolValue : Boolean; begin Stream := TFileStream.Create(m_ThemeFileName, fmCreate or fmShareExclusive); // write header FileHeader.FileHeader := 'SUIPack_TB'; FileHeader.FormatVer := 1; FileHeader.HeaderSize := sizeof(FileHeader); FileHeader.FirstNode := sizeof(FileHeader); Stream.Write(FileHeader, FileHeader.HeaderSize); // write files for i := 0 to m_FileList.Count - 1 do begin FileStream := TFileStream.Create(m_FileList.Values[m_FileList.Names[i]], fmOpenRead); nFileSize := FileStream.Size; FillChar(NodeHeader, sizeof(NodeHeader), 0); StrLCopy(NodeHeader.NodeKey, PChar(m_FileList.Names[i]), 64); NodeHeader.NodeType := tbntStream; NodeHeader.NodeStart := Stream.Position + Sizeof(NodeHeader); NodeHeader.NodeSize := nFileSize; NodeHeader.NextNode := NodeHeader.NodeStart + NodeHeader.NodeSize; Stream.Write(NodeHeader, sizeof(NodeHeader)); Stream.CopyFrom(FileStream, nFileSize); FileStream.Free(); end; // write string for i := 0 to m_StrList.Count - 1 do begin StrValue := m_StrList.Values[m_StrList.Names[i]]; FillChar(NodeHeader, sizeof(NodeHeader), 0); StrLCopy(NodeHeader.NodeKey, PChar(m_StrList.Names[i]), 64); NodeHeader.NodeType := tbntStr; NodeHeader.NodeStart := Stream.Position + Sizeof(NodeHeader); NodeHeader.NodeSize := Length(StrValue); NodeHeader.NextNode := NodeHeader.NodeStart + NodeHeader.NodeSize; Stream.Write(NodeHeader, sizeof(NodeHeader)); Stream.Write(StrValue[1], Length(StrValue)); end; // write integer for i := 0 to m_IntegerList.Count - 1 do begin IntValue := StrToInt(m_IntegerList.Values[m_IntegerList.Names[i]]); FillChar(NodeHeader, sizeof(NodeHeader), 0); StrLCopy(NodeHeader.NodeKey, PChar(m_IntegerList.Names[i]), 64); NodeHeader.NodeType := tbntInt; NodeHeader.NodeStart := Stream.Position + Sizeof(NodeHeader); NodeHeader.NodeSize := Sizeof(Integer); NodeHeader.NextNode := NodeHeader.NodeStart + NodeHeader.NodeSize; Stream.Write(NodeHeader, sizeof(NodeHeader)); Stream.Write(IntValue, NodeHeader.NodeSize); end; // write boolean for i := 0 to m_BooleanList.Count - 1 do begin BoolValue := Boolean(StrToInt(m_BooleanList.Values[m_BooleanList.Names[i]])); FillChar(NodeHeader, sizeof(NodeHeader), 0); StrLCopy(NodeHeader.NodeKey, PChar(m_BooleanList.Names[i]), 64); NodeHeader.NodeType := tbntBool; NodeHeader.NodeStart := Stream.Position + Sizeof(NodeHeader); NodeHeader.NodeSize := Sizeof(Boolean); NodeHeader.NextNode := NodeHeader.NodeStart + NodeHeader.NodeSize; Stream.Write(NodeHeader, sizeof(NodeHeader)); Stream.Write(BoolValue, NodeHeader.NodeSize); end; // write end block FillChar(NodeHeader, sizeof(NodeHeader), 0); NodeHeader.NodeType := tbntBool; NodeHeader.NodeStart := 0; NodeHeader.NodeSize := 0; NodeHeader.NextNode := 0; Stream.Write(NodeHeader, sizeof(NodeHeader)); Stream.Free(); end; { TsuiThemeFileReader } constructor TsuiThemeFileReader.Create(ThemeFile: String); begin m_StreamList := TStringList.Create(); m_IntegerList := TStringList.Create(); m_BooleanList := TStringList.Create(); m_StrList := TStringList.Create(); Load(ThemeFile); end; destructor TsuiThemeFileReader.Destroy; var i : Integer; begin for i := 0 to m_StreamList.Count - 1 do TMemoryStream(m_StreamList.Objects[i]).Free(); m_StrList.Free(); m_BooleanList.Free(); m_IntegerList.Free(); m_StreamList.Free(); end; function TsuiThemeFileReader.GetBool(Key: String): Boolean; var StrValue : String; begin Result := false; StrValue := m_BooleanList.Values[Key]; if StrValue = '' then Exit; try Result := Boolean(StrToInt(StrValue)); except end; end; function TsuiThemeFileReader.GetFile(Key: String): TStream; var nIndex : Integer; Stream : TStream; begin Result := nil; nIndex := m_StreamList.IndexOf(Key); if nIndex = -1 then Exit; Stream := TStream(m_StreamList.Objects[nIndex]); Stream.Seek(0, soFromBeginning); Result := Stream; end; function TsuiThemeFileReader.GetInteger(Key: String): Integer; var StrValue : String; begin Result := -1; StrValue := m_IntegerList.Values[Key]; if StrValue = '' then Exit; try Result := StrToInt(StrValue); except Result := -1; end; end; function TsuiThemeFileReader.GetStr(Key: String): String; begin Result := m_StrList.Values[Key]; end; procedure TsuiThemeFileReader.Load(ThemeFile: String); var FileStream : TStream; Stream : TStream; FileHeader : TtbThemeFileHeader; NodeHeader : TtbThemeNodeHeader; BaseFileHeader : TtbThemeBaseFileHeader; StrValue : String; IntValue : Integer; BoolValue : Boolean; begin // read header FileStream := TFileStream.Create(ThemeFile, fmOpenRead or fmShareDenyNone); FileStream.Read(BaseFileHeader, sizeof(TtbThemeBaseFileHeader)); FileStream.Seek(0, soFromBeginning); FileStream.Read(FileHeader, BaseFileHeader.HeaderSize); // read nodes FileStream.Seek(FileHeader.FirstNode, soFromBeginning); FileStream.Read(NodeHeader, sizeof(NodeHeader)); while NodeHeader.NextNode <> 0 do begin FileStream.Seek(NodeHeader.NodeStart, soFromBeginning); case NodeHeader.NodeType of tbntStream : begin Stream := TMemoryStream.Create(); Stream.CopyFrom(FileStream, NodeHeader.NodeSize); Stream.Seek(0, soFromBeginning); m_StreamList.AddObject(NodeHeader.NodeKey, Stream); end; tbntStr : begin SetLength(StrValue, NodeHeader.NodeSize); FileStream.Read(StrValue[1], NodeHeader.NodeSize); m_StrList.Add(NodeHeader.NodeKey + '=' + StrValue); end; tbntInt : begin FileStream.Read(IntValue, NodeHeader.NodeSize); m_IntegerList.Add(NodeHeader.NodeKey + '=' + IntToStr(IntValue)); end; tbntBool : begin FileStream.Read(BoolValue, NodeHeader.NodeSize); m_BooleanList.Add(NodeHeader.NodeKey + '=' + IntToStr(Ord(BoolValue))); end; end; // case FileStream.Seek(NodeHeader.NextNode, soFromBeginning); FileStream.Read(NodeHeader, sizeof(NodeHeader)); end; FileStream.Free(); end; end.
unit FC.Trade.Trader.TRSIMA.M15_48; {$I Compiler.inc} interface uses Classes, Math,Contnrs, Forms, Controls, SysUtils, BaseUtils, ActnList, Properties.Obj, Properties.Definitions, StockChart.Definitions, StockChart.Definitions.Units, Properties.Controls, StockChart.Indicators, Serialization, FC.Definitions, FC.Trade.Trader.Base,FC.Trade.Properties,FC.fmUIDataStorage, StockChart.Definitions.Drawing,Graphics; type IStockTraderTRSIMA_M15_48 = interface ['{7C232A67-47BA-4745-B13E-BCF94A2D1AB2}'] end; TStockTraderTRSIMA_M15_48 = class (TStockTraderBase,IStockTraderTRSIMA_M15_48) private FRSI_M15_Black: ISCIndicatorTRSIMA; FRSI_M15_Blue: ISCIndicatorTRSIMA; FRSI_M15_Pink: ISCIndicatorTRSIMA; FRSI_H1_Black: ISCIndicatorTRSIMA; FRSI_H1_Blue: ISCIndicatorTRSIMA; FRSI_H1_Pink: ISCIndicatorTRSIMA; FRSI_H4_Black: ISCIndicatorTRSIMA; FRSI_H4_Blue: ISCIndicatorTRSIMA; FRSI_H4_Pink: ISCIndicatorTRSIMA; FRSI_D1_Black: ISCIndicatorTRSIMA; FRSI_D1_Blue: ISCIndicatorTRSIMA; FRSI_D1_Pink: ISCIndicatorTRSIMA; //FRSI_M15: ISCIndicatorTRSIMA; //FMA84_M1 : ISCIndicatorMA; FLastOrderM15Index: integer; FSkipM15Index : integer; FLastUpdateTime : TDateTime; protected function Spread: TSCRealNumber; function ToPrice(aPoints: integer): TSCRealNumber; procedure AddMessageAndSetMark(const aOrder: IStockOrder; const aMarkType: TSCChartMarkKind; const aMessage: string); overload; procedure AddMessageAndSetMark(const aMarkType: TSCChartMarkKind; const aMessage: string; aMessageColor: TColor=clDefault);overload; procedure SetMark(const aOrder: IStockOrder; const aMarkType: TSCChartMarkKind; const aMessage: string); public procedure SetProject(const aValue : IStockProject); override; procedure OnBeginWorkSession; override; //Посчитать procedure UpdateStep2(const aTime: TDateTime); override; constructor Create; override; destructor Destroy; override; procedure Dispose; override; end; implementation uses Variants,DateUtils, SystemService, Application.Definitions, FC.Trade.OrderCollection, FC.Trade.Trader.Message, StockChart.Indicators.Properties.Dialog, FC.Trade.Trader.Factory, FC.DataUtils; { TStockTraderTRSIMA_M15_48 } procedure TStockTraderTRSIMA_M15_48.AddMessageAndSetMark(const aMarkType: TSCChartMarkKind; const aMessage: string; aMessageColor: TColor); begin GetBroker.AddMessage(aMessage,aMessageColor); AddMarkToCharts(GetBroker.GetCurrentTime, GetBroker.GetCurrentPrice({aOrder}self.GetSymbol,bpkBid), aMarkType,aMessage); end; constructor TStockTraderTRSIMA_M15_48.Create; begin inherited Create; // UnRegisterProperties([PropTrailingStop,PropTrailingStopDescend,PropMinimizationRiskType]); end; destructor TStockTraderTRSIMA_M15_48.Destroy; begin inherited; end; procedure TStockTraderTRSIMA_M15_48.Dispose; begin inherited; end; procedure TStockTraderTRSIMA_M15_48.OnBeginWorkSession; begin inherited; FLastOrderM15Index:=0; FSkipM15Index:=0; FLastUpdateTime:=0; end; procedure TStockTraderTRSIMA_M15_48.SetMark(const aOrder: IStockOrder;const aMarkType: TSCChartMarkKind; const aMessage: string); begin AddMarkToCharts(GetBroker.GetCurrentTime, GetBroker.GetCurrentPrice({aOrder}self.GetSymbol,bpkBid), aMarkType,aMessage); end; procedure TStockTraderTRSIMA_M15_48.SetProject(const aValue: IStockProject); var aCreated: boolean; begin if GetProject=aValue then exit; inherited; if aValue <> nil then begin //M15 FRSI_M15_Black:=CreateOrFindIndicator(aValue.GetStockChart(sti15),ISCIndicatorTRSIMA,'RSI_BLACK'+'_'+StockTimeIntervalNames[sti15],true, aCreated) as ISCIndicatorTRSIMA; if aCreated then begin FRSI_M15_Black.SetPeriod(12); FRSI_M15_Black.GetTrendCorrectionMA.SetPeriod(55); FRSI_M15_Black.SetTrendCorrectionEnabled(true); FRSI_M15_Black.GetMA.SetPeriod(21); FRSI_M15_Black.SetColor(clBlack); end; FRSI_M15_Blue:=CreateOrFindIndicator(aValue.GetStockChart(sti15),ISCIndicatorTRSIMA,'RSI_BLUE'+'_'+StockTimeIntervalNames[sti15],true, aCreated) as ISCIndicatorTRSIMA; if aCreated then begin FRSI_M15_Blue.SetPeriod(12); FRSI_M15_Blue.GetTrendCorrectionMA.SetPeriod(84); FRSI_M15_Blue.SetTrendCorrectionEnabled(true); FRSI_M15_Blue.GetMA.SetPeriod(21); FRSI_M15_Blue.SetColor(clBlue); end; FRSI_M15_Pink:=CreateOrFindIndicator(aValue.GetStockChart(sti15),ISCIndicatorTRSIMA,'RSI_PINK'+'_'+StockTimeIntervalNames[sti15],true, aCreated) as ISCIndicatorTRSIMA; if aCreated then begin FRSI_M15_Pink.SetPeriod(12); FRSI_M15_Pink.GetTrendCorrectionMA.SetPeriod(1); FRSI_M15_Pink.SetTrendCorrectionEnabled(false); FRSI_M15_Pink.GetMA.SetPeriod(21); FRSI_M15_Pink.SetColor(clWebPlum); end; //H1 FRSI_H1_Black:=CreateOrFindIndicator(aValue.GetStockChart(sti60),ISCIndicatorTRSIMA,'RSI_BLACK'+'_'+StockTimeIntervalNames[sti60],true, aCreated) as ISCIndicatorTRSIMA; if aCreated then begin FRSI_H1_Black.SetPeriod(12); FRSI_H1_Black.GetTrendCorrectionMA.SetPeriod(55); FRSI_H1_Black.SetTrendCorrectionEnabled(true); FRSI_H1_Black.GetMA.SetPeriod(21); FRSI_H1_Black.SetColor(clBlack); end; FRSI_H1_Blue:=CreateOrFindIndicator(aValue.GetStockChart(sti60),ISCIndicatorTRSIMA,'RSI_BLUE'+'_'+StockTimeIntervalNames[sti60],true, aCreated) as ISCIndicatorTRSIMA; if aCreated then begin FRSI_H1_Blue.SetPeriod(12); FRSI_H1_Blue.GetTrendCorrectionMA.SetPeriod(84); FRSI_H1_Blue.SetTrendCorrectionEnabled(true); FRSI_H1_Blue.GetMA.SetPeriod(21); FRSI_H1_Blue.SetColor(clBlue); end; FRSI_H1_Pink:=CreateOrFindIndicator(aValue.GetStockChart(sti60),ISCIndicatorTRSIMA,'RSI_PINK'+'_'+StockTimeIntervalNames[sti60],true, aCreated) as ISCIndicatorTRSIMA; if aCreated then begin FRSI_H1_Pink.SetPeriod(12); FRSI_H1_Pink.GetTrendCorrectionMA.SetPeriod(1); FRSI_H1_Pink.SetTrendCorrectionEnabled(false); FRSI_H1_Pink.GetMA.SetPeriod(21); FRSI_H1_Pink.SetColor(clWebPlum); end; //H4 FRSI_H4_Black:=CreateOrFindIndicator(aValue.GetStockChart(sti240),ISCIndicatorTRSIMA,'RSI_BLACK'+'_'+StockTimeIntervalNames[sti240],true, aCreated) as ISCIndicatorTRSIMA; if aCreated then begin FRSI_H4_Black.SetPeriod(12); FRSI_H4_Black.GetTrendCorrectionMA.SetPeriod(55); FRSI_H4_Black.SetTrendCorrectionEnabled(true); FRSI_H4_Black.GetMA.SetPeriod(21); FRSI_H4_Black.SetColor(clBlack); end; FRSI_H4_Blue:=CreateOrFindIndicator(aValue.GetStockChart(sti240),ISCIndicatorTRSIMA,'RSI_BLUE'+'_'+StockTimeIntervalNames[sti240],true, aCreated) as ISCIndicatorTRSIMA; if aCreated then begin FRSI_H4_Blue.SetPeriod(12); FRSI_H4_Blue.GetTrendCorrectionMA.SetPeriod(84); FRSI_H4_Blue.SetTrendCorrectionEnabled(true); FRSI_H4_Blue.GetMA.SetPeriod(21); FRSI_H4_Blue.SetColor(clBlue); end; FRSI_H4_Pink:=CreateOrFindIndicator(aValue.GetStockChart(sti240),ISCIndicatorTRSIMA,'RSI_PINK'+'_'+StockTimeIntervalNames[sti240],true, aCreated) as ISCIndicatorTRSIMA; if aCreated then begin FRSI_H4_Pink.SetPeriod(12); FRSI_H4_Pink.GetTrendCorrectionMA.SetPeriod(1); FRSI_H4_Pink.SetTrendCorrectionEnabled(false); FRSI_H4_Pink.GetMA.SetPeriod(21); FRSI_H4_Pink.SetColor(clWebPlum); end; //D1 FRSI_D1_Black:=CreateOrFindIndicator(aValue.GetStockChart(sti1440),ISCIndicatorTRSIMA,'RSI_BLACK'+'_'+StockTimeIntervalNames[sti1440],true, aCreated) as ISCIndicatorTRSIMA; if aCreated then begin FRSI_D1_Black.SetPeriod(12); FRSI_D1_Black.GetTrendCorrectionMA.SetPeriod(55); FRSI_D1_Black.SetTrendCorrectionEnabled(true); FRSI_D1_Black.GetMA.SetPeriod(21); FRSI_D1_Black.SetColor(clBlack); end; FRSI_D1_Blue:=CreateOrFindIndicator(aValue.GetStockChart(sti1440),ISCIndicatorTRSIMA,'RSI_BLUE'+'_'+StockTimeIntervalNames[sti1440],true, aCreated) as ISCIndicatorTRSIMA; if aCreated then begin FRSI_D1_Blue.SetPeriod(12); FRSI_D1_Blue.GetTrendCorrectionMA.SetPeriod(84); FRSI_D1_Blue.SetTrendCorrectionEnabled(true); FRSI_D1_Blue.GetMA.SetPeriod(21); FRSI_D1_Blue.SetColor(clBlue); end; FRSI_D1_Pink:=CreateOrFindIndicator(aValue.GetStockChart(sti1440),ISCIndicatorTRSIMA,'RSI_PINK'+'_'+StockTimeIntervalNames[sti1440],true, aCreated) as ISCIndicatorTRSIMA; if aCreated then begin FRSI_D1_Pink.SetPeriod(12); FRSI_D1_Pink.GetTrendCorrectionMA.SetPeriod(1); FRSI_D1_Pink.SetTrendCorrectionEnabled(false); FRSI_D1_Pink.GetMA.SetPeriod(21); FRSI_D1_Pink.SetColor(clWebPlum); end; //FRSI_M15:=CreateOrFindIndicator(aValue.GetStockChart(sti15),ISCIndicatorTRSIMA,'RSI'+'_'+StockTimeIntervalNames[sti15],true, aCreated) as ISCIndicatorTRSIMA; //FMA84_M1:=CreateOrFindIndicator(aValue.GetStockChart(sti1),ISCIndicatorMA,'MA84'+'_'+StockTimeIntervalNames[sti1],true, aCreated) as ISCIndicatorMA; //Ничего не нашли, создадим нового эксперта if aCreated then begin //FMA84_M1.SetPeriod(84); end; end; end; function TStockTraderTRSIMA_M15_48.ToPrice(aPoints: integer): TSCRealNumber; begin result:=GetBroker.PointToPrice(GetSymbol,1); end; function TStockTraderTRSIMA_M15_48.Spread: TSCRealNumber; begin result:=GetBroker.PointToPrice(GetSymbol,GetBroker.GetMarketInfo(GetSymbol).Spread); end; procedure TStockTraderTRSIMA_M15_48.UpdateStep2(const aTime: TDateTime); var aIdxM15 : integer; //aIdxH1 : integer; //aIdxH4 : integer; aOpen,aClose : integer; aRSIValueBlack,aRSIValueBlue,aRSIValuePink: TSCRealNumber; aRSIValueBlack_1,aRSIValueBlue_1,aRSIValuePink_1: TSCRealNumber; aRSIChangedBlack,aRSIChangedBlue,aRSIChangedPink: boolean; x: integer; begin RemoveClosedOrders; //Не чаще одного раза в минуту //if (aTime-FLastUpdateTime)*MinsPerDay<1 then // exit; //if (not DateUtils.MinuteOf(aTime) in [1,16,31,46]) then // exit; FLastUpdateTime:=aTime; aIdxM15:=TStockDataUtils.FindBar(FRSI_M15_Black.GetInputData,aTime,sti15); if aIdxM15=FSkipM15Index then exit; if aIdxM15=FLastOrderM15Index then exit; //aIdxH1:=TStockDataUtils.FindBar(FRSI_H1_Black.GetInputData,aTime,sti60); //if aIdxH1<=2 then // exit; //aIdxH4:=TStockDataUtils.FindBar(FRSI_H4_Black.GetInputData,aTime,sti240); //if aIdxH4<=2 then // exit; if (aIdxM15<>-1) and (aIdxM15>=100) then begin aOpen:=0; aClose:=0; aRSIValueBlack:=FRSI_M15_Black.GetValue(aIdxM15); aRSIValueBlue:=FRSI_M15_Blue.GetValue(aIdxM15); aRSIValuePink:=FRSI_M15_Pink.GetValue(aIdxM15); aRSIValueBlack_1:=FRSI_M15_Black.GetValue(aIdxM15-1); aRSIValueBlue_1:=FRSI_M15_Blue.GetValue(aIdxM15-1); aRSIValuePink_1:=FRSI_M15_Pink.GetValue(aIdxM15-1); //Анализ BUY aRSIChangedBlack:=(aRSIValueBlack>=50) and (aRSIValueBlack_1<50); aRSIChangedBlue:= (aRSIValueBlue>=50) and (aRSIValueBlue_1<50); aRSIChangedPink:= (aRSIValuePink>=50) and (aRSIValuePink_1<50); if aRSIChangedBlack or aRSIChangedBlue or aRSIChangedPink then begin x:= integer(aRSIValueBlack>=50)+integer(aRSIValueBlue>=50)+integer(aRSIValuePink>=50); if (x=2) and (aRSIValuePink<20) then x:=0; //x:= integer((aRSIValueBlack>=50) or (aRSIValueBlue>=50))+integer(aRSIValuePink>=50); if x>=2 then begin if (aIdxM15-FLastOrderM15Index)<=2 then begin FSkipM15Index:=aIdxM15; //AddMessageAndSetMark(mkStop,'Reject opening BUY: too close to previous order',clRed); end //Если поменялся Blue или Black, и при этом Pink уже отчскочил от верхней границы, то игнорируем сигнал else if (aRSIChangedBlack or aRSIChangedBlue) and (FRSI_M15_Pink.GetLastSide(aIdxM15,1)=1) then begin //AddMessageAndSetMark(mkStop,'Reject opening BUY: RSI M15 on top',clRed); end (*else if FRSI_H1_Pink.GetTrendDirection(aIdxH1)=-1 then begin AddMessageAndSetMark(mkStop,'Reject opening BUY: RSI Pink H1 trend down',clRed); end*) else begin aOpen:=1; aClose:=-1; end; end; end; //Анализ SELL aRSIChangedBlack:=(aRSIValueBlack<=50) and (aRSIValueBlack_1>50); aRSIChangedBlue:= (aRSIValueBlue<=50) and (aRSIValueBlue_1>50); aRSIChangedPink:= (aRSIValuePink<=50) and (aRSIValuePink_1>50); if aRSIChangedBlack or aRSIChangedBlue or aRSIChangedPink then begin x:=integer(aRSIValueBlack<=50) + integer(aRSIValueBlue<=50) + integer(aRSIValuePink<=50); if (x=2) and (aRSIValuePink>80) then x:=0; //x:=integer((aRSIValueBlack<=50) or (aRSIValueBlue<=50)) + integer(aRSIValuePink<=50); if x>=2 then begin if (aIdxM15-FLastOrderM15Index)<=2 then begin FSkipM15Index:=aIdxM15; //AddMessageAndSetMark(mkStop,'Reject opening SELL: too close to previous order',clRed); end //Если поменялся Blue или Black, и при этом Pink уже отчскочил нижней от границы, то игнорируем сигнал else if (aRSIChangedBlack or aRSIChangedBlue) and (FRSI_M15_Pink.GetLastSide(aIdxM15,1)=-1) then begin //AddMessageAndSetMark(mkStop,'Reject opening SELL: RSI M15 on bottom',clRed); end (*else if FRSI_H1_Pink.GetTrendDirection(aIdxH1)=1 then begin AddMessageAndSetMark(mkStop,'Reject opening SELL: RSI Pink H1 trend up',clRed); end*) (*else if FRSI_H4_Pink.GetTrendDirection(aIdxH4)=1 then begin AddMessageAndSetMark(mkStop,'Reject opening SELL: RSI Pink H4 trend up',clRed); end*) (*else if FRSI_H1_Pink.GetDelta(aIdxH1)=1 then begin AddMessageAndSetMark(mkStop,'Reject opening SELL: RSI Pink H1 delta up',clRed); end*) (*else if FRSI_H4_Pink.GetDelta(aIdxH4)=1 then begin AddMessageAndSetMark(mkStop,'Reject opening SELL: RSI Pink H4 delta up',clRed); end*) else begin aOpen:=-1; aClose:=1; end; end; end; if aClose=-1 then CloseAllSellOrders('') else if aClose=1 then CloseAllBuyOrders(''); if aOpen<>0 then begin //BUY if (aOpen=1) {and (LastOrderType<>lotBuy)} then begin OpenOrder(okBuy); FLastOrderM15Index:=aIdxM15; end //SELL else if (aOpen=-1) {and (LastOrderType<>lotSell)} then begin FLastOrderM15Index:=aIdxM15; OpenOrder(okSell); end; end; end; end; procedure TStockTraderTRSIMA_M15_48.AddMessageAndSetMark(const aOrder: IStockOrder; const aMarkType: TSCChartMarkKind; const aMessage: string); begin GetBroker.AddMessage(aOrder,aMessage); AddMarkToCharts(GetBroker.GetCurrentTime, GetBroker.GetCurrentPrice({aOrder}self.GetSymbol,bpkBid), aMarkType,aMessage); end; initialization FC.Trade.Trader.Factory.TraderFactory.RegisterTrader('Basic','TRSIMA M15 48',TStockTraderTRSIMA_M15_48,IStockTraderTRSIMA_M15_48); end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { SOAP Attachment Interfaces } { } { Copyright (c) 2001 Inprise Corporation } { } {*******************************************************} unit SOAPAttachIntf; interface uses Classes, InvokeRegistry; type { TODO Owner:BB What does this class offer compared to TObjectList ?? } TSoapDataList = class(TList) public procedure Clear; override; function Add(Item: Pointer): Integer; reintroduce; procedure Assign(ListA: TList; AOperator: TListAssignOp = laCopy; ListB: TList = Nil); reintroduce; procedure Insert(Index: Integer; aClass: TClass); reintroduce; function Remove(aClass: TClass): Integer; reintroduce; end; TOnSendAttachmentEvent = procedure(AttachmentStream: TStream; Attachment: TSOAPAttachment) of object; TOnGetAttachmentEvent = procedure(AttachmentStream: TStream; Attachment: TSOAPAttachment) of object; IMimeAttachmentHandler = interface ['{6B742425-FE6A-4EC2-ACF9-4751AF4E0EF8}'] procedure ProcessMultiPartForm( const ASourceStream, ADestStream: TStream; AMimeBoundary: string; SoapHeaders: TStrings; Attachments: TSoapDataList; TempDir: string); { Add a new Soap Header } procedure AddSoapHeader(Value: string); procedure CreateMimeStream(Envelope: TStream; Attachments: TSoapDataList); { combine MimeBoundary, Soap Headers and Envelope, and Attachments into single Stream } procedure FinalizeStream; function GetMIMEStream(Release: Boolean = False): TStream; function GetMIMEBoundary: String; procedure SetMIMEBoundary(const MimeBndry: String); function GetOnSendAttachmentEvent: TOnSendAttachmentEvent; procedure SetOnSendAttachmentEvent(OnSendAttachment: TOnSendAttachmentEvent); function GetOnGetAttachmentEvent: TOnGetAttachmentEvent; procedure SetOnGetAttachmentEvent(OnGetAttachment: TOnGetAttachmentEvent); property MIMEBoundary: string read GetMimeBoundary write SetMimeBoundary; property OnSendAttachment: TOnSendAttachmentEvent read GetOnSendAttachmentEvent write SetOnSendAttachmentEvent; property OnGetAttachment: TOnGetAttachmentEvent read GetOnGetAttachmentEvent write SetOnGetAttachmentEvent; end; implementation uses SysUtils, SOAPConst, SOAPAttach; procedure TSoapDataList.Clear; var I: Integer; begin for I := 0 to Count -1 do TSOAPAttachmentData(Items[I]).Free; inherited Clear; end; procedure TSoapDataList.Assign(ListA: TList; AOperator: TListAssignOp = laCopy; ListB: TList = Nil); begin raise Exception.Create(SInvalidMethod); end; function TSoapDataList.Add(Item: Pointer): Integer; begin Result := inherited Add(Item); end; procedure TSoapDataList.Insert(Index: Integer; aClass: TClass); begin raise Exception.Create(SInvalidMethod); end; function TSoapDataList.Remove(aClass: TClass): Integer; begin raise Exception.Create(SInvalidMethod); end; end.
unit fNoteCslt; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, fAutoSz, StdCtrls, ORCtrls, ORFn, VA508AccessibilityManager; type TfrmNoteConsult = class(TfrmAutoSz) Label1: TStaticText; Label2: TStaticText; lstRequests: TORListBox; Label3: TLabel; Label4: TLabel; Label5: TLabel; cmdOK: TButton; cmdCancel: TButton; Label6: TLabel; Label7: TLabel; procedure cmdCancelClick(Sender: TObject); procedure cmdOKClick(Sender: TObject); procedure lstRequestsClick(Sender: TObject); private { Private declarations } FSelectedRequest: Integer; public { Public declarations } end; function SelectConsult: Integer; implementation {$R *.DFM} uses rTIU; const TX_NO_REQUEST = 'There are no consult requests available for this patient.' + CRLF + 'Another progress note title must be selected.'; TX_NO_REQUEST_CAP = 'No Consult Requests'; function SelectConsult: Integer; var frmNoteConsult: TfrmNoteConsult; AConsultList: TStringList; begin Result := 0; frmNoteConsult := TfrmNoteConsult.Create(Application); AConsultList := TStringList.Create; try ListConsultRequests(AConsultList); if AConsultList.Count > 0 then begin ResizeFormToFont(TForm(frmNoteConsult)); FastAssign(AConsultList, frmNoteConsult.lstRequests.Items); frmNoteConsult.ShowModal; Result := frmNoteConsult.FSelectedRequest; end else InfoBox(TX_NO_REQUEST, TX_NO_REQUEST_CAP, MB_OK); finally frmNoteConsult.Release; AConsultList.Free; end; end; procedure TfrmNoteConsult.lstRequestsClick(Sender: TObject); begin inherited; if lstRequests.ItemIEN > 0 then cmdOK.Enabled := True else cmdOK.Enabled := False; end; procedure TfrmNoteConsult.cmdOKClick(Sender: TObject); begin inherited; FSelectedRequest := lstRequests.ItemIEN; Close; end; procedure TfrmNoteConsult.cmdCancelClick(Sender: TObject); begin inherited; FSelectedRequest := 0; Close; end; end.
namespace RemObjects.SDK.CodeGen4; uses RemObjects.Elements.RTL; type RodlEnum = public class(RodlComplexEntity<RodlEnumValue>) public constructor; begin inherited constructor("EnumValue", "Values"); end; method LoadFromXmlNode(node: XmlElement); override; begin LoadFromXmlNode(node, -> new RodlEnumValue); PrefixEnumValues := not assigned(node.Attribute["Prefix"]) or (node.Attribute["Prefix"]:Value ≠ '0'); end; method LoadFromJsonNode(node: JsonNode); override; begin LoadFromJsonNode(node, -> new RodlEnumValue); PrefixEnumValues := not assigned(node["Prefix"]) or node["Prefix"].BooleanValue = true; end; property PrefixEnumValues: Boolean; property DefaultValueName: String read if Count > 0 then Item[0].Name; end; RodlEnumValue = public class(RodlEntity) end; // // // RodlArray = public class(RodlEntity) public method LoadFromXmlNode(node: XmlElement); override; begin inherited LoadFromXmlNode(node); ElementType := FixLegacyTypes(node.FirstElementWithName("ElementType"):Attribute["DataType"]:Value); end; method LoadFromJsonNode(node: JsonNode); override; begin inherited LoadFromJsonNode(node); ElementType := FixLegacyTypes(node["DataType"]:StringValue); end; property ElementType: String; end; // // // RodlStructEntity = public abstract class (RodlComplexEntity<RodlField>) public constructor; begin inherited constructor("Element"); end; method LoadFromXmlNode(node: XmlElement); override; begin LoadFromXmlNode(node,-> new RodlField); if (node.Attribute["AutoCreateParams"] ≠ nil) then AutoCreateProperties := not assigned(node.Attribute["AutoCreateParams"]) or (node.Attribute["AutoCreateParams"].Value ≠ "0"); end; method LoadFromJsonNode(node: JsonNode); override; begin LoadFromJsonNode(node, -> new RodlField); AutoCreateProperties := not assigned(node["AutoCreateProperties"]) or (node["AutoCreateProperties"].BooleanValue = true); end; property AutoCreateProperties: Boolean := False; end; RodlStruct = public class(RodlStructEntity) end; RodlException = public class(RodlStructEntity) end; RodlField = public class(RodlTypedEntity) end; end.
unit XMLBuilderComp; interface uses Windows, Messages, SysUtils, Classes, WebComp, MidComp, SiteComp, XMLDoc, XMLIntf, HTTPProd, HTTPApp; type IXMLWriter = interface ['{3CA5F192-0A5C-4AE4-98B9-05D31A847ABB}'] procedure PushNode; procedure PopNode; procedure AddNode(const AName: WideString); procedure WritePropertyValue(AName: WideString; AValue: Variant); function GetXMLDocument: XMLIntf.IXMLDocument; property XMLDocument: IXMLDocument read GetXMLDocument; end; IWriteXMLData = interface ['{B085441C-582A-4F4D-B3D5-E404E988AD24}'] procedure WriteXMLData(AXMLWriter: IXMLWriter); end; IWriteXMLLayout = interface ['{2B13DC5A-E9E7-4CF9-B6D9-7130430BAF83}'] procedure WriteXMLLayout(AXMLWriter: IXMLWriter); end; IXMLTopLevelChild = interface ['{8AE3E9D4-97D1-4578-94E9-AD15937D884C}'] end; TXSLTemplate = class(TXMLDocument, ISetAppDispatcher) private FDispatcher: TComponent; function GetLocateFileService: ILocateFileService; function GetTemplateStream(var AOwned: Boolean): TStream; { ISetAppDispatcher } procedure SetAppDispatcher(const Value: TComponent); public procedure PrepareXSL; property DispatcherComponent: TComponent read FDispatcher; function TransformNode(ANode: IXMLNode): WideString; virtual; end; TCustomXMLBuilder = class(TComponent, IGetXMLStream, IWebComponentEditor, IGetWebComponentList, ITopLevelWebComponent, IGetProducerTemplate, IProducerEditorViewSupport, IProduceContent) private FTagName: WideString; FWebPageItems: TWebComponentList; FXSLTemplate: TXSLTemplate; procedure SetXSLTemplate(const Value: TXSLTemplate); function GetXMLDocument: IXMLDocument; function Content: string; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure WriteDesigntimeWarnings(AXMLWriter: IXMLWriter); procedure WriteDataSection(XMLWriter: IXMLWriter); virtual; { IGetXMLStream } // Allows this component to be used by XSLPageProducer function GetXMLStream(var AOwned: Boolean): TStream; function ImplGetXMLStream(var AOwned: Boolean): TStream; virtual; { IGetWebComponentsList } function GetComponentList: TObject; function GetDefaultComponentList: TObject; procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; procedure SetChildOrder(Component: TComponent; Order: Integer); override; { IWebComponentEditor } function CanAddClass(AParent: TComponent; AClass: TClass): Boolean; function ImplCanAddClass(AParent: TComponent; AClass: TClass): Boolean; virtual; { IProduceContent } function ProduceContent: string; { IGetProducerTemplate } function GetProducerTemplateStream(out AOwned: Boolean): TStream; function GetProducerTemplateFileName: string; { IProducerEditorViewSupport } function HasScriptView: Boolean; function HasXMLBrowserView: Boolean; function HasXSLBrowserView: Boolean; function HasHTMLBrowserView: Boolean; function GetXMLData(var Owned: Boolean): TStream; function GetXSLData(var Owned: Boolean): TStream; function GetTemplateFileType: string; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property TagName: WideString read FTagName write FTagName; property WebPageItems: TWebComponentList read FWebPageItems; property XSLTemplate: TXSLTemplate read FXSLTemplate write SetXSLTemplate; property XMLDocument: IXMLDocument read GetXMLDocument; end; procedure ComponentListWriteXMLData(AComponentList: TWebComponentList; AXMLWriter: IXMLWriter); procedure ComponentListWriteXMLLayout(AComponentList: TWebComponentList; AXMLWriter: IXMLWriter); implementation uses XMLBuilderWriter, ActiveX, Variants, Contnrs; const sWarnings = WideString('Warnings'); sWarning = WideString('Warning'); sMessage = WideString('Message'); type TDesigntimeWarnings = class(TAbstractDesigntimeWarnings) private FStrings: TStrings; FObjects: TObjectList; public procedure AddString(AWarning: string); override; procedure AddObject(AObject: TObject); override; property Strings: TStrings read FStrings; constructor Create; destructor Destroy; override; end; { TDesigntimeWarnings } procedure TDesigntimeWarnings.AddString(AWarning: string); begin FStrings.Add(AWarning); end; procedure TDesigntimeWarnings.AddObject(AObject: TObject); procedure ContainerWarnings(Container: IWebComponentContainer); var I: Integer; begin if Container <> nil then for I := 0 to Container.ComponentCount - 1 do Self.AddObject(Container.Components[I]); end; var GetIntf: IGetDesignTimeWarnings; WebDataFields: IWebDataFields; WebActionsList: IWebActionsList; GetWebComponentList: IGetWebComponentList; Container: IWebComponentContainer; I: Integer; begin if FObjects.IndexOf(AObject) > 0 then Exit; FObjects.Add(AObject); if Container <> nil then for I := 0 to Container.ComponentCount - 1 do Self.AddObject(Container.Components[I]); if Supports(AObject, IGetDesigntimeWarnings, GetIntf) then GetIntf.GetDesigntimeWarnings(Self); if Supports(AObject, IWebDataFields, WebDataFields) then begin Container := WebDataFields.GetVisibleFields; ContainerWarnings(Container); end; if Supports(AObject, IWebActionsList, WebActionsList) then begin Container := WebActionsList.GetVisibleActions; ContainerWarnings(Container); end; if Supports(AObject, IGetWebComponentList, GetWebComponentList) then begin Supports(GetWebComponentList.GetComponentList, IWebComponentContainer, Container); ContainerWarnings(Container); end; end; constructor TDesigntimeWarnings.Create; begin FStrings := TStringList.Create; FObjects := TObjectList.Create(False { not owned} ); inherited; end; destructor TDesigntimeWarnings.Destroy; begin FStrings.Free; FObjects.Free; inherited; end; { TCustomXMLBuilder } function TCustomXMLBuilder.CanAddClass(AParent: TComponent; AClass: TClass): Boolean; begin Result := ImplCanAddClass(AParent, AClass); end; constructor TCustomXMLBuilder.Create(AOwner: TComponent); begin FWebPageItems := TWebComponentList.Create(Self); FTagName := 'XMLBuilder'; inherited; end; procedure TCustomXMLBuilder.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = FXSLTemplate) then FXSLTemplate := nil; end; destructor TCustomXMLBuilder.Destroy; begin inherited; FWebPageItems.Free; end; procedure TCustomXMLBuilder.GetChildren(Proc: TGetChildProc; Root: TComponent); var I: Integer; WebComponent: TComponent; begin inherited GetChildren(Proc, Root); for I := 0 to FWebPageItems.Count - 1 do begin WebComponent := FWebPageItems.WebComponents[I]; if WebComponent.Owner = Root then Proc(WebComponent); end; end; function TCustomXMLBuilder.GetComponentList: TObject; begin Result := FWebPageItems; end; function TCustomXMLBuilder.GetDefaultComponentList: TObject; begin Assert(False, 'No default components list'); { Do not localize } Result := nil; end; function TCustomXMLBuilder.GetXMLStream( var AOwned: Boolean): TStream; begin Result := ImplGetXMLStream(AOwned); end; function TCustomXMLBuilder.ImplCanAddClass(AParent: TComponent; AClass: TClass): Boolean; begin Result := Supports(AClass, IXMLTopLevelChild); end; procedure ComponentListWriteXMLData(AComponentList: TWebComponentList; AXMLWriter: IXMLWriter); var I: Integer; Component: TComponent; WriteXMLData: IWriteXMLData; begin for I := 0 to AComponentList.Count - 1 do begin Component := AComponentList.WebComponents[I]; if Supports(IInterface(Component), IWriteXMLData, WriteXMLDAta) then begin WriteXMLData.WriteXMLData(AXMLWriter); end; end; end; procedure ComponentListWriteXMLLayout(AComponentList: TWebComponentList; AXMLWriter: IXMLWriter); var I: Integer; Component: TComponent; WriteXMLLayout: IWriteXMLLayout; begin for I := 0 to AComponentList.Count - 1 do begin Component := AComponentList.WebComponents[I]; if Supports(IUnknown(Component), IWriteXMLLayout, WriteXMLLayout) then begin WriteXMLLayout.WriteXMLLayout(AXMLWriter); end; end; end; function TCustomXMLBuilder.ImplGetXMLStream( var AOwned: Boolean): TStream; var XMLWriter: IXMLWriter; begin XMLWriter := TXMLWriter.Create; XMLWriter.AddNode(TagName); WriteDataSection(XMLWriter); AOwned := True; Result := TMemoryStream.Create; try XMLWriter.XMLDocument.SaveToStream(Result); except FreeAndNil(Result); raise; end; end; procedure TCustomXMLBuilder.WriteDataSection(XMLWriter: IXMLWriter); begin if csDesigning in ComponentState then WriteDesigntimeWarnings(XMLWriter); ComponentListWriteXMLData(WebPageItems, XMLWriter); end; function TCustomXMLBuilder.GetXMLDocument: IXMLDocument; var XMLWriter: IXMLWriter; begin XMLWriter := TXMLWriter.Create; XMLWriter.AddNode(TagName); WriteDataSection(XMLWriter); Result := XMLWriter.XMLDocument; end; procedure TCustomXMLBuilder.WriteDesigntimeWarnings(AXMLWriter: IXMLWriter); var Warnings: TDesigntimeWarnings; I, J: Integer; begin Warnings := TDesignTimeWarnings.Create; try for I := 0 to WebPageItems.Count - 1 do Warnings.AddObject(WebPageItems[I]); if Warnings.Strings.Count > 0 then begin AXMLWriter.PushNode; try AXMLWriter.AddNode(sWarnings); for J := 0 to Warnings.Strings.Count - 1 do begin AXMLWriter.PushNode; try AXMLWriter.AddNode(sWarning); AXMLWriter.WritePropertyValue(sMessage, Warnings.Strings[J]); finally AXMLWriter.PopNode; end; end; finally AXMLWriter.PopNode; end; end; finally Warnings.Free; end; end; procedure TCustomXMLBuilder.SetChildOrder(Component: TComponent; Order: Integer); var Intf: IWebComponent; begin if FWebPageItems.IndexOf(Component) >= 0 then if Supports(IInterface(Component), IWebComponent, Intf) then Intf.Index := Order else Assert(False, 'Interface not supported'); end; function TCustomXMLBuilder.GetProducerTemplateFileName: string; begin if XSLTemplate <> nil then Result := XSLTemplate.FileName else Result := ''; end; function TCustomXMLBuilder.GetProducerTemplateStream( out AOwned: Boolean): TStream; begin Result := nil; end; function TCustomXMLBuilder.GetTemplateFileType: string; begin Result := 'XSL'; end; function TCustomXMLBuilder.GetXMLData(var Owned: Boolean): TStream; begin Result := GetXMLStream(Owned); end; function TCustomXMLBuilder.GetXSLData(var Owned: Boolean): TStream; begin if XSLTemplate <> nil then begin XSLTemplate.PrepareXSL; Owned := True; Result := TMemoryStream.Create; try XSLTemplate.SaveToStream(Result); except FreeAndNil(Result); raise; end; end else Result := nil; end; function TCustomXMLBuilder.HasHTMLBrowserView: Boolean; begin Result := True; end; function TCustomXMLBuilder.HasScriptView: Boolean; begin Result := False; end; function TCustomXMLBuilder.HasXMLBrowserView: Boolean; begin Result := True; end; function TCustomXMLBuilder.HasXSLBrowserView: Boolean; begin Result := True; end; procedure TCustomXMLBuilder.SetXSLTemplate(const Value: TXSLTemplate); begin if FXSLTemplate <> Value then begin FXSLTemplate := Value; if Value <> nil then Value.FreeNotification(Self); end; end; function TCustomXMLBuilder.Content: string; var W: WideString; XMLDocument: IXMLDocument; begin if XSLTemplate = nil then raise Exception.Create('XSLTemplate is nil'); XMLDocument := GetXMLDocument; W := XSLTemplate.TransformNode(XMLDocument.DocumentElement.ParentNode); Result := W; end; function TCustomXMLBuilder.ProduceContent: string; begin Result := Content; end; { TXSLTemplate } function TXSLTemplate.TransformNode(ANode: IXMLNode): WideString; begin PrepareXSL; ANode.TransformNode(DocumentElement, Result); end; function TXSLTemplate.GetLocateFileService: ILocateFileService; var GetIntf: IGetLocateFileService; begin Result := nil; if DispatcherComponent <> nil then if Supports(IUnknown(DispatcherComponent), IGetLocateFileService, GetIntf) then Result := GetIntf.GetLocateFileService; end; function TXSLTemplate.GetTemplateStream(var AOwned: Boolean): TStream; var ManagerIntf: ILocateFileService; S: string; begin Result := nil; if FileName <> '' then begin if DesignerFileManager <> nil then begin S := DesignerFileManager.QualifyFileName(FileName); if S <> '' then Result := DesignerFileManager.GetStream(S, AOwned); end; if Result = nil then begin ManagerIntf := GetLocateFileService; if ManagerIntf <> nil then Result := ManagerIntf.GetTemplateStream(Self, FileName, AOwned) end; end end; procedure TXSLTemplate.PrepareXSL; var S: TStream; Owned: Boolean; QualifiedName: string; begin if (not Active) or (csDesigning in ComponentState) then begin S := GetTemplateStream(Owned); try if S <> nil then LoadFromStream(S); finally if Owned then S.Free; end; if (S = nil) and (not Active) then if FileName <> '' then begin // Support filenames without fully qualified path QualifiedName := WebComp.QualifyFileName(FileName); if AnsiCompareFileName(QualifiedName, FileName) <> 0 then // Set to directory of project or directory of executable SetCurrentDir(ExtractFilePath(WebComp.QualifyFileName('x'))); end; end; Active := True; end; procedure TXSLTemplate.SetAppDispatcher(const Value: TComponent); begin if FDispatcher <> Value then begin if Value <> nil then Value.FreeNotification(Self); FDispatcher := Value; end; end; end.
unit Diff; {$IFDEF FPC} {$mode delphi}{$H+} {$ENDIF} (******************************************************************************* * Component TDiff * * Version: 1.0 * * Date: 12 July 2023 * * Compilers: Delphi 10.x * * Author: Rickard Johansson * * Copyright: © 2023 Rickard Johansson * * * * Licence to use, terms and conditions: * * The code in the TDiff component is released as freeware * * provided you agree to the following terms & conditions: * * 1. the copyright notice, terms and conditions are * * left unchanged * * 2. modifications to the code by other authors must be * * clearly documented and accompanied by the modifier's name. * * 3. the TDiff component may be freely compiled into binary * * format and no acknowledgement is required. However, a * * discrete acknowledgement would be appreciated (eg. in a * * program's 'About Box'). * * * * Description: Component to list differences between two integer arrays * * using a "longest common subsequence" algorithm. * * Typically, this component is used to diff 2 text files * * once their individuals lines have been hashed. * * * * * *******************************************************************************) (******************************************************************************* * History: * * 12 July 2023 - Original Release. * *******************************************************************************) interface uses {$IFnDEF FPC} Generics.Collections, Windows, {$ELSE} LCLIntf, LCLType, FGL, {$ENDIF} SysUtils, Math, Forms, Classes, DiffTypes, Diff_ND, Diff_NP; type TDiff = class(TComponent) private FCancelled: boolean; FExecuting: boolean; FDiffAlgorithm: TDiffAlgorithm; FDiff_ND: TNDDiff; FDiff_NP: TNPDiff; function GetCompareCount: integer; function GetCompare(index: integer): TCompareRec; function GetDiffStats: TDiffStats; public constructor Create(aOwner: TComponent); override; destructor Destroy; override; // Compare strings or list of Cardinals ... {$IFDEF FPC} function Execute(const alist1, alist2: TIntegerList): boolean; overload; {$ELSE} function Execute(const alist1, alist2: TList<Cardinal>; const aDiffAlgorithm: TDiffAlgorithm = algND): boolean; overload; {$ENDIF} function Execute(const s1, s2: string; const aDiffAlgorithm: TDiffAlgorithm = algND): boolean; overload; // Cancel allows interrupting excessively prolonged comparisons procedure Cancel; procedure Clear; property Cancelled: boolean read FCancelled; property Count: integer read GetCompareCount; property Compares[index: integer]: TCompareRec read GetCompare; default; property DiffAlgorithm: TDiffAlgorithm read FDiffAlgorithm write FDiffAlgorithm; property DiffStats: TDiffStats read GetDiffStats; end; procedure Register; implementation procedure Register; begin RegisterComponents('Samples', [TDiff]); end; constructor TDiff.Create(aOwner: TComponent); begin inherited; FDiff_ND := TNDDiff.Create(AOwner); FDiff_NP := TNPDiff.Create(AOwner); FDiffAlgorithm := algNP; end; //------------------------------------------------------------------------------ destructor TDiff.Destroy; begin // FDiff_ND.Free; // FDiff_NP.Free; inherited; end; //------------------------------------------------------------------------------ function TDiff.Execute(const s1, s2: string; const aDiffAlgorithm: TDiffAlgorithm = algND): boolean; begin Result := not FExecuting; if not Result then exit; FCancelled := false; FExecuting := true; FDiffAlgorithm := aDiffAlgorithm; try if aDiffAlgorithm = algND then FDiff_ND.Execute(s1, s2) else if aDiffAlgorithm = algNP then FDiff_NP.Execute(s1, s2); finally FExecuting := false; end; end; //------------------------------------------------------------------------------ {$IFDEF FPC} function TDiff.Execute(const alist1, alist2: TIntegerList; const aDiffAlgorithm: TDiffAlgorithm): boolean; {$ELSE} function TDiff.Execute(const alist1, alist2: TList<Cardinal>; const aDiffAlgorithm: TDiffAlgorithm = algND): boolean; {$ENDIF} begin Result := not FExecuting; if not Result then exit; FCancelled := false; FExecuting := true; FDiffAlgorithm := aDiffAlgorithm; try if aDiffAlgorithm = algND then FDiff_ND.Execute(alist1, alist2) else if aDiffAlgorithm = algNP then FDiff_NP.Execute(alist1, alist2); finally FExecuting := false; end; end; //------------------------------------------------------------------------------ function TDiff.GetCompareCount: integer; begin if FDiffAlgorithm = algND then Result := FDiff_ND.CompareList.Count else Result := FDiff_NP.CompareList.count; end; //------------------------------------------------------------------------------ function TDiff.GetCompare(index: integer): TCompareRec; begin if FDiffAlgorithm = algND then Result := PCompareRec(FDiff_ND.CompareList[index])^ else if FDiffAlgorithm = algNP then Result := PCompareRec(FDiff_NP.CompareList[index])^; end; //------------------------------------------------------------------------------ procedure TDiff.Cancel; begin FCancelled := True; if FDiffAlgorithm = algND then FDiff_ND.Cancel else if FDiffAlgorithm = algNP then FDiff_NP.Cancel; end; procedure TDiff.Clear; begin if FDiffAlgorithm = algND then FDiff_ND.Clear else if FDiffAlgorithm = algNP then FDiff_NP.Clear; end; function TDiff.GetDiffStats: TDiffStats; begin if FDiffAlgorithm = algND then Result := FDiff_ND.DiffStats else if FDiffAlgorithm = algNP then Result := FDiff_NP.DiffStats; end; //------------------------------------------------------------------------------ end.
unit Form.SQLMonitoring; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, Form.BaseForm, cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore, dxSkinMetropolis, cxTextEdit, cxMemo, dxBevel, cxClasses, dxSkinsForm, Vcl.Menus, Vcl.StdCtrls, cxButtons, Vcl.ExtCtrls, System.Generics.Collections, System.ImageList, Vcl.ImgList, cxCheckBox, DASQLMonitor; type TfrmSQLMonitoring = class(TfrmBase) mmoLog: TcxMemo; pnlButton: TPanel; btnClear: TcxButton; chkEnableMonitor: TcxCheckBox; procedure btnClearClick(Sender: TObject); procedure chkEnableMonitorClick(Sender: TObject); procedure FormCreate(Sender: TObject); private class var FInstance: TfrmSqlMonitoring; private procedure SQLMonitor(Sender: TObject; Text: string; Flag: TDATraceFlag); private procedure Log(const S: string); procedure BreakLine; end; implementation {$R *.dfm} uses ConnectionModule; { TfrmSQLMonitoring } procedure TfrmSQLMonitoring.BreakLine; begin mmoLog.Lines.Add('================================================'); end; procedure TfrmSQLMonitoring.btnClearClick(Sender: TObject); begin mmoLog.Clear; end; procedure TfrmSQLMonitoring.chkEnableMonitorClick(Sender: TObject); begin DM.ActiveMonitoring := chkEnableMonitor.Checked; end; procedure TfrmSQLMonitoring.FormCreate(Sender: TObject); begin DM.OnSQLEvent := SQLMonitor; end; procedure TfrmSQLMonitoring.Log(const S: string); begin mmoLog.Lines.Add(S); end; procedure TfrmSQLMonitoring.SQLMonitor(Sender: TObject; Text: string; Flag: TDATraceFlag); begin BreakLine; Log(Text); BreakLine; end; end.
unit UProdutoCompra; interface uses UProduto, UCfop; type ProdutoCompra = class(Produto) private protected umCfop : Cfop; ncm_sh : string[8]; cst_compra : string[3]; unidade_compra : string[3]; quantidade_compra : Real; valorUnitario_compra : Real; desconto_compra : Real; icms_compra : Real; ipi_compra : Real; valorTotal_compra : Real; baseIcms_compra : Real; valorIcms_compra : Real; valorIpi_compra : Real; public Constructor CrieObjeto; Destructor Destrua_Se; Procedure setUmCfop (vCfop : Cfop); Procedure setNCMSH (vNCMSH : String); Procedure setCSTCompra (vCSTCompra : String); Procedure setUnidadeCompra (vUnidade : String); Procedure setQuantidadeCompra (vQuantidade : Real); Procedure setValorUnitarioCompra (vPrecoCusto : Real); Procedure setDescontoCompra (vDesconto : Real); Procedure setICMSCompra (vICMS : Real); Procedure setIPICompra (vIPI : Real); Procedure setValorTotalCompra (vValorTotal : Real); Procedure setBaseIcmsCompra (vBaseIcms : Real); Procedure setValorIcmsCompra (vValorIcms : Real); Procedure setValorIpiCompra (vValorIpi : Real); Function getUmCfop : Cfop; Function getNCMSH : String; Function getCSTCompra : String; Function getUnidadeCompra : String; Function getQuantidadeCompra : Real; Function getValorUnitarioCompra : Real; Function getDescontoCompra : Real; Function getICMSCompra : Real; Function getIPICompra : Real; Function getValorTotalCompra : Real; Function getBaseIcmsCompra : Real; Function getValorIcmsCompra : Real; Function getValorIpiCompra : Real; end; implementation { ProdutoCompra } constructor ProdutoCompra.CrieObjeto; begin inherited; umCfop := Cfop.CrieObjeto; ncm_sh := ''; cst_compra := ''; unidade_compra := ''; quantidade_compra := 0.0; valorUnitario_compra := 0.0; desconto_compra := 0.0; icms_compra := 0.0; ipi_compra := 0.0; valorTotal_compra := 0.0; baseIcms_compra := 0.0; valorIcms_compra := 0.0; valorIpi_compra := 0.0; end; destructor ProdutoCompra.Destrua_Se; begin end; function ProdutoCompra.getBaseIcmsCompra: Real; begin Result := baseIcms_compra; end; function ProdutoCompra.getUmCfop: Cfop; begin Result := umCfop; end; function ProdutoCompra.getCSTCompra: String; begin Result := cst_compra; end; function ProdutoCompra.getDescontoCompra: Real; begin Result := desconto_compra; end; function ProdutoCompra.getICMSCompra: Real; begin Result := icms_compra; end; function ProdutoCompra.getIPICompra: Real; begin Result := ipi_compra; end; function ProdutoCompra.getNCMSH: String; begin Result := ncm_sh; end; function ProdutoCompra.getValorUnitarioCompra: Real; begin Result := valorUnitario_compra; end; function ProdutoCompra.getQuantidadeCompra: Real; begin Result := quantidade_compra; end; function ProdutoCompra.getUnidadeCompra: String; begin Result := unidade_compra; end; function ProdutoCompra.getValorIcmsCompra: Real; begin Result := valorIcms_compra; end; function ProdutoCompra.getValorIpiCompra: Real; begin Result := valorIpi_compra end; function ProdutoCompra.getValorTotalCompra: Real; begin Result := valorTotal_compra; end; procedure ProdutoCompra.setBaseIcmsCompra(vBaseIcms: Real); begin baseIcms_compra := vBaseIcms; end; procedure ProdutoCompra.setUmCfop(vCfop: Cfop); begin umCfop := vCfop; end; procedure ProdutoCompra.setCSTCompra(vCSTCompra: String); begin cst_compra := vCSTCompra; end; procedure ProdutoCompra.setDescontoCompra(vDesconto: Real); begin desconto_compra := vDesconto; end; procedure ProdutoCompra.setICMSCompra(vICMS: Real); begin icms_compra := vICMS; end; procedure ProdutoCompra.setIPICompra(vIPI: Real); begin ipi_compra := vIPI; end; procedure ProdutoCompra.setNCMSH(vNCMSH: String); begin ncm_sh := vNCMSH; end; procedure ProdutoCompra.setValorUnitarioCompra(vPrecoCusto: Real); begin valorUnitario_compra := vPrecoCusto; end; procedure ProdutoCompra.setQuantidadeCompra(vQuantidade: Real); begin quantidade_compra := vQuantidade; end; procedure ProdutoCompra.setUnidadeCompra(vUnidade: String); begin unidade_compra := vUnidade; end; procedure ProdutoCompra.setValorIcmsCompra(vValorIcms: Real); begin valorIcms_compra := vValorIcms; end; procedure ProdutoCompra.setValorIpiCompra(vValorIpi: Real); begin valorIpi_compra := vValorIpi; end; procedure ProdutoCompra.setValorTotalCompra(vValorTotal: Real); begin valorTotal_compra := vValorTotal; end; end.
unit amqp_tcp_socket; {$INCLUDE config.inc} //DEFINE EAGAIN Operation would have caused the process to be suspended. interface uses AMQP.Types, {$IFDEF CrossSocket} Net.Winsock2, Net.Wship6, {$ELSE} Winsock2, IdWship6, {$ENDIF} amqp.socket, System.SysUtils; function amqp_tcp_socket_new( state : Pamqp_connection_state):Pamqp_socket; function amqp_tcp_socket_recv(base, buf: Pointer; len : size_t; flags : integer):ssize_t; function amqp_tcp_socket_open( base: Pointer; host : PAMQPChar; port : integer;const timeout: Ptimeval):integer; function amqp_tcp_socket_get_sockfd(base: Pointer):int; function amqp_tcp_socket_close(base: Pointer; force: Tamqp_socket_close_enum):integer; procedure amqp_tcp_socket_set_sockfd(base : Pamqp_socket; sockfd : integer); procedure amqp_tcp_socket_delete(base: Pointer); var amqp_tcp_socket_class: Tamqp_socket_class; implementation (*TCP_CORK is Linux only; TCP_NOPUSH is BSD only; Windows does its own thing: https://baus.net/on-tcp_cork/ https://docs.microsoft.com/en-us/windows/win32/winsock/ipproto-tcp-socket-options *) procedure amqp_tcp_socket_set_sockfd(base : Pamqp_socket; sockfd : integer); var self : Pamqp_tcp_socket; s: string; begin if base.klass <> @amqp_tcp_socket_class then begin s := Format('<%p> is not of type Tamqp_tcp_socket', [base]); raise Exception.Create(s); end; self := Pamqp_tcp_socket(base); self.sockfd := sockfd; end; procedure amqp_tcp_socket_delete(base: Pointer); var self : Pamqp_tcp_socket; begin self := Pamqp_tcp_socket(base); if Assigned(self) then begin amqp_tcp_socket_close(self, AMQP_SC_NONE); freeMem(self); end; end; function amqp_tcp_socket_get_sockfd(base: Pointer):int; var self : Pamqp_tcp_socket; begin self := Pamqp_tcp_socket(base); Result := self.sockfd; end; function amqp_tcp_socket_close(base: Pointer; force: Tamqp_socket_close_enum):integer; var self : Pamqp_tcp_socket; begin self := Pamqp_tcp_socket(base); if -1 = self.sockfd then begin Exit(Int(AMQP_STATUS_SOCKET_CLOSED)); end; if amqp_os_socket_close(self.sockfd) > 0 then begin Exit(Int(AMQP_STATUS_SOCKET_ERROR)); end; self.sockfd := -1; Result := Int(AMQP_STATUS_OK); end; function amqp_tcp_socket_open( base: Pointer; host : PAMQPChar; port : integer;const timeout: Ptimeval):integer; var self : Pamqp_tcp_socket; err : integer; begin self := Pamqp_tcp_socket(base); if -1 <> self.sockfd then begin Exit(Int(AMQP_STATUS_SOCKET_INUSE)); end; self.sockfd := amqp_open_socket_noblock(host, port, timeout); if 0 > self.sockfd then begin err := self.sockfd; self.sockfd := -1; Exit(err); end; Result := Int(AMQP_STATUS_OK); end; function amqp_tcp_socket_recv(base, buf: Pointer; len : size_t; flags : integer):ssize_t; var self : Pamqp_tcp_socket; ret : ssize_t; label start; begin self := Pamqp_tcp_socket(base); if -1 = self.sockfd then Exit(Int(AMQP_STATUS_SOCKET_CLOSED)); start: {$IFDEF _WIN32} ret := recv(self.sockfd, buf^, len, flags); {$ELSE} ret = recv(self.sockfd, buf, len, flags); {$ENDIF} if 0 > ret then begin self.internal_error := amqp_os_socket_error(); case self.internal_error of EINTR: goto start; {$IFDEF _WIN32} WSAEWOULDBLOCK, {$ELSE} EWOULDBLOCK: {$ENDIF} {$IF EAGAIN <> EWOULDBLOCK} EAGAIN: {$ENDIF} ret := Int(AMQP_PRIVATE_STATUS_SOCKET_NEEDREAD); else ret := Int(AMQP_STATUS_SOCKET_ERROR); end; end else if (0 = ret) then ret := Int(AMQP_STATUS_CONNECTION_CLOSED); Result := ret; end; function amqp_tcp_socket_send(base: Pointer;const buf: Pointer; len : size_t; flags : integer):ssize_t; var self : Pamqp_tcp_socket; res : ssize_t; flagz, one, zero : integer; LBuffer : Puint8_t; LArray: array of AnsiChar; label start; begin {$POINTERMATH ON} self := Pamqp_tcp_socket(base); flagz := 0; //sockfd=-1 ±ķʾsocket ŅѾ­closed if -1 = self.sockfd then Exit(Int(AMQP_STATUS_SOCKET_CLOSED)); {$IFDEF MSG_NOSIGNAL} flagz := flagz or MSG_NOSIGNAL; {$ENDIF} {$IF defined(MSG_MORE)} if flags and AMQP_SF_MORE then begin flagz := flagz or MSG_MORE; end; { Cygwin defines TCP_NOPUSH, but trying to use it will return not * implemented. Disable it here. } {$ELSEIF defined(TCP_NOPUSH) and not defined(__CYGWIN__)} if ( (flags and Int(AMQP_SF_MORE))>0 ) and (0> (self.state and Int(AMQP_SF_MORE) )) then begin one := 1; res := setsockopt(self.sockfd, IPPROTO_TCP, TCP_NOPUSH, &one, sizeof(one)); if 0 <> res then begin self.internal_error := res; Exit(AMQP_STATUS_SOCKET_ERROR); end; self.state := self.state or AMQP_SF_MORE; end else if ( 0= (flags and AMQP_SF_MORE) ) and ((self.state and AMQP_SF_MORE)>0) then begin zero := 0; res := setsockopt(self.sockfd, IPPROTO_TCP, TCP_NOPUSH, &zero, sizeof(&zero)); if 0 <> res then begin self.internal_error := res; res := AMQP_STATUS_SOCKET_ERROR; end else begin self.state &= ~AMQP_SF_MORE; end; end; {$ENDIF} start: {$IFDEF _WIN32} //LBuffer := Puint8_t(buf); {SetLength(LArray, len); for var I := 0 to Len - 1 do Larray[I] := AnsiChar(LBuffer[I]); } res := send(self.sockfd, buf^, len, flagz); {$ELSE} res := send(self.sockfd, buf, len, flagz); {$ENDIF} if res < 0 then begin self.internal_error := amqp_os_socket_error(); case self.internal_error of EINTR, {$IFDEF _WIN32} WSAEWOULDBLOCK, {$ELSE } EWOULDBLOCK: {$ENDIF} {$if EAGAIN <> EWOULDBLOCK} EAGAIN: {$ENDIF} res := int(AMQP_PRIVATE_STATUS_SOCKET_NEEDWRITE); else res := Int(AMQP_STATUS_SOCKET_ERROR); end; end else begin self.internal_error := 0; end; Result := res; {$POINTERMATH ON} end; function amqp_tcp_socket_new( state : Pamqp_connection_state):Pamqp_socket; var Lself : Pamqp_tcp_socket; begin Lself := calloc(1, sizeof(Lself^)); if not Assigned(Lself) then begin Exit(nil); end; Lself.klass := @amqp_tcp_socket_class; Lself.sockfd := -1; amqp_set_socket(state, Pamqp_socket(Lself)); Result := Pamqp_socket(Lself); end; initialization amqp_tcp_socket_class.send := @amqp_tcp_socket_send; amqp_tcp_socket_class.recv := @amqp_tcp_socket_recv; amqp_tcp_socket_class.open := @amqp_tcp_socket_open; amqp_tcp_socket_class.close := @amqp_tcp_socket_close; amqp_tcp_socket_class.get_sockfd := @amqp_tcp_socket_get_sockfd; amqp_tcp_socket_class.delete := @amqp_tcp_socket_delete; end.
unit TeeMalaysian; {$I TeeDefs.inc} interface Uses Classes; Var TeeMalaysianLanguage:TStringList=nil; Procedure TeeSetMalaysian; Procedure TeeCreateMalaysian; implementation Uses SysUtils, TeeConst, TeeProCo {$IFNDEF D5},TeCanvas{$ENDIF}; Procedure TeeMalaysianConstants; begin { TeeConst } TeeMsg_Copyright :='© 1995-2004 oleh David Berneda'; TeeMsg_LegendFirstValue :='Nilai Petunjuk Pertama mestilah > 0'; TeeMsg_LegendColorWidth :='Lebar Warna Petunjuk mestilah > 0%'; TeeMsg_SeriesSetDataSource:='Tiada CartaUtama untuk disahkan Sumber Data'; TeeMsg_SeriesInvDataSource:='Tiada Sumber Data yang sah: %s'; TeeMsg_FillSample :='ContohNilaiPenuh NomborNilai mestilah > 0'; TeeMsg_AxisLogDateTime :='Paksi TarikhMasa Tidak Boleh Logaritma'; TeeMsg_AxisLogNotPositive :='Nilai Minima dan Maksima Paksi Logaritma haruslah >= 0'; TeeMsg_AxisLabelSep :='Label Pemisahan % mestilah lebih besar dari 0'; TeeMsg_AxisIncrementNeg :='Kenaikan Paksi mestilah >= 0'; TeeMsg_AxisMinMax :='Nilai Minima Paksi mestilah <= Maksima'; TeeMsg_AxisMaxMin :='Nilai Maksima Paksi mestilah >= Minima'; TeeMsg_AxisLogBase :='Asas Paksi Logaritma haruslah >= 2'; TeeMsg_MaxPointsPerPage :='MakTitikSeMukasurat mestilah >= 0'; TeeMsg_3dPercent :='Peratus kesan 3D mestilah di antara %d dan %d'; TeeMsg_CircularSeries :='Turutan Bulat Kebergantungan tidak dibenarkan'; TeeMsg_WarningHiColor :='Warna 16k atau lebih diperlukan untuk paparan lebih baik'; TeeMsg_DefaultPercentOf :='%s dari %s'; TeeMsg_DefaultPercentOf2 :='%s'+#13+'dari %s'; TeeMsg_DefPercentFormat :='##0.## %'; TeeMsg_DefValueFormat :='#,##0.###'; TeeMsg_DefLogValueFormat :='#.0 "x10" E+0'; TeeMsg_AxisTitle :='Tajuk Paksi'; TeeMsg_AxisLabels :='Label Paksi'; TeeMsg_RefreshInterval :='Selang Segar Semula mestilah di antara 0 dan 60'; TeeMsg_SeriesParentNoSelf :='Turutan.CartaUtama bukan saya sendiri!'; TeeMsg_GalleryLine :='Garis'; TeeMsg_GalleryPoint :='Titik'; TeeMsg_GalleryArea :='Luas Terunjur'; TeeMsg_GalleryBar :='Palang'; TeeMsg_GalleryHorizBar :='Palang Mendatar'; TeeMsg_Stack :='Tindanan'; TeeMsg_GalleryPie :='Pai'; TeeMsg_GalleryCircled :='Bulatan'; TeeMsg_GalleryFastLine :='Garis Laju'; TeeMsg_GalleryHorizLine :='Garis Mendatar'; TeeMsg_PieSample1 :='Kereta'; TeeMsg_PieSample2 :='Talipon'; TeeMsg_PieSample3 :='Jadual'; TeeMsg_PieSample4 :='Peranti Paparan CRT'; TeeMsg_PieSample5 :='Lampu'; TeeMsg_PieSample6 :='Papan Kekunci'; TeeMsg_PieSample7 :='Motosikal'; TeeMsg_PieSample8 :='Kerusi'; TeeMsg_GalleryLogoFont :='Courier New'; TeeMsg_Editing :='Penyuntingan %s'; TeeMsg_GalleryStandard :='Piawai'; TeeMsg_GalleryExtended :='Diperluas'; TeeMsg_GalleryFunctions :='Fungsi'; TeeMsg_EditChart :='&Sunting Carta...'; TeeMsg_PrintPreview :='&Cetak Prapandang...'; TeeMsg_ExportChart :='E&ksport Carta...'; TeeMsg_CustomAxes :='Ubahsuai Paksi...'; TeeMsg_InvalidEditorClass :='%s: Kelas Editor Tidak Sah: %s'; TeeMsg_MissingEditorClass :='%s: Tiada Dialog Editor'; TeeMsg_GalleryArrow :='Anak Panah'; TeeMsg_ExpFinish :='Se&lesai'; TeeMsg_ExpNext :='Se&terusnya >'; TeeMsg_GalleryGantt :='Gantt'; TeeMsg_GanttSample1 :='Rekaan'; TeeMsg_GanttSample2 :='Pemprototaipan'; TeeMsg_GanttSample3 :='Pembangunan'; TeeMsg_GanttSample4 :='Jualan'; TeeMsg_GanttSample5 :='Pasaran'; TeeMsg_GanttSample6 :='Percubaan'; TeeMsg_GanttSample7 :='Perkilangan'; TeeMsg_GanttSample8 :='Penyahpepijatan'; TeeMsg_GanttSample9 :='Versi Baru'; TeeMsg_GanttSample10 :='Perbankan'; TeeMsg_ChangeSeriesTitle :='Tukar Tajuk Siri'; TeeMsg_NewSeriesTitle :='Tajuk Siri Baru:'; TeeMsg_DateTime :='TarikhMasa'; TeeMsg_TopAxis :='Paksi Atas'; TeeMsg_BottomAxis :='Paksi Bawah'; TeeMsg_LeftAxis :='Paksi Kiri'; TeeMsg_RightAxis :='Paksi Kanan'; TeeMsg_SureToDelete :='Padam %s ?'; TeeMsg_DateTimeFormat :='For&mat TarikhMasa:'; TeeMsg_Default :='Nilai Lalai'; TeeMsg_ValuesFormat :='Fo&rmat Nilai:'; TeeMsg_Maximum :='Maksima'; TeeMsg_Minimum :='Minima'; TeeMsg_DesiredIncrement :='Memerlukan %s Tambahan'; TeeMsg_IncorrectMaxMinValue:='Nilai Tidak Betul. Sebab: %s'; TeeMsg_EnterDateTime :='Masukkan [Jumlah Hari] '+TeeMsg_HHNNSS; TeeMsg_SureToApply :='Gunapakai Pertukaran ?'; TeeMsg_SelectedSeries :='(Turutan Pilihan)'; TeeMsg_RefreshData :='Se&gar Semula Data'; TeeMsg_DefaultFontSize :={$IFDEF LINUX}'10'{$ELSE}'8'{$ENDIF}; TeeMsg_DefaultEditorSize :='414'; TeeMsg_FunctionAdd :='Tambah'; TeeMsg_FunctionSubtract :='Tolak'; TeeMsg_FunctionMultiply :='Darab'; TeeMsg_FunctionDivide :='Bahagi'; TeeMsg_FunctionHigh :='Tinggi'; TeeMsg_FunctionLow :='Rendah'; TeeMsg_FunctionAverage :='Purata'; TeeMsg_GalleryShape :='Bentuk'; TeeMsg_GalleryBubble :='Gelembung'; TeeMsg_FunctionNone :='Salin'; TeeMsg_None :='(tiada)'; TeeMsg_PrivateDeclarations:='{ Private declarations }'; TeeMsg_PublicDeclarations :='{ Public declarations }'; TeeMsg_DefaultFontName :=TeeMsg_DefaultEngFontName; TeeMsg_CheckPointerSize :='Saiz Penuding mestilah lebih besar dari kosong'; TeeMsg_About :='Me&ngenai TeeChart...'; tcAdditional :='Tambahan'; tcDControls :='Kawalan Data'; tcQReport :='LaporanQ'; TeeMsg_DataSet :='Set Data'; TeeMsg_AskDataSet :='Set &Data'; TeeMsg_SingleRecord :='Satu Rekod'; TeeMsg_AskDataSource :='Sum&ber Data'; TeeMsg_Summary :='Ringkasan'; TeeMsg_FunctionPeriod :='Tempoh Fungsi seharusnya >= 0'; TeeMsg_WizardTab :='Perniagaan'; TeeMsg_TeeChartWizard :='TeeChart Bestari'; TeeMsg_ClearImage :='Leg&a'; TeeMsg_BrowseImage :='Semak Se&imbas...'; TeeMsg_WizardSureToClose :='Adakah anda pasti untuk menutup TeeChart bestari ?'; TeeMsg_FieldNotFound :='Medan %s tidak wujud'; TeeMsg_DepthAxis :='Ukur Dalam Paksi'; TeeMsg_PieOther :='Lain'; TeeMsg_ShapeGallery1 :='abc'; TeeMsg_ShapeGallery2 :='123'; TeeMsg_ValuesX :='X'; TeeMsg_ValuesY :='Y'; TeeMsg_ValuesPie :='Pai'; TeeMsg_ValuesBar :='Palang'; TeeMsg_ValuesAngle :='Sudut'; TeeMsg_ValuesGanttStart :='Mula'; TeeMsg_ValuesGanttEnd :='Akhir'; TeeMsg_ValuesGanttNextTask:='TugasBerikut'; TeeMsg_ValuesBubbleRadius :='Ukurlilit'; TeeMsg_ValuesArrowEndX :='AkhirX'; TeeMsg_ValuesArrowEndY :='AkhirY'; TeeMsg_Legend :='Petunjuk'; TeeMsg_Title :='Tajuk'; TeeMsg_Foot :='Catatan Kaki'; TeeMsg_Period :='Tempoh'; TeeMsg_PeriodRange :='Julat Tempoh'; TeeMsg_CalcPeriod :='Kira %s setiap:'; TeeMsg_SmallDotsPen :='Titik Kecil'; TeeMsg_InvalidTeeFile :='Carta Tidak Sah dalam fail *.'+TeeMsg_TeeExtension; TeeMsg_WrongTeeFileFormat :='Fail *.'+TeeMsg_TeeExtension+' silap format'; TeeMsg_EmptyTeeFile :='Fail *.'+TeeMsg_TeeExtension+' kosong'; { 5.01 } {$IFDEF D5} TeeMsg_ChartAxesCategoryName := 'Paksi Carta'; TeeMsg_ChartAxesCategoryDesc := 'Sifat dan Acara Paksi Carta'; TeeMsg_ChartWallsCategoryName := 'Dinding Carta'; TeeMsg_ChartWallsCategoryDesc := 'Sifat dan Acara Dinding Carta'; TeeMsg_ChartTitlesCategoryName := 'Tajuk Carta'; TeeMsg_ChartTitlesCategoryDesc := 'Sifat dan Acara Tajuk Carta'; TeeMsg_Chart3DCategoryName := 'Carta 3D'; TeeMsg_Chart3DCategoryDesc := 'Sifat dan Acara Chart 3D'; {$ENDIF} TeeMsg_CustomAxesEditor :='Ubahsuai'; TeeMsg_Series :='Turutan'; TeeMsg_SeriesList :='Turutan...'; TeeMsg_PageOfPages :='Mukasurat %d dari %d'; TeeMsg_FileSize :='%d bytes'; TeeMsg_First :='Pertama'; TeeMsg_Prior :='Sebelum'; TeeMsg_Next :='Seterusnya'; TeeMsg_Last :='Akhir'; TeeMsg_Insert :='Selit'; TeeMsg_Delete :='Padam'; TeeMsg_Edit :='Sunting'; TeeMsg_Post :='Hantar'; TeeMsg_Cancel :='Batal'; TeeMsg_All :='(semua)'; TeeMsg_Index :='Indeks'; TeeMsg_Text :='Teks'; TeeMsg_AsBMP :='sebagai &Bitmap'; TeeMsg_BMPFilter :='Bitmaps (*.bmp)|*.bmp'; TeeMsg_AsEMF :='sebagai &Metafile'; TeeMsg_EMFFilter :='Kenaikan Kualiti Metafiles (*.emf)|*.emf|Metafiles (*.wmf)|*.wmf'; TeeMsg_ExportPanelNotSet := 'Sifat Panel tidak diset dalam format Eksport'; TeeMsg_Normal :='Biasa'; TeeMsg_NoBorder :='Tiada Sempadan'; TeeMsg_Dotted :='Garis terputus-putus'; TeeMsg_Colors :='Warna'; TeeMsg_Filled :='Penuh'; TeeMsg_Marks :='Tanda'; TeeMsg_Stairs :='Tangga'; TeeMsg_Points :='Titik'; TeeMsg_Height :='Tinggi'; TeeMsg_Hollow :='Lompang'; TeeMsg_Point2D :='Titik 2D'; TeeMsg_Triangle :='Tigasegi'; TeeMsg_Star :='Bintang'; TeeMsg_Circle :='Bulatan'; TeeMsg_DownTri :='Tigasegi Ke Bawah'; TeeMsg_Cross :='Campur'; TeeMsg_Diamond :='Berlian'; TeeMsg_NoLines :='Tiada Garisan'; TeeMsg_Stack100 :='Tindanan 100%'; TeeMsg_Pyramid :='Piramid'; TeeMsg_Ellipse :='Elips'; TeeMsg_InvPyramid:='Piramid Terbalik'; TeeMsg_Sides :='Sudut'; TeeMsg_SideAll :='Semua sudut'; TeeMsg_Patterns :='Corak'; TeeMsg_Exploded :='Terburai'; TeeMsg_Shadow :='Bayang'; TeeMsg_SemiPie :='Separuh Pai'; TeeMsg_Rectangle :='Empatsegi'; TeeMsg_VertLine :='Garis Menegak'; TeeMsg_HorizLine :='Garis Mendatar'; TeeMsg_Line :='Garis'; TeeMsg_Cube :='Empatsegi Sama'; TeeMsg_DiagCross :='Pangkah'; TeeMsg_CanNotFindTempPath :='Tidak jumpa direktori sementara'; TeeMsg_CanNotCreateTempChart :='Tidak boleh buat fail sementara'; TeeMsg_CanNotEmailChart :='Tidak boleh email TeeChart. Kesilapan MAPI: %d'; TeeMsg_SeriesDelete :='Turutan Padam: Nilai Indeks %d di luar lingkungan (0 to %d).'; { 5.02 } { Moved from TeeImageConstants.pas unit } TeeMsg_AsJPEG :='sebagai &JPEG'; TeeMsg_JPEGFilter :='Fail JPEG (*.jpg)|*.jpg'; TeeMsg_AsGIF :='sebagai &GIF'; TeeMsg_GIFFilter :='Fail GIF (*.gif)|*.gif'; TeeMsg_AsPNG :='sebagai &PNG'; TeeMsg_PNGFilter :='Fail PNG (*.png)|*.png'; TeeMsg_AsPCX :='sebagai PC&X'; TeeMsg_PCXFilter :='Fail PCX (*.pcx)|*.pcx'; TeeMsg_AsVML :='sebagai &VML (HTM)'; TeeMsg_VMLFilter :='Fail VML (*.htm)|*.htm'; { 5.02 } TeeMsg_AskLanguage :='Ba&hasa...'; { TeeProCo } TeeMsg_GalleryPolar :='Kutub'; TeeMsg_GalleryCandle :='Lilin'; TeeMsg_GalleryVolume :='Muatan'; TeeMsg_GallerySurface :='Permukaan'; TeeMsg_GalleryContour :='Kontur'; TeeMsg_GalleryBezier :='Bezier'; TeeMsg_GalleryPoint3D :='Titik 3D'; TeeMsg_GalleryRadar :='Radar'; TeeMsg_GalleryDonut :='Donut'; TeeMsg_GalleryCursor :='Kursor'; TeeMsg_GalleryBar3D :='Palang 3D'; TeeMsg_GalleryBigCandle :='Lilin Besar'; TeeMsg_GalleryLinePoint :='Garis Titik'; TeeMsg_GalleryHistogram :='Histogram'; TeeMsg_GalleryWaterFall :='Air Terjun'; TeeMsg_GalleryWindRose :='Wind Rose'; TeeMsg_GalleryClock :='Jam'; TeeMsg_GalleryColorGrid :='WarnaGrid'; TeeMsg_GalleryBoxPlot :='KotakPlot'; TeeMsg_GalleryHorizBoxPlot:='KotakPlot Mendatar'; TeeMsg_GalleryBarJoin :='Palang Bercantum'; TeeMsg_GallerySmith :='Smith'; TeeMsg_GalleryPyramid :='Piramid'; TeeMsg_GalleryMap :='Peta'; TeeMsg_PolyDegreeRange :='Darjah Polinomial mestilah di antara 1 dan 20'; TeeMsg_AnswerVectorIndex :='Jawapan Indeks Vektor mestilah di antara 1 dan %d'; TeeMsg_FittingError :='Tidak boleh proses kemasan'; TeeMsg_PeriodRange :='Tempoh mestilah >= 0'; TeeMsg_ExpAverageWeight :='Purata Eksponen Wajaran mestilah di antara 0 dan 1'; TeeMsg_GalleryErrorBar :='Ralat Palang'; TeeMsg_GalleryError :='Ralat'; TeeMsg_GalleryHighLow :='Tinggi-Rendah'; TeeMsg_FunctionMomentum :='Momentum'; TeeMsg_FunctionMomentumDiv :='Pembahagian Momentum'; TeeMsg_FunctionExpAverage :='Purata Eksponen'; TeeMsg_FunctionMovingAverage:='Purata Bergerak'; TeeMsg_FunctionExpMovAve :='Purata Bergerak Eksponen'; TeeMsg_FunctionRSI :='R.S.I.'; TeeMsg_FunctionCurveFitting:='Keluk Kemasan'; TeeMsg_FunctionTrend :='Arah Aliran'; TeeMsg_FunctionExpTrend :='Arah Aliran Eksponen'; TeeMsg_FunctionLogTrend :='Pengelongan Arah Aliran'; TeeMsg_FunctionCumulative :='Kumulatif'; TeeMsg_FunctionStdDeviation:='Sisihan Piawai'; TeeMsg_FunctionBollinger :='Bollinger'; TeeMsg_FunctionRMS :='Punca Min Kuasa Dua'; TeeMsg_FunctionMACD :='MACD'; TeeMsg_FunctionStochastic :='Stastik'; TeeMsg_FunctionADX :='ADX'; TeeMsg_FunctionCount :='Bilang'; TeeMsg_LoadChart :='Buka TeeChart...'; TeeMsg_SaveChart :='Simpan TeeChart...'; TeeMsg_TeeFiles :='Fail TeeChart Pro'; TeeMsg_GallerySamples :='Lain-lain'; TeeMsg_GalleryStats :='Statistik'; TeeMsg_CannotFindEditor :='Tidak jumpa editor turutan: %s'; TeeMsg_CannotLoadChartFromURL:='Kod Ralat: %d muat turun Carta dari URL: %s'; TeeMsg_CannotLoadSeriesDataFromURL:='Kod Ralat: %d muat turun data Turutan dari URL: %s'; TeeMsg_Test :='Cubaan...'; TeeMsg_ValuesDate :='Tarikh'; TeeMsg_ValuesOpen :='Buka'; TeeMsg_ValuesHigh :='Tinggi'; TeeMsg_ValuesLow :='Rendah'; TeeMsg_ValuesClose :='Tutup'; TeeMsg_ValuesOffset :='Ofset'; TeeMsg_ValuesStdError :='RalatPiawai'; TeeMsg_Grid3D :='Grid 3D'; TeeMsg_LowBezierPoints :='Jumlah Titik Bezier mestilah > 1'; { TeeCommander component... } TeeCommanMsg_Normal :='Normal'; TeeCommanMsg_Edit :='Sunting'; TeeCommanMsg_Print :='Cetak'; TeeCommanMsg_Copy :='Salin'; TeeCommanMsg_Save :='Simpan'; TeeCommanMsg_3D :='3D'; TeeCommanMsg_Rotating :='Putaran: %d° Elevasi: %d°'; TeeCommanMsg_Rotate :='Putar'; TeeCommanMsg_Moving :='Ofset Mendatar: %d Ofset Menegak: %d'; TeeCommanMsg_Move :='Gerak'; TeeCommanMsg_Zooming :='Zum: %d %%'; TeeCommanMsg_Zoom :='Zum'; TeeCommanMsg_Depthing :='3D: %d %%'; TeeCommanMsg_Depth :='Ukur Dalam'; TeeCommanMsg_Chart :='Carta'; TeeCommanMsg_Panel :='Panel'; TeeCommanMsg_RotateLabel:='Seret %s untuk putar'; TeeCommanMsg_MoveLabel :='Seret %s untuk gerak'; TeeCommanMsg_ZoomLabel :='Seret %s untuk zum'; TeeCommanMsg_DepthLabel :='Seret %s untuk ubah saiz 3D'; TeeCommanMsg_NormalLabel:='Seret butang kiri untuk Zum, kanan untuk larikan'; TeeCommanMsg_NormalPieLabel:='Seret Hirisan Pai Untuk Terburaikan'; TeeCommanMsg_PieExploding :='Hiris: %d Terburai: %d %%'; TeeMsg_TriSurfaceLess :='Jumlah titik mestilah >= 4'; TeeMsg_TriSurfaceAllColinear :='Semua titik data segaris'; TeeMsg_TriSurfaceSimilar :='Titik serupa - tidak boleh lakukan'; TeeMsg_GalleryTriSurface :='Permukaan Segitiga'; TeeMsg_AllSeries :='Semua Turutan'; TeeMsg_Edit :='Sunting'; TeeMsg_GalleryFinancial :='Kewangan'; TeeMsg_CursorTool :='Aksara'; TeeMsg_DragMarksTool :='Seret Tanda'; TeeMsg_AxisArrowTool :='Anak Panah Paksi'; TeeMsg_DrawLineTool :='Lukis Garis'; TeeMsg_NearestTool :='Titik Terdekat'; TeeMsg_ColorBandTool :='Warna Jalur'; TeeMsg_ColorLineTool :='Warna Garis'; TeeMsg_RotateTool :='Putar'; TeeMsg_ImageTool :='Imej'; TeeMsg_MarksTipTool :='Tip Tanda'; TeeMsg_AnnotationTool:='Anotasi'; TeeMsg_CantDeleteAncestor :='Tidak boleh padam leluhur'; TeeMsg_Load :='Muat...'; TeeMsg_NoSeriesSelected :='Tiada turutan dipilih'; { TeeChart Actions } TeeMsg_CategoryChartActions :='Carta'; TeeMsg_CategorySeriesActions :='Carta Turutan'; TeeMsg_Action3D := '&3D'; TeeMsg_Action3DHint := 'Tukar 2D / 3D'; TeeMsg_ActionSeriesActive := '&Aktif'; TeeMsg_ActionSeriesActiveHint := 'Tunjuk / Sembunyi Turutan'; TeeMsg_ActionEditHint := 'Sunting Carta'; TeeMsg_ActionEdit := 'S&unting...'; TeeMsg_ActionCopyHint := 'Salin ke papan keratan'; TeeMsg_ActionCopy := 'Sa&lin'; TeeMsg_ActionPrintHint := 'Cetak Carta Pratonton'; TeeMsg_ActionPrint := '&Cetak...'; TeeMsg_ActionAxesHint := 'Tunjuk / Sembunyi Paksi'; TeeMsg_ActionAxes := 'Pa&ksi'; TeeMsg_ActionGridsHint := 'Tunjuk / Sembunyi Grid'; TeeMsg_ActionGrids := '&Grid'; TeeMsg_ActionLegendHint := 'Tunjuk / Sembunyi Petunjuk'; TeeMsg_ActionLegend := '&Petunjuk'; TeeMsg_ActionSeriesEditHint := 'Sunting Turutan'; TeeMsg_ActionSeriesMarksHint := 'Tunjuk / Sembunyi Tanda Turutan'; TeeMsg_ActionSeriesMarks := '&Tanda'; TeeMsg_ActionSaveHint := 'Simpan Carta'; TeeMsg_ActionSave := '&Simpan...'; TeeMsg_CandleBar := 'Palang'; TeeMsg_CandleNoOpen := 'Tidak Dibuka'; TeeMsg_CandleNoClose := 'Tidak Ditutup'; TeeMsg_NoLines := 'Tiada Garisan'; TeeMsg_NoHigh := 'Tiada Tinggi'; TeeMsg_NoLow := 'Tiada Rendah'; TeeMsg_ColorRange := 'Julat Warna'; TeeMsg_WireFrame := 'Garis Bingkau'; TeeMsg_DotFrame := 'Bingkau Titik '; TeeMsg_Positions := 'Posisi'; TeeMsg_NoGrid := 'Tiada Grid'; TeeMsg_NoPoint := 'Tiada Titik'; TeeMsg_NoLine := 'Tiada Garis'; TeeMsg_Labels := 'Label'; TeeMsg_NoCircle := 'Tiada Bulatan'; TeeMsg_Lines := 'Garisan'; TeeMsg_Border := 'Sempadan'; TeeMsg_SmithResistance := 'Rintangan'; TeeMsg_SmithReactance := 'Kesan Balas'; TeeMsg_Column := 'Lajur'; { 5.01 } TeeMsg_Separator := 'Pembahagi'; TeeMsg_FunnelSegment := 'Tembereng '; TeeMsg_FunnelSeries := 'Corong'; TeeMsg_FunnelPercent := '0.00 %'; TeeMsg_FunnelExceed := 'Terlebih Kuota'; TeeMsg_FunnelWithin := ' dalam kuota'; TeeMsg_FunnelBelow := ' atau lebih dibawah kuota'; TeeMsg_CalendarSeries := 'Kalendar'; TeeMsg_DeltaPointSeries := 'TitikDelta'; TeeMsg_ImagePointSeries := 'TitikImej'; TeeMsg_ImageBarSeries := 'PalangImej'; TeeMsg_SeriesTextFieldZero := 'TeksTurutan: Medan indeks mestilah lebih besar dari kosong.'; { 5.02 } TeeMsg_Origin := 'Asal'; TeeMsg_Transparency := 'Kelutsinaran'; TeeMsg_Box := 'Kotak'; TeeMsg_ExtrOut := 'KeluarLebih'; TeeMsg_MildOut := 'KeluarSederhana'; TeeMsg_PageNumber := 'Mukasurat'; TeeMsg_TextFile := 'Fail Teks'; { 5.03 } TeeMsg_DragPoint := 'Titik Seretan'; TeeMsg_OpportunityValues := 'NilaiKesempatan'; TeeMsg_QuoteValues := 'NilaiQuote'; end; Procedure TeeCreateMalaysian; begin if not Assigned(TeeMalaysianLanguage) then begin TeeMalaysianLanguage:=TStringList.Create; TeeMalaysianLanguage.Text:= 'LABELS=Label-label'+#13+ 'DATASET=Set Data'+#13+ 'ALL RIGHTS RESERVED.=Hak cipta terpelihara.'+#13+ 'APPLY=Gunapakai'+#13+ 'CLOSE=Tutup'+#13+ 'OK=Baik'+#13+ 'ABOUT TEECHART PRO V7.0=Tentang TeeChart Pro v7.0'+#13+ 'OPTIONS=Pilihan'+#13+ 'FORMAT=Format'+#13+ 'TEXT=Teks'+#13+ 'GRADIENT=Kecerunan'+#13+ 'SHADOW=Bayang-bayang'+#13+ 'POSITION=Kedudukan'+#13+ 'LEFT=Kiri'+#13+ 'TOP=Atas'+#13+ 'CUSTOM=Ubahsuai'+#13+ 'PEN=Pen'+#13+ 'PATTERN=Corak'+#13+ 'SIZE=Saiz'+#13+ 'BEVEL=Siku'+#13+ 'INVERTED=Dibalikkan'+#13+ 'INVERTED SCROLL=Gulung dibalikkan'+#13+ 'BORDER=Sempadan'+#13+ 'ORIGIN=Asal'+#13+ 'USE ORIGIN=Guna asal'+#13+ 'AREA LINES=Garis-garis kawasan'+#13+ 'AREA=Kawasan'+#13+ 'COLOR=Warna'+#13+ 'SERIES=Turutan'+#13+ 'SUM=Jumlah'+#13+ 'DAY=Hari'+#13+ 'QUARTER=Perempat'+#13+ '(MAX)=(maks)'+#13+ '(MIN)=(min)'+#13+ 'VISIBLE=Dapat dilihat'+#13+ 'CURSOR=Kursor'+#13+ 'GLOBAL=Global'+#13+ 'X=X'+#13+ 'Y=Y'+#13+ 'Z=Z'+#13+ '3D=3D'+#13+ 'HORIZ. LINE=Garis melintang'+#13+ 'LABEL AND PERCENT=Label dan peratus'+#13+ 'LABEL AND VALUE=Label dan nilai'+#13+ 'LABEL & PERCENT TOTAL=Label dan jumlah peratus'+#13+ 'PERCENT TOTAL=Jumlah peratus'+#13+ 'MSEC.=msaat.'+#13+ 'SUBTRACT=Tolak'+#13+ 'MULTIPLY=Kali'+#13+ 'DIVIDE=Bahagi'+#13+ 'STAIRS=Tangga'+#13+ 'MOMENTUM=Momentum'+#13+ 'AVERAGE=Purata'+#13+ 'XML=XML'+#13+ 'HTML TABLE=Jadual HTML'+#13+ 'EXCEL=Excel'+#13+ 'NONE=Tiada'+#13+ '(NONE)=(Tiada)'#13+ 'WIDTH=Lebar'+#13+ 'HEIGHT=Tinggi'+#13+ 'COLOR EACH=Warna Masing-Masing'+#13+ 'STACK=Tindanan'+#13+ 'STACKED=Tindan'+#13+ 'STACKED 100%=Tindan 100%'+#13+ 'AXIS=Paksi'+#13+ 'LENGTH=Panjang'+#13+ 'CANCEL=Batal'+#13+ 'SCROLL=Gulung'+#13+ 'INCREMENT=Penambahan'+#13+ 'VALUE=Nilai'+#13+ 'STYLE=Stail'+#13+ 'JOIN=Gabung'+#13+ 'AXIS INCREMENT=Penambahan paksi'+#13+ 'AXIS MAXIMUM AND MINIMUM=Paksi Maksimum dan Minimum'+#13+ '% BAR WIDTH=% Lebar Bar'+#13+ '% BAR OFFSET=% Ofset Bar'+#13+ 'BAR SIDE MARGINS=Garis sisi Bar'+#13+ 'AUTO MARK POSITION=Penanda Posisi Automatik'+#13+ 'DARK BAR 3D SIDES=Sisi Gelap Bar 3D'+#13+ 'MONOCHROME=Ekawarna'+#13+ 'COLORS=Warna-warna'+#13+ 'DEFAULT=Pilihan standard'+#13+ 'MEDIAN=Nilai tengah'+#13+ 'IMAGE=Imej'+#13+ 'DAYS=Hari-hari'+#13+ 'WEEKDAYS=Hari minggu'+#13+ 'TODAY=Hari ini'+#13+ 'SUNDAY=Ahad'+#13+ 'MONTHS=Bulan'+#13+ 'LINES=Garis'+#13+ 'UPPERCASE=Huruf besar'+#13+ 'STICK=Batang'+#13+ 'CANDLE WIDTH=Lebar lilin'+#13+ 'BAR=Bar'+#13+ 'OPEN CLOSE=Buka Tutup '+#13+ 'DRAW 3D=Lukis 3D'+#13+ 'DARK 3D=Gelap 3D'+#13+ 'SHOW OPEN=Tunjuk Buka'+#13+ 'SHOW CLOSE=Tunjuk Tutup'+#13+ 'UP CLOSE=Atas Tutup'+#13+ 'DOWN CLOSE=Bawah Tutup'+#13+ 'CIRCLED=Dibulatkan'+#13+ 'CIRCLE=Bulat'+#13+ '3 DIMENSIONS=3 Dimensi'+#13+ 'ROTATION=Putaran'+#13+ 'RADIUS=Radius'+#13+ 'HOURS=Jam'+#13+ 'HOUR=Jam'+#13+ 'MINUTES=Minit'+#13+ 'SECONDS=Saat'+#13+ 'FONT=Fon'+#13+ 'INSIDE=Didalam'+#13+ 'ROTATED=Diputar'+#13+ 'ROMAN=Roman'+#13+ 'TRANSPARENCY=Transparensi'+#13+ 'DRAW BEHIND=Lukis dibelakang'+#13+ 'RANGE=Linkungan'+#13+ 'PALETTE=Palet'+#13+ 'STEPS=Langkah'+#13+ 'GRID=Grid'+#13+ 'GRID SIZE=Saiz grid'+#13+ 'ALLOW DRAG=Seret dibenarkan'+#13+ 'AUTOMATIC=Automatik'+#13+ 'LEVEL=Tingkat'+#13+ 'LEVELS POSITION=Posisi tingkat'+#13+ 'SNAP=Sesuaikan'+#13+ 'FOLLOW MOUSE=Ikut Mouse'+#13+ 'TRANSPARENT=Lutsinar'+#13+ 'ROUND FRAME=Bingkai bulat'+#13+ 'FRAME=Bingkai'+#13+ 'START=Mula'+#13+ 'END=Akhir'+#13+ 'MIDDLE=Tengah'+#13+ 'NO MIDDLE=Tiada tengah'+#13+ 'DIRECTION=Arah'+#13+ 'DATASOURCE=Sumber data'+#13+ 'AVAILABLE=Boleh didapati'+#13+ 'SELECTED=Terpilih'+#13+ 'CALC=Hitung'+#13+ 'GROUP BY=Kumpul berdasarkan'+#13+ 'OF=dari'+#13+ 'HOLE %=Lubang %'+#13+ 'RESET POSITIONS=Set kembali posisi'+#13+ 'MOUSE BUTTON=Tombol Mouse'+#13+ 'ENABLE DRAWING=Izinkan Lukisan'+#13+ 'ENABLE SELECT=Izinkan Pilihan'+#13+ 'ORTHOGONAL=Ortogonal'+#13+ 'ANGLE=Sudut'+#13+ 'ZOOM TEXT=Perbesarkan teks'+#13+ 'PERSPECTIVE=Perspektif'+#13+ 'ZOOM=Perbesar'+#13+ 'ELEVATION=Peninggian'+#13+ 'BEHIND=Belakang'+#13+ 'AXES=Paksi-paksi'+#13+ 'SCALES=Skala'+#13+ 'TITLE=Tajuk'+#13+ 'TICKS=Detik'+#13+ 'MINOR=Kecil'+#13+ 'CENTERED=Ditengahkan'+#13+ 'CENTER=Tengah'+#13+ 'PATTERN COLOR EDITOR=Penyunting Corak Warna'+#13+ 'START VALUE=Nilai permulaan'+#13+ 'END VALUE=Nilai akhir'+#13+ 'COLOR MODE=Mode warna'+#13+ 'LINE MODE=Mode garis'+#13+ 'HEIGHT 3D=Tinggi 3D'+#13+ 'OUTLINE=Garis luar'+#13+ 'PRINT PREVIEW=Cetak Pratayang'+#13+ 'ANIMATED=Animasi'+#13+ 'ALLOW=Izin'+#13+ 'DASH=Sengkang'+#13+ 'DOT=Titik'+#13+ 'DASH DOT DOT=Sengkang titik titik'+#13+ 'PALE=Pucat'+#13+ 'STRONG=Kuat'+#13+ 'WIDTH UNITS=Unit lebar'+#13+ 'FOOT=Kaki'+#13+ 'SUBFOOT=Sub Kaki'+#13+ 'SUBTITLE=Sari kata'+#13+ 'LEGEND=Lagenda'+#13+ 'COLON=Noktah bertindih'+#13+ 'AXIS ORIGIN=Paksi asal'+#13+ 'UNITS=Unit-unit'+#13+ 'PYRAMID=Piramid'+#13+ 'DIAMOND=Berlian'+#13+ 'CUBE=Kiub'+#13+ 'TRIANGLE=Segitiga'+#13+ 'STAR=Bintang'+#13+ 'SQUARE=Empat segi'+#13+ 'DOWN TRIANGLE=Segitiga terbalik'+#13+ 'SMALL DOT=Titik kecil'+#13+ 'LOAD=Muat'+#13+ 'FILE=Fail'+#13+ 'RECTANGLE=Segi empat sama'+#13+ 'HEADER=Bahagian depan'+#13+ 'CLEAR=Bersihkan'+#13+ 'ONE HOUR=Satu jam'+#13+ 'ONE YEAR=Satu tahun'+#13+ 'ELLIPSE=Elips'+#13+ 'CONE=Kun'+#13+ 'ARROW=Panah'+#13+ 'CYLLINDER=Silinder'+#13+ 'TIME=Waktu'+#13+ 'BRUSH=Berus'+#13+ 'LINE=Garis'+#13+ 'VERTICAL LINE=Garis memanjang'+#13+ 'AXIS ARROWS=Panah paksi'+#13+ 'MARK TIPS=Tips penanda'+#13+ 'DASH DOT=Titik sengkang'+#13+ 'COLOR BAND=Pita warna'+#13+ 'COLOR LINE=Garis warna'+#13+ 'INVERT. TRIANGLE=Segitiga terbalik'+#13+ 'INVERT. PYRAMID=Piramid terbalik'+#13+ 'INVERTED PYRAMID=Piramid terbalik'+#13+ 'SERIES DATASOURCE TEXT EDITOR=Penyunting Teks Turutan Sumberdata'+#13+ 'SOLID=Kukuh'+#13+ 'WIREFRAME=Bingkai dawai'+#13+ 'DOTFRAME=Bingkai titik'+#13+ 'SIDE BRUSH=Berus sisi '+#13+ 'SIDE=Sisi'+#13+ 'SIDE ALL=Semua sisi'+#13+ 'ROTATE=Putar'+#13+ 'SMOOTH PALETTE=Palet licin'+#13+ 'CHART TOOLS GALLERY=Galeri Carta Alat'+#13+ 'ADD=Tambah'+#13+ 'BORDER EDITOR=Penyunting Batas'+#13+ 'DRAWING MODE=Mode lukis'+#13+ 'CLOSE CIRCLE=Tutup bulatan'+#13+ 'PICTURE=Gambar'+#13+ 'NATIVE=Asli'+#13+ 'DATA=Data'+#13+ 'KEEP ASPECT RATIO=Simpan nisbah aspek '+#13+ 'COPY=Salin'+#13+ 'SAVE=Simpan'+#13+ 'SEND=Hantar'+#13+ 'INCLUDE SERIES DATA=Termasuk turutan data'+#13+ 'FILE SIZE=Saiz fail'+#13+ 'INCLUDE=Termasuk'+#13+ 'POINT INDEX=Indeks penunjuk'+#13+ 'POINT LABELS=Label penunjuk'+#13+ 'DELIMITER=Pembatasan'+#13+ 'DEPTH=Kedalaman'+#13+ 'COMPRESSION LEVEL=Tingkat mampatan'+#13+ 'COMPRESSION=Mampatan'+#13+ 'PATTERNS=Corak-corak'+#13+ 'LABEL=Label'+#13+ 'GROUP SLICES=Bahagian Kumpulan'+#13+ 'EXPLODE BIGGEST=Lebarkan terbesar'+#13+ 'TOTAL ANGLE=Jumlah sudut'+#13+ 'HORIZ. SIZE=Saiz melintang'+#13+ 'VERT. SIZE=Saiz memanjang'+#13+ 'SHAPES=Bentuk-bentuk'+#13+ 'INFLATE MARGINS=Kembungkan garis'+#13+ 'QUALITY=Kualiti'+#13+ 'SPEED=Kepantasan'+#13+ '% QUALITY=% kualiti'+#13+ 'GRAY SCALE=Skala kelabu'+#13+ 'PERFORMANCE=Prestasi'+#13+ 'BROWSE=Melihat'+#13+ 'TILED=Jubin'+#13+ 'HIGH=Tinggi'+#13+ 'LOW=Rendah'+#13+ 'DATABASE CHART=Carta data induk'+#13+ 'NON DATABASE CHART=Bukan carta data induk'+#13+ 'HELP=Bantuan'+#13+ 'NEXT >=Seterusnya >'+#13+ '< BACK=< Kembali'+#13+ 'TEECHART WIZARD=TeeChart Bestari'+#13+ 'PERCENT=Peratus'+#13+ 'PIXELS=Piksel'+#13+ 'ERROR WIDTH=Lebar kesilapan'+#13+ 'ENHANCED=Tingkatkan'+#13+ 'VISIBLE WALLS=Dinding terlihat'+#13+ 'ACTIVE=Aktif'+#13+ 'DELETE=Padam'+#13+ 'ALIGNMENT=Penjajaran'+#13+ 'ADJUST FRAME=Betulkan bingkai'+#13+ 'HORIZONTAL=Melintang'+#13+ 'VERTICAL=Memanjang'+#13+ 'VERTICAL POSITION=Posisi memanjang'+#13+ 'NUMBER=Nombor'+#13+ 'LEVELS=Tingkat'+#13+ 'OVERLAP=Bertindih'+#13+ 'STACK 100%=Tindanan 100%'+#13+ 'MOVE=Pindah'+#13+ 'CLICK=Klik'+#13+ 'DELAY=Tunda'+#13+ 'DRAW LINE=Lukis garis'+#13+ 'FUNCTIONS=Fungsi'+#13+ 'SOURCE SERIES=Sumber turutan'+#13+ 'ABOVE=Atas'+#13+ 'BELOW=Bawah'+#13+ 'Dif. Limit=Perbezaan had'+#13+ 'WITHIN=Dalam'+#13+ 'EXTENDED=Lanjutkan'+#13+ 'STANDARD=Standard'+#13+ 'STATS=Statistik'+#13+ 'FINANCIAL=Kewangan'+#13+ 'OTHER=Lain'+#13+ 'TEECHART GALLERY=Galeri TeeChart'+#13+ 'CONNECTING LINES=Menghubung garisan'+#13+ 'REDUCTION=Pengurangan'+#13+ 'LIGHT=Cahaya'+#13+ 'INTENSITY=Intensiti'+#13+ 'FONT OUTLINES=Garis fon'+#13+ 'SMOOTH SHADING=Bayangan halus'+#13+ 'AMBIENT LIGHT=Cahaya Sekeliling'+#13+ 'MOUSE ACTION=Fungsi Mouse'+#13+ 'CLOCKWISE=Arah jam'+#13+ 'ANGLE INCREMENT=Kenaikan sudut'+#13+ 'RADIUS INCREMENT=Kenaikan radius'+#13+ 'PRINTER=Pencetak'+#13+ 'SETUP=Pilihan'+#13+ 'ORIENTATION=Orientasi'+#13+ 'PORTRAIT=Memanjang'+#13+ 'LANDSCAPE=Melintang'+#13+ 'MARGINS (%)=Garisan (%)'+#13+ 'MARGINS=Garisan'+#13+ 'DETAIL=Terperinci'+#13+ 'MORE=Lebih'+#13+ 'PROPORTIONAL=Perkadaran'+#13+ 'VIEW MARGINS=Lihat garisan'+#13+ 'RESET MARGINS=Set kembali garisan'+#13+ 'PRINT=Cetak'+#13+ 'TEEPREVIEW EDITOR=Penyunting Tee pratayang'+#13+ 'ALLOW MOVE=Izin bergerak'+#13+ 'ALLOW RESIZE=Izin saiz baru'+#13+ 'SHOW IMAGE=Tunjuk imej'+#13+ 'DRAG IMAGE=Seret imej'+#13+ 'AS BITMAP=Sebagai BITMAP'+#13+ 'SIZE %=Saiz %'+#13+ 'FIELDS=Ruang'+#13+ 'SOURCE=Sumber'+#13+ 'SEPARATOR=Pengasing'+#13+ 'NUMBER OF HEADER LINES=Bilangan garis bahagian depan'+#13+ 'COMMA=Koma'+#13+ 'EDITING=Menyunting'+#13+ 'TAB=Tab'+#13+ 'SPACE=Sela'+#13+ 'ROUND RECTANGLE=Segi empat sama kubah'+#13+ 'BOTTOM=Bawah'+#13+ 'RIGHT=Kanan'+#13+ 'C PEN=C Pen'+#13+ 'R PEN=R Pen'+#13+ 'C LABELS=Label C'+#13+ 'R LABELS=Label R'+#13+ 'MULTIPLE BAR=Bar berganda'+#13+ 'MULTIPLE AREAS=Kawasan berganda'+#13+ 'STACK GROUP=Tindanan kumpulan'+#13+ 'BOTH=Kedua-dua'+#13+ 'BACK DIAGONAL=Diagonal dibalikkan'+#13+ 'B.DIAGONAL=Diagonal diabilikkan'+#13+ 'DIAG.CROSS=Silang diagonal'+#13+ 'WHISKER=Whisker'+#13+ 'CROSS=Silang'+#13+ 'DIAGONAL CROSS=Silang Diagonal'+#13+ 'LEFT RIGHT=Kiri Kanan'+#13+ 'RIGHT LEFT=Kanan Kiri'+#13+ 'FROM CENTER=Dari tengah'+#13+ 'FROM TOP LEFT=Dari atas kiri'+#13+ 'FROM BOTTOM LEFT=Dari bawah kiri'+#13+ 'SHOW WEEKDAYS=Tunjuk hari minggu'+#13+ 'SHOW MONTHS=Tunjuk bulan'+#13+ 'SHOW PREVIOUS BUTTON=Tunjuk tombol sebelumnya'#13+ 'SHOW NEXT BUTTON=Tunjuk tombol seterusnya'#13+ 'TRAILING DAYS=Hari-hari berikutnya'+#13+ 'SHOW TODAY=Tunjuk hari ini'+#13+ 'TRAILING=Berikutnya'+#13+ 'LOWERED=Direndahkan'+#13+ 'RAISED=Ditinggikan'+#13+ 'HORIZ. OFFSET=Ofset melintang'+#13+ 'VERT. OFFSET=Ofset memanjang'+#13+ 'INNER=Dalam'+#13+ 'LEN=Panjang'+#13+ 'AT LABELS ONLY=Pada label sahaja'+#13+ 'MAXIMUM=Maksimum'+#13+ 'MINIMUM=Minimum'+#13+ 'CHANGE=Tukar'+#13+ 'LOGARITHMIC=Logaritma'+#13+ 'LOG BASE=Log dasar'+#13+ 'DESIRED INCREMENT=Kenaikan diingini'+#13+ '(INCREMENT)=(Kenaikan)'+#13+ 'MULTI-LINE=Garis berganda'+#13+ 'MULTI LINE=Garis berganda'+#13+ 'RESIZE CHART=Saiz carta baru'+#13+ 'X AND PERCENT=X dan peratus'+#13+ 'X AND VALUE=X dan nilai'+#13+ 'RIGHT PERCENT=Peratus kanan'+#13+ 'LEFT PERCENT=Peratus kiri'+#13+ 'LEFT VALUE=Nilai kiri'+#13+ 'RIGHT VALUE=Nilai kanan'+#13+ 'PLAIN=Mudah'+#13+ 'LAST VALUES=Nilai terakhir'+#13+ 'SERIES VALUES=Turutan nilai'+#13+ 'SERIES NAMES=Turutan nama-nama'+#13+ 'NEW=Baru'+#13+ 'EDIT=Sunting'+#13+ 'PANEL COLOR=Warna panel'+#13+ 'TOP BOTTOM=Atas Bawah'+#13+ 'BOTTOM TOP=Bawah Atas'+#13+ 'DEFAULT ALIGNMENT=Penjajaran standard '+#13+ 'EXPONENTIAL=Eksponen'+#13+ 'LABELS FORMAT=Format Label'+#13+ 'MIN. SEPARATION %=% Min. Pengasingan'+#13+ 'YEAR=Tahun'+#13+ 'MONTH=Bulan'+#13+ 'WEEK=Minggu'+#13+ 'WEEKDAY=Hari minggu'+#13+ 'MARK=Tanda'+#13+ 'ROUND FIRST=Bulat dahulu'+#13+ 'LABEL ON AXIS=Label pada paksi'+#13+ 'COUNT=Kira'+#13+ 'POSITION %=Posisi %'+#13+ 'START %=Mula %'+#13+ 'END %=Akhir %'+#13+ 'OTHER SIDE=Sisi lain'+#13+ 'INTER-CHAR SPACING=Ruang antara huruf'+#13+ 'VERT. SPACING=Ruang memanjang'+#13+ 'POSITION OFFSET %=Posisi ofset %'+#13+ 'GENERAL=Umum'+#13+ 'MANUAL=Manual'+#13+ 'PERSISTENT=Gigih'+#13+ 'PANEL=Panel'+#13+ 'ALIAS=Alias'+#13+ '2D=2D'+#13+ 'ADX=ADX'+#13+ 'BOLLINGER=Bollinger'+#13+ 'TEEOPENGL EDITOR=Penyunting TeeOpenGL'+#13+ 'FONT 3D DEPTH=Kedalaman Fon 3D'+#13+ 'NORMAL=Normal'+#13+ 'TEEFONT EDITOR=Penyunting TeeFon'+#13+ 'CLIP POINTS=Titik memotong'+#13+ 'CLIPPED=Dipotong'+#13+ '3D %=3D %'+#13+ 'QUANTIZE=Kira'+#13+ 'QUANTIZE 256=Kira 256'+#13+ 'DITHER=Kurangkan'+#13+ 'VERTICAL SMALL=Memanjang kecil'+#13+ 'HORIZ. SMALL=Melintang kecil'+#13+ 'DIAG. SMALL=Diagonal kecil'+#13+ 'BACK DIAG. SMALL=Diagonal kecil belakang'+#13+ 'DIAG. CROSS SMALL=Silang diagonal kecil'+#13+ 'MINIMUM PIXELS=Minimum piksel'+#13+ 'ALLOW SCROLL=Izin Gulung'+#13+ 'SWAP=Tukar'+#13+ 'GRADIENT EDITOR=Penyunting kecerunan'+#13+ 'TEXT STYLE=Stail teks'+#13+ 'DIVIDING LINES=Garis membahagi'+#13+ 'SYMBOLS=Simbol'+#13+ 'CHECK BOXES=Kotak kontrol'+#13+ 'FONT SERIES COLOR=Fon turutan warna'+#13+ 'LEGEND STYLE=Stail lagenda'+#13+ 'POINTS PER PAGE=Titik tiap mukasurat'+#13+ 'SCALE LAST PAGE=Skala mukasurat akhir'+#13+ 'CURRENT PAGE LEGEND=Lagenda mukasurat sekarang'+#13+ 'BACKGROUND=Latar belakang'+#13+ 'BACK IMAGE=Imej belakang'+#13+ 'STRETCH=Lebarkan'+#13+ 'TILE=Jubin'+#13+ 'BORDERS=Sempadan'+#13+ 'CALCULATE EVERY=Hitung tiap-tiap'+#13+ 'NUMBER OF POINTS=Bilangan titik'+#13+ 'RANGE OF VALUES=Lingkungan nilai'+#13+ 'FIRST=Pertama'+#13+ 'LAST=Akhir'+#13+ 'ALL POINTS=Semua titik'+#13+ 'DATA SOURCE=Sumber data'+#13+ 'WALLS=Dinding'+#13+ 'PAGING=Mukasurat'+#13+ 'CLONE=Klon'+#13+ 'TITLES=Tajuk'+#13+ 'TOOLS=Alat-alat'+#13+ 'EXPORT=Eksport'+#13+ 'CHART=Carta'+#13+ 'BACK=Kembali'+#13+ 'LEFT AND RIGHT=Kiri dan kanan'+#13+ 'SELECT A CHART STYLE=Pilih stail carta'+#13+ 'SELECT A DATABASE TABLE=Pilih jadual data induk'+#13+ 'TABLE=Jadual'+#13+ 'SELECT THE DESIRED FIELDS TO CHART=Pilih ruang diingini untuk dijadualkan'+#13+ 'SELECT A TEXT LABELS FIELD=Pilih ruang label teks'+#13+ 'CHOOSE THE DESIRED CHART TYPE=Pilih jenis carta diingini'+#13+ 'CHART PREVIEW=Carta pratayang'+#13+ 'SHOW LEGEND=Tunjuk lagenda'+#13+ 'SHOW MARKS=Tunjuk tanda-tanda'+#13+ 'FINISH=Habis'+#13+ 'RANDOM=Rawak'+#13+ 'DRAW EVERY=Lukis tiap-tiap'+#13+ 'ARROWS=Panah'+#13+ 'ASCENDING=Menaik'+#13+ 'DESCENDING=Menurun'+#13+ 'VERTICAL AXIS=Paksi memanjang'+#13+ 'DATETIME=TarikhMasa'+#13+ 'TOP AND BOTTOM=Atas dan bawah'+#13+ 'HORIZONTAL AXIS=Paksi melintang'+#13+ 'PERCENTS=Peratus'+#13+ 'VALUES=Nilai'+#13+ 'FORMATS=Format'+#13+ 'SHOW IN LEGEND=Tunjuk dalam lagenda'+#13+ 'SORT=Atur'+#13+ 'MARKS=Tanda-tanda'+#13+ 'BEVEL INNER=Siku dalam'+#13+ 'BEVEL OUTER=Siku luar'+#13+ 'PANEL EDITOR=Penyunting panel'+#13+ 'CONTINUOUS=Bersambungan'+#13+ 'HORIZ. ALIGNMENT=Penjajaran melintang'+#13+ 'EXPORT CHART=Eksport carta'+#13+ 'BELOW %=Bawah %'+#13+ 'BELOW VALUE=Nilai bawah'+#13+ 'NEAREST POINT=Titik terdekat'+#13+ 'DRAG MARKS=Seret tanda-tanda'+#13+ 'TEECHART PRINT PREVIEW=Pratayang cetak TeeChart'+#13+ 'X VALUE=Nilai X'+#13+ 'X AND Y VALUES=Nilai X dan Y'+#13+ 'SHININESS=Kecerahan'+#13+ 'ALL SERIES VISIBLE=Semua turutan terlihat'+#13+ 'MARGIN=Garis'+#13+ 'DIAGONAL=Diagonal'+#13+ 'LEFT TOP=Kiri Atas'+#13+ 'LEFT BOTTOM=Kiri Bawah'+#13+ 'RIGHT TOP=Kanan Atas'+#13+ 'RIGHT BOTTOM=Kanan Bawah'+#13+ 'EXACT DATE TIME=Tarikh Masa tepat'+#13+ 'RECT. GRADIENT=Kecerunan segi empat sama'+#13+ 'CROSS SMALL=Silang kecil'+#13+ 'AVG=Purata'+#13+ 'FUNCTION=Fungsi'+#13+ 'AUTO=Auto'+#13+ 'ONE MILLISECOND=Satu milisaat'+#13+ 'ONE SECOND=Satu saat'+#13+ 'FIVE SECONDS=Lima saat'+#13+ 'TEN SECONDS=Sepuluh saat'+#13+ 'FIFTEEN SECONDS=Lima belas saat'+#13+ 'THIRTY SECONDS=Tiga puluh saat'+#13+ 'ONE MINUTE=Satu minit'+#13+ 'FIVE MINUTES=Lima minit'+#13+ 'TEN MINUTES=Sepuluh minit'+#13+ 'FIFTEEN MINUTES=Lima belas minit'+#13+ 'THIRTY MINUTES=Tiga puluh minit'+#13+ 'TWO HOURS=Dua jam'+#13+ 'TWO HOURS=Dua jam'+#13+ 'SIX HOURS=Enam jam'+#13+ 'TWELVE HOURS=Dua belas jam'+#13+ 'ONE DAY=Satu hari'+#13+ 'TWO DAYS=Dua hari'+#13+ 'THREE DAYS=Diga hari'+#13+ 'ONE WEEK=Satu minggu'+#13+ 'HALF MONTH=Setengah bulan'+#13+ 'ONE MONTH=Satu bulan'+#13+ 'TWO MONTHS=Dua bulan'+#13+ 'THREE MONTHS=Tiga bulan'+#13+ 'FOUR MONTHS=Empat bulan'+#13+ 'SIX MONTHS=Enam bulan'+#13+ 'IRREGULAR=Tak malar'+#13+ 'CLICKABLE=Boleh diklik'+#13+ 'ROUND=Bulat'+#13+ 'FLAT=Leper'+#13+ 'PIE=Pai'+#13+ 'HORIZ. BAR=Bar melintang'+#13+ 'BUBBLE=Buih'+#13+ 'SHAPE=Bentuk'+#13+ 'POINT=Titik'+#13+ 'FAST LINE=Garis Cepat'+#13+ 'CANDLE=Lilin'+#13+ 'VOLUME=Volum'+#13+ 'HORIZ LINE=Garis melintang'+#13+ 'SURFACE=Permukaan'+#13+ 'LEFT AXIS=Paksi kiri'+#13+ 'RIGHT AXIS=Paksi kanan'+#13+ 'TOP AXIS=Paksi atas'+#13+ 'BOTTOM AXIS=Paksi bawah'+#13+ 'CHANGE SERIES TITLE=Tukar siri tajuk'+#13+ 'DELETE %S ?=Padam %s ?'+#13+ 'DESIRED %S INCREMENT=Kenaikan %s diingini'+#13+ 'INCORRECT VALUE. REASON: %S=Nilai tidak betul. Sebab: %s'+#13+ 'FillSampleValues NumValues must be > 0=PengisianNilaiContoh NomborNilai mestilah > 0.'+#13+ 'VISIT OUR WEB SITE !=Kunjungi Website kami !'+#13+ 'SHOW PAGE NUMBER=Tunjuk nombor mukasurat'+#13+ 'PAGE NUMBER=Nombor mukasurat'+#13+ 'PAGE %D OF %D=Mukasurat %d dari %d'+#13+ 'TEECHART LANGUAGES=Bahasa-bahasa TeeChart'+#13+ 'CHOOSE A LANGUAGE=Pilih satu bahasa'+#13+ 'SELECT ALL=Pilih semua'+#13+ 'MOVE UP=Pindah Keatas'+#13+ 'MOVE DOWN=Pindah Kebawah'+#13+ 'DRAW ALL=Lukis semua'+#13+ 'TEXT FILE=Fail teks'+#13+ 'IMAG. SYMBOL=Simbol imej'+#13+ 'DRAG REPAINT=Seret cat kembali'+#13+ 'NO LIMIT DRAG=Seretan tiada had' ; end; end; Procedure TeeSetMalaysian; begin TeeCreateMalaysian; TeeLanguage:=TeeMalaysianLanguage; TeeMalaysianConstants; TeeLanguageHotKeyAtEnd:=False; end; initialization finalization FreeAndNil(TeeMalaysianLanguage); end.
unit CopyToStoreCmd; interface procedure CopyToStore(fqFileName, StoreName : string; userId, password : String; hostName : String; hostPort : Integer); implementation uses Classes, SysUtils, SessionManager; procedure CopyToStore(fqFileName, StoreName : string; userId, password : String; hostName : String; hostPort : Integer); var sessionMgr : TSessionManager; stream : TFileStream; begin sessionMgr := TSessionManager.Create(userId, password, hostName, hostPort); stream := TFileStream.Create(fqFileName, fmOpenRead); try sessionMgr.session.Open; sessionMgr.session.SaveStreamToStoreFile(storeName, ExtractFileName(fqfileName), stream); sessionMgr.session.Close; finally sessionMgr.Free; stream.Free; end; end; end.
unit uReports; interface uses sysutils, classes, ORFN, ComCtrls, Forms, Graphics; type TCellObject = class //Data Object for each Cell in ListView private FName : string; //Column Name FSite : string; //Site (#;name) FInclude : string; //Set if data is to be included in detailed report FTextType : string; //Type of data (WP) FVisible : string; //Set if column property is visible FHandle : string; //Row:Col identifier FDataType : string; //Data Type of data in column (null or 0:freetext, 1:integer, 2:datetime) FData : TStringList; //Data for this field (could be WP) FCount : integer; public constructor Create; destructor Destroy; override; procedure Add(ASite, AHandle, AColumnData: string; AData: TStringList); property Name :string read FName write FName; property Site :string read FSite write FSite; property Include :string read FInclude write FInclude; property TextType :string read FTextType write FTextType; property Visible :string read FVisible write FVisible; property Handle :string read FHandle write FHandle; property DataType :string read FDataType write FDatatype; property Data :TStringList read FData write FData; property Count :integer read FCount write FCount; end; TRowObject = class //List of Row objects for ReportsTab ListView private FCount :integer; FColumnList:TList; public constructor Create; destructor Destroy; override; procedure Add(ASite, AHandle, AColumnData: string; AData: TStringList); procedure Clear; property Count :integer read FCount; property ColumnList :TList read FColumnList; end; TLabRowObject = class //List of Row objects for Labs Tab ListView private FCount :integer; FColumnList:TList; public constructor Create; destructor Destroy; override; procedure Add(ASite, AHandle, AColumnData: string; AData: TStringList); procedure Clear; property Count :integer read FCount; property ColumnList :TList read FColumnList; end; type PReportTreeObject = ^TReportTreeObject; TReportTreeObject = Record ID : String; //Report ID ID:Text => when passed to broker add: ;Remote~uHState Heading : String; //Report Heading Qualifier : String; //Report Qualifier Remote : String; //Remote Data Capable RptType : String; //Report Type Category : String; //Report Category RPCName : String; //Associated RPC IFN : String; //IFN of report in file 101.24 HSTAG : String; //Report extract tag;routine;component # SortOrder : String; //#:# of columns to use in a multi-column sort MaxDaysBack: String; //Maximum number of Days allowed for report Direct : String; //Direct Remote Call flag HDR : String; //HDR is data source if = 1 FHIE : String; //FHIE is data source if = 1 FHIEONLY : String; //FHIEONLY if data is to only include FHIE end; type PProcTreeObj = ^TProcedureTreeObject; TProcedureTreeObject = Record ParentName : String; //Parent procedure name for exam/print sets ProcedureName: String; //Same as ParentName for stand-alone procedures MemberOfSet : String; //1 = descendant procedures have individual reports //2 = descendant procedures have one shared report ExamDtTm : String; //Exam Date Time Associate : Integer; //Index of the associated TListItem in the lvReports end; var RowObjects: TRowObject; LabRowObjects: TLabRowObject; //procedures & functions for Report Tree & ListView objects function MakeReportTreeObject(x: string): PReportTreeObject; function IsValidNumber(S: string; var V: extended): boolean; function StringToFMDateTime(Str: string): TFMDateTime; function ShortDateStrToDate(shortdate: string): string ; function StripSpace(str:string):string; function MakeProcedureTreeObject(x: string): PProcTreeObj; function MakePrntProcTreeObject(x: string): PProcTreeObj; //procedures & functions for Report Fonts procedure ReportTextFontChange(Self, Sender: TObject); function CreateReportTextComponent(ParentForm: TForm): TRichEdit; implementation const Months: array[1..12] of String = ('JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'); constructor TCellObject.Create; begin FData := TStringList.Create; end; destructor TCellObject.Destroy; begin FData.Free; end; procedure TCellObject.Add(ASite, AHandle, AColumnData: string; AData: TStringList); begin FName := piece(AColumnData,'^',1); FSite := ASite; FInclude := piece(AColumnData,'^',5); FTextType := piece(AColumnData,'^',4); FVisible := piece(AColumnData,'^',2); FDataType := piece(AColumnData,'^',9); FHandle := AHandle; FCount := AData.Count; FastAssign(AData, FData); end; function MakeReportTreeObject(x: string): PReportTreeObject; var AnObject: PReportTreeObject; begin //x=id^Name^Qualifier^HSTag;Routine^Entry^Routine^Remote^Type^Category^RPC^ifn^SortOrder^MaxDaysBack^Direct^HDR^FHIE New(AnObject); with AnObject^ do begin ID := UpperCase(Piece(x, U, 1)) + ':' + UpperCase(Piece(x, U, 2)); Heading := Piece(x, U, 2); Qualifier := Piece(x, U, 3); Remote := Piece(x, U, 7); RptType := Piece(x, U, 8); Category := Piece(x, U, 9); RPCName := UpperCase(Piece(x, U, 10)); IFN := Piece(x, U, 11); HSTag := UpperCase(Piece(x, U, 4)); SortOrder := Piece(x, U, 12); MaxDaysBack := Piece(x, U, 13); Direct := Piece(x, U, 14); HDR := Piece(x, U, 15); FHIE := Piece(x, U, 16); FHIEONLY := Piece(x, U, 17); end; Result := AnObject; end; constructor TRowObject.Create; begin FColumnList := TList.Create; FCount := 0; end; destructor TRowObject.Destroy; begin //Clear; FColumnList.Free; inherited Destroy; end; procedure TRowObject.Add(ASite, AHandle, AColumnData: string; AData: TStringList); var ACell: TCellObject; begin ACell := TCellObject.Create; ACell.Add(ASite,AHandle,AColumnData,AData); FColumnList.Add(ACell); FCount := FColumnList.Count; end; procedure TRowObject.Clear; var i: Integer; begin with FColumnList do for i := 0 to Count - 1 do with TCellObject(Items[i]) do Free; FColumnList.Clear; FCount := 0; end; constructor TLabRowObject.Create; begin FColumnList := TList.Create; FCount := 0; end; destructor TLabRowObject.Destroy; begin //Clear; FColumnList.Free; inherited Destroy; end; procedure TLabRowObject.Add(ASite, AHandle, AColumnData: string; AData: TStringList); var ACell: TCellObject; begin ACell := TCellObject.Create; ACell.Add(ASite,AHandle,AColumnData,AData); FColumnList.Add(ACell); FCount := FColumnList.Count; end; procedure TLabRowObject.Clear; var i: Integer; begin with FColumnList do for i := 0 to Count - 1 do with TCellObject(Items[i]) do Free; FColumnList.Clear; FCount := 0; end; function IsValidNumber(S: string; var V: extended): boolean; var NumCode: integer; FirstSpace: integer; begin FirstSpace := Pos(' ', S); if FirstSpace > 0 then S := Copy(S, 1, FirstSpace - 1); Val(S, V, NumCode); Result := (NumCode = 0); if not Result then begin // Remove thousands seperators S := StringReplace(S, FormatSettings.ThousandSeparator, '', [rfReplaceAll]); // change DecimalSeperator to '.' because Val only recognizes that, not // the locale specific decimal char... then try again. Stupid Val. S := StringReplace(S, FormatSettings.DecimalSeparator, '.', [rfReplaceAll]); Val(S, V, NumCode); Result := (NumCode = 0); end; end; function StringToFMDateTime(Str: string): TFMDateTime; var mm,dd,yy,hh: integer; day,time,hr,min: string; begin day := piece(str,' ',1); time := piece(str,' ',2); hh := 0; if length(time) > 0 then begin hr := piece(time,':',1); if Copy(hr,1,1) = '0' then hr := Copy(hr,2,1); if Copy(hr,1,1) = '0' then hr := ''; min := piece(time,':',2); if Copy(min,1,1) = '0' then min := Copy(min,2,1); if Copy(min,1,1) = '0' then min := ''; hh := StrToIntDef(hr + min,0); end; mm := StrToIntDef(piece(day,'/',1),0); dd := StrToIntDef(piece(day,'/',2),0); yy := StrToIntDef(piece(day,'/',3),0) - 1700; Result := (yy * 10000) + (mm * 100) + dd + (hh/10000); end; function ShortDateStrToDate(shortdate: string): string ; {Converts date in format 'mmm dd,yy' or 'mmm dd,yyyy' to standard 'mm/dd/yy'} var month,day,year: string ; i: integer ; begin result := 'ERROR' ; if (Pos(' ',shortdate) <> 4) or ((Pos(',',shortdate) <> 7) and (Pos(',',shortdate) <> 6)) then exit ; {no spaces or comma} for i := 1 to 12 do if Months[i] = UpperCase(Copy(shortdate,1,3)) then month := IntToStr(i); if month = '' then exit ; {invalid month name} if length(month) = 1 then month := '0' + month; if Pos(',',shortdate) = 7 then begin day := IntToStr(StrToInt(Copy(shortdate,5,2))) ; year := IntToStr(StrToInt(Copy(shortdate,8,99))) ; end; if Pos(',',shortdate) = 6 then begin day := '0' + IntToStr(StrToInt(Copy(shortdate,5,1))) ; year := IntToStr(StrToInt(Copy(shortdate,7,99))) ; end; result := month+'/'+day+'/'+year ; end ; function StripSpace(str: string): string; var i,j: integer; begin i := 1; j := length(str); while str[i] = #32 do inc(i); while str[j] = #32 do dec(j); result := copy(str, i, j-i+1); end; function MakeProcedureTreeObject(x: string): PProcTreeObj; var AnObject: PProcTreeObj; begin New(AnObject); with AnObject^ do begin ParentName := Piece(x, U, 11); ProcedureName := Piece(x, U, 4); MemberOfSet := Piece(x, U, 10); ExamDtTm := Piece(x, U, 2); Associate := -1; end; Result := AnObject; end; function MakePrntProcTreeObject(x: string): PProcTreeObj; var AnObject: PProcTreeObj; begin New(AnObject); with AnObject^ do begin ParentName := Piece(x, U, 11); ExamDtTm := Piece(x, U, 2); Associate := -1; end; Result := AnObject; end; procedure ReportTextFontChange(Self, Sender: TObject); begin TFont(Sender).Size := 8; end; // CQ#70295 function CreateReportTextComponent(ParentForm: TForm): TRichEdit; var m: TMethod; begin Result := TRichEdit.Create(ParentForm); with Result do begin Parent := ParentForm; Visible := False; Width := 600; Font.Name := 'Courier New'; Font.Size := 8; m.Code := @ReportTextFontChange; m.Data := ParentForm; Font.OnChange := TNotifyEvent(m); end; end; end.
{ AD.A.P.T. Library Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved Original Source Location: https://github.com/LaKraven/ADAPT Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md } unit ADAPT.Streams.Intf; {$I ADAPT.inc} interface uses {$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES} System.Classes, System.SysUtils, {$ELSE} Classes, SysUtils, {$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES} ADAPT, ADAPT.Intf; {$I ADAPT_RTTI.INC} type { Forward Delcarations } IADStream = interface; IADStreamManagement = interface; { Exceptions } EADStreamException = class(EADException); EADStreamCaretException = class(EADStreamException); EADStreamCaretInvalid = class(EADStreamCaretException); /// <summary><c>A Caret for Reading from a Stream at a particular position.</c></summary> IADStreamCaretReader = interface(IADInterface) ['{3A03B581-5861-4566-9897-3B1EF58B656F}'] // Getters /// <returns> /// <para>False<c> if the Caret is Valid.</c></para> /// <para>True<c> if the Caret is Invalid.</c></para> /// </returns> function GetIsInvalid: Boolean; /// <returns> /// <para>False<c> if the Caret is Invalid.</c></para> /// <para>True<c> if the Caret is Valid.</c></para> /// </returns> function GetIsValid: Boolean; /// <returns><c>The Position of this Caret within the Stream.</c></returns> function GetPosition: Int64; // Management Methods /// <summary><c>Reads the specified number of Bytes from the Array into the specified Address</c></summary> /// <returns><c>Returns the number of Bytes actually read.</c></returns> function Read(var ABuffer; const ALength: Int64): Int64; // Properties /// <returns> /// <para>False<c> if the Caret is Valid.</c></para> /// <para>True<c> if the Caret is Invalid.</c></para> /// </returns> property IsInvalid: Boolean read GetIsInvalid; /// <returns> /// <para>False<c> if the Caret is Invalid.</c></para> /// <para>True<c> if the Caret is Valid.</c></para> /// </returns> property IsValid: Boolean read GetIsValid; /// <returns><c>The Position of this Caret within the Stream.</c></returns> property Position: Int64 read GetPosition; end; /// <summary><c>A Caret for Operating on a Stream at a particular position.</c></summary> /// <remarks><c>A Caret should take responsibility for ensuring any operation affecting OTHER Carets updates those Carets as necessary.</c></remarks> IADStreamCaret = interface(IADStreamCaretReader) ['{D8E849E5-A5A1-4B4F-9AF6-BBD397216C5B}'] // Getters function GetStream: IADStream; function GetStreamManagement: IADStreamManagement; // Setters procedure SetPosition(const APosition: Int64); // Management Methods /// <summary><c>Deletes the given number of Bytes from the current Position in the Stream, then compacts the Stream by that number of Bytes (shifting any subsequent Bytes to the left)</c></summary> /// <returns><c>Returns the number of Bytes deleted.</c></returns> /// <remarks> /// <para><c>Automatically shifts the Position of subsequent Carets by the offset of Bytes deleted.</c></para> /// </remarks> function Delete(const ALength: Int64): Int64; /// <summary><c>Inserts the given Buffer into the current Position within the Stream (shifting any subsequent Bytes to the right)</c></summary> /// <returns><c>Returns the number of Bytes actually written.</c></returns> /// <remarks> /// <para><c>Automatically shifts the Position of subsequent Carets by the offset of Bytes inserted.</c></para> /// </remarks> function Insert(const ABuffer; const ALength: Int64): Int64; /// <summary><c>Writes the given Buffer into the current Position within the Stream (overwriting any existing data, and expanding the Size of the Stream if required)</c></summary> /// <returns><c>Returns the number of Bytes actually written.</c></returns> function Write(const ABuffer; const ALength: Int64): Int64; /// <returns><c>Returns the new </c>Position<c> in the Stream.</c></returns> function Seek(const AOffset: Int64; const AOrigin: TSeekOrigin): Int64; /// <summary><c>Invalidates the Caret.</c></summary> /// <remarks><c>This is usually called by the owning Stream when a Caret has been Invalidated by an operation from another Caret.</c></remarks> procedure Invalidate; // Properties /// <summary><c>The Position of this Caret within the Stream.</c></summary> property Position: Int64 read GetPosition write SetPosition; /// <summary><c>Reference to the Caret's owning Stream</c></summary> property Stream: IADStream read GetStream; /// <summary><c>Reference to the Caret's owning Stream's Management Methods.</c><summary> property StreamManagement: IADStreamManagement read GetStreamManagement; end; /// <summary><c>A Stream.</c></summary> /// <remarks><c>The Stream enables you to request one or more Carets, and these Carets are used to Read from the Stream.</c></remarks> IADStreamReader = interface(IADInterface) ['{23E572B8-A998-4808-8EB8-D30EEE88044C}'] // Getters function GetSize: Int64; // Management Methods /// <returns><c>A new Stream Caret Reader pointing to the first Byte of the Stream.</c></returns> function NewCaretReader: IADStreamCaretReader; overload; /// <returns><c>A new Stream Caret Reader pointing to a specific Byte of the Stream.</c></returns> function NewCaretReader(const APosition: Int64): IADStreamCaretReader; overload; /// <summary><c>Save contents of the Stream to a File.</c></summary> procedure SaveToFile(const AFileName: String); /// <summary><c>Save contents of the Stream to another Stream.</c></summary> procedure SaveToStream(const AStream: IADStream); overload; /// <summary><c>Save contents of the Stream to another Stream.</c></summary> procedure SaveToStream(const AStream: TStream); overload; // Properties /// <summary><c>Size of the Stream.</c></summary> property Size: Int64 read GetSize; end; /// <summary><c>A Stream.</c></summary> /// <remarks><c>The Stream enables you to request one or more Carets, and these Carets are used to operate on the Stream.</c></remarks> IADStream = interface(IADStreamReader) ['{07F45B12-1DFC-453A-B95C-E00C9F5F4285}'] // Setters procedure SetSize(const ASize: Int64); // Management Methods /// <summary><c>Populate the Stream from a File.</c></summary> procedure LoadFromFile(const AFileName: String); /// <summary><c>Populate the Stream from the contents of another Stream.</c></summary> procedure LoadFromStream(const AStream: IADStream); overload; /// <summary><c>Populate the Stream from the contents of another Stream.</c></summary> procedure LoadFromStream(const AStream: TStream); overload; /// <returns><c>A new Stream Caret pointing to the first Byte of the Stream.</c></returns> function NewCaret: IADStreamCaret; overload; /// <returns><c>A new Stream Caret pointing to a specific Byte of the Stream.</c></returns> function NewCaret(const APosition: Int64): IADStreamCaret; overload; // Properties /// <summary><c>Size of the Stream.</c></summary> property Size: Int64 read GetSize write SetSize; end; /// <summary><c>The Stream Management Interface provides access to methods that need to be called internally by a Caret in order to manage other Carets contained by that Stream.</c></summary> /// <remarks><c>This interface is separated to protect an implementing developer from accidentally calling internal Stream Management Methods.</c></remarks> IADStreamManagement = interface(IADInterface) ['{3FBBB8FD-D115-40FC-9269-FB3C6820794B}'] procedure InvalidateCaret(const ACaret: IADStreamCaret; const AFromPosition, ACount: Int64); procedure InvalidateCarets(const AFromPosition, ACount: Int64); procedure ShiftCaretLeft(const ACaret: IADStreamCaret; const AFromPosition, ACount: Int64); procedure ShiftCaretRight(const ACaret: IADStreamCaret; const AFromPosition, ACount: Int64); procedure ShiftCaretsLeft(const AFromPosition, ACount: Int64); procedure ShiftCaretsRight(const AFromPosition, ACount: Int64); /// <summary><c>Removes a Caret from Stream's internal Caret List.</c></summary> /// <remarks> /// <para><c>WARNING - The Stream will no longer be able to manage this Caret.</c></para> /// <para><c>This is called internally by a Caret when it is destroyed.</c></para> /// </remarks> procedure UnregisterCaret(const ACaret: IADStreamCaret); end; /// <summary><c>Provides Methods/Properties specific to a Memory Stream.</c></summary> IADMemoryStream = interface(IADStream) ['{DD2B94EB-B752-4973-8639-833298CD410C}'] // Getters function GetCapacity: Int64; // Setters procedure SetCapacity(ACapacity: Int64); // Properties property Capacity: Int64 read GetCapacity write SetCapacity; end; implementation end.
unit fOrdersRefill; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, fAutoSz, StdCtrls, ORFn, ORCtrls, ExtCtrls, VA508AccessibilityManager; type TfrmRefillOrders = class(TfrmAutoSz) pnlBottom: TPanel; cmdOK: TButton; cmdCancel: TButton; grbPickUp: TGroupBox; radWindow: TRadioButton; radMail: TRadioButton; radClinic: TRadioButton; pnlClient: TPanel; lstOrders: TCaptionListBox; lblOrders: TLabel; procedure FormCreate(Sender: TObject); procedure cmdOKClick(Sender: TObject); procedure cmdCancelClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); private OKPressed: Boolean; PickupAt: string; end; function ExecuteRefillOrders(SelectedList: TList): Boolean; implementation {$R *.DFM} uses rOrders, rMeds, uCore, uConst, rMisc; function ExecuteRefillOrders(SelectedList: TList): Boolean; var frmRefillOrders: TfrmRefillOrders; AnOrder: TOrder; OriginalID: string; i: Integer; begin Result := False; if SelectedList.Count = 0 then Exit; frmRefillOrders := TfrmRefillOrders.Create(Application); try ResizeAnchoredFormToFont(frmRefillOrders); frmRefillOrders.Left := (Screen.WorkAreaWidth - frmRefillOrders.Width) div 2; frmRefillOrders.Top := (Screen.WorkAreaHeight - frmRefillOrders.Height) div 2; with SelectedList do for i := 0 to Count - 1 do frmRefillOrders.lstOrders.Items.Add(TOrder(Items[i]).Text); frmRefillOrders.ShowModal; if frmRefillOrders.OKPressed then begin StatusText('Requesting Refill...'); with SelectedList do for i := 0 to Count - 1 do begin AnOrder := TOrder(Items[i]); OriginalID := AnOrder.ID; Refill(OriginalID, frmRefillOrders.PickupAt); AnOrder.ActionOn := OriginalID + '=RF'; SendMessage(Application.MainForm.Handle, UM_NEWORDER, ORDER_ACT, Integer(Items[i])); end; Result := True; StatusText(''); end; finally with SelectedList do for i := 0 to Count - 1 do UnlockOrder(TOrder(Items[i]).ID); frmRefillOrders.Release; end; end; procedure TfrmRefillOrders.FormCreate(Sender: TObject); begin inherited; OKPressed := False; PickupAt := PickUpDefault; if PickupAt = 'M' then radMail.Checked := true else if PickupAt = 'C' then radClinic.Checked := true else begin PickupAt := 'W'; radWindow.Checked := true; end; end; procedure TfrmRefillOrders.cmdOKClick(Sender: TObject); const TX_LOCATION_REQ = 'A location for the refill must be selected.'; TC_LOCATION_REQ = 'Missing Refill Location'; begin inherited; if not (radWindow.Checked or radMail.Checked or radClinic.Checked) then begin InfoBox(TX_LOCATION_REQ, TC_LOCATION_REQ, MB_OK); Exit; end; OKPressed := True; if radWindow.Checked then PickupAt := 'W' else if radMail.Checked then PickupAt := 'M' else PickupAt := 'C'; Close; end; procedure TfrmRefillOrders.cmdCancelClick(Sender: TObject); begin inherited; Close; end; procedure TfrmRefillOrders.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveUserBounds(Self); end; procedure TfrmRefillOrders.FormShow(Sender: TObject); begin SetFormPosition(Self); end; end.
unit ncChromeUtils; interface procedure Chrome_Install_Ext(aID, aPath, aVersion: String); procedure Chrome_Remove_Ext(aID: String); function Chrome_BaseExt_Folder: String; function Chrome_Ext_Folder(aID, aVersion: String): String; function Chrome_Pref_Folder: String; procedure Chrome_Change_Open_URL(aURL: String); function GetLocalAppData: String; implementation uses ncCheckWin64, Registry, Windows, SHFolder, Classes, SysUtils; function GetLocalAppData: String; const TOKEN_DEFAULTUSER = $FFFF; // -1 var szBuffer: AnsiString; // <-- here ResultCode: Integer; begin Result := ''; // avoid function might return undefined warning SetLength(szBuffer, 255); ResultCode := SHGetFolderPathA(0, CSIDL_LOCAL_APPDATA, TOKEN_DEFAULTUSER, 0, PAnsiChar(szBuffer)); if ResultCode = 0 then Result := String(PAnsiChar(szBuffer)); end; function BasePath: String; begin if IsWow64 then Result := '\Software\Wow6432Node\Google\Chrome\Extensions' else Result := '\Software\Google\Chrome\Extensions'; end; function Chrome_BaseExt_Folder: String; begin Result := Chrome_Pref_Folder + '\Extensions'; end; function Chrome_Pref_Folder: String; begin Result := GetLocalAppData + '\Google\Chrome\User Data\Default'; end; function Chrome_Ext_Folder(aID, aVersion: String): String; begin Result := Chrome_BaseExt_Folder+'\'+aID+'\'+aVersion+'_0'; end; procedure Chrome_Install_Ext(aID, aPath, aVersion: String); var R: TRegistry; begin R := TRegistry.Create; try R.Access := KEY_ALL_ACCESS; R.RootKey := HKEY_LOCAL_MACHINE; R.OpenKey(BasePath+'\'+aID, True); R.WriteString('path', aPath); R.WriteString('version', aVersion); R.CloseKey; finally R.Free; end; end; procedure Chrome_Remove_Ext(aID: String); var R: TRegistry; begin R := TRegistry.Create; try R.Access := KEY_ALL_ACCESS; R.RootKey := HKEY_LOCAL_MACHINE; R.DeleteKey(BasePath+'\'+aID); R.CloseKey; finally R.Free; end; end; procedure Chrome_Change_Open_URL(aURL: String); const find_str = '"urls_to_restore_on_startup":'; var sl : TStrings; i, p : Integer; s : String; aChanged: Boolean; begin S := Chrome_Pref_Folder+'\preferences'; if not FileExists(S) then Exit; aChanged := False; sl := TStringList.Create; try sl.LoadFromFile(s); for i := 0 to sl.Count -1 do begin P := Pos(find_str, sl[i]); if P>0 then begin sl[i] := Copy(sl[i], 1, p+length(find_str)-1) + ' [ "'+aURL+'" ]'; aChanged := True; end; end; if aChanged then sl.SaveToFile(s); finally sl.Free; end; end; end.
unit MKnob; { TmKnob : Marco Caselli's Knob Control rel. 1.0 This component emulate the volume knob you could find on some HiFi devices; ********************************************************************** * Feel free to use or give away this software as you see fit. * * Please leave the credits in place if you alter the source. * * * * This software is delivered to you "as is", * * no guarantees of any kind. * * * * If you find any bugs, please let me know, I will try to fix them. * * If you modify the source code, please send me a copy * * * * If you like this component, and also if you dislike it ;), please * * send me an E-mail with your comment * * Marco Caselli * * Web site : http://members.tripod.com/dartclub * * E-mail : mcaselli@iname.com * * * * Thank to guy at news://marcocantu.public.italian.delphi * * for some math code. Check the site http://www.marcocantu.com * ********************************************************************** *** Sorry for my bad english ............... Properties : AllowUserDrag : Boolean; Specify if user can or not drag the control to a new value using mouse; FaceColor : TColor; Color of knob face; TickColor : TColor; Color of tick mark; Position : Longint; Current position of the knob; MarkStyle: TMarkStyle; Specify style of the tick mark ( actually only line or filled circle; RotationEffect:Boolean; If True, the knob will shake emulating a rotation visual effect. Position:Longint; Current value of knob; Max : Longint; Upper limit value for Position; Min : Longint; Lower limit value for Position; Events: property OnChange : This event is triggered every time you change the knob value; Lazarus port by W.Pamler *******************************************************************************} {$mode objfpc}{$H+} interface uses LclIntf, Types, SysUtils, Classes, Graphics, Math, Controls, Forms, Dialogs, ComCtrls; type TKnobAngleRange = ( arTop270, arTop180, arTop120, arTop90, arBottom270, arBottom180, arBottom120, arBottom90, arLeft270, arLeft180, arLeft120, arLeft90, arRight270, arRight180, arRight120, arRight90 ); TKnobChangeEvent = procedure(Sender: TObject; AValue: Longint) of object; TKnobMarkStyle = (msLine, msCircle, msTriangle); TKnobMarkSizeKind = (mskPercentage, mskPixels); TmKnob = class(TCustomControl) private const DEFAULT_KNOB_MARK_SIZE = 20; private FMaxValue: Integer; FMinValue: Integer; FCurValue: Integer; FFaceColor: TColor; FTickColor: TColor; FBorderColor: TColor; FAllowDrag: Boolean; FOnChange: TKnobChangeEvent; FFollowMouse: Boolean; FMarkSize: Integer; FMarkSizeKind: TKnobMarkSizeKind; FMarkStyle: TKnobMarkStyle; FAngleRange: TKnobAngleRange; FRotationEffect: Boolean; FShadow: Boolean; FShadowColor: TColor; FTransparent: Boolean; function GetAngleOrigin: Double; function GetAngleRange: Double; procedure SetAllowDrag(AValue: Boolean); procedure SetAngleRange(AValue: TKnobAngleRange); procedure SetBorderColor(AValue: TColor); procedure SetCurValue(AValue: Integer); procedure SetFaceColor(AColor: TColor); procedure SetMarkSize(AValue: Integer); procedure SetMarkSizeKind(AValue: TKnobMarkSizeKind); procedure SetMarkStyle(AValue: TKnobMarkStyle); procedure SetMaxValue(AValue: Integer); procedure SetMinValue(AValue: Integer); procedure SetShadow(AValue: Boolean); procedure SetShadowColor(AValue: TColor); procedure SetTickColor(AValue: TColor); procedure SetTransparent(AValue: Boolean); procedure UpdatePosition(X, Y: Integer); protected procedure DoAutoAdjustLayout(const AMode: TLayoutAdjustmentPolicy; const AXProportion, AYProportion: Double); override; class function GetControlClassDefaultSize: TSize; override; procedure KnobChange; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure Paint; override; public constructor Create(AOwner: TComponent); override; published property Align; property AllowUserDrag: Boolean read FAllowDrag write SetAllowDrag default True; property AngleRange: TKnobAngleRange read FAngleRange write SetAngleRange default arTop270; property BorderColor: TColor read FBorderColor write SetBorderColor default clBtnHighlight; property BorderSpacing; property Color; property FaceColor: TColor read FFaceColor write SetFaceColor default clSilver; property TickColor: TColor read FTickColor write SetTickColor default clBlack; property Position: Integer read FCurValue write SetCurValue; property RotationEffect: Boolean read FRotationEffect write FRotationEffect default false; property Enabled; property MarkSize: Integer read FMarkSize write SetMarkSize default DEFAULT_KNOB_MARK_SIZE; property MarkSizeKind: TKnobMarkSizeKind read FMarkSizeKind write SetMarkSizeKind default mskPercentage; property MarkStyle: TKnobMarkStyle read FMarkStyle write SetMarkStyle default msLine; property Max: Integer read FMaxValue write SetMaxValue default 100; property Min: Integer read FMinValue write SetMinvalue default 0; property OnChange: TKnobChangeEvent read FOnChange write FOnChange; property ParentColor; property ParentShowHint; property Shadow: Boolean read FShadow write SetShadow default true; property ShadowColor: TColor read FShadowColor write SetShadowColor default clBtnShadow; property ShowHint; property Transparent: Boolean read FTransparent write SetTransparent default true; property Visible; end; implementation { Rotates point P around the Center by the angle given by its sin and cos. The angle is relative to the upward y axis in clockwise direction. } function Rotate(P, Center: TPoint; SinAngle, CosAngle: Double): TPoint; begin P.X := P.X - Center.X; P.Y := P.Y - Center.Y; Result.X := round(cosAngle * P.X - sinAngle * P.Y) + Center.X; Result.Y := round(sinAngle * P.X + cosAngle * P.Y) + Center.Y; end; { TmKnob } constructor TmKnob.Create(AOwner: TComponent); begin inherited Create(AOwner); with GetControlClassDefaultSize do SetInitialBounds(0, 0, CX, CY); ControlStyle := ControlStyle + [csOpaque]; FMaxValue := 100; FMinValue := 0; FCurValue := 0; FRotationEffect := false; FMarkStyle := msLine; FMarkSize := DEFAULT_KNOB_MARK_SIZE; FTickColor := clBlack; FFaceColor := clSilver; FBorderColor := clBtnHighlight; FFollowMouse := false; FAllowDrag := true; FAngleRange := arTop270; FTransparent := true; FShadow := true; FShadowColor := clBtnShadow; end; procedure TmKnob.DoAutoAdjustLayout( const AMode: TLayoutAdjustmentPolicy; const AXProportion, AYProportion: Double); begin inherited DoAutoAdjustLayout(AMode, AXProportion, AYProportion); if AMode in [lapAutoAdjustWithoutHorizontalScrolling, lapAutoAdjustForDPI] then begin if FMarkSizeKind = mskPixels then FMarkSize := Round(FMarkSize * AXProportion); end; end; function TmKnob.GetAngleOrigin: Double; const ORIGIN: array[TKnobAngleRange] of Double = ( 0, 0, 0, 0, 180, 180, 180, 180, 90, 90, 90, 90, 270, 270, 270, 270 ); begin Result := DegToRad(ORIGIN[FAngleRange]); end; function TmKnob.GetAngleRange: Double; const ANGLE: array[TKnobAngleRange] of Double = ( 270, 180, 120, 90, 270, 180, 120, 90, 270, 180, 120, 90, 270, 180, 120, 90 ); begin Result := DegToRad(ANGLE[FAngleRange]); end; class function TmKnob.GetControlClassDefaultSize: TSize; begin Result.CX := 60; Result.CY := 60; end; procedure TmKnob.KnobChange; begin if Assigned(FOnChange) then FOnChange(Self, FCurValue); end; procedure TmKnob.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseDown(Button, Shift, X, Y); if FAllowDrag then begin FFollowMouse := True; UpdatePosition(X,Y); Refresh; end; end; procedure TmKnob.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseUp(Button, Shift, X, Y); FFollowMouse := False; end; procedure TmKnob.MouseMove(Shift: TShiftState; X, Y: Integer); begin inherited MouseMove(Shift, X, Y); if FFollowMouse then UpdatePosition(X,Y) end; procedure TmKnob.Paint; var R: TRect; bmp: TBitmap; Angle, sinAngle, cosAngle: Double; W, H: Integer; i: Integer; P: array[0..3] of TPoint; margin: Integer; markerSize: Integer; radius: Integer; ctr: TPoint; penwidth: Integer; begin margin := 4; penwidth := 1; { Initialize offscreen BitMap } bmp := TBitmap.Create; try bmp.Width := Width; bmp.Height := Height; if FTransparent then begin bmp.Transparent := true; bmp.TransparentColor := clForm; bmp.Canvas.Brush.Color := bmp.TransparentColor; end else begin bmp.Transparent := false; if Color = clDefault then bmp.Canvas.Brush.Color := clForm else bmp.Canvas.Brush.Color := Color; end; ctr := Point(Width div 2, Height div 2); R := Rect(0, 0, Width, Height); W := R.Right - R.Left - margin; H := R.Bottom - R.Top - margin; if H < W then radius := H div 2 else radius := W div 2; { This weird thing make knob "shake", emulating a rotation effect. Not so pretty, but I like it..............} if FRotationEffect and (Position mod 2 <> 0) then inc(H); with bmp.Canvas do begin FillRect(R); Brush.Color := FaceColor; Pen.Color := cl3dLight; Pen.Width := penwidth * 2; Pen.Style := psSolid; R := Rect(ctr.X, ctr.Y, ctr.X, ctr.Y); InflateRect(R, radius - penwidth, radius - penwidth); if FShadow then OffsetRect(R, -penwidth, -penwidth); Ellipse(R); if FShadow then begin Pen.Color := FShadowColor; OffsetRect(R, 3*penwidth, 3*penwidth); Ellipse(R); end; Pen.Color := FBorderColor; Pen.Width := 1; if FShadow then OffsetRect(R, -2*penwidth, -2*penwidth); Ellipse(R); if Position >= 0 then begin case FMarkSizeKind of mskPercentage: markersize := radius * FMarkSize div 100; mskPixels: markerSize := FMarkSize; end; if markersize < 2 then markersize := 2; Angle := (Position - (Min + Max)/2 ) / (Max - Min) * GetAngleRange + GetAngleOrigin; SinCos(Angle, sinAngle, cosAngle); case MarkStyle of msLine: begin Pen.Width := 3; Pen.Color := TickColor; P[0] := Point(ctr.X, ctr.Y - radius + penwidth); P[1] := Point(ctr.X, ctr.Y - radius + penwidth + markersize); for i:=0 to 1 do P[i] := Rotate(P[i], ctr, sinAngle, cosAngle); MoveTo(P[0].X, P[0].Y); LineTo(P[1].X, P[1].Y); end; msCircle: begin Brush.Color := TickColor; Pen.Style := psClear; P[0] := Point(ctr.X, ctr.Y - radius + markersize + 2*penwidth); P[0] := Rotate(P[0], ctr, sinAngle, cosAngle); R := Rect(P[0].X, P[0].Y, P[0].X, P[0].Y); InflateRect(R, markersize, markersize); Ellipse(R); end; msTriangle: begin Brush.Color := TickColor; Pen.Style := psClear; // P[0] := Point(ctr.X, H div 32); P[0] := Point(ctr.X, ctr.Y - radius + 2*penwidth); P[1] := Point(P[0].X - markersize, P[0].Y + markersize*2); P[2] := Point(P[0].X + markersize, P[0].Y + markersize*2); P[3] := P[0]; for i:=0 to High(P) do P[i] := Rotate(P[i], ctr, sinAngle, cosAngle); Polygon(P); end; end; end; end; Canvas.CopyMode := cmSrcCopy; Canvas.Draw(0, 0, bmp); finally bmp.Free; end; end; procedure TmKnob.SetAllowDrag(AValue: Boolean); begin if AValue <> FAllowDrag then begin FAllowDrag := AValue; Invalidate; end; end; procedure TmKnob.SetAngleRange(AValue: TKnobAngleRange); begin if AValue <> FAngleRange then begin FAngleRange := AValue; Invalidate; end; end; procedure TmKnob.SetBorderColor(AValue: TColor); begin if AValue <> FBorderColor then begin FBorderColor := AValue; Invalidate; end; end; procedure TmKnob.SetCurValue(AValue: Integer); var tmp: Integer; begin if AValue <> FCurValue then begin if FMinValue > FMaxValue then begin tmp := FMinValue; FMinValue := FMaxValue; FMaxValue := tmp; end; FCurValue := EnsureRange(AValue, FMinValue, FMaxValue); Invalidate; KnobChange; end; end; procedure TmKnob.SetFaceColor(AColor: TColor); begin if FFaceColor <> AColor then begin FFaceColor := AColor; Invalidate; end; end; procedure TmKnob.SetMarkSize(AValue: Integer); begin if AValue <> FMarkSize then begin FMarkSize := AValue; Invalidate; end; end; procedure TmKnob.SetMarkSizeKind(AValue: TKnobMarkSizeKind); begin if AValue <> FMarkSizeKind then begin FMarkSizeKind := AValue; Invalidate; end; end; procedure TmKnob.SetMarkStyle(AValue: TKnobMarkStyle); begin if AValue <> FMarkStyle then begin FMarkStyle := AValue; Invalidate; end; end; procedure TmKnob.SetMaxValue(AValue: Integer); begin if AValue <> FMaxValue then begin FMaxValue := AValue; Invalidate; end; end; procedure TmKnob.SetMinValue(AValue: Integer); begin if AValue <> FMinValue then begin FMinValue := AValue; Invalidate; end; end; procedure TmKnob.SetShadow(AValue: Boolean); begin if AValue <> FShadow then begin FShadow := AValue; Invalidate; end; end; procedure TmKnob.SetShadowColor(AValue: TColor); begin if AValue <> FShadowColor then begin FShadowColor := AValue; Invalidate; end; end; procedure TmKnob.SetTickColor(AValue: TColor); begin if AValue <> FTickColor then begin FTickColor := AValue; Invalidate; end; end; procedure TmKnob.SetTransparent(AValue: Boolean); begin if FTransparent = AValue then exit; FTransparent := AValue; Invalidate; end; procedure TmKnob.UpdatePosition(X, Y: Integer); var CX, CY: integer; Angle: double; begin CX := Width div 2; CY := Height div 2; Angle := -ArcTan2(CX-X, CY-Y); Position := Round((Angle - GetAngleOrigin) * (Max - Min) / GetAngleRange + (Min + Max) / 2); Refresh; end; end.
unit ExtScrollingWinControlUnit; interface uses Messages, Windows, SysUtils, Classes, Graphics, Menus, Imm, Controls, ActnList, MultiMon, Dialogs, HelpIntfs, ExtCtrls, StdCtrls, Forms, Grids; type { Forward declarations } TExScrollingWinControl = class; TExControlScrollBar = class(TPersistent) private FControl: TExScrollingWinControl; FIncrement: TScrollBarInc; FPageIncrement: TScrollbarInc; FPosition: Integer; FRange: Integer; FCalcRange: Integer; FKind: TScrollBarKind; FMargin: Word; FVisible: Boolean; // FTracking: Boolean; FScaled: Boolean; FSmooth: Boolean; FDelay: Integer; FButtonSize: Integer; FColor: TColor; FParentColor: Boolean; FSize: Integer; FStyle: TScrollBarStyle; FThumbSize: Integer; FPageDiv: Integer; FLineDiv: Integer; FUpdateNeeded: Boolean; constructor Create(AControl: TExScrollingWinControl; AKind: TScrollBarKind); procedure CalcAutoRange; function ControlSize(ControlSB, AssumeSB: Boolean): Integer; procedure DoSetRange(Value: Integer); function GetScrollPos: Integer; function NeedsScrollBarVisible: Boolean; function IsIncrementStored: Boolean; procedure SetButtonSize(Value: Integer); procedure SetColor(Value: TColor); procedure SetParentColor(Value: Boolean); procedure SetPosition(Value: Integer); procedure SetRange(Value: Integer); procedure SetSize(Value: Integer); procedure SetStyle(Value: TScrollBarStyle); procedure SetThumbSize(Value: Integer); procedure SetVisible(Value: Boolean); procedure ScrollMessage(var Msg: TWMScroll); function IsRangeStored: Boolean; procedure Update(ControlSB, AssumeSB: Boolean); public procedure Assign(Source: TPersistent); override; procedure ChangeBiDiPosition; property Kind: TScrollBarKind read FKind; function IsScrollBarVisible: Boolean; property ScrollPos: Integer read GetScrollPos; published property ButtonSize: Integer read FButtonSize write SetButtonSize default 0; property Color: TColor read FColor write SetColor default clBtnHighlight; property Increment: TScrollBarInc read FIncrement write FIncrement stored IsIncrementStored default 8; property Margin: Word read FMargin write FMargin default 0; property ParentColor: Boolean read FParentColor write SetParentColor default True; property Position: Integer read FPosition write SetPosition default 0; property Range: Integer read FRange write SetRange stored IsRangeStored default 0; property Smooth: Boolean read FSmooth write FSmooth default False; property Size: Integer read FSize write SetSize default 0; property Style: TScrollBarStyle read FStyle write SetStyle default ssRegular; property ThumbSize: Integer read FThumbSize write SetThumbSize default 0; // property Tracking: Boolean read FTracking write FTracking default False; property Visible: Boolean read FVisible write SetVisible default True; end; { TExScrollingWinControl } TWindowState = (wsNormal, wsMinimized, wsMaximized); TExScrollingWinControl = class(TWinControl) private FHorzScrollBar: TExControlScrollBar; FVertScrollBar: TExControlScrollBar; FAutoScroll: Boolean; FAutoRangeCount: Integer; FUpdatingScrollBars: Boolean; procedure CalcAutoRange; procedure ScaleScrollBars(M, D: Integer); procedure SetAutoScroll(Value: Boolean); procedure SetHorzScrollBar(Value: TExControlScrollBar); procedure SetVertScrollBar(Value: TExControlScrollBar); procedure UpdateScrollBars; procedure WMSize(var Message: TWMSize); message WM_SIZE; procedure WMHScroll(var Message: TWMHScroll); message WM_HSCROLL; procedure WMVScroll(var Message: TWMVScroll); message WM_VSCROLL; procedure CMBiDiModeChanged(var Message: TMessage); message CM_BIDIMODECHANGED; // procedure CMMouseWheel(var Message: TCMMouseWheel); message CM_MOUSEWHEEL; procedure WMMOUSEWHEEL(var Msg: TWMMouseWheel); message WM_MOUSEWHEEL; protected procedure AdjustClientRect(var Rect: TRect); override; procedure AlignControls(AControl: TControl; var ARect: TRect); override; function AutoScrollEnabled: Boolean; virtual; procedure AutoScrollInView(AControl: TControl); virtual; procedure ChangeScale(M, D: Integer); override; procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; procedure DoFlipChildren; override; property AutoScroll: Boolean read FAutoScroll write SetAutoScroll default True; procedure Resizing(State: TWindowState); virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DisableAutoRange; procedure EnableAutoRange; procedure ScrollInView(AControl: TControl); published property HorzScrollBar: TExControlScrollBar read FHorzScrollBar write SetHorzScrollBar; property VertScrollBar: TExControlScrollBar read FVertScrollBar write SetVertScrollBar; end; { TExScrollBox } TExScrollBox = class(TExScrollingWinControl) private FBorderStyle: TBorderStyle; FDescription: string; FConnectionString: string; procedure SetBorderStyle(Value: TBorderStyle); procedure WMNCHitTest(var Message: TMessage); message WM_NCHITTEST; procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED; protected procedure CreateParams(var Params: TCreateParams); override; public constructor Create(AOwner: TComponent); override; property Description: string read FDescription write FDescription; property ConnectionString: string read FConnectionString write FConnectionString; published property Align; property Anchors; property AutoScroll; property AutoSize; property BevelEdges; property BevelInner; property BevelOuter; property BevelKind; property BevelWidth; property BiDiMode; property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle; property Constraints; property DockSite; property DragCursor; property DragKind; property DragMode; property Enabled; property Color nodefault; property Ctl3D; property Font; property ParentBiDiMode; property ParentBackground default False; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnCanResize; property OnClick; property OnConstrainedResize; property OnContextPopup; property OnDblClick; property OnDockDrop; property OnDockOver; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnGetSiteInfo; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; property OnResize; property OnStartDock; property OnStartDrag; property OnUnDock; end; implementation uses ActiveX, Math, Printers, Consts, RTLConsts, CommCtrl, //FlatSB, StdActns{$IFDEF MSWINDOWS}, WinHelpViewer{$ENDIF}, Themes; { TExControlScrollBar } constructor TExControlScrollBar.Create(AControl: TExScrollingWinControl; AKind: TScrollBarKind); begin inherited Create; FControl := AControl; FKind := AKind; FPageIncrement := 80; FIncrement := FPageIncrement div 10; FVisible := True; FDelay := 10; FLineDiv := 4; FPageDiv := 12; FColor := clBtnHighlight; FParentColor := True; FUpdateNeeded := True; end; function TExControlScrollBar.IsIncrementStored: Boolean; begin Result := not Smooth; end; procedure TExControlScrollBar.Assign(Source: TPersistent); begin if Source is TExControlScrollBar then begin Visible := TExControlScrollBar(Source).Visible; Range := TExControlScrollBar(Source).Range; Position := TExControlScrollBar(Source).Position; Increment := TExControlScrollBar(Source).Increment; Exit; end; inherited Assign(Source); end; procedure TExControlScrollBar.ChangeBiDiPosition; begin if Kind = sbHorizontal then if IsScrollBarVisible then if not FControl.UseRightToLeftScrollBar then Position := 0 else Position := Range; end; procedure TExControlScrollBar.CalcAutoRange; var I: Integer; NewRange, AlignMargin: Integer; procedure ProcessHorz(Control: TControl); begin if Control.Visible then case Control.Align of alLeft, alNone: if (Control.Align = alLeft) or (Control.Anchors * [akLeft, akRight] = [akLeft]) then NewRange := Max(NewRange, Position + Control.Left + Control.Width); alRight: Inc(AlignMargin, Control.Width); end; end; procedure ProcessVert(Control: TControl); begin if Control.Visible then case Control.Align of alTop, alNone: if (Control.Align = alTop) or (Control.Anchors * [akTop, akBottom] = [akTop]) then NewRange := Max(NewRange, Position + Control.Top + Control.Height); alBottom: Inc(AlignMargin, Control.Height); end; end; begin if FControl.FAutoScroll then begin if FControl.AutoScrollEnabled then begin NewRange := 0; AlignMargin := 0; for I := 0 to FControl.ControlCount - 1 do if Kind = sbHorizontal then ProcessHorz(FControl.Controls[I]) else ProcessVert(FControl.Controls[I]); DoSetRange(NewRange + AlignMargin + Margin); end else DoSetRange(0); end; end; function TExControlScrollBar.IsScrollBarVisible: Boolean; var Style: Longint; begin Style := WS_HSCROLL; if Kind = sbVertical then Style := WS_VSCROLL; Result := (Visible) and (GetWindowLong(FControl.Handle, GWL_STYLE) and Style <> 0); end; function TExControlScrollBar.ControlSize(ControlSB, AssumeSB: Boolean): Integer; var BorderAdjust: Integer; function ScrollBarVisible(Code: Word): Boolean; var Style: Longint; begin Style := WS_HSCROLL; if Code = SB_VERT then Style := WS_VSCROLL; Result := GetWindowLong(FControl.Handle, GWL_STYLE) and Style <> 0; end; function Adjustment(Code, Metric: Word): Integer; begin Result := 0; if not ControlSB then if AssumeSB and not ScrollBarVisible(Code) then Result := -(GetSystemMetrics(Metric) - BorderAdjust) else if not AssumeSB and ScrollBarVisible(Code) then Result := GetSystemMetrics(Metric) - BorderAdjust; end; begin BorderAdjust := Integer(GetWindowLong(FControl.Handle, GWL_STYLE) and (WS_BORDER or WS_THICKFRAME) <> 0); if Kind = sbVertical then Result := FControl.ClientHeight + Adjustment(SB_HORZ, SM_CXHSCROLL) else Result := 0 {FControl.ClientWidth + Adjustment(SB_VERT, SM_CYVSCROLL)}; end; function TExControlScrollBar.GetScrollPos: Integer; begin Result := 0; if Visible then Result := Position; end; function TExControlScrollBar.NeedsScrollBarVisible: Boolean; begin Result := FRange > ControlSize(False, False); end; procedure TExControlScrollBar.ScrollMessage(var Msg: TWMScroll); var Incr, FinalIncr, Count: Integer; CurrentTime, StartTime, ElapsedTime: Longint; function GetRealScrollPosition: Integer; var SI: TScrollInfo; Code: Integer; begin SI.cbSize := SizeOf(TScrollInfo); SI.fMask := SIF_TRACKPOS; Code := SB_HORZ; if FKind = sbVertical then Code := SB_VERT; Result := Msg.Pos; if FlatSB_GetScrollInfo(FControl.Handle, Code, SI) then Result := SI.nTrackPos; end; begin with Msg do begin if FSmooth and (ScrollCode in [SB_LINEUP, SB_LINEDOWN, SB_PAGEUP, SB_PAGEDOWN]) then begin case ScrollCode of SB_LINEUP, SB_LINEDOWN: begin Incr := FIncrement div FLineDiv; FinalIncr := FIncrement mod FLineDiv; Count := FLineDiv; end; SB_PAGEUP, SB_PAGEDOWN: begin Incr := FPageIncrement; FinalIncr := Incr mod FPageDiv; Incr := Incr div FPageDiv; Count := FPageDiv; end; else Count := 0; Incr := 0; FinalIncr := 0; end; CurrentTime := 0; while Count > 0 do begin StartTime := GetCurrentTime; ElapsedTime := StartTime - CurrentTime; if ElapsedTime < FDelay then Sleep(FDelay - ElapsedTime); CurrentTime := StartTime; case ScrollCode of SB_LINEUP: SetPosition(FPosition - Incr); SB_LINEDOWN: SetPosition(FPosition + Incr); SB_PAGEUP: SetPosition(FPosition - Incr); SB_PAGEDOWN: SetPosition(FPosition + Incr); end; FControl.Update; Dec(Count); end; if FinalIncr > 0 then begin case ScrollCode of SB_LINEUP: SetPosition(FPosition - FinalIncr); SB_LINEDOWN: SetPosition(FPosition + FinalIncr); SB_PAGEUP: SetPosition(FPosition - FinalIncr); SB_PAGEDOWN: SetPosition(FPosition + FinalIncr); end; end; end else case ScrollCode of SB_LINEUP: SetPosition(FPosition - FIncrement); SB_LINEDOWN: SetPosition(FPosition + FIncrement); SB_PAGEUP: SetPosition(FPosition - ControlSize(True, False)); SB_PAGEDOWN: SetPosition(FPosition + ControlSize(True, False)); SB_THUMBPOSITION: if FCalcRange > 32767 then SetPosition(GetRealScrollPosition) else SetPosition(Pos); SB_THUMBTRACK: //if Tracking then 11 if FCalcRange > 32767 then SetPosition(GetRealScrollPosition) else SetPosition(Pos); SB_TOP: SetPosition(0); SB_BOTTOM: SetPosition(FCalcRange); SB_ENDSCROLL: begin end; end; end; end; procedure TExControlScrollBar.SetButtonSize(Value: Integer); const SysConsts: array[TScrollBarKind] of Integer = (SM_CXHSCROLL, SM_CXVSCROLL); var NewValue: Integer; begin if Value <> ButtonSize then begin NewValue := Value; if NewValue = 0 then Value := GetSystemMetrics(SysConsts[Kind]); FButtonSize := Value; FUpdateNeeded := True; FControl.UpdateScrollBars; if NewValue = 0 then FButtonSize := 0; end; end; procedure TExControlScrollBar.SetColor(Value: TColor); begin if Value <> Color then begin FColor := Value; FParentColor := False; FUpdateNeeded := True; FControl.UpdateScrollBars; end; end; procedure TExControlScrollBar.SetParentColor(Value: Boolean); begin if ParentColor <> Value then begin FParentColor := Value; if Value then Color := clBtnHighlight; end; end; procedure TExControlScrollBar.SetPosition(Value: Integer); var Code: Word; Form: TCustomForm; OldPos: Integer; begin if csReading in FControl.ComponentState then FPosition := Value else begin if Value > FCalcRange then Value := FCalcRange else if Value < 0 then Value := 0; if Kind = sbHorizontal then Code := SB_HORZ else Code := SB_VERT; if Value <> FPosition then begin OldPos := FPosition; FPosition := Value; if Kind = sbHorizontal then FControl.ScrollBy(OldPos - Value, 0) else FControl.ScrollBy(0, OldPos - Value); if csDesigning in FControl.ComponentState then begin Form := GetParentForm(FControl); if (Form <> nil) and (Form.Designer <> nil) then Form.Designer.Modified; end; end; if FlatSB_GetScrollPos(FControl.Handle, Code) <> FPosition then FlatSB_SetScrollPos(FControl.Handle, Code, FPosition, True); end; end; procedure TExControlScrollBar.SetSize(Value: Integer); const SysConsts: array[TScrollBarKind] of Integer = (SM_CYHSCROLL, SM_CYVSCROLL); var NewValue: Integer; begin if Value <> Size then begin NewValue := Value; if NewValue = 0 then Value := GetSystemMetrics(SysConsts[Kind]); FSize := Value; FUpdateNeeded := True; FControl.UpdateScrollBars; if NewValue = 0 then FSize := 0; end; end; procedure TExControlScrollBar.SetStyle(Value: TScrollBarStyle); begin if Style <> Value then begin FStyle := Value; FUpdateNeeded := True; FControl.UpdateScrollBars; end; end; procedure TExControlScrollBar.SetThumbSize(Value: Integer); begin if Value <> ThumbSize then begin FThumbSize := Value; FUpdateNeeded := True; FControl.UpdateScrollBars; end; end; procedure TExControlScrollBar.DoSetRange(Value: Integer); begin FRange := Value; if FRange < 0 then FRange := 0; FControl.UpdateScrollBars; end; procedure TExControlScrollBar.SetRange(Value: Integer); begin FControl.FAutoScroll := False; FScaled := True; DoSetRange(Value); end; function TExControlScrollBar.IsRangeStored: Boolean; begin Result := not FControl.AutoScroll; end; procedure TExControlScrollBar.SetVisible(Value: Boolean); begin FVisible := Value; FControl.UpdateScrollBars; end; procedure TExControlScrollBar.Update(ControlSB, AssumeSB: Boolean); type TPropKind = (pkStyle, pkButtonSize, pkThumbSize, pkSize, pkBkColor); const Props: array[TScrollBarKind, TPropKind] of Integer = ( { Horizontal } (WSB_PROP_HSTYLE, WSB_PROP_CXHSCROLL, WSB_PROP_CXHTHUMB, WSB_PROP_CYHSCROLL, WSB_PROP_HBKGCOLOR), { Vertical } (WSB_PROP_VSTYLE, WSB_PROP_CYVSCROLL, WSB_PROP_CYVTHUMB, WSB_PROP_CXVSCROLL, WSB_PROP_VBKGCOLOR)); Kinds: array[TScrollBarKind] of Integer = (WSB_PROP_HSTYLE, WSB_PROP_VSTYLE); Styles: array[TScrollBarStyle] of Integer = (FSB_REGULAR_MODE, FSB_ENCARTA_MODE, FSB_FLAT_MODE); var Code: Word; ScrollInfo: TScrollInfo; procedure UpdateScrollProperties(Redraw: Boolean); begin FlatSB_SetScrollProp(FControl.Handle, Props[Kind, pkStyle], Styles[Style], Redraw); if ButtonSize > 0 then FlatSB_SetScrollProp(FControl.Handle, Props[Kind, pkButtonSize], ButtonSize, False); if ThumbSize > 0 then FlatSB_SetScrollProp(FControl.Handle, Props[Kind, pkThumbSize], ThumbSize, False); if Size > 0 then FlatSB_SetScrollProp(FControl.Handle, Props[Kind, pkSize], Size, False); FlatSB_SetScrollProp(FControl.Handle, Props[Kind, pkBkColor], ColorToRGB(Color), False); end; begin FCalcRange := 0; Code := SB_HORZ; if Kind = sbVertical then Code := SB_VERT; if Visible then begin FCalcRange := Range - ControlSize(ControlSB, AssumeSB); if FCalcRange < 0 then FCalcRange := 0; end; ScrollInfo.cbSize := SizeOf(ScrollInfo); ScrollInfo.fMask := SIF_ALL; ScrollInfo.nMin := 0; if FCalcRange > 0 then ScrollInfo.nMax := Range else ScrollInfo.nMax := 0; ScrollInfo.nPage := ControlSize(ControlSB, AssumeSB) + 1; ScrollInfo.nPos := FPosition; ScrollInfo.nTrackPos := FPosition; UpdateScrollProperties(FUpdateNeeded); FUpdateNeeded := False; {1: Внесенные изменения} //if Code = SB_HORZ then FlatSB_SetScrollInfo(FControl.Handle, Code, ScrollInfo, True); SetPosition(FPosition); FPageIncrement := (ControlSize(True, False) * 9) div 10; if Smooth then FIncrement := FPageIncrement div 10; end; { TExScrollingWinControl } constructor TExScrollingWinControl.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csNeedsBorderPaint]; FHorzScrollBar := TExControlScrollBar.Create(Self, sbHorizontal); FVertScrollBar := TExControlScrollBar.Create(Self, sbVertical); FAutoScroll := True; end; destructor TExScrollingWinControl.Destroy; begin FHorzScrollBar.Free; FVertScrollBar.Free; inherited Destroy; end; procedure TExScrollingWinControl.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params.WindowClass do style := style and not (CS_HREDRAW or CS_VREDRAW); end; procedure TExScrollingWinControl.CreateWnd; begin inherited CreateWnd; //! Scroll bars don't move to the Left side of a TExScrollingWinControl when the //! WS_EX_LEFTSCROLLBAR flag is set and InitializeFlatSB is called. //! A call to UnInitializeFlatSB does nothing. if not SysLocale.MiddleEast and not CheckWin32Version(5, 1) then InitializeFlatSB(Handle); UpdateScrollBars; end; procedure TExScrollingWinControl.AlignControls(AControl: TControl; var ARect: TRect); begin CalcAutoRange; inherited AlignControls(AControl, ARect); end; function TExScrollingWinControl.AutoScrollEnabled: Boolean; begin Result := not AutoSize and not (DockSite and UseDockManager); end; procedure TExScrollingWinControl.DoFlipChildren; var Loop: Integer; TheWidth: Integer; ScrollBarActive: Boolean; FlippedList: TList; begin FlippedList := TList.Create; try TheWidth := ClientWidth; with HorzScrollBar do begin ScrollBarActive := (IsScrollBarVisible) and (TheWidth < Range); if ScrollBarActive then begin TheWidth := Range; Position := 0; end; end; for Loop := 0 to ControlCount - 1 do with Controls[Loop] do begin FlippedList.Add(Controls[Loop]); Left := TheWidth - Width - Left; end; { Allow controls that have associations to realign themselves } for Loop := 0 to FlippedList.Count - 1 do TControl(FlippedList[Loop]).Perform(CM_ALLCHILDRENFLIPPED, 0, 0); if ScrollBarActive then HorzScrollBar.ChangeBiDiPosition; finally FlippedList.Free; end; end; procedure TExScrollingWinControl.CalcAutoRange; begin if FAutoRangeCount <= 0 then begin HorzScrollBar.CalcAutoRange; VertScrollBar.CalcAutoRange; end; end; procedure TExScrollingWinControl.SetAutoScroll(Value: Boolean); begin if FAutoScroll <> Value then begin FAutoScroll := Value; if Value then CalcAutoRange else begin HorzScrollBar.Range := 0; VertScrollBar.Range := 0; end; end; end; procedure TExScrollingWinControl.SetHorzScrollBar(Value: TExControlScrollBar); begin FHorzScrollBar.Assign(Value); end; procedure TExScrollingWinControl.SetVertScrollBar(Value: TExControlScrollBar); begin FVertScrollBar.Assign(Value); end; procedure TExScrollingWinControl.UpdateScrollBars; begin if not FUpdatingScrollBars and HandleAllocated then try FUpdatingScrollBars := True; if FVertScrollBar.NeedsScrollBarVisible then begin FHorzScrollBar.Update(False, True); FVertScrollBar.Update(True, False); end else if FHorzScrollBar.NeedsScrollBarVisible then begin FVertScrollBar.Update(False, True); FHorzScrollBar.Update(True, False); end else begin FVertScrollBar.Update(False, False); FHorzScrollBar.Update(True, False); end; finally FUpdatingScrollBars := False; end; end; procedure TExScrollingWinControl.AutoScrollInView(AControl: TControl); begin if (AControl <> nil) and not (csLoading in AControl.ComponentState) and not (csLoading in ComponentState) then ScrollInView(AControl); end; procedure TExScrollingWinControl.DisableAutoRange; begin Inc(FAutoRangeCount); end; procedure TExScrollingWinControl.EnableAutoRange; begin if FAutoRangeCount > 0 then begin Dec(FAutoRangeCount); if (FAutoRangeCount = 0) and (FHorzScrollBar.Visible or FVertScrollBar.Visible) then CalcAutoRange; end; end; procedure TExScrollingWinControl.ScrollInView(AControl: TControl); var Rect: TRect; begin if AControl = nil then Exit; Rect := AControl.ClientRect; Dec(Rect.Left, HorzScrollBar.Margin); Inc(Rect.Right, HorzScrollBar.Margin); Dec(Rect.Top, VertScrollBar.Margin); Inc(Rect.Bottom, VertScrollBar.Margin); Rect.TopLeft := ScreenToClient(AControl.ClientToScreen(Rect.TopLeft)); Rect.BottomRight := ScreenToClient(AControl.ClientToScreen(Rect.BottomRight)); if Rect.Left < 0 then with HorzScrollBar do Position := Position + Rect.Left else if Rect.Right > ClientWidth then begin if Rect.Right - Rect.Left > ClientWidth then Rect.Right := Rect.Left + ClientWidth; with HorzScrollBar do Position := Position + Rect.Right - ClientWidth; end; if Rect.Top < 0 then with VertScrollBar do Position := Position + Rect.Top else if Rect.Bottom > ClientHeight then begin if Rect.Bottom - Rect.Top > ClientHeight then Rect.Bottom := Rect.Top + ClientHeight; with VertScrollBar do Position := Position + Rect.Bottom - ClientHeight; end; end; procedure TExScrollingWinControl.ScaleScrollBars(M, D: Integer); begin if M <> D then begin if not (csLoading in ComponentState) then begin HorzScrollBar.FScaled := True; VertScrollBar.FScaled := True; end; HorzScrollBar.Position := 0; VertScrollBar.Position := 0; if not FAutoScroll then begin with HorzScrollBar do if FScaled then Range := MulDiv(Range, M, D); with VertScrollBar do if FScaled then Range := MulDiv(Range, M, D); end; end; HorzScrollBar.FScaled := False; VertScrollBar.FScaled := False; end; procedure TExScrollingWinControl.ChangeScale(M, D: Integer); begin ScaleScrollBars(M, D); inherited ChangeScale(M, D); end; procedure TExScrollingWinControl.Resizing(State: TWindowState); begin // Overridden by TCustomFrame end; procedure TExScrollingWinControl.WMSize(var Message: TWMSize); var NewState: TWindowState; begin Inc(FAutoRangeCount); try inherited; NewState := wsNormal; case Message.SizeType of SIZENORMAL: NewState := wsNormal; SIZEICONIC: NewState := wsMinimized; SIZEFULLSCREEN: NewState := wsMaximized; end; Resizing(NewState); finally Dec(FAutoRangeCount); end; FUpdatingScrollBars := True; try CalcAutoRange; finally FUpdatingScrollBars := False; end; if FHorzScrollBar.Visible or FVertScrollBar.Visible then UpdateScrollBars; end; procedure TExScrollingWinControl.WMHScroll(var Message: TWMHScroll); begin if (Message.ScrollBar = 0) and FHorzScrollBar.Visible then FHorzScrollBar.ScrollMessage(Message) else inherited; end; procedure TExScrollingWinControl.WMVScroll(var Message: TWMVScroll); begin if (Message.ScrollBar = 0) and FVertScrollBar.Visible then begin FVertScrollBar.ScrollMessage(Message); end else inherited; end; procedure TExScrollingWinControl.AdjustClientRect(var Rect: TRect); begin Rect := Bounds(-HorzScrollBar.Position, -VertScrollBar.Position, Max(HorzScrollBar.Range, ClientWidth), Max(ClientHeight, VertScrollBar.Range)); inherited AdjustClientRect(Rect); end; procedure TExScrollingWinControl.CMBiDiModeChanged(var Message: TMessage); var Save: Integer; begin Save := Message.WParam; try { prevent inherited from calling Invalidate & RecreateWnd } if not (Self is TExScrollBox) then Message.wParam := 1; inherited; finally Message.wParam := Save; end; if HandleAllocated then begin HorzScrollBar.ChangeBiDiPosition; UpdateScrollBars; end; end; procedure TExScrollingWinControl.WMMOUSEWHEEL(var Msg: TWMMouseWheel); begin if KeysToShiftState(Msg.Keys) = [] then FVertScrollBar.Position:=FVertScrollBar.Position-Msg.WheelDelta else inherited; end; { TExScrollBox } constructor TExScrollBox.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := [csAcceptsControls, csCaptureMouse, csClickEvents, csSetCaption, csDoubleClicks]; Width := 101; Height := 41; FBorderStyle := bsSingle; HorzScrollBar.Visible := True; VertScrollBar.Visible := True; end; procedure TExScrollBox.CreateParams(var Params: TCreateParams); const BorderStyles: array[TBorderStyle] of DWORD = (0, WS_BORDER); begin inherited CreateParams(Params); with Params do begin Style := Style or BorderStyles[FBorderStyle]; if NewStyleControls and Ctl3D and (FBorderStyle = bsSingle) then begin Style := Style and not WS_BORDER; ExStyle := ExStyle or WS_EX_CLIENTEDGE; end; end; end; procedure TExScrollBox.SetBorderStyle(Value: TBorderStyle); begin if Value <> FBorderStyle then begin FBorderStyle := Value; RecreateWnd; end; end; procedure TExScrollBox.WMNCHitTest(var Message: TMessage); begin DefaultHandler(Message); end; procedure TExScrollBox.CMCtl3DChanged(var Message: TMessage); begin if NewStyleControls and (FBorderStyle = bsSingle) then RecreateWnd; inherited; end; end.
unit uSavePicThread; interface uses System.Classes, SysUtils, uGlobal, uCommon; type TSavePicThread = class(TThread) private function GetPic(url: String; var fileName: String): Boolean; function PutPic(fileName, ftpPath: String): Boolean; function UpdateVioUrl(id, p1, p2, p3, path: String): Boolean; protected procedure Execute; override; end; implementation { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure TSavePicThread.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; or Synchronize( procedure begin Form1.Caption := 'Updated in thread via an anonymous method' end ) ); where an anonymous method is passed. Similarly, the developer can call the Queue method with similar parameters as above, instead passing another TThread class as the first parameter, putting the calling thread in a queue with the other thread. } { TSavePicThread } procedure TSavePicThread.Execute; var s, id, p1, p2, p3, fwqdz: String; localp1, localp2, localp3, ftpPath: String; wfsj: TDatetime; begin gLogger.Info('Resave VioPic Thread Start'); s := 'select Systemid, WFSJ, FWQDZ, PHOTOFILE1,PHOTOFILE2,PHOTOFILE3 ' + ' from T_VIO_HIS where ZT=''8'' and IsReSave=''0'''; try with gSQLHelper.Query(s) do begin while not Eof do begin id := Fields[0].AsString; wfsj := Fields[1].AsDateTime; fwqdz := Trim(Fields[2].AsString); p1 := Trim(Fields[3].AsString); p2 := Trim(Fields[4].AsString); p3 := Trim(Fields[5].AsString); if p1 <> '' then p1 := fwqdz + p1; if p2 <> '' then p2 := fwqdz + p2; if p3 <> '' then p3 := fwqdz + p3; if not GetPic(p1, localp1) or not GetPic(p2, localp2) or not GetPic(p3, localp3) then begin Next; continue; end; ftpPath := '/' + FormatDateTime('yyyymmdd', wfsj) + '/'; if not PutPic(localp1, ftpPath) or not PutPic(localp2, ftpPath) or not PutPic(localp3, ftpPath) then begin Next; continue; end; UpdateVioUrl(id, localp1, localp2, localp3, ftpPath); if FileExists(gTempPath + localp1) then DeleteFile(gTempPath + localp1); if FileExists(gTempPath + localp2) then DeleteFile(gTempPath + localp2); if FileExists(gTempPath + localp3) then DeleteFile(gTempPath + localp3); Next; end; Free; end; except on e: exception do gLogger.Error(e.Message); end; gLogger.Info('Resave VioPic Thread End'); end; function TSavePicThread.GetPic(url: String; var fileName: String): Boolean; begin Result := True; fileName := ''; if url <> '' then begin fileName := FormatDateTime('yyyymmddhhnnsszzz', Now()) + '.jpg'; if not TCommon.DownloadPic(url, gTempPath + fileName) then begin gLogger.Error('pic Download Error ' + url); Result := False; end; end; end; function TSavePicThread.PutPic(fileName, ftpPath: String): Boolean; begin Result := True; if fileName <> '' then begin if not TCommon.UploadPic(gTempPath + fileName, ftpPath + fileName) then begin gLogger.Error('pic Upload Error ' + ftpPath + fileName); Result := False; end; end; end; function TSavePicThread.UpdateVioUrl(id, p1, p2, p3, path: String): Boolean; var s: String; begin s := 'update T_VIO_HIS set IsReSave=''1'', FWQDZ=''' + gRootUrl + path + ''', PHOTOFILE1=''' + p1 + ''', PHOTOFILE2=''' + p2 + ''', PHOTOFILE3=''' + p3 + ''' where SystemID=''' + id + ''''; if gSQLHelper.ExecuteSql(s) then gLogger.Info('vio pic url modify OK ' + #13#10 + s) else gLogger.Error('vio pic url modify Error ' + #13#10 + s); end; end.
unit ErrorMessage; interface const ID_ERROR = '사번이 틀렸습니다'; ID_ERROR_C = '사번 오류'; PASS_ERROR = '비밀번호가 틀렸습니다.' + #13#10 + '비밀번호는 주민등록번호입니다'; PASS_ERROR_C = '비번 오류'; implementation end.
unit adot.Tools.IO; interface { TCustomStreamExt = class Extensions of TStream. TDelegatedMemoryStream = class Readonly stream for specified memory block. TArrayStream<T: record> = class Makes any array of ordinal type to be accessable as stream of bytes. TStreamUtils = class Block reader and other utils. TPIReader = class Platform independent stream reader. TPIWriter = class Platform independent stream writer. TReader = record Stream block reader (ReadNext to get next block of data from stream as array of byte) TFileUtils = class File manipulation utils. TBuffer = record Simple and fast managed analog of TMemoryStream. } uses adot.Types, adot.Collections, adot.Collections.Sets, {$If Defined(MSWindows)} { Option "$HINTS OFF" doesn't hide following hint (Delphi 10.2.1), we add Windows here to suppress it: H2443 Inline function 'RenameFile' has not been expanded because unit 'Winapi.Windows' is not specified in USES list } Winapi.Windows, {$EndIf} {$If Defined(POSIX)} Posix.Unistd, Posix.Stdio, {$EndIf} System.StrUtils, System.IniFiles, System.SysConst, System.Classes, System.SysUtils, System.Math, System.DateUtils, System.Generics.Collections, System.Generics.Defaults, System.Types, System.IOUtils; type { Extensions of TStream } TCustomStreamExt = class(TStream) public procedure Clear; procedure SaveToStream(Stream: TStream); procedure SaveToFile(const FileName: string); procedure LoadFromStream(Stream: TStream); procedure LoadFromFile(const FileName: string); end; { Readonly stream for specified memory block } TDelegatedMemoryStream = class(TCustomMemoryStream) public constructor Create(Buf: pointer; Size: integer); overload; procedure SetMemory(Buf: pointer; Size: integer); procedure SetSize(const NewSize: Int64); override; procedure SetSize(NewSize: Longint); override; function Write(const Buffer; Count: Longint): Longint; override; function Write(const Buffer: TBytes; Offset, Count: Longint): Longint; override; end; { Makes any array of ordinal type to be accessable as stream of bytes } TArrayStream<T: record> = class(TCustomStreamExt) protected FItems: TArray<T>; FPos: integer; FSize: integer; FCapacity: integer; procedure SetItems(const Value: TArray<T>); procedure SetCapacity(NewByteCapacity: integer); public constructor Create(const AItems: TArray<T>); overload; function Read(var Buffer; Count: Longint): Longint; override; function Read(Buffer: TBytes; Offset, Count: Longint): Longint; override; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; procedure SetSize(const NewSize: Int64); override; procedure SetSize(NewSize: Longint); override; function Write(const Buffer; Count: Longint): Longint; override; function Write(const Buffer: TBytes; Offset, Count: Longint): Longint; override; property Items: TArray<T> read FItems write SetItems; end; { Basic class for readonly streams. All Write/Seek methods will generate exception.} TCustomReadOnlyStream = class(TStream) protected function GetSize: Int64; override; procedure SetSize(NewSize: Longint); override; procedure SetSize(const NewSize: Int64); override; public function Write(const Buffer; Count: Longint): Longint; override; function Write(const Buffer: TBytes; Offset, Count: Longint): Longint; override; function Seek(Offset: Longint; Origin: Word): Longint; override; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; { methods to be implemented in descendants } //function Read(var Buffer; Count: Longint): Longint; override; //function Read(Buffer: TBytes; Offset, Count: Longint): Longint; override; end; { Block reader and other utils } TStreamUtils = class public class procedure StringToStream(const S: string; Dst: TStream; Encoding: TEncoding = nil); static; { Copy stream functions (from simple to feature-rich): 1. TStreamUtils.Copy: uses standard Delphi streams, UI will freeze until operation is complete. 2. TVCLStreamUtils.Copy: uses standard Delphi streams, UI will not freeze. } class function Copy(Src,Dst: TStream; Count,BufSize: integer; ProgressProc: TCopyStreamProgressProc): int64; overload; static; class function Copy(Src,Dst: TStream; ProgressProc: TCopyStreamProgressProc): int64; overload; static; class function Copy(Src,Dst: TStream): int64; overload; static; end; { Delphi 10 Seattle doesn't have 100% platform independent reader/writer (inherited from TFiler or any other). But TWriter class has set of platform independent functions WriteVar. We write wrapper around TWriter in order to expose only platform independent functionality (and extend it for other basic types). } { Platform independent stream writer } TPIWriter = class protected Writer: TWriter; public constructor Create(ADst: TStream); destructor Destroy; override; { mapped to TWriter } procedure Write(const Value: Char); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: Int8); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: UInt8); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: Int16); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: UInt16); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: Int32); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: UInt32); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: Int64); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: UInt64); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: Single); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: Double); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: Extended); overload; {$IFDEF UseInline}inline;{$ENDIF} { extentions } procedure Write(const Buf; Count: integer); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: TBytes); overload; procedure Write(const Value: string); overload; end; { Platform independent stream reader } TPIReader = class protected Reader: TReader; public constructor Create(ASrc: TStream); destructor Destroy; override; { mapped to TReader } procedure Read(out Value: Char); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: Int8); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: UInt8); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: Int16); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: UInt16); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: Int32); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: UInt32); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: Int64); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: UInt64); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: Single); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: Double); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: Extended); overload; {$IFDEF UseInline}inline;{$ENDIF} { extentions } procedure Read(var Buf; Count: integer); overload; procedure Read(out Value: TBytes); overload; procedure Read(out Value: string); overload; end; TDelegatedOnFile = reference to procedure(const APath: string; const AFile: TSearchRec; var ABreak: Boolean); { File manipulation utils } TFileUtils = class public { remove incorrect chars } class function RemoveInvalidChars(const AFileName: string): string; static; class function FileModeToString(AMode: Integer): string; static; class function AccessAllowed(const AFileName: string; ADesiredAccess: word = fmOpenReadWrite or fmShareExclusive): boolean; static; class function GetOpenFiles(const AMasks,Exceptions: array of string; Recursive: boolean): TArray<string>; overload; static; class function GetOpenFiles(const AMasks,Exceptions: array of string; Recursive: boolean; Delim: string): string; overload; static; class function GetSize(const AFileName: string): int64; static; { enumerate files with callback function and posibility to break/stop } class procedure EnumFiles(const AFileNamePattern: string; AOnfile: TDelegatedOnFile); static; { simple API to clean up old files and keep used space in some ranges (log files, temp files etc) } class procedure CleanUpOldFiles( const AFileNamePattern : string; const AMaxAllowedTotalSize, AMaxAllowedCount : int64; AChanceToRun : Double = 1 { 1 = 100%, 0.3=30% etc }); static; class function DeleteFile(const AFileName: string; out AErrorMessage: string): boolean; static; class function RenameFile(const ASrcFileName,ADstFileName: string; out AErrorMessage: string): boolean; static; { Copy file functions (from simple to feature-rich): 1. TFileUtils.CopyFile: uses standard Delphi streams, UI will freeze until operation is complete. 2. TWinFileUtils.CopyFile: uses Windows function CopyFileEx, UI will freeze until operation is complete. 3. TVCLFileUtils.Copyfile: uses standard Delphi streams, UI will not freeze. 4. TCopyFileProgressDlg.CopyFile: uses either Delphi streams or CopyFileEx, UI will not freeze, progress bar with cancel command will be available for long operations). } class function CopyFile(const SrcFileName,DstFileName: string; out ErrorMessage: string; ProgressProc: TCopyFileProgressProc): boolean; overload; class function CopyFile(const SrcFileName,DstFileName: string; out ErrorMessage: string): boolean; overload; class procedure Load<T: record>(const FileName: string; var Dst: TArray<T>); overload; class procedure Save<T: record>(const FileName: string; const Src: TArray<T>; Index,Count: integer); overload; class procedure Save<T: record>(const FileName: string; const Src: TArray<T>); overload; { Encode disabled chars (hex), check disabled names ("COM1", "PRN", "NUL" etc). } class function StringToFilename(const AStr: string): string; static; { When we check all/lot of files for existance in some folder, it is faster to list files than call FileExists. It is especially true for network drives. Example of timings for network folder with many files: FileExists for every file : 31.65 sec Enumerate all files : 4.19 sec } { Preload list of files into cache } class procedure ExistsBuildCache(const CacheFolder: string; var Cache: TSet<string>; Recursive: boolean = True); static; { Will use preloaded Cache when possible and FileExists function otherwise } class function Exists(const FullFileName,CacheFolder: string; var Cache: TSet<string>): boolean; static; { returns True if it is time to perform } class function Debounce( const FolderOrEmpty : string; { if empty, then AppData folder will be used } const SubfolderOrEmpty : string; { could be "CompanyName\ProductName" for example } const FileNameSuffixOrEmpty : string; { To be used as part of filename for params (exe name will be used if empty) } const MinIntervalHours : double; { min/desired interval between actions } const InfoHash : TArray<Byte> { If InfoHash is changed, then action must be performed } ): boolean; overload; static; { returns True is actions should be performed now } class function Debounce(const MinIntervalHours: double): boolean; overload; static; end; { Lightweight and managed analog of TBytesStream. Has mixed set of methods - byte and string-compatible } TBuffer = record private FData: TArray<Byte>; FSize: integer; FPosition: integer; procedure SetSize(Value: integer); function GetCapacity: integer; {$IFDEF UseInline}inline;{$ENDIF} procedure SetCapacity(Value: integer); {$IFDEF UseInline}inline;{$ENDIF} procedure CheckCapacity(MinCapacity: integer); {$IFDEF UseInline}inline;{$ENDIF} function GetLeft: integer; {$IFDEF UseInline}inline;{$ENDIF} procedure SetLeft(Value: integer); {$IFDEF UseInline}inline;{$ENDIF} function GetCurrentData: pointer; {$IFDEF UseInline}inline;{$ENDIF} function GetEOF: boolean; {$IFDEF UseInline}inline;{$ENDIF} function GetText: string; procedure SetText(const Value: string); function GetEmpty: Boolean; {$IFDEF UseInline}inline;{$ENDIF} procedure SetData(AData: TArray<Byte>); public procedure Init; { writes bytes from Src to current position. } procedure Write(const Src; ByteCount: integer); overload; { writes characters from Src to the buffer (usually 1 char = 2 bytes). } procedure Write(const Src: string; CharOffset,CharCount: integer); overload; { writes all characters from Src to the buffer (usually 1 char = 2 bytes). } procedure Write(const Src: string); overload; { Reads bytes from the buffer to Dst. } procedure Read(var Dst; ByteCount: integer); overload; { Reads characters from the buffer to specific position of Dst (usually 1 char = 2 bytes). } procedure Read(var Dst: string; DstCharOffset,CharCount: integer); overload; { Reads characters from the buffer to Dst (usually 1 char = 2 bytes). } procedure Read(var Dst: string; CharCount: integer); overload; { Removes part of data from the buffer. } procedure Cut(Start,Len: integer); { Returns range of the buffer as array of bytes. } function Slice(Start,Len: integer): TArray<byte>; { Makes sure that Capacity is equal to Size. After that Data field can be used directly. } procedure TrimExcess; procedure Clear; procedure LoadFromFile(const FileName: string); procedure SaveToFile(const FileName: string); property Size: integer read FSize write SetSize; property Capacity: integer read GetCapacity write SetCapacity; property Position: integer read FPosition write FPosition; property Left: integer read GetLeft write SetLeft; property CurrentData: pointer read GetCurrentData; property EOF: boolean read GetEOF; property Empty: boolean read GetEmpty; property Text: string read GetText write SetText; property Data: TArray<Byte> read FData write SetData; end; implementation uses adot.Tools; { TCustomStreamExt } procedure TCustomStreamExt.Clear; begin Size := 0; end; procedure TCustomStreamExt.LoadFromFile(const FileName: string); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try LoadFromStream(Stream); finally Stream.Free; end; end; procedure TCustomStreamExt.SaveToFile(const FileName: string); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmCreate); try SaveToStream(Stream); finally Stream.Free; end; end; procedure TCustomStreamExt.LoadFromStream(Stream: TStream); var P: Int64; begin Size := Stream.Size; P := Stream.Position; try Stream.Position := 0; CopyFrom(Stream, Stream.Size); finally Stream.Position := P; end; end; procedure TCustomStreamExt.SaveToStream(Stream: TStream); var P: Int64; begin P := Position; try Position := 0; Stream.CopyFrom(Self, Size); finally Position := P; end; end; { TDelegatedMemoryStream } constructor TDelegatedMemoryStream.Create(Buf: pointer; Size: integer); begin inherited Create; SetPointer(Buf, Size); end; procedure TDelegatedMemoryStream.SetMemory(Buf: pointer; Size: integer); begin SetPointer(Buf, Size); Position := 0; end; procedure TDelegatedMemoryStream.SetSize(NewSize: Longint); begin raise Exception.Create('Error'); end; procedure TDelegatedMemoryStream.SetSize(const NewSize: Int64); begin raise Exception.Create('Error'); end; function TDelegatedMemoryStream.Write(const Buffer; Count: Longint): Longint; begin raise Exception.Create('Error'); end; function TDelegatedMemoryStream.Write(const Buffer: TBytes; Offset, Count: Longint): Longint; begin raise Exception.Create('Error'); end; { TArrayStream<T> } constructor TArrayStream<T>.Create(const AItems: TArray<T>); begin inherited Create; Items := AItems; end; procedure TArrayStream<T>.SetItems(const Value: TArray<T>); begin FItems := Value; FPos := 0; FCapacity := Length(FItems)*SizeOf(T); FSize := FCapacity; end; procedure TArrayStream<T>.SetCapacity(NewByteCapacity: integer); begin if NewByteCapacity mod SizeOf(T)<>0 then raise Exception.Create('Error'); SetLength(FItems, NewByteCapacity div SizeOf(T)); FCapacity := NewByteCapacity; if FSize>FCapacity then FSize := FCapacity; if FPos>FCapacity then FPos := FCapacity; end; function TArrayStream<T>.Read(var Buffer; Count: Longint): Longint; begin if (FPos >= 0) and (Count >= 0) then begin Result := FSize - FPos; if Result > 0 then begin if Result > Count then Result := Count; Move((PByte(FItems) + FPos)^, Buffer, Result); Inc(FPos, Result); Exit; end; end; Result := 0; end; function TArrayStream<T>.Read(Buffer: TBytes; Offset, Count: Longint): Longint; begin Result := Read(Buffer[Offset], Count); end; procedure TArrayStream<T>.SetSize(const NewSize: Int64); var OldPosition: Longint; begin OldPosition := FPos; SetCapacity(NewSize); { Will check that NewSize mod SizeOf(T)=0 } FSize := NewSize; if OldPosition > NewSize then Seek(0, soEnd); end; procedure TArrayStream<T>.SetSize(NewSize: Longint); begin SetSize(Int64(NewSize)); end; function TArrayStream<T>.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; begin case Origin of soBeginning : FPos := Offset; soCurrent : Inc(FPos, Offset); soEnd : FPos := FSize + Offset; end; if FPos<0 then FPos := 0; Result := FPos; end; function TArrayStream<T>.Write(const Buffer; Count: Longint): Longint; var P: integer; begin if (FPos >= 0) and (Count >= 0) then begin P := FPos + Count; if P > 0 then begin if P > FSize then begin if P > FCapacity then SetCapacity(P); FSize := P; end; System.Move(Buffer, (PByte(FItems) + FPos)^, Count); FPos := P; Result := Count; Exit; end; end; Result := 0; end; function TArrayStream<T>.Write(const Buffer: TBytes; Offset, Count: Longint): Longint; begin Result := Write(Buffer[Offset], Count); end; { TCustomReadOnlyStream } function TCustomReadOnlyStream.GetSize: Int64; begin raise EAbstractError.CreateRes(@SAbstractError); end; function TCustomReadOnlyStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; begin raise EAbstractError.CreateRes(@SAbstractError); end; function TCustomReadOnlyStream.Seek(Offset: Longint; Origin: Word): Longint; begin raise EAbstractError.CreateRes(@SAbstractError); end; procedure TCustomReadOnlyStream.SetSize(const NewSize: Int64); begin raise EAbstractError.CreateRes(@SAbstractError); end; procedure TCustomReadOnlyStream.SetSize(NewSize: Longint); begin raise EAbstractError.CreateRes(@SAbstractError); end; function TCustomReadOnlyStream.Write(const Buffer; Count: Longint): Longint; begin raise EAbstractError.CreateRes(@SAbstractError); end; function TCustomReadOnlyStream.Write(const Buffer: TBytes; Offset, Count: Longint): Longint; begin raise EAbstractError.CreateRes(@SAbstractError); end; { TStreamUtils } class function TStreamUtils.Copy(Src, Dst: TStream; Count,BufSize: integer; ProgressProc: TCopyStreamProgressProc): int64; var N: Integer; Buffer: TBytes; LastOnProgressTime: TDateTime; Cancel: Boolean; begin { check TVCLStreamUtils.Copy if you don't want UI to freeze until operation is complete } { based on TStream.CopyFrom, but provides time-based callback ProgressProc } Result := 0; LastOnProgressTime := 0; if Count <= 0 then begin Src.Position := 0; Count := Src.Size; end; if BufSize=0 then BufSize := 65536 else BufSize := Max(BufSize, 4096); SetLength(Buffer, BufSize); Cancel := False; if Assigned(ProgressProc) then begin ProgressProc(0, Cancel); LastOnProgressTime := Now; end; while (Count <> 0) and not Cancel do begin N := Min(Count, BufSize); Src.ReadBuffer(Buffer, N); Dst.WriteBuffer(Buffer, N); Dec(Count, N); Inc(Result, N); if Assigned(ProgressProc) and (MilliSecondsBetween(Now, LastOnProgressTime)>=50) then begin ProgressProc(Result, Cancel); LastOnProgressTime := Now; end; end; if Assigned(ProgressProc) then ProgressProc(Result, Cancel); end; class function TStreamUtils.Copy(Src, Dst: TStream; ProgressProc: TCopyStreamProgressProc): int64; begin { check TVCLStreamUtils.Copy if you don't want UI to freeze until operation is complete } result := Copy(Src, Dst, 0,0,ProgressProc); end; class function TStreamUtils.Copy(Src, Dst: TStream): int64; begin { check TVCLStreamUtils.Copy if you don't want UI to freeze until operation is complete } result := Copy(Src, Dst, 0,0,nil); end; class procedure TStreamUtils.StringToStream(const S: string; Dst: TStream; Encoding: TEncoding); var B: TArray<Byte>; begin if Encoding=nil then Encoding := TEncoding.UTF8; B := Encoding.GetBytes(S); if Length(B) > 0 then Dst.WriteBuffer(B[0], Length(B)); end; { TPIWriter } constructor TPIWriter.Create(ADst: TStream); begin inherited Create; Writer := TWriter.Create(ADst, 4096); end; destructor TPIWriter.Destroy; begin Sys.FreeAndNil(Writer); inherited; end; procedure TPIWriter.Write(const Value: Int16); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: UInt16); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: Int32); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: Char); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: Int8); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: UInt8); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: Extended); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: Double); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: Int64); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: UInt32); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: Single); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: UInt64); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Buf; Count: integer); begin Writer.Write(Buf, Count); end; procedure TPIWriter.Write(const Value: TBytes); var i: Integer; begin i := Length(Value); Write(i); if i>0 then Write(Value[0], i); end; procedure TPIWriter.Write(const Value: string); begin Write(TEncoding.UTF8.GetBytes(Value)); end; { TPIReader } constructor TPIReader.Create(ASrc: TStream); begin inherited Create; Reader := TReader.Create(ASrc, 4096); end; destructor TPIReader.Destroy; begin Sys.FreeAndNil(Reader); inherited; end; procedure TPIReader.Read(out Value: Int16); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: UInt16); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: Int32); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: Char); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: Int8); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: UInt8); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: Single); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: Double); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: Extended); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: UInt32); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: Int64); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: UInt64); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(var Buf; Count: integer); begin Reader.Read(Buf, Count); end; procedure TPIReader.Read(out Value: TBytes); var i: integer; begin Read(i); SetLength(Value, i); if i>0 then Read(Value[0], i); end; procedure TPIReader.Read(out Value: string); var Bytes: TBytes; begin Read(Bytes); Value := TEncoding.UTF8.GetString(Bytes); end; { TFileUtils } class procedure TFileUtils.CleanUpOldFiles(const AFileNamePattern: string; const AMaxAllowedTotalSize, AMaxAllowedCount: int64; AChanceToRun: Double); type TFileInfo = record Name: string; Size: int64; Age: TDateTime; end; var List: TList<TFileInfo>; Comparer: IComparer<TFileInfo>; TotalSize: Int64; TotalCount: Integer; FilePath: string; i: Integer; begin if (Random>AChanceToRun) or (AMaxAllowedTotalSize<0) and (AMaxAllowedCount<0) then Exit; List := TList<TFileInfo>.Create; try FilePath := ExtractFilePath(AFileNamePattern); EnumFiles(AFileNamePattern, procedure(const APath: string; const AFile: TSearchRec; var ABreak: Boolean) var R: TFileInfo; begin R.Name := AFile.Name; R.Size := AFile.Size; R.Age := AFile.TimeStamp; List.Add(R); end); Comparer := TDelegatedComparer<TFileInfo>.Create( function(const A,B: TFileInfo): Integer begin result := Sign(A.Age-B.Age); end); List.Sort(Comparer); TotalCount := List.Count; TotalSize := 0; for i := 0 to List.Count-1 do inc(TotalSize, List[i].Size); for i := 0 to List.Count-1 do if not ( (AMaxAllowedTotalSize>=0) and (TotalSize>AMaxAllowedTotalSize) or (AMaxAllowedCount>=0) and (TotalCount>AMaxAllowedCount) ) then Break else if System.SysUtils.DeleteFile(FilePath+List[i].Name) then begin Dec(TotalSize, List[i].Size); Dec(TotalCount); end; finally Sys.FreeAndNil(List); end; end; class function TFileUtils.CopyFile(const SrcFileName, DstFileName: string; out ErrorMessage: string; ProgressProc: TCopyFileProgressProc): boolean; var AutoFreeCollection: TAutoFreeCollection; CI: TCopyFileInfo; Src,Dst: TStream; begin { check TVCLFileUtils.CopyFile if you don''t want UI to freeze until operation is complete } try Result := True; Src := AutoFreeCollection.Add(TFileStream.Create(SrcFileName, fmOpenRead or fmShareDenyWrite)); Dst := AutoFreeCollection.Add(TFileStream.Create(DstFileName, fmCreate)); if not Assigned(ProgressProc) then TStreamUtils.Copy(Src, Dst) else begin CI.FileSize := Src.Size; CI.SrcFileName := SrcFileName; CI.DstFileName := DstFileName; TStreamUtils.Copy(Src, Dst, procedure(const Transferred: int64; var Cancel: boolean) begin CI.Copied := Transferred; ProgressProc(CI, Cancel); end); end; except on e: exception do begin Result := True; ErrorMessage := Format('Can''t copy file "%s" to "%s": %s', [SrcFileName, DstFileName, SysErrorMessage(GetLastError)]); end; end; end; class function TFileUtils.CopyFile(const SrcFileName, DstFileName: string; out ErrorMessage: string): boolean; begin { check TVCLFileUtils.CopyFile if you don''t want UI to freeze until operation is complete } result := CopyFile(SrcFileName, DstFileName, ErrorMessage, nil); end; class function TFileUtils.Debounce( const FolderOrEmpty : string; const SubfolderOrEmpty : string; const FileNameSuffixOrEmpty : string; const MinIntervalHours : double; const InfoHash : TArray<Byte> ): boolean; const cSec = 'Debouncing'; cTime = 'LastActionTime'; cHash = 'InfoHash'; var FS: TFormatSettings; Ini: TIniFile; Filename,LastHash,NewHash: string; CurTime, LastActionTime: TDateTime; begin FS := TDateTimeUtils.StdEuFormatSettings; if FolderOrEmpty = '' then Filename := TPath.GetPublicPath else Filename := FolderOrEmpty; Filename := IncludeTrailingPathDelimiter(IncludeTrailingPathDelimiter(Filename) + SubfolderOrEmpty); ForceDirectories(Filename); Filename := Filename + 'Debouncing.' + IfThen(FileNameSuffixOrEmpty<>'', FileNameSuffixOrEmpty, ChangeFileExt(ExtractFileName(ParamStr(0)),'')) + '.ini'; Ini := TIniFile.Create(Filename); try CurTime := Now; NewHash := THex.Encode(InfoHash); if not FileExists(Filename) then Result := True else begin LastActionTime := TDateTimeUtils.FromStringStd( Ini.ReadString(cSec, cTime, ''), 0); LastHash := Ini.ReadString(cSec, cHash, ''); Result := (MinutesBetween(CurTime, LastActionTime) >= MinIntervalHours*60) or (NewHash <> LastHash) end; if Result then begin Ini.WriteString(cSec, cTime, TDateTimeUtils.ToStringStd(CurTime)); Ini.WriteString(cSec, cHash, NewHash); end; finally Sys.FreeAndNil(Ini); end; end; class function TFileUtils.Debounce(const MinIntervalHours: double): boolean; var H: TArray<Byte>; begin SetLength(H, 0); result := Debounce('', '', '', MinIntervalHours, H); end; class function TFileUtils.DeleteFile(const AFileName: string; out AErrorMessage: string): boolean; begin result := System.SysUtils.DeleteFile(AFileName); if not result then AErrorMessage := Format('Can''t delete file "%s" (%s)', [AFileName, SysErrorMessage(GetLastError)]); end; class function TFileUtils.RenameFile(const ASrcFileName, ADstFileName: string; out AErrorMessage: string): boolean; begin result := System.SysUtils.RenameFile(ASrcFileName, ADstFileName); if not result then AErrorMessage := Format('Can''t rename file "%s" to "%s" (%s)', [ASrcFileName, ADstFileName, SysErrorMessage(GetLastError)]); end; class procedure TFileUtils.EnumFiles(const AFileNamePattern: string; AOnfile: TDelegatedOnFile); var F: System.SysUtils.TSearchRec; B: Boolean; P: string; begin if System.SysUtils.FindFirst(AFileNamePattern, faAnyfile, F)=0 then try P := ExtractFilePath(AFileNamePattern); B := False; repeat if (F.Attr and faDirectory<>0) then Continue; AOnFile(P, F, B); until B or (System.SysUtils.FindNext(F)<>0); finally System.SysUtils.FindClose(F); end; end; class function TFileUtils.FileModeToString(AMode: Integer): string; const OpenMode : array[0..3] of string = ('fmOpenRead', 'fmOpenWrite', 'fmOpenReadWrite', 'unknown_open_mode'); begin {$WARN SYMBOL_PLATFORM OFF} result := '{' + OpenMode[AMode and 3]; if AMode and fmShareExclusive = fmShareExclusive then result := result + ', fmShareExclusive'; if AMode and fmShareDenyWrite = fmShareDenyWrite then result := result + ', fmShareDenyWrite'; {$IFDEF MSWINDOWS} if AMode and fmShareDenyRead = fmShareDenyRead then result := result + ', fmShareDenyRead'; {$EndIf} if AMode and fmShareDenyNone = fmShareDenyNone then result := result + ', fmShareDenyNone'; result := result + '}'; {$WARN SYMBOL_PLATFORM ON} end; class function TFileUtils.AccessAllowed(const AFileName: string; ADesiredAccess: word): boolean; var F: TFileStream; begin try F := TFileStream.Create(AFileName, ADesiredAccess); F.Free; result := True; except result := False; end; end; class procedure TFileUtils.Load<T>(const FileName: string; var Dst: TArray<T>); var Stream: TFileStream; begin Stream := TFileStream.Create(FileName, fmOpenRead); try SetLength(Dst, Stream.Size div SizeOf(T)); if Length(Dst)>0 then Stream.ReadBuffer(Dst[0], Length(Dst)*SizeOf(T)); finally Stream.Free; end; end; class procedure TFileUtils.Save<T>(const FileName: string; const Src: TArray<T>; Index,Count: integer); var Stream: TFileStream; begin Stream := TFileStream.Create(FileName, fmCreate); try Stream.WriteBuffer(Src[Index], Count*SizeOf(T)); finally Stream.Free; end; end; class procedure TFileUtils.Save<T>(const FileName: string; const Src: TArray<T>); begin Save<T>(FileName, Src, 0, Length(Src)); end; class function TFileUtils.StringToFilename(const AStr: string): string; const DisabledNames: array[0..21] of string = ( 'CON', 'PRN', 'AUX', 'NUL', 'COM1','COM2','COM3','COM4','COM5','COM6','COM7','COM8','COM9', 'LPT1','LPT2','LPT3','LPT4','LPT5','LPT6','LPT7','LPT8','LPT9' ); DisabledChars = [0..31, Byte('<'), Byte('>'), Byte(':'), Byte('"'), Byte('/'), Byte('\'), Byte('|'), Byte('?'), Byte('*')]; var i: Integer; c: Char; Path,Name: string; begin { Trailing spaces. Windows allows filenames with spaces: " 1.txt", " 1 .txt", " 1 . txt" and even " .txt" but does not allow "1.txt ", so only trailing spaces are not allowed http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx "Do not end a file or directory name with a space or a period." } Path := ExtractFilePath(AStr); Name := TrimRight(ExtractFileName(AStr)); { Disabled chars: http://stackoverflow.com/questions/960772/how-can-i-sanitize-a-string-for-use-as-a-filename } result := ''; for i := Low(Name) to High(Name) do begin c := Name[i]; if (c<#127) and (Byte(c) in DisabledChars) then result := result + '%' + THex.Encode(c, SizeOf(c)) else result := result + c; end; { Disabled names } for i := Low(DisabledNames) to High(DisabledNames) do if AnsiSameText(result, DisabledNames[i]) then begin result := result + '_'; Break; end; result := Path + Name; end; procedure FindOpenFiles( const AFilesMask : string; AExceptions : TSet<string>; ARecursive : boolean; ADst : TList<string>); var Files,Subdirs: TStringDynArray; Dir,FileName,Subdir: string; begin try Dir := ExtractFilePath(AFilesMask); if not TDirectory.Exists(Dir) then Exit; Files := TDirectory.GetFiles(Dir, ExtractFileName(AFilesMask)); for FileName in Files do if not (FileName in AExceptions) and not TFileUtils.AccessAllowed(FileName) then ADst.Add(FileName); if ARecursive then begin Subdirs := TDirectory.GetDirectories(Dir); for Subdir in Subdirs do FindOpenFiles(Subdir + '\' + ExtractFileName(AFilesMask), AExceptions, True, ADst); end; except end; end; class function TFileUtils.GetOpenFiles(const AMasks,Exceptions: array of string; Recursive: boolean): TArray<string>; var FilesMask: string; Exc: TSet<string>; FoundFiles: TList<string>; begin FoundFiles := TList<string>.Create; try Exc.Add(Exceptions); for FilesMask in AMasks do FindOpenFiles(FilesMask, Exc, Recursive, FoundFiles); result := FoundFiles.ToArray; finally Sys.FreeAndNil(FoundFiles); end; end; class function TFileUtils.GetOpenFiles(const AMasks, Exceptions: array of string; Recursive: boolean; Delim: string): string; var FoundFiles: TArray<string>; i: Integer; begin FoundFiles := GetOpenFiles(AMasks, Exceptions, Recursive); if Length(FoundFiles)=0 then result := '' else result := FoundFiles[0]; for i := 1 to High(FoundFiles) do result := result + Delim + FoundFiles[i]; end; class function TFileUtils.GetSize(const AFileName: string): int64; var F: TSearchRec; begin if FindFirst(AFileName, faAnyfile, F)<>0 then result := 0 else begin result := F.Size; FindClose(F); end; end; class function TFileUtils.RemoveInvalidChars(const AFileName: string): string; var I: Integer; vPath, vFile: string; begin Result := ''; vPath := ExtractFilePath(AFileName); vFile := ExtractFileName(AFileName); for I := Low(vPath) to High(vPath) do if TPath.IsValidPathChar(vPath[I]) then Result := Result + vPath[I]; Result := IncludeTrailingPathDelimiter(Result); for I := Low(vFile) to High(vFile) do if TPath.IsValidFileNameChar(vFile[I]) then Result := Result + vFile[I]; end; class procedure TFileUtils.ExistsBuildCache(const CacheFolder: string; var Cache: TSet<string>; Recursive: boolean = True); var SearchOption: TSearchOption; begin Cache.Clear; if Recursive then SearchOption := TSearchOption.soAllDirectories else SearchOption := TSearchOption.soTopDirectoryOnly; if TDirectory.Exists(CacheFolder) then Cache.Add(TDirectory.GetFiles(IncludeTrailingPathDelimiter(TrimRight(CacheFolder)), '*.*', SearchOption)); end; class function TFileUtils.Exists(const FullFileName,CacheFolder: string; var Cache: TSet<string>): boolean; begin if not AnsiLowerCase(FullFileName).StartsWith(AnsiLowerCase(IncludeTrailingPathDelimiter(TrimRight(CacheFolder)))) then result := FileExists(FullFileName) else begin { We check files when they should exist, non existing file is very rare case. To make check robust/reliable we use two different aproaches in different time: - We check file in preloaded list of files. It is very fast, if file is here, then check is done. - If file is not in the list, then we check with FixeExists function. We report non existing file after double check only. } result := FullFileName in Cache; if not result then result := FileExists(FullFileName); end; end; { TBuffer } procedure TBuffer.Clear; begin Size := 0; Capacity := Size; end; function TBuffer.GetCapacity: integer; begin result := Length(FData); end; function TBuffer.GetCurrentData: pointer; begin result := @FData[Position]; end; function TBuffer.GetEmpty: Boolean; begin result := Size=0; end; function TBuffer.GetEOF: boolean; begin result := Position >= Size; end; function TBuffer.GetLeft: integer; begin result := Size-Position; end; procedure TBuffer.SetText(const Value: string); begin Clear; Write(Value); Position := 0; end; function TBuffer.GetText: string; var P: Integer; begin P := Position; Position := 0; Read(Result, Size div SizeOf(Char)); Position := P; end; procedure TBuffer.Init; begin Self := Default(TBuffer); end; procedure TBuffer.LoadFromFile(const FileName: string); begin TFileUtils.Load<Byte>(FileName, FData); FSize := Length(FData); FPosition := 0; end; procedure TBuffer.SaveToFile(const FileName: string); begin TFileUtils.Save<Byte>(FileName, FData, 0,Size); end; procedure TBuffer.SetLeft(Value: integer); begin Size := Position + Value; end; procedure TBuffer.SetCapacity(Value: integer); begin Assert(Value >= Size); SetLength(FData, Value); end; procedure TBuffer.CheckCapacity(MinCapacity: integer); begin if Capacity < MinCapacity then Capacity := Sys.Max(MinCapacity, Capacity shl 1, 16); end; procedure TBuffer.SetSize(Value: integer); begin CheckCapacity(Value); FSize := Value; FPosition := Max(Min(FPosition, FSize), 0); end; procedure TBuffer.TrimExcess; begin Capacity := Size; end; procedure TBuffer.Read(var Dst; ByteCount: integer); begin Assert(Position + ByteCount <= Size); System.Move(FData[Position], Dst, ByteCount); inc(FPosition, ByteCount); end; procedure TBuffer.Read(var Dst: string; DstCharOffset, CharCount: integer); begin Read(Dst[DstCharOffset+Low(Dst)], CharCount*SizeOf(Char)); end; procedure TBuffer.Read(var Dst: string; CharCount: integer); begin SetLength(Dst, CharCount); Read(Dst[Low(Dst)], CharCount*SizeOf(Char)); end; procedure TBuffer.Write(const Src; ByteCount: integer); begin CheckCapacity(Position + ByteCount); System.Move(Src, FData[Position], ByteCount); inc(FPosition, ByteCount); if FPosition > FSize then FSize := FPosition; end; procedure TBuffer.Write(const Src: string; CharOffset,CharCount: integer); begin if CharCount<>0 then Write(Src[CharOffset+Low(Src)], CharCount*SizeOf(Char)); end; procedure TBuffer.Write(const Src: string); begin if Src<>'' then Write(Src[Low(Src)], Length(Src)*SizeOf(Char)); end; procedure TBuffer.Cut(Start, Len: integer); begin Len := TArrayUtils.Cut<byte>(FData, Size, Start, Len); dec(FSize, Len); if Position > Size then Position := Size; end; function TBuffer.Slice(Start, Len: integer): TArray<byte>; begin result := TArrayUtils.Slice<byte>(FData, Size, Start, Len); end; procedure TBuffer.SetData(AData: TArray<Byte>); begin FData := AData; FSize := Length(FData); FPosition := 0; end; end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit SvrLogColSettingsFrame; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, SvrLogFrame, Vcl.ComCtrls, SvrLog; type TLogColSettingsFrame = class(TFrame) lvColumns: TListView; procedure FrameResize(Sender: TObject); private FLogFrame: TLogFrame; procedure SetLogFrame(const Value: TLogFrame); public procedure UpdateColumns; property LogFrame: TLogFrame read FLogFrame write SetLogFrame; end; implementation {$R *.dfm} { TLogColumnsFrame } procedure TLogColSettingsFrame.SetLogFrame(const Value: TLogFrame); var Item: TListItem; I: Integer; LogColumn: TLogColumn; Positions: TLogColumnOrder; begin FLogFrame := Value; FLogFrame.SynchColumnInfo; FLogFrame.GetColumnOrder(Positions); for I := Low(Positions) to High(Positions) do begin Item := lvColumns.Items.Add; LogColumn := Positions[I]; Item.Caption := LogFrame.ColumnCaption[LogColumn]; Item.Checked := LogFrame.ColumnVisible[LogColumn]; Item.Data := Pointer(LogColumn); end; lvColumns.Columns[0].Width := lvColumns.ClientWidth; end; procedure TLogColSettingsFrame.FrameResize(Sender: TObject); begin // The following line causes AV's in some cases the Log tab is clicked. Code moved // into SetLogFrame. // lvColumns.Columns[0].Width := lvColumns.ClientWidth; end; procedure TLogColSettingsFrame.UpdateColumns; var I: Integer; Item: TListItem; begin for I := 0 to lvColumns.Items.Count - 1 do begin Item := lvColumns.Items[I]; LogFrame.ColumnVisible[TLogColumn(Item.Data)] := Item.Checked; end; LogFrame.RefreshColumns; LogFrame.RefreshSubItems; end; end.
unit port_RWStreams; interface uses SysUtils, Classes; type { TRWStream } TRWStream = class private FChar: Char; FHasChar: Boolean; FStream: TStream; function GetCurrentChar: Char; public constructor Create(Stream: TStream); destructor Destroy; override; function ReaderHasChar: Boolean; function ReaderNextChar: Char; procedure WriterWriteChar(C: Char); property CurrentChar: Char read GetCurrentChar; end; implementation { TRWStream } constructor TRWStream.Create(Stream: TStream); begin FStream := Stream; end; destructor TRWStream.Destroy; begin FStream.Free; inherited Destroy; end; function TRWStream.GetCurrentChar: Char; begin // exceção ativada se não houver caractere lido if not FHasChar then raise Exception.Create(''); // retorna o último caractere lido Result := FChar; end; function TRWStream.ReaderHasChar: Boolean; begin // presume que tem Result := True; // nada a fazer se já registrou que tem if FHasChar then Exit; // tenta ler if FStream.Read(FChar, 1) < 1 then Result := False; // registra FHasChar := Result; end; function TRWStream.ReaderNextChar: Char; begin // exceção ativada se não houver caractere lido if not FHasChar then raise Exception.Create(''); // retorna o último caractere lido e desmarca o flag Result := FChar; FHasChar := False; end; procedure TRWStream.WriterWriteChar(C: Char); begin FStream.Write(C, 1); end; end.
unit nii_mat; //basic Matrix and Vector Types and Transforms //{$D-,O+,Q-,R-,S-} // L-,Y-, {$H+} {$IFDEF FPC}{$mode delphi}{$ENDIF} interface uses dialogs; type TMatrix = record matrix: array [1..4, 1..4] of single; end; TVector = record vector: array [1..4] of single; end; function zero3D: TMatrix; function eye3D: TMatrix; //identity matrix procedure invertMatrix(VAR a: TMatrix); function invertMatrixF(VAR a: TMatrix): TMatrix; function matrix2D(a,b,c, d,e,f, g,h,i: single): TMatrix; function matrix3D(a,b,c,d, e,f,g,h, i,j,k,l: single): TMatrix; function multiplymatrices(a, b: TMatrix): TMatrix; function sameVec (a,b: TVector): boolean; function isIdentity (m: TMatrix): boolean; function transform3D(v: TVector; m: TMatrix): TVector; procedure transposeMatrix(var lMat: TMatrix); function vec3D (x, y, z: single): TVector; implementation function eye3D: TMatrix; //identity matrix begin result := Matrix3D(1,0,0,0, 0,1,0,0, 0,0,1,0); end; function zero3D: TMatrix; begin result := Matrix3D(0,0,0,0, 0,0,0,0, 0,0,0,0); end; function invertMatrixF(VAR a: TMatrix): TMatrix; //Translated by Chris Rorden, from C function "nifti_mat44_inverse" // Authors: Bob Cox, revised by Mark Jenkinson and Rick Reynolds // License: public domain // http://niftilib.sourceforge.net //Note : For higher performance we could assume the matrix is orthonormal and simply Transpose //Note : We could also compute Gauss-Jordan here var r11,r12,r13,r21,r22,r23,r31,r32,r33,v1,v2,v3 , deti : double; begin r11 := a.matrix[1,1]; r12 := a.matrix[1,2]; r13 := a.matrix[1,3]; //* [ r11 r12 r13 v1 ] */ r21 := a.matrix[2,1]; r22 := a.matrix[2,2]; r23 := a.matrix[2,3]; //* [ r21 r22 r23 v2 ] */ r31 := a.matrix[3,1]; r32 := a.matrix[3,2]; r33 := a.matrix[3,3]; //* [ r31 r32 r33 v3 ] */ v1 := a.matrix[1,4]; v2 := a.matrix[2,4]; v3 := a.matrix[3,4]; //* [ 0 0 0 1 ] */ deti := r11*r22*r33-r11*r32*r23-r21*r12*r33 +r21*r32*r13+r31*r12*r23-r31*r22*r13 ; if( deti <> 0.0 ) then deti := 1.0 / deti ; result.matrix[1,1] := deti*( r22*r33-r32*r23) ; result.matrix[1,2] := deti*(-r12*r33+r32*r13) ; result.matrix[1,3] := deti*( r12*r23-r22*r13) ; result.matrix[1,4] := deti*(-r12*r23*v3+r12*v2*r33+r22*r13*v3 -r22*v1*r33-r32*r13*v2+r32*v1*r23) ; result.matrix[2,1] := deti*(-r21*r33+r31*r23) ; result.matrix[2,2] := deti*( r11*r33-r31*r13) ; result.matrix[2,3] := deti*(-r11*r23+r21*r13) ; result.matrix[2,4] := deti*( r11*r23*v3-r11*v2*r33-r21*r13*v3 +r21*v1*r33+r31*r13*v2-r31*v1*r23) ; result.matrix[3,1] := deti*( r21*r32-r31*r22) ; result.matrix[3,2] := deti*(-r11*r32+r31*r12) ; result.matrix[3,3] := deti*( r11*r22-r21*r12) ; result.matrix[3,4] := deti*(-r11*r22*v3+r11*r32*v2+r21*r12*v3 -r21*r32*v1-r31*r12*v2+r31*r22*v1) ; result.matrix[4,1] := 0; result.matrix[4,2] := 0; result.matrix[4,3] := 0.0 ; if (deti = 0.0) then result.matrix[4,4] := 0 else result.matrix[4,4] := 1;// failure flag if deti == 0 end; procedure invertMatrix(VAR a: TMatrix); begin a := invertMatrixF(a); end; function matrix2D(a,b,c, d,e,f, g,h,i: single): TMatrix; begin result := matrix3D(a,b,c,0.0, d,e,f,0.0, g,h,i,0.0 ); end; //matrix2D() function matrix3D(a,b,c,d, e,f,g,h, i,j,k,l: single): TMatrix; begin result.matrix[1,1] := a; result.matrix[1,2] := b; result.matrix[1,3] := c; result.matrix[1,4] := d; result.matrix[2,1] := e; result.matrix[2,2] := f; result.matrix[2,3] := g; result.matrix[2,4] := h; result.matrix[3,1] := i; result.matrix[3,2] := j; result.matrix[3,3] := k; result.matrix[3,4] := l; result.matrix[4,1] := 0.0; result.matrix[4,2] := 0.0; result.matrix[4,3] := 0.0; result.matrix[4,4] := 1.0; end; //matrix3D() function multiplymatrices(a, b: TMatrix): TMatrix; var i,j: integer; begin result := Eye3D; for i := 1 to 4 do begin for j := 1 to 4 do begin result.matrix[i, j] := A.matrix[i, 1] * B.matrix[1,j] + A.matrix[i, 2] * B.matrix[2, j] + A.matrix[i, 3] * B.matrix[3, j] + A.matrix[i, 4] * B.matrix[4, j]; end; //for j end; //for i end; //multiplymatrices() function sameVec (a,b: TVector): boolean; begin result := ( (a.vector[1]=b.vector[1]) and (a.vector[2]=b.vector[2]) and (a.vector[3]=b.vector[3])); end; //sameVec() function isIdentity (m: TMatrix): boolean; begin result := ( (m.matrix[1,1]=1) and (m.matrix[1,2]=0) and (m.matrix[1,3]=0) and (m.matrix[1,4]=0) and (m.matrix[2,1]=0) and (m.matrix[2,2]=1) and (m.matrix[2,3]=0) and (m.matrix[2,4]=0) and (m.matrix[3,1]=0) and (m.matrix[3,2]=0) and (m.matrix[3,3]=1) and (m.matrix[3,4]=0) and (m.matrix[4,1]=0) and (m.matrix[4,2]=0) and (m.matrix[4,3]=0) and (m.matrix[4,4]=1)); end; //isIdentity() function transform3D(v: TVector; m: TMatrix): TVector; {$IFDEF FPC} inline; {$ENDIF} //vec4 nifti_vect44mat44_mul(vec4 v, mat44 m ) //multiply vector * 4x4matrix var i, j: integer; begin for i := 1 to 3 do begin//multiply Pcrs * m result.vector[i] := 0.0; for j := 1 to 4 do result.vector[i] := result.vector[i] + m.matrix[j,i]*v.vector[j]; end; result.vector[4] := 1.0; end; //transform() procedure transposeMatrix(var lMat: TMatrix); var lTemp: TMatrix; i,j: integer; begin lTemp := lMat; for i := 1 to 4 do for j := 1 to 4 do lMat.matrix[i,j] := lTemp.matrix[j,i]; end; //transposeMatrix() function vec3D (x, y, z: single): TVector; {$IFDEF FPC}inline;{$ENDIF} begin result.vector[1] := x; result.vector[2] := y; result.vector[3] := z; result.vector[4] := 1.0; end; //vector3D() end. //unit nii_mat
unit uInterfaces; interface type IConversao = Interface function Converter(Texto : String) : String; end; IFactoryMethod = interface function TipoConversao(const Tipo: string): IConversao; end; implementation end.
unit uDatos; interface uses SysUtils, Classes, DB, dbTables, dbisamtb, frxClass, frxDBSet, pngimage, Dialogs, JvBaseDlg, JvProgressDialog, Variants, frxDesgn, frxChart, frxDCtrl, frxDMPExport, frxGradient, frxChBox, frxCross, frxRich, frxBarcode, frxExportCSV, frxExportText, frxExportRTF, frxExportPDF, frxDBI4Components; type TdmDatos = class(TDataModule) dbReportes: TDBISAMDatabase; tbReportes: TDBISAMTable; tbCompanias: TDBISAMTable; tbReportesIdReporte: TAutoIncField; tbReportesIdCompania: TIntegerField; tbReportesReporte: TStringField; tbCompaniasIdCompania: TAutoIncField; tbCompaniasCompania: TStringField; tbCompaniasRuta: TStringField; Reporte: TfrxReport; frxDesigner1: TfrxDesigner; dsCompanias: TDataSource; dsReportes: TDataSource; qrReportes: TDBISAMQuery; qrReportesIdCompania: TAutoIncField; qrReportesIdReporte: TIntegerField; qrReportesReporte: TStringField; frxPDFExport1: TfrxPDFExport; frxRTFExport1: TfrxRTFExport; frxSimpleTextExport1: TfrxSimpleTextExport; frxCSVExport1: TfrxCSVExport; frxBarCodeObject1: TfrxBarCodeObject; frxRichObject1: TfrxRichObject; frxCrossObject1: TfrxCrossObject; frxCheckBoxObject1: TfrxCheckBoxObject; frxGradientObject1: TfrxGradientObject; frxDotMatrixExport1: TfrxDotMatrixExport; frxDialogControls1: TfrxDialogControls; frxChartObject1: TfrxChartObject; pProgreso: TJvProgressDialog; frxDBI4Components1: TfrxDBI4Components; fxComponentes: TfrxDBI4Components; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); procedure ReportePrintPage(Page: TfrxReportPage; CopyNo: Integer); private { Private declarations } public { Public declarations } FIdCompaniaActual: integer; procedure CrearTablas; procedure BorrarTablas; procedure ReportesCompania(AIdCompania: integer); end; const kDatos = 'Datos\'; kReportes = 'Reportes\'; var dmDatos: TdmDatos; gRutaReportes: String; implementation uses uBaseDatosA2, uTablasConBlobAdministrativo, uTablasConBlobNomina, uTablasConBlobContabilidad, uUtilidadesSPA; {$R *.dfm} procedure TdmDatos.BorrarTablas; var i: integer; begin // Busca las tablas de DBIsam que se crearon dinamicamente for i := ComponentCount - 1 downto 0 do begin if (Components[i].Tag = 10) or (Components[i].Tag = 100) then Components[i].Free(); end; end; procedure TdmDatos.CrearTablas; var T: TDBISAMTable; i: integer; F: TSearchRec; S: String; Ruta: String; P : TFloatField; procedure AdicionarDataSetAReporte( Tabla : TDBISAMTable); var frDS: TfrxDBDataset; AdicionarDS : Boolean; i : integer; begin AdicionarDS := True; // Busca los si la tabla no esta creada en el reporte for i := 0 to Reporte.DataSets.Count - 1 do begin frDS := Reporte.DataSets[i].DataSet as TfrxDBDataset; if frDS.Name = '_' + Tabla.Name then begin AdicionarDS := False; Exit; end; end; if AdicionarDS then begin frDS := TfrxDBDataset.Create(Self); frDS.Tag := 10; With frDS do begin DataSet := Tabla; Name := '_' + Tabla.Name; Visible := False; UserName := Tabla.Name; end; Tabla.Active := False; // Adiciona el dataset al reporte Reporte.DataSets.Add(frDS); end; end; // Adiciona la tabla procedure AdicionarTabla( db : TDBISAMDatabase; Nombre, NombreTabla : string); begin try T := TDBISAMTable.Create(self); T.Tag := 100; T.DatabaseName := db.DatabaseName; T.Name := Nombre; T.TableName := NombreTabla; fxComponentes.DefaultDatabase := db; // Crea el dataset para el reporte AdicionarDataSetAReporte( T); Except T.Free; end; end; begin if dbReportes.Connected then begin BorrarTablas; FIdCompaniaActual := qrReportesIdCompania.Value; Ruta := tbCompaniasRuta.Value; pProgreso.Show; try dmBasesDatos.ConectarDB( Ruta); try Reporte.DataSets.Clear; FindFirst(Ruta + '\*.dat', 0, F); pProgreso.Max := 100; pProgreso.Show; i := 1; repeat pProgreso.Position := i; S := UpperCase(ChangeFileExt(ExtractFileName(F.Name), '')); if (S <> 'A2CONVERSION') then // Crea la tabla try if // Tablas Administrativas (S <> 'SFIXED') and (S <> 'SOPERACIONINV') and (S <> 'SCUENTASXCOBRAR') and (S <> 'SCUENTASXPAGAR') and (S <> 'SDETALLEVENTA') // Tablas Contabilidad and (S <> 'A2CAUXILIARESSALDO') and (S <> 'A2CCUENTAS') // Tablas Nomina and (S <> UpperCase('a2AcumConcepto')) and (S <> UpperCase('a2AcumGenDetalle')) and (S <> UpperCase('a2Concepto')) and (S <> UpperCase('a2Incremento')) and (S <> UpperCase('a2Tabla')) then begin AdicionarTabla( dmBasesDatos.dbA2, S, F.Name); Inc(i); end else begin if (S = 'SFIXED') Then AdicionarDataSetAReporte( dmAdministrativo.sFixed); if (S = 'SOPERACIONINV') then AdicionarDataSetAReporte( dmAdministrativo.sOperacionInv); if (S = 'SDETALLEVENTA') then AdicionarDataSetAReporte( dmAdministrativo.sDetalleVenta); if (S = 'SCUENTASXCOBRAR') then AdicionarDataSetAReporte( dmAdministrativo.sCuentasXCobrar); if (S = 'SCUENTASXPAGAR') then AdicionarDataSetAReporte( dmAdministrativo.sCuentasXPagar); if (S = 'A2CAUXILIARESSALDO') then AdicionarDataSetAReporte( dmContable.A2CAUXILIARESSALDO); if (S = 'A2CCUENTAS') then AdicionarDataSetAReporte( dmContable.A2CCUENTAS); // Tablas Nomina if (S = UpperCase('a2AcumConcepto')) then AdicionarDataSetAReporte( dmNomina.a2AcumConcepto); if (S = UpperCase('a2AcumGenDetalle')) then AdicionarDataSetAReporte( dmNomina.a2AcumGenDetalle); if (S = UpperCase('a2Concepto')) then AdicionarDataSetAReporte( dmNomina.a2Concepto); if (S = UpperCase('a2Incremento')) then AdicionarDataSetAReporte( dmNomina.a2Incremento); if (S = UpperCase('a2Tabla')) then AdicionarDataSetAReporte( dmNomina.a2Tabla); end; Except End; until FindNext(F) <> 0; except dmBasesDatos.CerrarDB; ShowMessage('No se pudo cargar las tablas de la compañia.'); end; except ShowMessage('No se pudo conectar a los datos de la compañía.'); end; pProgreso.Hide; end; end; procedure TdmDatos.DataModuleCreate(Sender: TObject); var R: string; begin // Carga la ruta base para los directorios de control R := ExtractFilePath(ParamStr(0)); // Carga la ruta base para los reportes gRutaReportes := R + kReportes; // Revisa si existe el directorio de datos if Not DirectoryExists(R + kDatos) then CreateDir(R + kDatos); // Revisa si existe el directorio de reportes if Not DirectoryExists(gRutaReportes) then CreateDir(gRutaReportes); dbReportes.Connected := False; dbReportes.Directory := R + kDatos; dbReportes.Connected := True; try tbCompanias.Open; except tbCompanias.CreateTable(); tbCompanias.Open; end; try tbReportes.Open; except tbReportes.CreateTable(); tbReportes.Open; end; end; procedure TdmDatos.DataModuleDestroy(Sender: TObject); begin tbCompanias.Close; tbReportes.Close; dbReportes.Close; BorrarTablas; end; procedure TdmDatos.ReportePrintPage(Page: TfrxReportPage; CopyNo: Integer); begin if ModoDemo then Page.Clear; end; procedure TdmDatos.ReportesCompania(AIdCompania: integer); begin try qrReportes.Close; qrReportes.ParamByName('IdCompania').Value := AIdCompania; qrReportes.Open; except end; end; end.
//////////////////////////////////////////////////////////////////////////////// // // // FileName : SUIListBox.pas // Creator : Shen Min // Date : 2002-08-21 V1-V3 // 2003-07-02 V4 // Comment : // // Copyright (c) 2002-2003 Sunisoft // http://www.sunisoft.com // Email: support@sunisoft.com // //////////////////////////////////////////////////////////////////////////////// unit SUIListBox; interface {$I SUIPack.inc} uses Windows, Messages, StdCtrls, Forms, Graphics, Classes, Controls, filectrl, SysUtils, SUIScrollBar, SUIThemes, SUIMgr; type TsuiListBox = class(TCustomListBox) private m_BorderColor : TColor; m_UIStyle : TsuiUIStyle; m_FileTheme : TsuiFileTheme; // scroll bar m_VScrollBar : TsuiScrollBar; m_MouseDown : Boolean; m_SelfChanging : Boolean; procedure SetVScrollBar(const Value: TsuiScrollBar); procedure OnVScrollBarChange(Sender : TObject); procedure UpdateScrollBars(); procedure UpdateScrollBarsPos(); procedure CMEnabledChanged(var Msg : TMessage); message CM_ENABLEDCHANGED; procedure CMVisibleChanged(var Msg : TMEssage); message CM_VISIBLECHANGED; procedure WMSIZE(var Msg : TMessage); message WM_SIZE; procedure WMMOVE(var Msg : TMessage); message WM_MOVE; procedure WMMOUSEWHEEL(var Message: TMessage); message WM_MOUSEWHEEL; procedure WMLBUTTONDOWN(var Message: TMessage); message WM_LBUTTONDOWN; procedure WMLButtonUp(var Message: TMessage); message WM_LBUTTONUP; procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN; procedure LBADDSTRING(var Msg : TMessage); message LB_ADDSTRING; procedure LBDELETESTRING(var Msg : TMessage); message LB_DELETESTRING; procedure LBINSERTSTRING(var Msg : TMessage); message LB_INSERTSTRING; procedure LBSETCOUNT(var Msg : TMessage); message LB_SETCOUNT; procedure LBNSELCHANGE(var Msg : TMessage); message LBN_SELCHANGE; procedure LBNSETFOCUS(var Msg : TMessage); message LBN_SETFOCUS; procedure WMDELETEITEM(var Msg : TMessage); message WM_DELETEITEM; procedure WMMOUSEMOVE(var Message: TMessage); message WM_MOUSEMOVE; procedure WMVSCROLL(var Message: TWMVScroll); message WM_VSCROLL; procedure WMHSCROLL(var Message: TWMHScroll); message WM_HSCROLL; procedure WMPAINT(var Msg : TMessage); message WM_PAINT; procedure WMEARSEBKGND(var Msg : TMessage); message WM_ERASEBKGND; procedure SetBorderColor(const Value: TColor); procedure SetFileTheme(const Value: TsuiFileTheme); procedure SetUIStyle(const Value: TsuiUIStyle); private FShowFocusRect: Boolean; FAlignment: TAlignment; FSelectedTextColor: TColor; FSelectedColor: TColor; FDisabledTextColor: TColor; procedure CNDrawItem(var Msg: TWMDrawItem); message CN_DRAWITEM; procedure SetAlignment(const Value: TAlignment); procedure SetSelectedColor(const Value: TColor); procedure SetSelectedTextColor(const Value: TColor); procedure SetShowFocusRect(const Value: Boolean); procedure SetDisabledTextColor(const Value: TColor); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); override; procedure MeasureItem(Index: Integer; var Height: Integer); override; public constructor Create(AOwner : TComponent); override; function MeasureString(const S: string; WidthAvail: Integer): Integer; procedure DefaultDrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); virtual; published property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme; property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle; property BorderColor : TColor read m_BorderColor write SetBorderColor; property Alignment: TAlignment read FAlignment write SetAlignment default taLeftJustify; property SelectedColor: TColor read FSelectedColor write SetSelectedColor default clHighlight; property SelectedTextColor: TColor read FSelectedTextColor write SetSelectedTextColor default clHighlightText; property DisabledTextColor: TColor read FDisabledTextColor write SetDisabledTextColor default clGrayText; property ShowFocusRect: Boolean read FShowFocusRect write SetShowFocusRect default True; // scroll bar property VScrollBar : TsuiScrollBar read m_VScrollBar write SetVScrollBar; property Style; property Align; property Anchors; property BiDiMode; property Color; property Columns; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property ExtendedSelect; property Font; property ImeMode; property ImeName; property IntegralHeight; property ItemHeight; property Items; property MultiSelect; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property Sorted; property TabOrder; property TabStop; property TabWidth; property Visible; property OnClick; {$IFDEF SUIPACK_D6UP} property OnData; property OnDataFind; property OnDataObject; {$ENDIF} property OnDblClick; property OnDragDrop; property OnDragOver; property OnDrawItem; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMeasureItem; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; end; TsuiDirectoryListBox = class(TDirectoryListBox) private m_BorderColor : TColor; m_UIStyle : TsuiUIStyle; m_FileTheme : TsuiFileTheme; // scroll bar m_VScrollBar : TsuiScrollBar; m_MouseDown : Boolean; m_SelfChanging : Boolean; procedure SetVScrollBar(const Value: TsuiScrollBar); procedure OnVScrollBarChange(Sender : TObject); procedure UpdateScrollBars(); procedure UpdateScrollBarsPos(); procedure CMEnabledChanged(var Msg : TMessage); message CM_ENABLEDCHANGED; procedure CMVisibleChanged(var Msg : TMEssage); message CM_VISIBLECHANGED; procedure WMSIZE(var Msg : TMessage); message WM_SIZE; procedure WMMOVE(var Msg : TMessage); message WM_MOVE; procedure WMMOUSEWHEEL(var Message: TMessage); message WM_MOUSEWHEEL; procedure WMLBUTTONDOWN(var Message: TMessage); message WM_LBUTTONDOWN; procedure WMLButtonUp(var Message: TMessage); message WM_LBUTTONUP; procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN; procedure LBADDSTRING(var Msg : TMessage); message LB_ADDSTRING; procedure LBDELETESTRING(var Msg : TMessage); message LB_DELETESTRING; procedure LBINSERTSTRING(var Msg : TMessage); message LB_INSERTSTRING; procedure LBSETCOUNT(var Msg : TMessage); message LB_SETCOUNT; procedure LBNSELCHANGE(var Msg : TMessage); message LBN_SELCHANGE; procedure LBNSETFOCUS(var Msg : TMessage); message LBN_SETFOCUS; procedure WMDELETEITEM(var Msg : TMessage); message WM_DELETEITEM; procedure WMMOUSEMOVE(var Message: TMessage); message WM_MOUSEMOVE; procedure WMVSCROLL(var Message: TWMVScroll); message WM_VSCROLL; procedure WMHSCROLL(var Message: TWMHScroll); message WM_HSCROLL; procedure WMPAINT(var Msg : TMessage); message WM_PAINT; procedure WMEARSEBKGND(var Msg : TMessage); message WM_ERASEBKGND; procedure SetBorderColor(const Value: TColor); procedure SetFileTheme(const Value: TsuiFileTheme); procedure SetUIStyle(const Value: TsuiUIStyle); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner : TComponent); override; published property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme; property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle; property BorderColor : TColor read m_BorderColor write SetBorderColor; // scroll bar property VScrollBar : TsuiScrollBar read m_VScrollBar write SetVScrollBar; end; TsuiFileListBox = class(TFileListBox) private m_BorderColor : TColor; m_UIStyle : TsuiUIStyle; m_FileTheme : TsuiFileTheme; // scroll bar m_VScrollBar : TsuiScrollBar; m_MouseDown : Boolean; m_SelfChanging : Boolean; procedure SetVScrollBar(const Value: TsuiScrollBar); procedure OnVScrollBarChange(Sender : TObject); procedure UpdateScrollBars(); procedure UpdateScrollBarsPos(); procedure CMEnabledChanged(var Msg : TMessage); message CM_ENABLEDCHANGED; procedure CMVisibleChanged(var Msg : TMEssage); message CM_VISIBLECHANGED; procedure WMSIZE(var Msg : TMessage); message WM_SIZE; procedure WMMOVE(var Msg : TMessage); message WM_MOVE; procedure WMMOUSEWHEEL(var Message: TMessage); message WM_MOUSEWHEEL; procedure WMLBUTTONDOWN(var Message: TMessage); message WM_LBUTTONDOWN; procedure WMLButtonUp(var Message: TMessage); message WM_LBUTTONUP; procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN; procedure LBADDSTRING(var Msg : TMessage); message LB_ADDSTRING; procedure LBDELETESTRING(var Msg : TMessage); message LB_DELETESTRING; procedure LBINSERTSTRING(var Msg : TMessage); message LB_INSERTSTRING; procedure LBSETCOUNT(var Msg : TMessage); message LB_SETCOUNT; procedure LBNSELCHANGE(var Msg : TMessage); message LBN_SELCHANGE; procedure LBNSETFOCUS(var Msg : TMessage); message LBN_SETFOCUS; procedure WMDELETEITEM(var Msg : TMessage); message WM_DELETEITEM; procedure WMMOUSEMOVE(var Message: TMessage); message WM_MOUSEMOVE; procedure WMVSCROLL(var Message: TWMVScroll); message WM_VSCROLL; procedure WMHSCROLL(var Message: TWMHScroll); message WM_HSCROLL; procedure WMPAINT(var Msg : TMessage); message WM_PAINT; procedure WMEARSEBKGND(var Msg : TMessage); message WM_ERASEBKGND; procedure SetBorderColor(const Value: TColor); procedure SetFileTheme(const Value: TsuiFileTheme); procedure SetUIStyle(const Value: TsuiUIStyle); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner : TComponent); override; published property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme; property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle; property BorderColor : TColor read m_BorderColor write SetBorderColor; // scroll bar property VScrollBar : TsuiScrollBar read m_VScrollBar write SetVScrollBar; end; implementation uses SUIPublic, SUIProgressBar; const AlignFlags: array [TAlignment] of DWORD = (DT_LEFT, DT_RIGHT, DT_CENTER); { TsuiListBox } procedure TsuiListBox.CMEnabledChanged(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiListBox.CMVisibleChanged(var Msg: TMEssage); begin inherited; if not Visible then begin if m_VScrollBar <> nil then m_VScrollBar.Visible := Visible; end else UpdateScrollBarsPos(); end; constructor TsuiListBox.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [csOpaque]; BorderStyle := bsNone; BorderWidth := 2; m_SelfChanging := false; m_MouseDown := false; FAlignment := taLeftJustify; FSelectedColor := clHighlight; FSelectedTextColor := clHighlightText; FDisabledTextColor := clGrayText; FShowFocusRect := True; Style := lbOwnerDrawFixed; UIStyle := GetSUIFormStyle(AOwner); end; procedure TsuiListBox.LBADDSTRING(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiListBox.LBDELETESTRING(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiListBox.LBINSERTSTRING(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiListBox.LBNSELCHANGE(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiListBox.LBNSETFOCUS(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiListBox.LBSETCOUNT(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiListBox.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if AComponent = nil then Exit; if ( (Operation = opRemove) and (AComponent = m_VScrollBar) )then begin m_VScrollBar := nil; end; if ( (Operation = opRemove) and (AComponent = m_FileTheme) )then begin m_FileTheme := nil; SetUIStyle(SUI_THEME_DEFAULT); end; end; procedure TsuiListBox.OnVScrollBarChange(Sender: TObject); begin if m_SelfChanging then Exit; SendMessage(Handle, WM_VSCROLL, MakeWParam(SB_THUMBPOSITION, m_VScrollBar.Position), 0); // SetScrollPos(Handle, SB_VERT, m_VScrollBar.Position, true); UpdateScrollBars(); end; procedure TsuiListBox.SetBorderColor(const Value: TColor); begin m_BorderColor := Value; Repaint(); end; procedure TsuiListBox.SetFileTheme(const Value: TsuiFileTheme); begin m_FileTheme := Value; if m_VScrollBar <> nil then m_VScrollBar.FileTheme := Value; SetUIStyle(m_UIStyle); end; procedure TsuiListBox.SetUIStyle(const Value: TsuiUIStyle); var OutUIStyle : TsuiUIStyle; begin m_UIStyle := Value; if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then m_BorderColor := m_FileTheme.GetColor(SUI_THEME_CONTROL_BORDER_COLOR) else m_BorderColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_CONTROL_BORDER_COLOR); if m_VScrollBar <> nil then m_VScrollBar.UIStyle := OutUIStyle; Repaint(); end; procedure TsuiListBox.SetVScrollBar(const Value: TsuiScrollBar); begin if m_VScrollBar = Value then Exit; if m_VScrollBar <> nil then begin m_VScrollBar.OnChange := nil; m_VScrollBar.LineButton := 0; m_VScrollBar.Max := 100; m_VScrollBar.Enabled := true; end; m_VScrollBar := Value; if m_VScrollBar = nil then Exit; m_VScrollBar.Orientation := suiVertical; m_VScrollBar.OnChange := OnVScrollBArChange; m_VScrollBar.BringToFront(); UpdateScrollBarsPos(); end; procedure TsuiListBox.UpdateScrollBars; var info : tagScrollInfo; barinfo : tagScrollBarInfo; R : Boolean; begin m_SelfChanging := true; if m_VScrollBar <> nil then begin barinfo.cbSize := SizeOf(barinfo); R := SUIGetScrollBarInfo(Handle, Integer(OBJID_VSCROLL), barinfo); if (barinfo.rgstate[0] = STATE_SYSTEM_INVISIBLE) or (barinfo.rgstate[0] = STATE_SYSTEM_UNAVAILABLE) or (not R) then begin m_VScrollBar.LineButton := 0; m_VScrollBar.Enabled := false; m_VScrollBar.Visible := false; end else if not Enabled then begin m_VScrollBar.Enabled := false; end else begin m_VScrollBar.LineButton := abs(barinfo.xyThumbBottom - barinfo.xyThumbTop); m_VScrollBar.Enabled := true; m_VScrollBar.Visible := true; end; info.cbSize := SizeOf(info); info.fMask := SIF_ALL; GetScrollInfo(Handle, SB_VERT, info); m_VScrollBar.Max := info.nMax - Integer(info.nPage) + 1; m_VScrollBar.Min := info.nMin; m_VScrollBar.Position := info.nPos; end; m_SelfChanging := false; end; procedure TsuiListBox.UpdateScrollBarsPos; var L2R : Boolean; begin if m_VScrollBar <> nil then begin if m_VScrollBar.Width > Width then m_VScrollBar.Left := Left else begin L2R := ((BidiMode = bdLeftToRight) or (BidiMode = bdRightToLeftReadingOnly)) or (not SysLocale.MiddleEast); if L2R then m_VScrollBar.Left := Left + Width - m_VScrollBar.Width - 2 else m_VScrollBar.Left := Left + 2; end; m_VScrollBar.Top := Top + 1; m_VScrollBar.Height := Height - 2; end; UpdateScrollBars(); end; procedure TsuiListBox.WMDELETEITEM(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiListBox.WMEARSEBKGND(var Msg: TMessage); begin inherited; DrawControlBorder(self, m_BorderColor, Color); end; procedure TsuiListBox.WMHSCROLL(var Message: TWMHScroll); begin inherited; UpdateScrollBars(); end; procedure TsuiListBox.WMKeyDown(var Message: TWMKeyDown); begin inherited; UpdateScrollBars(); end; procedure TsuiListBox.WMLBUTTONDOWN(var Message: TMessage); begin inherited; m_MouseDown := true; UpdateScrollBars(); end; procedure TsuiListBox.WMLButtonUp(var Message: TMessage); begin inherited; m_MouseDown := false; end; procedure TsuiListBox.WMMOUSEMOVE(var Message: TMessage); begin inherited; if m_MouseDown then UpdateScrollBars(); end; procedure TsuiListBox.WMMOUSEWHEEL(var Message: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiListBox.WMMOVE(var Msg: TMessage); begin inherited; UpdateScrollBarsPos(); end; procedure TsuiListBox.WMPAINT(var Msg: TMessage); begin inherited; DrawControlBorder(self, m_BorderColor, COlor); end; procedure TsuiListBox.WMSIZE(var Msg: TMessage); begin inherited; UpdateScrollBarsPos(); end; procedure TsuiListBox.WMVSCROLL(var Message: TWMVScroll); begin inherited; UpdateScrollBars(); end; procedure TsuiListBox.CNDrawItem(var Msg: TWMDrawItem); var State: TOwnerDrawState; begin with Msg.DrawItemStruct^ do begin State := TOwnerDrawState(LongRec(itemState).Lo); Canvas.Handle := hDC; Canvas.Font := Font; Canvas.Brush := Brush; if Integer(itemID) >= 0 then begin if odSelected in State then begin Canvas.Brush.Color := FSelectedColor; Canvas.Font.Color := FSelectedTextColor; end; if (([odDisabled, odGrayed] * State) <> []) or not Enabled then Canvas.Font.Color := FDisabledTextColor; end; if Integer(itemID) >= 0 then DrawItem(itemID, rcItem, State) else begin Canvas.FillRect(rcItem); if odFocused in State then DrawFocusRect(hDC, rcItem); end; Canvas.Handle := 0; end; end; procedure TsuiListBox.DefaultDrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); var Flags: Longint; begin Canvas.FillRect(Rect); if Index < Items.Count then begin Flags := DrawTextBiDiModeFlags(DT_SINGLELINE or DT_VCENTER or DT_NOPREFIX or AlignFlags[FAlignment]); if not UseRightToLeftAlignment then Inc(Rect.Left, 2) else Dec(Rect.Right, 2); DrawText(Canvas.Handle, PChar(Items[Index]), Length(Items[Index]), Rect, Flags); end; end; procedure TsuiListBox.DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); begin if Assigned(OnDrawItem) then inherited DrawItem(Index, Rect, State) else begin DefaultDrawItem(Index, Rect, State); if FShowFocusRect and (odFocused in State) then Canvas.DrawFocusRect(Rect); end; end; procedure TsuiListBox.MeasureItem(Index: Integer; var Height: Integer); begin if Assigned(OnMeasureItem) or (not true) or (Index < 0) or (Index >= items.count) then inherited MeasureItem(Index, Height) else Height := MeasureString(Items[index], ClientWidth); end; function TsuiListBox.MeasureString(const S: string; WidthAvail: Integer): Integer; var Flags: Longint; R: TRect; begin Canvas.Font := Font; Result := Canvas.TextWidth(S); { Note: doing the TextWidth unconditionally makes sure the font is properly selected into the device context. } if WidthAvail > 0 then begin Flags := DrawTextBiDiModeFlags(DT_SINGLELINE or DT_VCENTER or DT_NOPREFIX or DT_CALCRECT or AlignFlags[FAlignment]); R := Rect(0, 0, WidthAvail - 2, 1); DrawText(canvas.handle, Pchar(S), Length(S), R, Flags); Result := R.Bottom; if Result > 255 then Result := 255; { Note: item height in a listbox is limited to 255 pixels since Windows stores the height in a single byte.} end; end; procedure TsuiListBox.SetAlignment(const Value: TAlignment); begin if (FAlignment <> Value) then begin FAlignment := Value; Invalidate; end; end; procedure TsuiListBox.SetDisabledTextColor(const Value: TColor); begin if FDisabledTextColor <> Value then begin FDisabledTextColor := Value; Invalidate; end; end; procedure TsuiListBox.SetSelectedColor(const Value: TColor); begin if FSelectedColor <> Value then begin FSelectedColor := Value; Invalidate; end; end; procedure TsuiListBox.SetSelectedTextColor(const Value: TColor); begin if FSelectedTextColor <> Value then begin FSelectedTextColor := Value; Invalidate; end; end; procedure TsuiListBox.SetShowFocusRect(const Value: Boolean); begin if FShowFocusRect <> Value then begin FShowFocusRect := Value; if Focused then Invalidate; end; end; { TsuiDirectoryListBox } procedure TsuiDirectoryListBox.CMEnabledChanged(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiDirectoryListBox.CMVisibleChanged(var Msg: TMEssage); begin inherited; if not Visible then begin if m_VScrollBar <> nil then m_VScrollBar.Visible := Visible; end else UpdateScrollBarsPos(); end; constructor TsuiDirectoryListBox.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [csOpaque]; BorderStyle := bsNone; BorderWidth := 2; m_SelfChanging := false; m_MouseDown := false; UIStyle := GetSUIFormStyle(AOwner); end; procedure TsuiDirectoryListBox.LBADDSTRING(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiDirectoryListBox.LBDELETESTRING(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiDirectoryListBox.LBINSERTSTRING(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiDirectoryListBox.LBNSELCHANGE(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiDirectoryListBox.LBNSETFOCUS(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiDirectoryListBox.LBSETCOUNT(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiDirectoryListBox.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if AComponent = nil then Exit; if ( (Operation = opRemove) and (AComponent = m_VScrollBar) )then begin m_VScrollBar := nil; end; if ( (Operation = opRemove) and (AComponent = m_FileTheme) )then begin m_FileTheme := nil; SetUIStyle(SUI_THEME_DEFAULT); end; end; procedure TsuiDirectoryListBox.OnVScrollBarChange(Sender: TObject); begin if m_SelfChanging then Exit; SendMessage(Handle, WM_VSCROLL, MakeWParam(SB_THUMBPOSITION, m_VScrollBar.Position), 0); Invalidate; end; procedure TsuiDirectoryListBox.SetBorderColor(const Value: TColor); begin m_BorderColor := Value; Repaint(); end; procedure TsuiDirectoryListBox.SetFileTheme(const Value: TsuiFileTheme); begin m_FileTheme := Value; if m_VScrollBar <> nil then m_VScrollBar.FileTheme := Value; SetUIStyle(m_UIStyle); end; procedure TsuiDirectoryListBox.SetUIStyle(const Value: TsuiUIStyle); var OutUIStyle : TsuiUIStyle; begin m_UIStyle := Value; if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then m_BorderColor := m_FileTheme.GetColor(SUI_THEME_CONTROL_BORDER_COLOR) else m_BorderColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_CONTROL_BORDER_COLOR); if m_VScrollBar <> nil then m_VScrollBar.UIStyle := OutUIStyle; Repaint(); end; procedure TsuiDirectoryListBox.SetVScrollBar(const Value: TsuiScrollBar); begin if m_VScrollBar = Value then Exit; if m_VScrollBar <> nil then begin m_VScrollBar.OnChange := nil; m_VScrollBar.LineButton := 0; m_VScrollBar.Max := 100; m_VScrollBar.Enabled := true; end; m_VScrollBar := Value; if m_VScrollBar = nil then Exit; m_VScrollBar.Orientation := suiVertical; m_VScrollBar.OnChange := OnVScrollBArChange; m_VScrollBar.BringToFront(); UpdateScrollBarsPos(); end; procedure TsuiDirectoryListBox.UpdateScrollBars; var info : tagScrollInfo; barinfo : tagScrollBarInfo; R : Boolean; begin m_SelfChanging := true; if m_VScrollBar <> nil then begin barinfo.cbSize := SizeOf(barinfo); R := SUIGetScrollBarInfo(Handle, Integer(OBJID_VSCROLL), barinfo); if (barinfo.rgstate[0] = STATE_SYSTEM_INVISIBLE) or (barinfo.rgstate[0] = STATE_SYSTEM_UNAVAILABLE) or (not R) then begin m_VScrollBar.LineButton := 0; m_VScrollBar.Enabled := false; m_VScrollBar.Visible := false; end else if not Enabled then m_VScrollBar.Enabled := false else begin m_VScrollBar.LineButton := abs(barinfo.xyThumbBottom - barinfo.xyThumbTop); m_VScrollBar.Enabled := true; m_VScrollBar.Visible := true; end; info.cbSize := SizeOf(info); info.fMask := SIF_ALL; GetScrollInfo(Handle, SB_VERT, info); m_VScrollBar.Max := info.nMax - Integer(info.nPage) + 1; m_VScrollBar.Min := info.nMin; m_VScrollBar.Position := info.nPos; end; m_SelfChanging := false; end; procedure TsuiDirectoryListBox.UpdateScrollBarsPos; var L2R : Boolean; begin if m_VScrollBar <> nil then begin if m_VScrollBar.Width > Width then m_VScrollBar.Left := Left else begin L2R := ((BidiMode = bdLeftToRight) or (BidiMode = bdRightToLeftReadingOnly)) or (not SysLocale.MiddleEast); if L2R then m_VScrollBar.Left := Left + Width - m_VScrollBar.Width - 2 else m_VScrollBar.Left := Left + 2; end; m_VScrollBar.Top := Top + 1; m_VScrollBar.Height := Height - 2; end; UpdateScrollBars(); end; procedure TsuiDirectoryListBox.WMDELETEITEM(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiDirectoryListBox.WMEARSEBKGND(var Msg: TMessage); begin inherited; DrawControlBorder(self, m_BorderColor, Color); end; procedure TsuiDirectoryListBox.WMHSCROLL(var Message: TWMHScroll); begin inherited; UpdateScrollBars(); end; procedure TsuiDirectoryListBox.WMKeyDown(var Message: TWMKeyDown); begin inherited; UpdateScrollBars(); end; procedure TsuiDirectoryListBox.WMLBUTTONDOWN(var Message: TMessage); begin inherited; m_MouseDown := true; UpdateScrollBars(); end; procedure TsuiDirectoryListBox.WMLButtonUp(var Message: TMessage); begin inherited; m_MouseDown := false; end; procedure TsuiDirectoryListBox.WMMOUSEMOVE(var Message: TMessage); begin inherited; if m_MouseDown then UpdateScrollBars(); end; procedure TsuiDirectoryListBox.WMMOUSEWHEEL(var Message: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiDirectoryListBox.WMMOVE(var Msg: TMessage); begin inherited; UpdateScrollBarsPos(); end; procedure TsuiDirectoryListBox.WMPAINT(var Msg: TMessage); begin inherited; DrawControlBorder(self, m_BorderColor, COlor); end; procedure TsuiDirectoryListBox.WMSIZE(var Msg: TMessage); begin inherited; UpdateScrollBarsPos(); end; procedure TsuiDirectoryListBox.WMVSCROLL(var Message: TWMVScroll); begin inherited; UpdateScrollBars(); end; { TsuiFileListBox } procedure TsuiFileListBox.CMEnabledChanged(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiFileListBox.CMVisibleChanged(var Msg: TMEssage); begin inherited; if not Visible then begin if m_VScrollBar <> nil then m_VScrollBar.Visible := Visible; end else UpdateScrollBarsPos(); end; constructor TsuiFileListBox.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [csOpaque]; BorderStyle := bsNone; BorderWidth := 2; m_SelfChanging := false; m_MouseDown := false; UIStyle := GetSUIFormStyle(AOwner); end; procedure TsuiFileListBox.LBADDSTRING(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiFileListBox.LBDELETESTRING(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiFileListBox.LBINSERTSTRING(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiFileListBox.LBNSELCHANGE(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiFileListBox.LBNSETFOCUS(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiFileListBox.LBSETCOUNT(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiFileListBox.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if AComponent = nil then Exit; if ( (Operation = opRemove) and (AComponent = m_VScrollBar) )then begin m_VScrollBar := nil; end; if ( (Operation = opRemove) and (AComponent = m_FileTheme) )then begin m_FileTheme := nil; SetUIStyle(SUI_THEME_DEFAULT); end; end; procedure TsuiFileListBox.OnVScrollBarChange(Sender: TObject); begin if m_SelfChanging then Exit; SendMessage(Handle, WM_VSCROLL, MakeWParam(SB_THUMBPOSITION, m_VScrollBar.Position), 0); Invalidate; end; procedure TsuiFileListBox.SetBorderColor(const Value: TColor); begin m_BorderColor := Value; Repaint(); end; procedure TsuiFileListBox.SetFileTheme(const Value: TsuiFileTheme); begin m_FileTheme := Value; if m_VScrollBar <> nil then m_VScrollBar.FileTheme := Value; SetUIStyle(m_UIStyle); end; procedure TsuiFileListBox.SetUIStyle(const Value: TsuiUIStyle); var OutUIStyle : TsuiUIStyle; begin m_UIStyle := Value; if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then m_BorderColor := m_FileTheme.GetColor(SUI_THEME_CONTROL_BORDER_COLOR) else m_BorderColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_CONTROL_BORDER_COLOR); if m_VScrollBar <> nil then m_VScrollBar.UIStyle := OutUIStyle; Repaint(); end; procedure TsuiFileListBox.SetVScrollBar(const Value: TsuiScrollBar); begin if m_VScrollBar = Value then Exit; if m_VScrollBar <> nil then begin m_VScrollBar.OnChange := nil; m_VScrollBar.LineButton := 0; m_VScrollBar.Max := 100; m_VScrollBar.Enabled := true; end; m_VScrollBar := Value; if m_VScrollBar = nil then Exit; m_VScrollBar.Orientation := suiVertical; m_VScrollBar.OnChange := OnVScrollBArChange; m_VScrollBar.BringToFront(); UpdateScrollBarsPos(); end; procedure TsuiFileListBox.UpdateScrollBars; var info : tagScrollInfo; barinfo : tagScrollBarInfo; R : Boolean; begin m_SelfChanging := true; if m_VScrollBar <> nil then begin barinfo.cbSize := SizeOf(barinfo); R := SUIGetScrollBarInfo(Handle, Integer(OBJID_VSCROLL), barinfo); if (barinfo.rgstate[0] = STATE_SYSTEM_INVISIBLE) or (barinfo.rgstate[0] = STATE_SYSTEM_UNAVAILABLE) or (not R) then begin m_VScrollBar.LineButton := 0; m_VScrollBar.Enabled := false; m_VScrollBar.Visible := false; end else if not Enabled then m_VScrollBar.Enabled := false else begin m_VScrollBar.LineButton := abs(barinfo.xyThumbBottom - barinfo.xyThumbTop); m_VScrollBar.Enabled := true; m_VScrollBar.Visible := true; end; info.cbSize := SizeOf(info); info.fMask := SIF_ALL; GetScrollInfo(Handle, SB_VERT, info); m_VScrollBar.Max := info.nMax - Integer(info.nPage) + 1; m_VScrollBar.Min := info.nMin; m_VScrollBar.Position := info.nPos; end; m_SelfChanging := false; end; procedure TsuiFileListBox.UpdateScrollBarsPos; var L2R : Boolean; begin if m_VScrollBar <> nil then begin if m_VScrollBar.Width > Width then m_VScrollBar.Left := Left else begin L2R := ((BidiMode = bdLeftToRight) or (BidiMode = bdRightToLeftReadingOnly)) or (not SysLocale.MiddleEast); if L2R then m_VScrollBar.Left := Left + Width - m_VScrollBar.Width - 2 else m_VScrollBar.Left := Left + 2; end; m_VScrollBar.Top := Top + 1; m_VScrollBar.Height := Height - 2; end; UpdateScrollBars(); end; procedure TsuiFileListBox.WMDELETEITEM(var Msg: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiFileListBox.WMEARSEBKGND(var Msg: TMessage); begin inherited; DrawControlBorder(self, m_BorderColor, COlor); end; procedure TsuiFileListBox.WMHSCROLL(var Message: TWMHScroll); begin inherited; UpdateScrollBars(); end; procedure TsuiFileListBox.WMKeyDown(var Message: TWMKeyDown); begin inherited; UpdateScrollBars(); end; procedure TsuiFileListBox.WMLBUTTONDOWN(var Message: TMessage); begin inherited; m_MouseDown := true; UpdateScrollBars(); end; procedure TsuiFileListBox.WMLButtonUp(var Message: TMessage); begin inherited; m_MouseDown := false; end; procedure TsuiFileListBox.WMMOUSEMOVE(var Message: TMessage); begin inherited; if m_MouseDown then UpdateScrollBars(); end; procedure TsuiFileListBox.WMMOUSEWHEEL(var Message: TMessage); begin inherited; UpdateScrollBars(); end; procedure TsuiFileListBox.WMMOVE(var Msg: TMessage); begin inherited; UpdateScrollBarsPos(); end; procedure TsuiFileListBox.WMPAINT(var Msg: TMessage); begin inherited; DrawControlBorder(self, m_BorderColor, COlor); end; procedure TsuiFileListBox.WMSIZE(var Msg: TMessage); begin inherited; UpdateScrollBarsPos(); end; procedure TsuiFileListBox.WMVSCROLL(var Message: TWMVScroll); begin inherited; UpdateScrollBars(); end; end.
(* **************************************************************** *) (* Copyright (C) 1999-2010, Jon Gentle, All right reserved. *) (* **************************************************************** *) (* This program is free software; you can redistribute it under the *) (* terms of the Artistic License, as specified in the LICENSE file. *) (* **************************************************************** *) unit draak; interface uses SysUtils, Classes, StrUtils, //Contnrs, filedrv, gmrdrv, Macro, parser, hashs, error; type TDraakNotify = procedure(sender: TObject; s: string) of object; TDraakFlags = set of (TimeStat, HashTime); TDraak = class(TComponent) private error: TError; Grammar: TGmr; root: PParseNode; FonError: TDraakNotify; FonStatus: TDraakNotify; FonStream: TdraakNotify; FonNodeCreate: TDraakNotify; FonNodeChild: TDraakNotify; FonNodePop: TDraakNotify; FonCompile: TDraakNotify; FonAssemble: TDraakNotify; FonLink: TDraakNotify; Flag: TDraakFlags; FSearchPath: string; FMacroClass: TMacroClass; finalSuccess: boolean; public property rootNode: PParseNode read root; property success: boolean read finalSuccess; published property Flags: TDraakFlags read Flag write Flag; property SearchPath: string read FSearchPath write FSearchPath; property MacroClass: TMacroClass read FMacroClass write FMacroClass; property onError: TDraakNotify read FonError write FonError; property onStatus: TDraakNotify read FonStatus write FonStatus; property onStream: TDraakNotify read FonStream write FonStream; property onNodeCreate: TDraakNotify read FonNodeCreate write FonNodeCreate; property onNodeChild: TDraakNotify read FonNodeChild write FonNodeChild; property onNodePop: TDraakNotify read FonNodePop write FonNodePop; property onCompile: TDraakNotify read FonCompile write FonCompile; property onAssemble: TDraakNotify read FonAssemble write FonAssemble; property onLink: TDraakNotify read FonLink write FonLink; constructor create(AOwner: TComponent); override; procedure compile(outStream: TFileStream; inFile: string); procedure parse(inFile: string); procedure clearGrammer; procedure clear; procedure produceCopyright; { Published declarations } end; EDraakNoCompile = class(Exception) end; procedure Register; implementation //uses cmddrv{$ifdef MSWindows}, windows {$endif} ; uses parrotdrv; function timeCount(var t: int64): double; var i, f: int64; begin {$ifdef MSWindows} if t = 0 then begin QueryPerformanceCounter(t); result := 0; end else begin QueryPerformanceCounter(i); QueryPerformanceFrequency(f); result := (i-t) / f; end; {$endif} {$ifdef Linux} result := 0;{$Endif} end; constructor TDraak.create(AOwner: TComponent); begin inherited Create(AOwner); //FMacroClass := TMacro; error := TError.create(self); end; procedure TDraak.parse(inFile: string); var loadedFile: string; ext, gmrfile: string; name: string; noext: string; lPath: PChar; t: int64; tim: double; parse: TParser; begin loadedFile := inFile; ext := AnsiStrRScan(PChar(loadedFile), '.')+1; lPath := AnsiStrRScan(PChar(loadedFile), PathDelim); if lPath <> nil then name := lPath+1 else name := loadedFile; noext := Leftstr(name, AnsiPos('.', name)-1); gmrFile := FileSearch({ext+PathDelim+}ext+'.gmr', FSearchPath); t := 0; timeCount(t); if Grammar = nil then Grammar := TGmr.init(TFile.init(gmrFile)); tim := timeCount(t); if HashTime in Flag then error.status(FloatToStrF(tim,ffFixed, 0, 2)+' seconds to hash.'); t := 0; timeCount(t); parse := TParser.Create; parse.err := error; parse.parse(TFile.init(inFile), Grammar); if (parse.rootNode <> nil) AND (root = nil) then root := parse.rootNode; tim := timeCount(t); if TimeStat in Flag then error.status(FloatToStrF(tim, ffFixed, 0, 2)+' seconds.'); end; procedure TDraak.compile(outStream: TFileStream; inFile: string); var loadedFile: string; ext, gmrFile: string; name: string; noext: string; lPath: PChar; t: int64; tim: double; macro: TMacroDrv; parse: TParser; begin loadedFile := inFile; ext := AnsiStrRScan(PChar(loadedFile), '.')+1; lPath := AnsiStrRScan(PChar(loadedFile), PathDelim); if lPath <> nil then name := lPath+1 else name := loadedFile; noext := Leftstr(name, AnsiPos('.', name)-1); gmrFile := FileSearch({ext+PathDelim+}ext+'.gmr', FSearchPath); if gmrFile='' then begin error.err('Couldn''t find grammar file for extention: '+ext); exit; end; t := 0; timeCount(t); if Grammar = nil then Grammar := TGmr.init(TFile.init(gmrFile)); tim := timeCount(t); if HashTime in Flag then error.status(FloatToStrF(tim, ffFixed, 0, 2)+' seconds to hash.'); t := 0; timeCount(t); parse := TParser.Create; parse.err := error; parse.parse(TFile.init(inFile), Grammar); if parse.rootNode <> nil then begin finalSuccess := true; if root = nil then root := parse.rootNode; FMacroClass := TMacroClass(GetClass('TDrv'+Grammar.settings.last('OutputDrv'))); writeln(not assigned(FMacroClass)); if not assigned(FMacroClass) then begin writeln('Could not load macro driver "'+Grammar.settings.last('OutputDrv')+'"'); end else begin writeln(FMacroClass.ClassName); macro := FMacroClass.create; macro.err := error; macro.gmr := Grammar; macro.searchDirs := FSearchPath; macro.execute(parse.rootNode); macro.write(outStream); { if macro.giantError = false then begin macro.outCode.SaveToStream(outStream); macro.outData.SaveToStream(outStream); error.status(noext+'.pas: Compiled! ('+intToStr(parse.lines)+' lines)' ); finalSuccess := true; end else begin finalSuccess := false; error.err('Error compiling file.'); end; macro.free; } end; end; parse.Free; tim := timeCount(t); if TimeStat in Flag then error.status(FloatToStrF(tim, ffFixed, 0, 2)+' seconds.'); end; procedure TDraak.clearGrammer; begin Grammar := nil; root := nil; end; {Clear: destroys all internal data. Wipes it out. Frees all the mem Draak uses} { without destroying the DraakComp. Grammar and Root are destroyed and set to } { nil.} procedure TDraak.clear; begin if assigned(Grammar) then Grammar.Free; if assigned(root) then rootDestroy(root); Grammar := nil; root := nil; end; procedure TDraak.produceCopyright; begin error.status('(* ************************************************************ *)'); error.status('(* Copyright (c) 1999-2010 Jon Gentle, All right reserved. *)'); error.status('(* ************************************************************ *)'); end; procedure Register; begin RegisterComponents('TOASC', [TDraak]); end; begin end.
{ Find Faces Of A Planar Graph Greedy Alg. O(N3) Input: N: Number of vertices G[I]: List of vertices adjacent to I in counter-clockwise order D[I]: Degree of vertex I P[I]: Position of Vertex P Output: Edge[I][J]: Number of the face that lies to the left of edge (I,J) FaceNum: Number of faces, including the outer one FaceDeg[I]: Number of vertices on face I Face[I]: Vertices of face I Notes: G should represent a valid embedding of a planar connected graph A, B that FindFaces accepts represent these: A = Index of point with minimum X (and with minimum Y within them) B = The rightmost point that A is connected to These are used to set the face number of outer face of graph to 1 Pass 0, 0 to ignore these Edge[I][J] <> Edge[J][I] FindOuterFaceEdge finds A and B for FindFaces By Behdad } program Faces; const MaxN = 30 + 1; var N: Integer; G, Edge: array [1 .. MaxN, 0 .. MaxN] of Integer; D, FaceDeg: array [1 .. MaxN] of Integer; Face: array [1 .. MaxN * 3, 0 .. MaxN * 6] of Integer; FaceNum: Integer; P: array [1 .. MaxN] of record X, Y: Integer; end; procedure FindFace (A, B: Integer); var I, S, T: Integer; begin Inc(FaceNum); S := A; T := B; FaceDeg[FaceNum] := 0; Face[FaceNum, 0] := A; repeat Inc(FaceDeg[FaceNum]); Face[FaceNum, FaceDeg[FaceNum]] := B; Edge[A, B] := FaceNum; for I := 1 to D[b] do if A = G[B, I] then Break; A := B; B := G[B, I - 1]; until (A = S) and (B = T); end; procedure FindFaces (A, B: Integer); var I, J: Integer; begin for I := 1 to N do G[I, 0] := G[I, D[I]]; FillChar(Edge, SizeOf(Edge), 0); for I := 1 to N do for J := 1 to D[I] do Edge[I, G[I, J]] := -1; FaceNum := 0; if (A > 0) and (B > 0) then FindFace(B, A); for I := 1 to N do for J := 1 to N do if Edge[I, J] = -1 then FindFace(I, J); end; procedure FindOuterFaceEdge (var A, B: Integer); var I, J: Integer; begin A := 1; for I := 2 to N do if (P[I].X < P[A].X) or ((P[I].X = P[A].X) and (P[I].Y <= P[A].Y)) then A := I; B := G[A, 1]; for I := 2 to D[A] do begin J := G[A, I]; if (P[J].X-P[A].X) * (P[B].Y-P[A].Y) > (P[J].Y-P[A].Y) * (P[B].X-P[A].X) then B := J; end; end; var A, B: Integer; begin FindOuterFaceEdge(A, B); FindFaces(A, B); end.
unit BitPatternHelp; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, JvExStdCtrls, JvRichEdit, ExtCtrls; type TFormBitPatternHelp = class(TForm) JvRichEditUsage: TJvRichEdit; PanelMemoContainer: TPanel; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormBitPatternHelp: TFormBitPatternHelp; implementation {$R *.dfm} procedure TFormBitPatternHelp.FormCreate(Sender: TObject); procedure PutHeader(E: TJvRichEdit; S: String); begin E.SelAttributes.Style := [fsBold]; E.SelAttributes.Size := 11; E.SelText := S + sLineBreak; end; procedure PutMessage(E: TJvRichEdit; S: String); begin E.SelAttributes.Style := []; E.SelAttributes.Size := 8; E.SelText := sLineBreak + S + sLineBreak; end; begin JvRichEditUsage.Clear; PutHeader(JvRichEditUsage, 'Input'); PutMessage(JvRichEditUsage, 'This tool accepts input numeric values of one data type ("source" type), and re-interprets the underlying bit pattern for that type''s value in each of the other supported data types ("target" types).'); PutMessage(JvRichEditUsage, 'When re-interpreting the bit pattern, the following rules are used when the source size "SZ" (bytes) and target size "TZ" (bytes) are unequal:'); PutMessage(JvRichEditUsage, ' 1.) SZ greater than TZ => The least significant SZ-TZ bytes are used; discard remaining bytes.'); PutMessage(JvRichEditUsage, ' 2.) TZ greater than SZ => The most significant TZ-SZ bytes are padded with zeroes; no sign extension.'); PutMessage(JvRichEditUsage, 'Double-click the "Interpreted value" edit box of a data type to select that type as the new source (currently selected source is indicated by the "Source" checkbox).' + ' Once selected, each of the target types are then re-interpreted accordingly.'); PutHeader(JvRichEditUsage, sLineBreak + 'Integer and floating point'); PutMessage(JvRichEditUsage, 'For input integer values, base 10 (decimal) is used by default.' + ' Base 16 (hexadecimal) can be forced by prepending the input string with a dollar sign ($).' + ' Additionally, any input string that contains one of the characters ''A'' .. ''F'' will be automatically interpreted as hexadecimal.'); PutMessage(JvRichEditUsage, 'Floating point values must be specified in decimal.' + ' Note that the re-interpretation rules above for unequal-sized data types totally clobbers any meaningful relationship between the 32-bit and 64-bit floating point interpreted (IEEE-754) values.'); PutHeader(JvRichEditUsage, sLineBreak + 'Bit layout'); PutMessage(JvRichEditUsage, 'In addition to providing integer and floating point input values, the bit pattern to be re-interpreted may be manually specified by clicking the panel for each corresponding bit in the "Bit layout" group box.'); PutMessage(JvRichEditUsage, 'For convenience, you may drag your cursor over the bit panels while holding down the right mouse button to select a subrange of bits.' + ' The value of this hightlighted range is interpreted as an unsigned integer and displayed in the edit box below the bit panels.'); PutHeader(JvRichEditUsage, sLineBreak + 'Base conversions'); PutMessage(JvRichEditUsage, 'The "Base conversions" group box displays read-only data.' + ' The interpreted 32-bit and 64-bit unsigned integer values are displayed here for base 2 (binary), 8 (octal), 10 (decimal), and 16 (hexadecimal).' + ' Various endianness (byte order) conventions are also displayed for each base and type.'); PutMessage(JvRichEditUsage, 'The "Show digit groupings" checkbox inserts spaces between logical groups of digits for each base. This is just for the reader''s clarity.'); HideCaret(JvRichEditUsage.Handle); // JvRichEditUsage.SelStart := 0; // JvRichEditUsage.SelLength := 0; end; end.
unit BrickCamp.Resources.TProduct; interface uses System.Classes, System.SysUtils, Spring.Container.Common, Spring.Container, MARS.Core.Registry, MARS.Core.Attributes, MARS.Core.MediaType, MARS.Core.JSON, MARS.Core.MessageBodyWriters, MARS.Core.MessageBodyReaders, BrickCamp.Repositories.IProduct, BrickCamp.Resources.IProduct, BrickCamp.Model, BrickCamp.Model.IProduct, BrickCamp.Model.TProduct; type [Path('/product'), Produces(TMediaType.APPLICATION_JSON_UTF8)] TProductResource = class(TInterfacedObject, IProductResurce) protected function GetProductFromJSON(const Value: TJSONValue): TProduct; public [GET, Path('/getone/{Id}')] function GetOne(const [PathParam] Id: Integer): TProduct; [GET, Path('/getlist/')] function GetList: TJSONArray; [POST] procedure Insert(const [BodyParam] Value: TJSONValue); [PUT] procedure Update(const [BodyParam] Value: TJSONValue); [DELETE, Path('/{Id}')] procedure Delete(const [PathParam] Id: Integer); end; implementation { THelloWorldResource } function TProductResource.GetOne(const Id: Integer): TProduct; begin Result := GlobalContainer.Resolve<IProductRepository>.GetOne(Id); end; function TProductResource.GetProductFromJSON(const Value: TJSONValue): TProduct; var JSONObject: TJSONObject; begin Result := GlobalContainer.Resolve<TProduct>; JSONObject := TJSONObject.ParseJSONValue(Value.ToJSON) as TJSONObject; try Result.Name := JSONObject.ReadStringValue('Name', ''); Result.Description := JSONObject.ReadStringValue('Description', ''); Result.Price := JSONObject.ReadDoubleValue('Price', 0.0); finally JSONObject.Free; end; end; procedure TProductResource.Delete(const Id: Integer); begin GlobalContainer.Resolve<IProductRepository>.Delete(Id); end; procedure TProductResource.Insert(const Value: TJSONValue); var Product: TProduct; begin Product := GetProductFromJSON(Value); try if Assigned(Product) then GlobalContainer.Resolve<IProductRepository>.Insert(Product); finally Product.Free; end; end; procedure TProductResource.Update(const Value: TJSONValue); var Product: TProduct; begin Product := GetProductFromJSON(Value); try if Assigned(Product) then GlobalContainer.Resolve<IProductRepository>.Update(Product); finally Product.Free; end; end; function TProductResource.GetList: TJSONArray; begin result := GlobalContainer.Resolve<IProductRepository>.GetList; end; initialization TMARSResourceRegistry.Instance.RegisterResource<TProductResource>; end.
unit Clavier_AZERTY; interface type TKeys = Record Key : Word; Note : string; Down: boolean; end; var // Paramétrage des touches pour un clavier AZERTY (La2 -> Mi4) Keys: Array[0..19] of TKeys =( // Touches du clavier : (Key:81; Note:'La2'; Down:false), // q (Key:83; Note:'Si2'; Down:false), // s (Key:68; Note:'Do3'; Down:false), // d (Key:70; Note:'Re3'; Down:false), // f (Key:71; Note:'Mi3'; Down:false), // g (Key:72; Note:'Fa3'; Down:false), // h (Key:74; Note:'Sol3'; Down:false), // j (Key:75; Note:'La3'; Down:false), // k (Key:76; Note:'Si3'; Down:false), // l (Key:77; Note:'Do4'; Down:false), // m (Key:192; Note:'Re4'; Down:false), // ů (Key:220; Note:'Mi4'; Down:false), // * (Key:90; Note:'La2d'; Down:false), // z (Key:82; Note:'Do3d'; Down:false), // r (Key:84; Note:'Re3d'; Down:false), // t (Key:85; Note:'Fa3d'; Down:false), // u (Key:73; Note:'Sol3d'; Down:false), // i (Key:79; Note:'La3d'; Down:false), // o (Key:221; Note:'Do4d'; Down:false), // ^ (Key:186; Note:'Re4d'; Down:false) // $ ); implementation end.
//=============================================// // uDate // //---------------------------------------------// // Unit yang menangani tanggal dalam program // //=============================================// unit uDate; interface uses parsertuanyon; {* KAMUS *} { *** Definisi ABSTRACT DATA TYPE Date ***} type Date = record DD : integer; MM : integer; YYYY : integer; end; function ParseDate(var dateString : string) : Date; {Menghasilkan tanggal bertipe Date dari string tanggal berformat DD/MM/YYYY} procedure WriteDate(var dateofdate : Date); {Menulis tanggal bertipe Date ke layar dengan format DD/MM/YYYY tanpa akhiran End of Line} {I.S. : Atribut Date lengkap} {F.S. : Date tercetak ke layar sesuai format DD/MM/YYYY tanpa akhiran End of Line} procedure WritelnDate(var dateofdate : Date); {Menulis tanggal bertipe Date ke layar dengan format DD/MM/YYYY dengan akhiran End of Line} {I.S. : Atribut Date lengkap} {F.S. : Date tercetak ke layar sesuai format DD/MM/YYYY dengan akhiran End of Line} procedure ProcessDate(dateComponent : integer); {Memroses atribut Date (DD atau MM) yang hanya terdiri dari 1 digit menjadi 2 digit (1 -> 01) dan mencetaknya ke layar} {I.S. : Atribut Date hanya terdiri dari 1 digit} {F.S. : Atribut Date tercetak ke layar dalam format 2 digit tanpa akhiran End of Line} implementation function ParseDate(var datestring : string) : Date; {Menghasilkan tanggal bertipe Date dari string tanggal berformat DD/MM/YYYY} { KAMUS LOKAL } var i, slashcount : integer; temp_string : string; { ALGORITMA } begin i := 1; slashcount := 0; // Penanda banyak garis miring yang telah ditemukan temp_string := ''; // Variabel sementara untuk menyimpan string while (i <= Length(datestring)) do begin // While loop untuk mengambil bagian string tanggal yang bukan '/' // dan menyimpannya ke variabel temp_string while (datestring[i] <> '/') and (i < Length(datestring)) do begin temp_string := temp_string + dateString[i]; inc(i); end; // If digunakan untuk menentukan ke atribut Date mana (DD/MM) // temp_string akan dimasukkan // Penentuan menggunakan variabel slashcount sebagai penanda banyaknya // garis miring yang telah ditemukan if (datestring[i] = '/') then begin case slashcount of 0 : begin ParseDate.DD := StrToInt(temp_string); inc(slashcount); temp_string := ''; end; 1 : begin ParseDate.MM := StrToInt(temp_string); inc(slashcount); temp_string := ''; end; end; inc(i); end; // If terakhir digunakan untuk bagian atribut Date YYYY dengan kondisi iterasi telah // mencapai char terakhir, sehingga dipastikan bagian terakhir adalah tahun if (i = Length(datestring)) then begin temp_string := temp_string + dateString[i]; ParseDate.YYYY := StrToInt(temp_string); slashcount := 0; temp_string := ''; inc(i); end; end; end; procedure ProcessDate(dateComponent : integer); {Memroses atribut Date (DD atau MM) yang hanya terdiri dari 1 digit menjadi 2 digit (1 -> 01) dan mencetaknya ke layar} {I.S. : Atribut Date hanya terdiri dari 1 digit} {F.S. : Atribut Date tercetak ke layar dalam format 2 digit tanpa akhiran End of Line} { ALGORITMA } begin if((dateComponent/10) < 1) then begin write('0',dateComponent); end else begin write(dateComponent); end; end; procedure WriteDate(var dateofdate : Date); {Menulis tanggal bertipe Date ke layar dengan format DD/MM/YYYY tanpa akhiran End of Line} {I.S. : Atribut Date lengkap} {F.S. : Date tercetak ke layar sesuai format DD/MM/YYYY tanpa akhiran End of Line} { ALGORITMA } begin ProcessDate(dateofdate.DD); write('/'); ProcessDate(dateofdate.MM); write('/'); ProcessDate(dateofdate.YYYY); end; procedure WritelnDate(var dateofdate : Date); {Menulis tanggal bertipe Date ke layar dengan format DD/MM/YYYY dengan akhiran End of Line} {I.S. : Atribut Date lengkap} {F.S. : Date tercetak ke layar sesuai format DD/MM/YYYY dengan akhiran End of Line} { ALGORITMA } begin ProcessDate(dateofdate.DD); write('/'); ProcessDate(dateofdate.MM); write('/'); ProcessDate(dateofdate.YYYY); writeln(''); end; end.
{**********************************************************************} {* Иллюстрация к книге "OpenGL в проектах Delphi" *} {* Краснов М.В. softgl@chat.ru *} {**********************************************************************} unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OpenGL; type TfrmGL = class(TForm) procedure FormCreate(Sender: TObject); procedure FormPaint(Sender: TObject); procedure FormDestroy(Sender: TObject); private hrc: HGLRC; end; var frmGL: TfrmGL; implementation {$R *.DFM} {======================================================================= Перерисовка окна} procedure TfrmGL.FormPaint(Sender: TObject); const Level = 15; // уровень детализации radius = 0.4; // радиус отверстия var i : 0 .. Level - 1; begin wglMakeCurrent(Canvas.Handle, hrc); glViewPort (0, 0, ClientWidth, ClientHeight); glClearColor (1.0, 1.0, 1.0, 1.0); glClear (GL_COLOR_BUFFER_BIT); glColor3f(0.0, 0.0, 0.0); glBegin(GL_QUAD_STRIP); // верхняя четверть For i := 0 to Level - 1 do begin glVertex2f(radius * sin (Pi * i / (2 * Level) - Pi /4), radius * cos (Pi * i / (2 * Level) - Pi /4)); glVertex2f(i / Level - 0.5, 0.5); glVertex2f(radius * sin (Pi * (i + 1) / (2 * Level) - Pi /4), radius * cos (Pi * (i + 1) / (2 * Level) - Pi /4)); glVertex2f((i + 1) / Level - 0.5, 0.5); end; glEnd; // правая четверть glBegin(GL_QUAD_STRIP); For i := 0 to Level - 1 do begin glVertex2f(radius * sin (Pi * i / (2 * Level) + Pi / 4), radius * cos (Pi * i / (2 * Level) + Pi / 4)); glVertex2f(0.5, 0.5 - i / Level); glVertex2f(radius * sin (Pi * (i + 1) / (2 * Level) + Pi / 4), radius * cos (Pi * (i + 1) / (2 * Level) + Pi / 4)); glVertex2f(0.5, 0.5 - (i + 1)/ Level); end; glEnd; // левая четверть glBegin(GL_QUAD_STRIP); For i := 0 to Level - 1 do begin glVertex2f(radius * sin (Pi * i / (2 * Level) - 3 * Pi / 4 ), radius * cos (Pi * i / (2 * Level) - 3 * Pi / 4)); glVertex2f(-0.5, i / Level - 0.5); glVertex2f(radius * sin (Pi * (i + 1) / (2 * Level) - 3 * Pi / 4 ), radius * cos (Pi * (i + 1) / (2 * Level) - 3 * Pi / 4)); glVertex2f(-0.5, (i + 1) / Level - 0.5); end; glEnd; // нижняя четверть glBegin(GL_QUAD_STRIP); For i := 0 to Level - 1 do begin glVertex2f(radius * sin (Pi * i / (2 * Level) + 3 * Pi / 4 ), radius * cos (Pi * i / (2 * Level) + 3 * Pi / 4)); glVertex2f(0.5 - i / Level, -0.5); glVertex2f(radius * sin (Pi * (i + 1) / (2 * Level) + 3 * Pi / 4), radius * cos (Pi * (i + 1) / (2 * Level) + 3 * Pi / 4)); glVertex2f(0.5 - (i + 1) / Level, -0.5); end; glEnd; SwapBuffers(Canvas.Handle); // содержимое буфера - на экран wglMakeCurrent(0, 0); end; {======================================================================= Формат пикселя} procedure SetDCPixelFormat (hdc : HDC); var pfd : TPixelFormatDescriptor; nPixelFormat : Integer; begin FillChar (pfd, SizeOf (pfd), 0); pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; nPixelFormat := ChoosePixelFormat (hdc, @pfd); SetPixelFormat (hdc, nPixelFormat, @pfd); end; {======================================================================= Создание формы} procedure TfrmGL.FormCreate(Sender: TObject); begin SetDCPixelFormat(Canvas.Handle); hrc := wglCreateContext(Canvas.Handle); end; {======================================================================= Конец работы приложения} procedure TfrmGL.FormDestroy(Sender: TObject); begin wglDeleteContext(hrc); end; end.
unit Main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, Db, DBTables, Grids, DBGrids, ComCtrls, ExtCtrls, ToolWin, ImgList, ADODB; type TForm1 = class(TForm) DBGrid1: TDBGrid; CustSource: TDataSource; Panel1: TPanel; Label3: TLabel; Label4: TLabel; Edit1: TEdit; Edit2: TEdit; FindBtn: TBitBtn; Cust: TTable; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FindBtnClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.FormShow(Sender: TObject); begin try Cust.Open; except on E: EDBEngineError do ShowMessage('Ошибка при открытии таблицы'); end; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin Cust.Close; end; procedure TForm1.FindBtnClick(Sender: TObject); begin try if not Cust.FindKey([Edit1.Text, Edit2.Text]) then ShowMessage('Запись не найдена'); except on E: EDatabaseError do ShowMessage('Ошибка поиска'); end; end; end.
unit export_form; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, sf_export, CheckLst, metadata, query_filter, Buttons, Spin, fpspreadsheet; type { TExportForm } TExportForm = class(TForm) private FColsCount: integer; FRowsCount: integer; FCheckList: TCheckListBox; FFilters: TQueryFilterDynArray; FHorzField: TDBField; FVertField: TDBField; btnApply: TBitbtn; FCheckedCount: ^integer; FIsColEmpty: TBoolDynArray; FIsRowEmpty: TBoolDynArray; FStrings: TDblStrinListDynArray; public procedure HTMLFillStringList(StringList: TStringList); procedure HTMLAppendDescription(StringList: TStringList); procedure HTMLAppendCells(StringList: TStringList); procedure XLFillWorkbook(Workbook: TsWorkbook); procedure XLAddDescription(DescrSheet: TsWorksheet); procedure RefreshData(AStrings: TDblStrinListDynArray; AColsCount, ARowsCount: integer; AHorzField, AVertField: TDBField; AFilters: TQueryFilterDynArray; IsColEmpty, IsRowEmpty: TBoolDynArray); constructor Create(AParent: TForm; ACheckList: TCheckListBox; AbtnApply: TBitbtn; var ACheckedCount: integer); published lbFontSize: TLabel; seFontSize: TSpinEdit; btnOk: TBitBtn; btnCancel: TBitBtn; btnBrowse: TButton; cgParams: TCheckGroup; lbePath: TLabeledEdit; rgFormat: TRadioGroup; SaveDialog: TSaveDialog; procedure btnBrowseClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); end; var ExportForm: TExportForm; implementation {$R *.lfm} procedure TExportForm.btnBrowseClick(Sender: TObject); begin SaveDialog.FilterIndex := rgFormat.ItemIndex + 1; if SaveDialog.Execute then begin lbePath.Text := SaveDialog.FileName; rgFormat.ItemIndex := SaveDialog.FilterIndex - 1; end; end; procedure TExportForm.btnCancelClick(Sender: TObject); begin Close; end; procedure TExportForm.btnOkClick(Sender: TObject); var StringList: TStringList; Stream: TFileStream; Workbook: TsWorkbook; begin Stream := TFileStream.Create(Utf8ToAnsi(lbePath.Text), fmCreate); case rgFormat.ItemIndex of 0: begin StringList := TStringList.Create; HTMLFillStringList(StringList); StringList.SaveToStream(Stream); StringList.Free; end; 1: begin Workbook := TsWorkbook.Create; XLFillWorkbook(Workbook); Workbook.WriteToStream(Stream, sfExcel8); Workbook.Free; end; end; Stream.Free; Close; end; procedure TExportForm.XLFillWorkbook(Workbook: TsWorkbook); var Worksheet: TsWorksheet; Description: TsWorksheet; i, j: integer; begin Worksheet := Workbook.AddWorksheet(FVertField.Caption + ' - ' + FHorzField.Caption); Description := Workbook.AddWorksheet('Описание'); with Worksheet do begin DefaultColWidth := 10; DefaultRowHeight := 10; Options := Worksheet.Options + [soHasFrozenPanes]; LeftPaneWidth := 1; TopPaneHeight := 1; for i := 0 to FRowsCount - 1 do begin for j := 0 to FColsCount - 1 do begin if Assigned(FStrings[i, j]) then WriteUTF8Text(i, j, FStrings[i, j].Text); WriteVertAlignment(i, j, vaTop); WriteColWidth(j, 25); WriteWordwrap(i, j, true); Worksheet.WriteFontSize(i, j, seFontSize.Value); end; WriteRowHeight(i, 25); end; for i := 0 to FRowsCount do begin WriteBorders(i, 0, [cbEast]); WriteColWidth(0, 15); WriteVertAlignment(i, 0, vaCenter); WriteHorAlignment(i, 0, haCenter); if cgParams.Checked[4] and FIsRowEmpty[i] then WriteRowHeight(i, 0); end; for j := 0 to FColsCount do begin WriteBorders(0, j, [cbSouth]); WriteRowHeight(0, 2); WriteVertAlignment(0, j, vaCenter); WriteHorAlignment(0, j, haCenter); if cgParams.Checked[3] and FIsColEmpty[j] then WriteColWidth(j, 0); end; end; XLAddDescription(Description); end; procedure TExportForm.XLAddDescription(DescrSheet: TsWorksheet); procedure StartDescrSection(DescrSheet: TsWorksheet; Shift: integer; Caption: string); begin with DescrSheet do begin MergeCells(Shift, 0, Shift, 5); WriteUTF8Text(Shift, 0, Caption); WriteBorders(Shift, 0, [cbSouth, cbWest, cbEast, cbNorth]); WriteBorders(Shift, 5, [cbEast, cbNorth]); WriteRowHeight(Shift, 2); WriteVertAlignment(Shift, 0, vaCenter); end; end; procedure AddDescr(DescrSheet: TsWorksheet; Shift, Count: integer; StringList: TStringList); begin with DescrSheet do begin MergeCells(Shift + 1, 0, Shift + 1, 3); WriteUTF8Text(Shift + 1, 0, StringList.Text); WriteRowHeight(Shift + 1, 1 + Count); WriteVertAlignment(Shift + 1, 0, vaTop); end; end; var Shift: integer = 0; i: integer; StringList: TStringList; FieldCaption: string; begin StringList := TStringList.Create; with DescrSheet do begin if btnApply.Enabled then begin StartDescrSection(DescrSheet, Shift, 'Описание может не соответствовать содержимому таблицы'); inc(Shift, 2); end; if (FCheckedCount^ > 0) and (cgParams.Checked[0]) then begin StringList.Clear; StartDescrSection(DescrSheet, Shift, 'Отображаемые поля:'); for i := 0 to FCheckList.Count - 1 do if FCheckList.Checked[i] then StringList.Append(FCheckList.Items.Strings[i]); AddDescr(DescrSheet, Shift, FCheckedCount^, StringList); inc(Shift, 3); end; if (Length(FFilters) > 0) and (cgParams.Checked[1]) then begin StringList.Clear; StartDescrSection(DescrSheet, Shift, 'Фильтры:'); for i := 0 to High(FFilters) do begin FieldCaption := ''; if Assigned(FFilters[i].ChosenField) then FieldCaption := FFilters[i].ChosenField.Caption else if Assigned(FFilters[i].ConstantEditor) then FieldCaption := 'ИЛИ' else continue; StringList.Append( FieldCaption + ' ' + FFilters[i].Operation.Caption + ' ' + string(FFilters[i].Value)); end; AddDescr(DescrSheet, Shift, Length(FFilters), StringList); inc(Shift, 3); end; if cgParams.Checked[2] then StartDescrSection(DescrSheet, Shift, FVertField.Caption + ' \ ' + FHorzField.Caption); end; end; procedure TExportForm.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin CloseAction := caHide; end; constructor TExportForm.Create(AParent: TForm; ACheckList: TCheckListBox; AbtnApply: TBitbtn; var ACheckedCount: integer); var i: integer; begin inherited Create(AParent); FCheckList := ACheckList; btnApply := AbtnApply; FCheckedCount := @ACheckedCount; with cgParams do for i := 0 to Items.Count - 1 do Checked[i] := true; end; procedure TExportForm.RefreshData(AStrings: TDblStrinListDynArray; AColsCount, ARowsCount: integer; AHorzField, AVertField: TDBField; AFilters: TQueryFilterDynArray; IsColEmpty, IsRowEmpty: TBoolDynArray); begin FColsCount := AColsCount; FRowsCount := ARowsCount; FFilters := AFilters; FHorzField := AHorzField; FVertField := AVertField; FIsColEmpty := IsColEmpty; FIsRowEmpty := IsRowEmpty; FStrings := AStrings; end; procedure TExportForm.HTMLAppendDescription(StringList: TStringList); var i: integer; FieldCaption: string; begin with StringList do begin if btnApply.Enabled then Append('Описание может не соответствовать содержимому таблицы' + '<br><br>'); if (FCheckedCount^ > 0) and (cgParams.Checked[0]) then begin Append('<li>' + 'Отображаемые поля:' + '</li>'); for i := 0 to FCheckList.Count - 1 do if FCheckList.Checked[i] then Append(FCheckList.Items.Strings[i] + ' <br>'); end; if (Length(FFilters) > 0) and (cgParams.Checked[1]) then begin Append('<br><li>' + 'Фильтры:' + ' </li>'); for i := 0 to High(FFilters) do begin FieldCaption := ''; if Assigned(FFilters[i].ChosenField) then FieldCaption := FFilters[i].ChosenField.Caption else if Assigned(FFilters[i].ConstantEditor) then FieldCaption := 'ИЛИ' else continue; Append( FieldCaption + ' ' + FFilters[i].Operation.Caption + ' ' + string(FFilters[i].Value) + '<br>'); end; end; if cgParams.Checked[2] then Append( '<br><br>' + FVertField.Caption + ' \ ' + FHorzField.Caption); end; end; procedure TExportForm.HTMLAppendCells(StringList: TStringList); var i, j, k: integer; begin with StringList do begin Append('<table>'); for i := 0 to FRowsCount - 1 do begin if cgParams.Checked[4] and FIsRowEmpty[i] then continue; Append('<tr>'); for j := 0 to FColsCount - 1 do begin if cgParams.Checked[3] and FIsColEmpty[j] then continue; Append('<td>'); if (i < Length(FStrings)) and (j < Length(FStrings[i])) and Assigned(FStrings[i, j]) then for k := 0 to FStrings[i, j].Count - 1 do Append(FStrings[i, j].Strings[k] + ' <br>'); Append('</td>'); end; Append('</tr>'); end; Append('</table>'); end; end; procedure TExportForm.HTMLFillStringList(StringList: TStringList); begin with StringList do begin Append('<html> <head> <meta charset="utf-8">'); Append('<style>'); Append('table { border: 1px solid #000; border-collapse:collapse;}'); Append('td { border: 1px solid #000; padding: 5px; vertical-align: top; font-size: ' + seFontSize.Text + 'px}'); Append('</style>'); Append('</head>'); Append('<body>'); HTMLAppendDescription(StringList); HTMLAppendCells(StringList); Append('</body> </html>'); end; end; end.
unit ncGuidUtils; interface uses SysUtils; type TGuidEx = class //Creates and returns a new globally unique identifier class function NewGuid : TGuid; class function New: TGuid; //sometimes we need to have an "empty" value, like NULL class function EmptyGuid : TGuid; class function Empty: TGuid; //Checks whether a Guid is EmptyGuid class function IsEmptyGuid(Guid : TGuid) : boolean; class function IsEmpty(Guid : TGuid) : boolean; //Convert to string class function ToString(Guid : TGuid) : string; //convert to quoted string class function ToQuotedString(Guid : TGuid) : string; //return a GUID from string class function FromString(Value : string) : TGuid; //Indicates whether two TGUID values are the same class function EqualGuids(Guid1, Guid2 : TGuid) : boolean; end; implementation { TGuidEx } var vEmptyGuid : TGUID; class function TGuidEx.Empty: TGuid; begin Result := vEmptyGuid; end; class function TGuidEx.EmptyGuid: TGuid; begin result := vEmptyGuid; end; class function TGuidEx.EqualGuids(Guid1, Guid2: TGuid): boolean; begin result := IsEqualGUID(Guid1, Guid2); end; class function TGuidEx.FromString(Value: string): TGuid; begin result := StringToGuid(Value); end; class function TGuidEx.IsEmpty(Guid: TGuid): boolean; begin Result := IsEmptyGuid(Guid); end; class function TGuidEx.IsEmptyGuid(Guid : TGuid): boolean; begin result := EqualGuids(Guid,EmptyGuid); end; class function TGuidEx.New: TGuid; begin Result := NewGuid; end; class function TGuidEx.NewGuid: TGuid; begin CreateGUID(Result); end; class function TGuidEx.ToQuotedString(Guid: TGuid): string; begin result := QuotedStr(ToString(Guid)); end; class function TGuidEx.ToString(Guid: TGuid): string; begin result := GuidToString(Guid); end; initialization vEmptyGuid := TGuidEx.FromString('{00000000-0000-0000-0000-000000000000}'); end.//GuidEx
{$INCLUDE ..\cDefines.inc} unit cRandom; { } { Random number functions v3.08 } { } { This unit is copyright © 1999-2002 by David Butler (david@e.co.za) } { } { This unit is part of Delphi Fundamentals. } { Its original file name is cRandom.pas } { The latest version is available from the Fundamentals home page } { http://fundementals.sourceforge.net/ } { } { I invite you to use this unit, free of charge. } { I invite you to distibute this unit, but it must be for free. } { I also invite you to contribute to its development, } { but do not distribute a modified copy of this file. } { } { A forum is available on SourceForge for general discussion } { http://sourceforge.net/forum/forum.php?forum_id=2117 } { } { } { Revision history: } { 1999/11/07 0.01 Added RandomSeed. } { 1999/12/01 0.02 Added RandomUniform. } { 1999/12/03 0.03 Added RandomNormal. } { 2000/01/23 1.04 Added RandomPseudoWord. } { 2000/07/13 1.05 Fixed bug in RandomUniform reported by Andrew Driazgov } { <andrey@asp.tstu.ru> } { 2000/08/22 1.06 Added RandomHex. } { 2000/09/20 1.07 Added more random states to RandomSeed. } { 2002/06/01 3.08 Created cRandom unit from cSysUtils and cMaths. } { } interface { } { RandomSeed } { Returns a random seed value, based on the Windows counter, the CPU counter } { and the current date/time and other 'random' states. } { } function RandomSeed: LongWord; { } { Uniform random number generator } { Returns a random number from a uniform density distribution (ie all number } { have an equal probability of being 'chosen') } { RandomFloat returns an random floating point value between 0 and 1. } { RandomPseudoWord returns a random word-like string. } { } function RandomUniform: LongWord; overload; function RandomUniform(const N: Integer): Integer; overload; function RandomBoolean: Boolean; function RandomByte: Byte; function RandomInt64: Int64; overload; function RandomInt64(const N: Int64): Int64; overload; function RandomHex(const Digits: Integer = 8): String; function RandomFloat: Extended; function RandomPseudoWord(const Length: Integer): String; { } { Normal distribution random number generator } { RandomNormalF returns a random number that has a Normal(0,1) distribution } { (Gaussian distribution) } { } function RandomNormalF: Extended; { } { GUIDs } { } type TGUID128 = Array[0..3] of LongWord; function GenerateGUID32: LongWord; function GenerateGUID64: Int64; function GenerateGUID128: TGUID128; function GUID128ToHex(const GUID: TGUID128): String; implementation uses { Delphi } Windows, SysUtils; { } { RandomSeed } { } function RandomSeed: LongWord; var I : Int64; Ye, Mo, Da : Word; H, Mi, S, S1 : Word; begin Result := $A5F04182; // Date DecodeDate(Date, Ye, Mo, Da); Result := Result xor Ye xor (Mo shl 16) xor (Da shl 24); // Time DecodeTime(Time, H, Mi, S, S1); Result := Result xor H xor (Mi shl 8) xor (S1 shl 16) xor (S shl 24); {$IFDEF OS_WIN32} // OS Counter (Ticks since OS start-up) Result := Result xor GetTickCount; // CPU Counter (Ticks since CPU start-up) if QueryPerformanceCounter(I) then Result := Result xor LongWord(I) xor LongWord(I shr 32); // CPU Frequency (Specific to CPU model) if QueryPerformanceFrequency(I) then Result := Result xor LongWord(I) xor LongWord(I shr 32); // Process Result := Result xor GetCurrentProcessID xor GetCurrentThreadID; {$ENDIF} end; { } { Uniform Random } { } { Random number generator from ACM Transactions on Modeling and Computer } { Simulation 8(1) 3-30, 1990. Supposedly it has a period of -1 + 2^19937. } { The original was in C; this translation returns the same values as the } { original. It is called the Mersenne Twister. } { The following code was written by Toby Ewing <ewing@iastate.edu>, slightly } { modified by Frank Heckenbach <frank@pascal.gnu.de>. } { It was inspired by C code, released under the GNU Library General Public } { License, written by Makoto Matsumoto <matumoto@math.keio.ac.jp> and } { Takuji Nishimura, considering the suggestions by Topher Cooper and } { Marc Rieffel in July-Aug 97. } const N = 624; // Period parameters M = 397; var mti : Integer; mt : Array[0..N - 1] of LongWord; // the array for the state vector RandomUniformInitialized : Boolean = False; { Set initial seeds to mt [N] using the generator Line 25 of Table 1 in } { [KNUTH 1981, The Art of Computer Programming Vol. 2 (2nd Ed.), pp 102]. } Procedure RandomUniformInit(const Seed: LongWord); var I : Integer; begin mt[0] := Seed; For I := 1 to N - 1 do mt[I] := LongWord(Int64(69069) * mt[I - 1]); mti := N; RandomUniformInitialized := True end; function RandomUniform: LongWord; const Matrix_A = $9908B0DF; // constant vector a T_Mask_B = $9D2C5680; // Tempering parameters T_Mask_C = $EFC60000; Up_Mask = $80000000; // most significant w-r bits Low_Mask = $7FFFFFFF; // least significant r bits mag01 : Array[0..1] of LongWord = (0, Matrix_A); var y : LongWord; kk : Integer; begin if not RandomUniformInitialized then RandomUniformInit(RandomSeed); if mti >= N then { generate N words at one time } begin For kk := 0 to N - M - 1 do begin y := (mt[kk] and Up_Mask) or (mt[kk + 1] and Low_Mask); mt[kk] := mt[kk + M] xor (y shr 1) xor mag01[y and 1] end; For kk := N - M to N - 2 do begin y := (mt[kk] and Up_Mask) or (mt[kk + 1] and Low_Mask); mt[kk] := mt[kk + M - N] xor (y shr 1) xor mag01[y and 1] end; y := (mt[N - 1] and Up_Mask) or (mt[0] and Low_Mask); mt[N - 1] := mt[M - 1] xor (y shr 1) xor mag01[y and 1]; mti := 0 end; y := mt[mti]; Inc(mti); y := y xor (y shr 11); y := y xor ((y shl 7) and T_Mask_B); y := y xor ((y shl 15) and T_Mask_C); y := y xor (y shr 18); Result := y; end; function RandomUniform(const N: Integer): Integer; begin if N = 0 then Result := 0 else Result := Integer(Int64(RandomUniform) mod N); end; function RandomBoolean: Boolean; begin Result := RandomUniform and 1 = 1; end; function RandomByte: Byte; begin Result := Byte(RandomUniform and $FF); end; function RandomFloat: Extended; begin Result := RandomUniform / High(LongWord); end; function RandomInt64: Int64; begin Int64Rec(Result).Lo := RandomUniform; Int64Rec(Result).Hi := RandomUniform; end; function RandomInt64(const N: Int64): Int64; begin if N = 0 then Result := 0 else begin Result := RandomInt64; if Result < 0 then Result := -Result; Result := Result mod N; end; end; function RandomHex(const Digits: Integer): String; var I : Integer; begin Result := ''; Repeat I := Digits - Length(Result); if I > 0 then Result := Result + IntToHex(RandomUniform, 8); Until I <= 0; SetLength(Result, Digits); end; function RandomPseudoWord(const Length: Integer): String; const Vowels = 'AEIOUY'; Consonants = 'BCDFGHJKLMNPQRSTVWXZ'; var I : Integer; begin Assert(Length >= 0, 'RandomPseudoWord: Invalid Length parameter'); SetLength(Result, Length); For I := 1 to Length do Case RandomUniform(2) of 0 : Result[I] := Vowels[RandomUniform(6) + 1]; 1 : Result[I] := Consonants[RandomUniform(20) + 1]; end; end; { } { Normal Random } { } var HasRandomNormal : Boolean = False; ARandomNormal : Extended; function RandomNormalF: Extended; var fac, r, v1, v2: Extended; begin if not HasRandomNormal then begin Repeat v1 := 2.0 * RandomFloat - 1.0; v2 := 2.0 * RandomFloat - 1.0; r := Sqr(v1) + Sqr(v2); Until r < 1.0; fac := Sqrt(-2.0 * ln(r) / r); ARandomNormal := v1 * fac; Result := v2 * fac; HasRandomNormal := True; end else begin Result := ARandomNormal; HasRandomNormal := False; end; end; { } { GUID } { } var GUIDInit : Boolean = False; GUIDBase : TGUID128 = (0, 0, 0, 0); procedure InitGUID; var I : Integer; begin GUIDBase[0] := RandomSeed; For I := 1 to 3 do GUIDBase[I] := RandomUniform; GUIDInit := True; end; function GenerateGUID32: LongWord; begin if not GUIDInit then InitGUID; Result := GUIDBase[3]; GUIDBase[3] := LongWord(GUIDBase[3] + 1); end; function GenerateGUID64: Int64; begin if not GUIDInit then InitGUID; Int64Rec(Result).Hi := GUIDBase[2]; Int64Rec(Result).Lo := GUIDBase[3]; GUIDBase[3] := LongWord(GUIDBase[3] + 1); end; function GenerateGUID128: TGUID128; begin if not GUIDInit then InitGUID; Result := GUIDBase; GUIDBase[3] := LongWord(GUIDBase[3] + 1); if GUIDBase[3] = 0 then GUIDBase[2] := LongWord(GUIDBase[2] + 1); GUIDBase[1] := RandomUniform; end; function GUID128ToHex(const GUID: TGUID128): String; begin Result := IntToHex(GUIDBase[0], 8) + IntToHex(GUIDBase[1], 8) + IntToHex(GUIDBase[2], 8) + IntToHex(GUIDBase[3], 8); end; end.
unit nifti_hdr; {$include opts.inc} {$D-,O+,Q-,R-,S-} interface uses {$H+} {$Include isgui.inc} {$IFNDEF FPC} gziod, {$ELSE} gzio2, {$ENDIF} {$IFNDEF FPC} Windows, {$ENDIF} {$IFDEF DGL} dglOpenGL, {$ELSE} gl, {$ENDIF} nifti_types, clipbrd, define_types,SysUtils,nii_mat,nifti_foreign, //GLMisc, //GLTexture, GLContext, {$IFDEF GUI}dialogs;{$ELSE} dialogsx;{$ENDIF} type TMRIcroHdr = record //Next: analyze Format Header structure NIFTIhdr : TNIFTIhdr; AutoBalMinUnscaled,AutoBalMaxUnscaled ,WindowScaledMin,WindowScaledMax //,GlMaxNegUnscaledS,GlMinPosUnscaledS //<- used for thresholded images ,GlMinUnscaledS,GlMaxUnscaledS,Zero8Bit,Slope8bit: double; //brightness and contrast NIfTItransform,DiskDataNativeEndian,UsesCustomPalette,RGB,LutFromZero,LutVisible: boolean; HdrFileName,ImgFileName: string; gzBytes: Int64; //ClusterSize, LUTindex,ScrnBufferItems,ImgBufferItems,RenderBufferItems,ImgBufferBPP,RenderDim: longint; ImgBufferUnaligned: Pointer; //raw address of Image Buffer: address may not be aligned ScrnBuffer,ImgBuffer: Bytep; LUT: TLUT; Mat: TMatrix; end; //TNIFTIhdr Header Structure function NIFTIvolumes (var lFilename: string): integer; function FixDataType (var lHdr: TNIFTIhdr): boolean; overload; function FixDataType (var lHdr: TMRIcroHdr): boolean; overload; function ComputeImageDataBytes (var lHdr: TMRIcroHdr): longint; //size of image data in bytes function ComputeImageDataBytes8bpp (var lHdr: TMRIcroHdr): longint; //size of image as 32-bit per voxel data in bytes function ComputeImageDataBytes32bpp (var lHdr: TMRIcroHdr): longint; //size of image as 32-bit per voxel data in bytes procedure NIFTIhdr_SwapBytes (var lAHdr: TNIFTIhdr); //Swap Byte order for the Analyze type //procedure NIFTIhdr_ClearHdr (var lHdr: TNIfTIHdr); overload; //set all values of header to something reasonable procedure NIFTIhdr_ClearHdr (out lHdr: TMRIcroHdr); overload;//set all values of header to something reasonable function NIFTIhdr_LoadHdr (var lFilename: string; out lHdr: TMRIcroHdr; lFlipYZ: boolean): boolean; function NIFTIhdr_SaveHdr (var lFilename: string; var lHdr: TMRIcroHdr; lAllowOverwrite: boolean): boolean; overload; function NIFTIhdr_SaveHdr (var lFilename: string; var lHdr: TNIFTIHdr; lAllowOverwrite,lSPM2: boolean): boolean; overload; //procedure NIFTIhdr_SetIdentityMatrix (var lHdr: TMRIcroHdr); //create neutral rotation matrix function CopyNiftiHdr (var lInHdr,lOutHdr: TNIFTIhdr): boolean; function IsNIfTIHdrExt (var lFName: string):boolean; //1494 function IsNifTiMagic (var lHdr: TNIFTIhdr): boolean; procedure WriteNiftiMatrix (var lHdr: TNIFTIhdr; m11,m12,m13,m14, m21,m22,m23,m24, m31,m32,m33,m34: Single); function niftiflip (var lHdr: TMRIcrohdr): boolean; procedure nifti_mat44_to_quatern( lR :TMatrix; var qb, qc, qd, qx, qy, qz, dx, dy, dz, qfac : single); function IsVOIROIExt (var lFName: string):boolean; implementation uses mainunit; function NIFTIvolumes (var lFilename: string): integer; var lHdr: TMRIcroHdr; begin result := -1; if not NIFTIhdr_LoadHdr (lFilename, lHdr, gPrefs.FlipYZ) then exit; result := lHdr.NIFTIhdr.dim[4]; if (result < 1) then result := 1; end; function NIFTIhdr_SaveHdr (var lFilename: string; var lHdr: TNIFTIHdr; lAllowOverwrite,lSPM2: boolean): boolean; overload; var lOutHdr: TNIFTIhdr; lExt: string; lF: File; lOverwrite: boolean; begin lOverwrite := false; //will we overwrite existing file? result := false; //assume failure if lHdr.magic = kNIFTI_MAGIC_EMBEDDED_HDR then begin lExt := UpCaseExt(lFileName); if (lExt = '.GZ') or (lExt = '.NII.GZ') then begin showmessage('Unable to save .nii.gz headers (first ungzip your image if you wish to edit the header)'); exit; end; lFilename := changefileext(lFilename,'.nii') end else begin lFilename := changefileext(lFilename,'.hdr'); lHdr.magic := kNIFTI_MAGIC_SEPARATE_HDR; end; if ((sizeof(TNIFTIhdr))> DiskFreeEx(lFileName)) then begin ShowMessage('There is not enough free space on the destination disk to save the header. '+kCR+ lFileName+ kCR+' Bytes Required: '+inttostr(sizeof(TNIFTIhdr)) ); exit; end; if Fileexists(lFileName) then begin if lAllowOverwrite then begin case MessageDlg('Do you wish to modify the existing file '+lFilename+'?', mtConfirmation,[mbYes, mbNo], 0) of { produce the message dialog box } 6: lOverwrite := true; //6= mrYes, 7=mrNo... not sure what this is for Linux. Hardcoded as we do not include Form values end;//case end else showmessage('Error: the file '+lFileName+' already exists.'); if not lOverwrite then Exit; end; if lHdr.magic = kNIFTI_MAGIC_EMBEDDED_HDR then if lHdr.vox_offset < sizeof(TNIFTIHdr) then lHdr.vox_offset := sizeof(TNIFTIHdr); //embedded images MUST start after header if lHdr.magic = kNIFTI_MAGIC_SEPARATE_HDR then lHdr.vox_offset := 0; //embedded images MUST start after header if lSPM2 then begin //SPM2 does not recognize NIfTI - origin values will be wrong lHdr.magic := 0; end; result := true; move(lHdr, lOutHdr, sizeof(lOutHdr)); Filemode := 1; AssignFile(lF, lFileName); {WIN} if lOverwrite then //this allows us to modify just the 348byte header of an existing NII header without touching image data Reset(lF,sizeof(TNIFTIhdr)) else Rewrite(lF,sizeof(TNIFTIhdr)); BlockWrite(lF,lOutHdr, 1 {, NumWritten}); CloseFile(lF); Filemode := 2; end; //func NIFTIhdr_SaveHdr function CopyNiftiHdr (var lInHdr,lOutHdr: TNIFTIhdr): boolean; begin move(lInHdr,lOutHdr,sizeof(TNIFTIhdr)); result := true; end; function IsVOIROIExt (var lFName: string):boolean; var lExt: string; begin lExt := UpCaseExt(lFName); if (lExt = '.VOI') or (lExt = '.ROI') then result := true else result := false; end; procedure WriteNiftiMatrix (var lHdr: TNIFTIhdr; m11,m12,m13,m14, m21,m22,m23,m24, m31,m32,m33,m34: Single); begin with lHdr do begin srow_x[0] := m11; srow_x[1] := m12; srow_x[2] := m13; srow_x[3] := m14; srow_y[0] := m21; srow_y[1] := m22; srow_y[2] := m23; srow_y[3] := m24; srow_z[0] := m31; srow_z[1] := m32; srow_z[2] := m33; srow_z[3] := m34; end; //with lHdr end; procedure FromMatrix (M: TMatrix; out m11,m12,m13, m21,m22,m23, m31,m32,m33: DOUBLE) ; BEGIN m11 := M.Matrix[1,1]; m12 := M.Matrix[1,2]; m13 := M.Matrix[1,3]; m21 := M.Matrix[2,1]; m22 := M.Matrix[2,2]; m23 := M.Matrix[2,3]; m31 := M.Matrix[3,1]; m32 := M.Matrix[3,2]; m33 := M.Matrix[3,3]; END {FromMatrix3D}; procedure WriteNiftiMatrix2 (var lHdr: TNIFTIhdr; M: TMatrix); begin with lHdr do begin srow_x[0] := M.Matrix[1,1]; srow_x[1] := M.Matrix[1,2]; srow_x[2] := M.Matrix[1,3]; srow_x[3] := M.Matrix[1,4]; srow_y[0] := M.Matrix[2,1]; srow_y[1] := M.Matrix[2,2]; srow_y[2] := M.Matrix[2,3]; srow_y[3] := M.Matrix[2,4]; srow_z[0] := M.Matrix[3,1]; srow_z[1] := M.Matrix[3,2]; srow_z[2] := M.Matrix[3,3]; srow_z[3] := M.Matrix[3,4]; end; //with lHdr end; function niftiflip (var lHdr: TMRIcrohdr): boolean; var lR,lF,lO: TMatrix; begin result := false; if (lHdr.NIFTIhdr.srow_x[0]+lHdr.NIFTIhdr.srow_y[0]+lHdr.NIFTIhdr.srow_z[0]) > 0 then exit; result := true; lR := Matrix3D ( lHdr.NIFTIhdr.srow_x[0],lHdr.NIFTIhdr.srow_x[1],lHdr.NIFTIhdr.srow_x[2],lHdr.NIFTIhdr.srow_x[3], lHdr.NIFTIhdr.srow_y[0],lHdr.NIFTIhdr.srow_y[1],lHdr.NIFTIhdr.srow_y[2],lHdr.NIFTIhdr.srow_y[3], lHdr.NIFTIhdr.srow_z[0],lHdr.NIFTIhdr.srow_z[1],lHdr.NIFTIhdr.srow_z[2],lHdr.NIFTIhdr.srow_z[3]); lF := Matrix3D (-1,0,0,0, 0,1,0,0, 0,0,1,0 ); lO := MultiplyMatrices(lR,lF); WriteNiftiMatrix2(lHdr.NIFTIhdr,lO); end; function IsNifTiMagic (var lHdr: TNIFTIhdr): boolean; begin if (lHdr.magic =kNIFTI_MAGIC_SEPARATE_HDR) or (lHdr.Magic = kNIFTI_MAGIC_EMBEDDED_HDR ) then result := true else result :=false; //analyze end; function IsNIfTIHdrExt (var lFName: string):boolean; var lExt: string; begin lExt := UpCaseExt(lFName); if (lExt='.NII') or (lExt = '.HDR') or (lExt = '.NII.GZ') or (lExt = '.VOI') then result := true else result := false; end; function ComputeImageDataBytes32bpp (var lHdr: TMRIcroHdr): integer; var lDim, lBytes : integer; begin //result := 0; with lHdr.NIFTIhdr do begin if Dim[0] < 1 then begin showmessage('NIFTI format error: datasets must have at least one dimension (dim[0] < 1).'); Dim[0] := 3; //exit; end; lBytes := 4; //bits per voxel for lDim := 1 to 3 {Dim[0]} do lBytes := lBytes * Dim[lDim]; end; //with niftihdr result := lBytes; //+7 to ensure binary data not clipped end; //func ComputeImageDataBytes32bpp function ComputeImageDataBytes8bpp (var lHdr: TMRIcroHdr): integer; var lDim, lBytes : integer; begin result := 0; with lHdr.NIFTIhdr do begin if Dim[0] < 1 then begin showmessage('NIFTI format error: datasets must have at least one dimension (dim[0] < 1).'); exit; end; lBytes := 1; //bits per voxel for lDim := 1 to 3 {Dim[0]} do lBytes := lBytes * Dim[lDim]; end; //with niftihdr result := lBytes; end; //func ComputeImageDataBytes8bpp function ComputeImageDataBytes (var lHdr: TMRIcroHdr): integer; var lDim : integer; lSzInBits : Int64; begin result := 0; with lHdr.NIFTIhdr do begin if Dim[0] < 1 then begin showmessage('NIFTI format error: datasets must have at least one dimension (dim[0] < 1).'); exit; end; lSzInBits := bitpix; //bits per voxel //showmessage(inttostr(Dim[0])); for lDim := 1 to 3 {Dim[0]} do lSzInBits := lSzInBits * Dim[lDim]; end; //with niftihdr result := (lSzInBits + 7) div 8; //+7 to ensure binary data not clipped end; //func ComputeImageDataBytes function orthogonalMatrix(var lHdr: TMRIcroHdr): boolean; var lM: TMatrix; lRow,lCol,lN0: integer; begin result := false; lM := Matrix3D ( lHdr.NIFTIhdr.srow_x[0],lHdr.NIFTIhdr.srow_x[1],lHdr.NIFTIhdr.srow_x[2],lHdr.NIFTIhdr.srow_x[3], lHdr.NIFTIhdr.srow_y[0],lHdr.NIFTIhdr.srow_y[1],lHdr.NIFTIhdr.srow_y[2],lHdr.NIFTIhdr.srow_y[3], lHdr.NIFTIhdr.srow_z[0],lHdr.NIFTIhdr.srow_z[1],lHdr.NIFTIhdr.srow_z[2],lHdr.NIFTIhdr.srow_z[3]); for lRow := 1 to 3 do begin lN0 := 0; for lCol := 1 to 3 do if lM.matrix[lRow,lCol] = 0 then inc(lN0); if lN0 <> 2 then exit; //exactly two values are zero end; for lCol := 1 to 3 do begin lN0 := 0; for lRow := 1 to 3 do if lM.matrix[lRow,lCol] = 0 then inc(lN0); if lN0 <> 2 then exit; //exactly two values are zero end; result := true; end; procedure showmat(lMat: TMatrix); begin clipboard.AsText:= format('o=[%g %g %g %g; %g %g %g %g; %g %g %g %g; 0 0 0 1]',[ lMat.matrix[1,1], lMat.matrix[1,2], lMat.matrix[1,3], lMat.matrix[1,4], lMat.matrix[2,1], lMat.matrix[2,2], lMat.matrix[2,3], lMat.matrix[2,4], lMat.matrix[3,1], lMat.matrix[3,2], lMat.matrix[3,3], lMat.matrix[3,4] ]); end; function EmptyMatrix(var lHdr: TMRIcroHdr): boolean; var lM: TMatrix; lRow,lCol: integer; isUnity: boolean; begin result := false; lM := Matrix3D ( lHdr.NIFTIhdr.srow_x[0],lHdr.NIFTIhdr.srow_x[1],lHdr.NIFTIhdr.srow_x[2],lHdr.NIFTIhdr.srow_x[3], lHdr.NIFTIhdr.srow_y[0],lHdr.NIFTIhdr.srow_y[1],lHdr.NIFTIhdr.srow_y[2],lHdr.NIFTIhdr.srow_y[3], lHdr.NIFTIhdr.srow_z[0],lHdr.NIFTIhdr.srow_z[1],lHdr.NIFTIhdr.srow_z[2],lHdr.NIFTIhdr.srow_z[3]); isUnity := true; for lRow := 1 to 3 do begin {3/2008} for lCol := 1 to 4 do begin if (lRow = lCol) then begin if lM.matrix[lRow,lCol] <> 1 then isUnity := false; end else begin if lM.matrix[lRow,lCol] <> 0 then isUnity := false; end// unity matrix does not count - mriconvert creates bogus [1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 0] end; //each col end;//each row if isUnity then exit; for lRow := 1 to 3 do begin {3/2008} for lCol := 1 to 4 do begin if lM.matrix[lRow,lCol] <> 0 then exit; end; //each col end;//each row (* for lRow := 1 to 3 do for lCol := 1 to 4 do if lM.matrix[lRow,lCol] <> 0 then exit;*) result := true; end; procedure nifti_quatern_to_mat44( out lR :TMatrix; var qb, qc, qd, qx, qy, qz, dx, dy, dz, qfac : single); var a,b,c,d,xd,yd,zd: double; begin //a := qb; b := qb; c := qc; d := qd; //* last row is always [ 0 0 0 1 ] */ lR.matrix[4,1] := 0; lR.matrix[4,2] := 0; lR.matrix[4,3] := 0; lR.matrix[4,4] := 1; //* compute a parameter from b,c,d */ a := 1.0 - (b*b + c*c + d*d) ; if( a < 1.e-7 ) then begin//* special case */ a := 1.0 / sqrt(b*b+c*c+d*d) ; b := b*a ; c := c*a ; d := d*a ;//* normalize (b,c,d) vector */ a := 0.0 ;//* a = 0 ==> 180 degree rotation */ end else begin a := sqrt(a) ; //* angle = 2*arccos(a) */ end; //* load rotation matrix, including scaling factors for voxel sizes */ if dx > 0 then xd := dx else xd := 1; if dy > 0 then yd := dy else yd := 1; if dz > 0 then zd := dz else zd := 1; if( qfac < 0.0 ) then zd := -zd ;//* left handedness? */ lR.matrix[1,1]:= (a*a+b*b-c*c-d*d) * xd ; lR.matrix[1,2]:= 2.0 * (b*c-a*d ) * yd ; lR.matrix[1,3]:= 2.0 * (b*d+a*c ) * zd ; lR.matrix[2,1]:= 2.0 * (b*c+a*d ) * xd ; lR.matrix[2,2]:= (a*a+c*c-b*b-d*d) * yd ; lR.matrix[2,3]:= 2.0 * (c*d-a*b ) * zd ; lR.matrix[3,1]:= 2.0 * (b*d-a*c ) * xd ; lR.matrix[3,2]:= 2.0 * (c*d+a*b ) * yd ; lR.matrix[3,3]:= (a*a+d*d-c*c-b*b) * zd ; //* load offsets */ lR.matrix[1,4]:= qx ; lR.matrix[2,4]:= qy ; lR.matrix[3,4]:= qz ; end; function HasQuat( var lHdr: TNIfTIHdr ): boolean; //var lR :TMatrix; begin result := false; if (lHdr.qform_code <= kNIFTI_XFORM_UNKNOWN) or (lHdr.qform_code > kNIFTI_XFORM_MNI_152) then exit; result := true; end; function Quat2Mat( var lHdr: TNIfTIHdr ): boolean; var lR :TMatrix; begin result := false; if (lHdr.qform_code <= kNIFTI_XFORM_UNKNOWN) or (lHdr.qform_code > kNIFTI_XFORM_MNI_152) then exit; result := true; nifti_quatern_to_mat44(lR,lHdr.quatern_b,lHdr.quatern_c,lHdr.quatern_d, lHdr.qoffset_x,lHdr.qoffset_y,lHdr.qoffset_z, lHdr.pixdim[1],lHdr.pixdim[2],lHdr.pixdim[3], lHdr.pixdim[0]); lHdr.srow_x[0] := lR.matrix[1,1]; lHdr.srow_x[1] := lR.matrix[1,2]; lHdr.srow_x[2] := lR.matrix[1,3]; lHdr.srow_x[3] := lR.matrix[1,4]; lHdr.srow_y[0] := lR.matrix[2,1]; lHdr.srow_y[1] := lR.matrix[2,2]; lHdr.srow_y[2] := lR.matrix[2,3]; lHdr.srow_y[3] := lR.matrix[2,4]; lHdr.srow_z[0] := lR.matrix[3,1]; lHdr.srow_z[1] := lR.matrix[3,2]; lHdr.srow_z[2] := lR.matrix[3,3]; lHdr.srow_z[3] := lR.matrix[3,4]; lHdr.sform_code := 1; showmat(lR); end; function nifti_mat33_determ( R: TMatrix ):double; //* determinant of 3x3 matrix */ begin result := r.matrix[1,1]*r.matrix[2,2]*r.matrix[3,3] -r.matrix[1,1]*r.matrix[3,2]*r.matrix[2,3] -r.matrix[2,1]*r.matrix[1,2]*r.matrix[3,3] +r.matrix[2,1]*r.matrix[3,2]*r.matrix[1,3] +r.matrix[3,1]*r.matrix[1,2]*r.matrix[2,3] -r.matrix[3,1]*r.matrix[2,2]*r.matrix[1,3] ; end; function nifti_mat33_rownorm( A: TMatrix ): single; //* max row norm of 3x3 matrix */ var r1,r2,r3: single ; begin r1 := abs(A.matrix[1,1])+abs(A.matrix[1,2])+abs(A.matrix[1,3]) ; r2 := abs(A.matrix[2,1])+abs(A.matrix[2,2])+abs(A.matrix[2,3]) ; r3 := abs(A.matrix[3,1])+abs(A.matrix[3,2])+abs(A.matrix[3,3]) ; if( r1 < r2 ) then r1 := r2 ; if( r1 < r3 ) then r1 := r3 ; result := r1 ; end; function nifti_mat33_colnorm( A: TMatrix ): single; //* max column norm of 3x3 matrix */ var r1,r2,r3: single ; begin r1 := abs(A.matrix[1,1])+abs(A.matrix[2,1])+abs(A.matrix[3,1]) ; r2 := abs(A.matrix[1,2])+abs(A.matrix[2,2])+abs(A.matrix[3,2]) ; r3 := abs(A.matrix[1,3])+abs(A.matrix[2,3])+abs(A.matrix[3,3]) ; if( r1 < r2 ) then r1 := r2 ; if( r1 < r3 ) then r1 := r3 ; result := r1 ; end; function nifti_mat33_inverse( R: TMatrix ): TMatrix; //* inverse of 3x3 matrix */ var r11,r12,r13,r21,r22,r23,r31,r32,r33 , deti: double ; Q: TMatrix ; begin FromMatrix(R,r11,r12,r13,r21,r22,r23,r31,r32,r33); deti := r11*r22*r33-r11*r32*r23-r21*r12*r33 +r21*r32*r13+r31*r12*r23-r31*r22*r13 ; if( deti <> 0.0 ) then deti := 1.0 / deti ; Q.matrix[1,1] := deti*( r22*r33-r32*r23) ; Q.matrix[1,2] := deti*(-r12*r33+r32*r13) ; Q.matrix[1,3] := deti*( r12*r23-r22*r13) ; Q.matrix[2,1] := deti*(-r21*r33+r31*r23) ; Q.matrix[2,2] := deti*( r11*r33-r31*r13) ; Q.matrix[2,3] := deti*(-r11*r23+r21*r13) ; Q.matrix[3,1] := deti*( r21*r32-r31*r22) ; Q.matrix[3,2] := deti*(-r11*r32+r31*r12) ; Q.matrix[3,3] := deti*( r11*r22-r21*r12) ; result := Q; end; function nifti_mat33_polar( A: TMatrix ): TMatrix; var dif: single; k: integer; X , Y , Z: TMatrix ; alp,bet,gam,gmi : single; begin dif:=1.0 ; k:=0 ; X := A ; // force matrix to be nonsingular //reportmatrix('x',X); gam := nifti_mat33_determ(X) ; while( gam = 0.0 )do begin //perturb matrix gam := 0.00001 * ( 0.001 + nifti_mat33_rownorm(X) ) ; X.matrix[1,1] := X.matrix[1,1]+gam ; X.matrix[2,2] := X.matrix[2,2]+gam ; X.matrix[3,3] := X.matrix[3,3] +gam ; gam := nifti_mat33_determ(X) ; end; while true do begin Y := nifti_mat33_inverse(X) ; if( dif > 0.3 )then begin // far from convergence alp := sqrt( nifti_mat33_rownorm(X) * nifti_mat33_colnorm(X) ) ; bet := sqrt( nifti_mat33_rownorm(Y) * nifti_mat33_colnorm(Y) ) ; gam := sqrt( bet / alp ) ; gmi := 1.0 / gam ; end else begin gam := 1.0; gmi := 1.0 ; //close to convergence end; Z.matrix[1,1] := 0.5 * ( gam*X.matrix[1,1] + gmi*Y.matrix[1,1] ) ; Z.matrix[1,2] := 0.5 * ( gam*X.matrix[1,2] + gmi*Y.matrix[2,1] ) ; Z.matrix[1,3] := 0.5 * ( gam*X.matrix[1,3] + gmi*Y.matrix[3,1] ) ; Z.matrix[2,1] := 0.5 * ( gam*X.matrix[2,1] + gmi*Y.matrix[1,2] ) ; Z.matrix[2,2] := 0.5 * ( gam*X.matrix[2,2] + gmi*Y.matrix[2,2] ) ; Z.matrix[2,3] := 0.5 * ( gam*X.matrix[2,3] + gmi*Y.matrix[3,2] ) ; Z.matrix[3,1] := 0.5 * ( gam*X.matrix[3,1] + gmi*Y.matrix[1,3] ) ; Z.matrix[3,2] := 0.5 * ( gam*X.matrix[3,2] + gmi*Y.matrix[2,3] ) ; Z.matrix[3,3] := 0.5 * ( gam*X.matrix[3,3] + gmi*Y.matrix[3,3] ) ; dif := abs(Z.matrix[1,1]-X.matrix[1,1])+abs(Z.matrix[1,2]-X.matrix[1,2]) +abs(Z.matrix[1,3]-X.matrix[1,3])+abs(Z.matrix[2,1]-X.matrix[2,1]) +abs(Z.matrix[2,2]-X.matrix[2,2])+abs(Z.matrix[2,3]-X.matrix[2,3]) +abs(Z.matrix[3,1]-X.matrix[3,1])+abs(Z.matrix[3,2]-X.matrix[3,2]) +abs(Z.matrix[3,3]-X.matrix[3,3]) ; k := k+1 ; if( k > 100) or (dif < 3.e-6 ) then begin result := Z; break ; //convergence or exhaustion end; X := Z ; end; result := Z ; end; procedure nifti_mat44_to_quatern( lR :TMatrix; var qb, qc, qd, qx, qy, qz, dx, dy, dz, qfac : single); var r11,r12,r13 , r21,r22,r23 , r31,r32,r33, xd,yd,zd , a,b,c,d : double; P,Q: TMatrix; //3x3 begin (* offset outputs are read write out of input matrix *) qx := lR.matrix[1,4]; qy := lR.matrix[2,4]; qz := lR.matrix[3,4]; (* load 3x3 matrix into local variables *) FromMatrix(lR,r11,r12,r13,r21,r22,r23,r31,r32,r33); (* compute lengths of each column; these determine grid spacings *) xd := sqrt( r11*r11 + r21*r21 + r31*r31 ) ; yd := sqrt( r12*r12 + r22*r22 + r32*r32 ) ; zd := sqrt( r13*r13 + r23*r23 + r33*r33 ) ; (* if a column length is zero, patch the trouble *) if( xd = 0.0 )then begin r11 := 1.0 ; r21 := 0; r31 := 0.0 ; xd := 1.0 ; end; if( yd = 0.0 )then begin r22 := 1.0 ; r12 := 0; r32 := 0.0 ; yd := 1.0 ; end; if( zd = 0.0 )then begin r33 := 1.0 ; r13 := 0; r23 := 0.0 ; zd := 1.0 ; end; (* assign the output lengths *) dx := xd; dy := yd; dz := zd; (* normalize the columns *) r11 := r11/xd ; r21 := r21/xd ; r31 := r31/xd ; r12 := r12/yd ; r22 := r22/yd ; r32 := r32/yd ; r13 := r13/zd ; r23 := r23/zd ; r33 := r33/zd ; (* At this point, the matrix has normal columns, but we have to allow for the fact that the hideous user may not have given us a matrix with orthogonal columns. So, now find the orthogonal matrix closest to the current matrix. One reason for using the polar decomposition to get this orthogonal matrix, rather than just directly orthogonalizing the columns, is so that inputting the inverse matrix to R will result in the inverse orthogonal matrix at this point. If we just orthogonalized the columns, this wouldn't necessarily hold. *) Q := Matrix2D (r11,r12,r13, // 2D "graphics" matrix r21,r22,r23, r31,r32,r33); P := nifti_mat33_polar(Q) ; (* P is orthog matrix closest to Q *) FromMatrix(P,r11,r12,r13,r21,r22,r23,r31,r32,r33); (* [ r11 r12 r13 ] *) (* at this point, the matrix [ r21 r22 r23 ] is orthogonal *) (* [ r31 r32 r33 ] *) (* compute the determinant to determine if it is proper *) zd := r11*r22*r33-r11*r32*r23-r21*r12*r33 +r21*r32*r13+r31*r12*r23-r31*r22*r13 ; (* should be -1 or 1 *) if( zd > 0 )then begin (* proper *) qfac := 1.0 ; end else begin (* improper ==> flip 3rd column *) qfac := -1.0 ; r13 := -r13 ; r23 := -r23 ; r33 := -r33 ; end; (* now, compute quaternion parameters *) a := r11 + r22 + r33 + 1.0; if( a > 0.5 ) then begin (* simplest case *) a := 0.5 * sqrt(a) ; b := 0.25 * (r32-r23) / a ; c := 0.25 * (r13-r31) / a ; d := 0.25 * (r21-r12) / a ; end else begin (* trickier case *) xd := 1.0 + r11 - (r22+r33) ; (* 4*b*b *) yd := 1.0 + r22 - (r11+r33) ; (* 4*c*c *) zd := 1.0 + r33 - (r11+r22) ; (* 4*d*d *) if( xd > 1.0 ) then begin b := 0.5 * sqrt(xd) ; c := 0.25* (r12+r21) / b ; d := 0.25* (r13+r31) / b ; a := 0.25* (r32-r23) / b ; end else if( yd > 1.0 ) then begin c := 0.5 * sqrt(yd) ; b := 0.25* (r12+r21) / c ; d := 0.25* (r23+r32) / c ; a := 0.25* (r13-r31) / c ; end else begin d := 0.5 * sqrt(zd) ; b := 0.25* (r13+r31) / d ; c := 0.25* (r23+r32) / d ; a := 0.25* (r21-r12) / d ; end; if( a < 0.0 )then begin b:=-b ; c:=-c ; d:=-d; {a:=-a; not used} end; end; qb := b ; qc := c ; qd := d ; end; procedure FixCrapMat(var lMat: TMatrix); var lVec000,lVec100,lVec010,lVec001: TVector; begin lVec000 := Vec3D (0, 0, 0); lVec100 := Vec3D (1, 0, 0); lVec010 := Vec3D (0, 1, 0); lVec001 := Vec3D (0, 0, 1); lVec000 := Transform3D (lVec000, lMat); lVec100 := Transform3D (lVec100, lMat); lVec010 := Transform3D (lVec010, lMat); lVec001 := Transform3D (lVec001, lMat); if SameVec(lVec000,lVec100) or SameVec(lVec000,lVec010) or SameVec(lVec000,lVec001) then begin lMat := eye3D; showmessage('Warning: the transformation matrix is corrupt [some dimensions have zero size]'); end; end; procedure Mat2Hdr(var lMat: TMatrix; var lHdr: TNIFTIhdr); begin lHdr.srow_x[0]:= lMat.matrix[1,1]; lHdr.srow_x[1] := lMat.matrix[1,2]; lHdr.srow_x[2] := lMat.matrix[1,3]; lHdr.srow_x[3] := lMat.matrix[1,4]; lHdr.srow_y[0]:= lMat.matrix[2,1]; lHdr.srow_y[1] := lMat.matrix[2,2]; lHdr.srow_y[2] := lMat.matrix[2,3]; lHdr.srow_y[3] := lMat.matrix[2,4]; lHdr.srow_z[0]:= lMat.matrix[3,1]; lHdr.srow_z[1] := lMat.matrix[3,2]; lHdr.srow_z[2] := lMat.matrix[3,3]; lHdr.srow_z[3] := lMat.matrix[3,4]; end; procedure MatFlipYZ(var lMat: TMatrix; var lHdr: TNIFTIhdr); var lRot: TMatrix; lOrigin: TVector; begin lOrigin := Vec3D (lMat.matrix[1,4], lMat.matrix[2,4], lMat.matrix[3,4]); lMat.matrix[1,4] := 0; lMat.matrix[2,4] := 0; lMat.matrix[3,4] := 0; // lRot := Matrix3D(1,0,0,0, 0,0,1,0, 0,1,0,0); lMat := multiplymatrices(lMat, lRot); lMat.matrix[1,4] := lOrigin.vector[1]; lMat.matrix[2,4] := lOrigin.vector[3]; lMat.matrix[3,4] := lOrigin.vector[2]; // //GLForm1.Caption := 'xxx'+inttostr(random(888)); (*clipboard.AsText:= format('x=[%g %g %g %g; %g %g %g %g; %g %g %g %g; 0 0 0 1]',[ lMat.matrix[1,1], lMat.matrix[1,2], lMat.matrix[1,3], lMat.matrix[1,4], lMat.matrix[2,1], lMat.matrix[2,2], lMat.matrix[2,3], lMat.matrix[2,4], lMat.matrix[3,1], lMat.matrix[3,2], lMat.matrix[3,3], lMat.matrix[3,4] ]); *) Mat2Hdr(lMat,lHdr); end; function FixDataType (var lHdr: TNIFTIhdr): boolean; overload; label 191; var ldatatypebpp,lbitpix: integer; begin result := true; lbitpix := lHdr.bitpix; case lHdr.datatype of kDT_BINARY : ldatatypebpp := 1; kDT_UNSIGNED_CHAR : ldatatypebpp := 8; // unsigned char (8 bits/voxel) kDT_SIGNED_SHORT : ldatatypebpp := 16; // signed short (16 bits/voxel) kDT_SIGNED_INT : ldatatypebpp := 32; // signed int (32 bits/voxel) kDT_FLOAT : ldatatypebpp := 32; // float (32 bits/voxel) kDT_COMPLEX : ldatatypebpp := 64; // complex (64 bits/voxel) kDT_DOUBLE : ldatatypebpp := 64; // double (64 bits/voxel) kDT_RGB : ldatatypebpp := 24; // RGB triple (24 bits/voxel) kDT_INT8 : ldatatypebpp := 8; // signed char (8 bits) kDT_UINT16 : ldatatypebpp := 16; // unsigned short (16 bits) kDT_UINT32 : ldatatypebpp := 32; // unsigned int (32 bits) kDT_INT64 : ldatatypebpp := 64; // long long (64 bits) kDT_UINT64 : ldatatypebpp := 64; // unsigned long long (64 bits) kDT_FLOAT128 : ldatatypebpp := 128; // long double (128 bits) kDT_COMPLEX128 : ldatatypebpp := 128; // double pair (128 bits) kDT_COMPLEX256 : ldatatypebpp := 256; // long double pair (256 bits) else ldatatypebpp := 0; end; if (ldatatypebpp = lHdr.bitpix) and (ldatatypebpp <> 0) then exit; //showmessage(inttostr(ldatatypebpp)); if (ldatatypebpp <> 0) then begin //use bitpix from datatype... lHdr.bitpix := ldatatypebpp; exit; end; if (lbitpix <> 0) and (ldatatypebpp = 0) then begin //assume bitpix is correct.... //note that several datatypes correspond to each bitpix, so assume most popular... case lbitpix of 1: lHdr.datatype := kDT_BINARY; 8: lHdr.datatype := kDT_UNSIGNED_CHAR; 16: lHdr.datatype := kDT_SIGNED_SHORT; 24: lHdr.datatype := kDT_RGB; 32: lHdr.datatype := kDT_FLOAT; 64: lHdr.datatype := kDT_DOUBLE; else goto 191; //impossible bitpix end; exit; end; 191: //Both bitpix and datatype are wrong... assume most popular format result := false; lHdr.bitpix := 16; lHdr.datatype := kDT_SIGNED_SHORT; end; function FixDataType (var lHdr: TMRIcroHdr): boolean; overload; begin result := FixDataType(lHdr.NIFTIhdr); end; procedure SwapNifti2(var h: TNIFTI2hdr); var i: integer; begin h.HdrSz := swap(h.HdrSz); h.datatype := swap(h.datatype); h.bitpix := swap(h.bitpix); for i := 0 to 7 do h.dim[i] := swap(h.dim[i]); h.intent_p1 := swap64r(h.intent_p1); h.intent_p2 := swap64r(h.intent_p2); h.intent_p3 := swap64r(h.intent_p3); for i := 0 to 7 do h.pixdim[i] := swap64r(h.pixdim[i]); h.vox_offset := swap(h.vox_offset); h.scl_slope := swap64r(h.scl_slope); h.scl_inter := swap64r(h.scl_inter); h.cal_max := swap64r(h.cal_max); h.cal_min := swap64r(h.cal_min); h.slice_duration := swap64r(h.slice_duration); h.toffset := swap64r(h.toffset); h.slice_start := swap(h.slice_start); h.slice_end := swap(h.slice_end); h.qform_code := swap(h.qform_code); h.sform_code := swap(h.sform_code); h.quatern_b := swap64r(h.quatern_b); h.quatern_c := swap64r(h.quatern_c); h.quatern_d := swap64r(h.quatern_d); h.qoffset_x := swap64r(h.qoffset_x); h.qoffset_y := swap64r(h.qoffset_y); h.qoffset_z := swap64r(h.qoffset_z); for i := 0 to 3 do begin h.srow_x[i] := swap64r(h.srow_x[i]); h.srow_y[i] := swap64r(h.srow_y[i]); h.srow_z[i] := swap64r(h.srow_z[i]); end; h.slice_code := swap(h.slice_code); h.xyzt_units := swap(h.xyzt_units); h.intent_code := swap(h.intent_code); end; function LoadNifti2(var lFilename: string; isGz: boolean): TNIFTIhdr; var lHdr1: TNIFTIhdr; lHdr2: TNIFTI2hdr; i: integer; lHdrFile: file; lBuff: Bytep; begin FileMode := 0; { Set file access to read only } if (isGz) then begin lBuff := @lHdr2; UnGZip(lFileName,lBuff,0,sizeof(TNIFTI2hdr)); end else begin {$I-} AssignFile(lHdrFile, lFileName); FileMode := 0; { Set file access to read only } Reset(lHdrFile, 1); {$I+} if ioresult <> 0 then begin ShowMessage('Error in reading NIFTI header.'+inttostr(IOResult)); FileMode := 2; exit; end; BlockRead(lHdrFile, lHdr2, sizeof(TNIFTI2hdr)); CloseFile(lHdrFile); end; FileMode := 2; //swap if lHdr2.HdrSz <> sizeof(TNIFTI2hdr) then SwapNifti2(lHdr2); //FILL NIFTI-1 header with NIFTI-2 lHdr1.HdrSz := sizeof(TNIFTIhdr); lHdr1.magic := kNIFTI_MAGIC_EMBEDDED_HDR; lHdr1.datatype := lHdr2.datatype; lHdr1.bitpix := lHdr2.bitpix; for i := 0 to 7 do begin if (lHdr2.dim[i] > 32767) then lHdr2.dim[i] := 32767; lHdr1.dim[i] := lHdr2.dim[i]; end; lHdr1.intent_p1 := lHdr2.intent_p1; lHdr1.intent_p2 := lHdr2.intent_p2; lHdr1.intent_p3 := lHdr2.intent_p3; for i := 0 to 7 do lHdr1.pixdim[i] := lHdr2.pixdim[i]; lHdr1.vox_offset := lHdr2.vox_offset; lHdr1.scl_slope := lHdr2.scl_slope; lHdr1.scl_inter := lHdr2.scl_inter; lHdr1.cal_max := lHdr2.cal_max; lHdr1.cal_min := lHdr2.cal_min; lHdr1.slice_duration := lHdr2.slice_duration; lHdr1.toffset := lHdr2.toffset; lHdr1.slice_start := lHdr2.slice_start; lHdr1.slice_end := lHdr2.slice_end; for i := 1 to 80 do lHdr1.descrip[i] := lHdr2.descrip[i]; for i := 1 to 24 do lHdr1.aux_file[i] := lHdr2.aux_file[i]; lHdr1.qform_code := lHdr2.qform_code; lHdr1.sform_code := lHdr2.sform_code; lHdr1.quatern_b := lHdr2.quatern_b; lHdr1.quatern_c := lHdr2.quatern_c; lHdr1.quatern_d := lHdr2.quatern_d; lHdr1.qoffset_x := lHdr2.qoffset_x; lHdr1.qoffset_y := lHdr2.qoffset_y; lHdr1.qoffset_z := lHdr2.qoffset_z; for i := 0 to 3 do begin lHdr1.srow_x[i] := lHdr2.srow_x[i]; lHdr1.srow_y[i] := lHdr2.srow_y[i]; lHdr1.srow_z[i] := lHdr2.srow_z[i]; end; lHdr1.slice_code := lHdr2.slice_code; lHdr1.xyzt_units := lHdr2.xyzt_units; lHdr1.intent_code := lHdr2.intent_code; for i := 1 to 16 do lHdr1.intent_name[i] := lHdr2.intent_name[i]; lHdr1.dim_info := lHdr2.dim_info; //removed fields https://brainder.org/2015/04/03/the-nifti-2-file-format/ for i := 1 to 10 do lHdr1.data_type[i] := chr(0); for i := 1 to 16 do lHdr1.db_name[i] := chr(0); lHdr1.extents := 0; lHdr1.session_error := 0; lHdr1.regular := 'r'; lHdr1.glmax := 0; lHdr1.glmin := 0; result := lHdr1; end; function NIFTIhdr_LoadHdr (var lFilename: string; out lHdr: TMRIcroHdr; lFlipYZ: boolean): boolean; var lHdrFile: file; lOri: array [1..3] of single; lBuff: Bytep; lAHdr: TAnalyzeHdrSection; lHdrSz,lReportedSz, lSwappedReportedSz: integer; lFileSz: Int64; lExt: string; //1494 swapEndian, isDimPermute2341: boolean; begin Result := false; //assume error swapEndian := false; isDimPermute2341 := false; NIFTIhdr_ClearHdr(lHdr); if lFilename = '' then exit; lExt := UpCaseExt(lFilename); lHdr.ImgFileName:= lFilename; if (lExt = '.HDR') then lHdr.ImgFileName:= changefileext(lFilename,'.img'); if lExt = '.IMG' then begin lHdr.ImgFileName := lFilename; lFilename := changeFileExt(lFilename,'.hdr'); end; if (lExt = '.BRIK') or (lExt='.BRIK.GZ') then lFilename := changeFileExtX(lFilename,'.head'); if not FileExistsEX(lFilename) then exit; lHdr.HdrFileName:= lFilename; if (lExt <> '.IMG') and (lExt <> '.NII') and (lExt <> '.VOI') and (lExt <> '.HDR') and (lExt <> '.NII.GZ') then begin result := readForeignHeader (lFilename, lHdr.NIFTIhdr, lHdr.gzBytes, swapEndian, isDimPermute2341); lHdr.ImgFileName := lfilename; lfilename := lHdr.HdrFileName; //expects filename to be header not image! lHdr.DiskDataNativeEndian := not swapEndian; exit; end else if (lExt = '.NII.GZ') or (lExt = '.VOI') then lHdr.gzBytes := K_gzBytes_headerAndImageCompressed; lHdrSz := sizeof(TniftiHdr); lFileSz := FSize (lFilename); if lFileSz = 0 then begin ShowMessage('Unable to find NIFTI header named '+lFilename); exit; end; if (lFileSz < lHdrSz) and (lHdr.gzBytes = K_gzBytes_headerAndImageUncompressed) then begin ShowMessage('Error in reading NIFTI header: NIfTI headers need to be at least '+inttostr(lHdrSz)+ ' bytes: '+lFilename); exit; end; FileMode := 0; { Set file access to read only } if (lHdr.gzBytes <> K_gzBytes_headerAndImageUncompressed) then begin//1388 lBuff := @lHdr; UnGZip(lFileName,lBuff,0,lHdrSz); end else begin //if gzip {$I-} AssignFile(lHdrFile, lFileName); FileMode := 0; { Set file access to read only } Reset(lHdrFile, 1); {$I+} if ioresult <> 0 then begin ShowMessage('Error in reading NIFTI header.'+inttostr(IOResult)); FileMode := 2; exit; end; BlockRead(lHdrFile, lHdr, lHdrSz); CloseFile(lHdrFile); end; FileMode := 2; if (IOResult <> 0) then exit; lReportedSz := lHdr.niftiHdr.HdrSz; lSwappedReportedSz := lReportedSz; swap4(lSwappedReportedSz); if lReportedSz = lHdrSz then begin lHdr.DiskDataNativeEndian := true; end else if lSwappedReportedSz = lHdrSz then begin lHdr.DiskDataNativeEndian := false; NIFTIhdr_SwapBytes (lHdr.niftiHdr); end else if (lReportedSz = 540) or (lSwappedReportedSz = 540) then begin lHdr.niftiHdr := LoadNifti2(lFilename, (lHdr.gzBytes <> K_gzBytes_headerAndImageUncompressed)); lHdr.DiskDataNativeEndian := (lReportedSz = 540); end else begin //result := NIFTIhdr_LoadDCM (lFilename,lHdr); //2/2008 //if not result then ShowMessage('Warning: the header file is not in NIfTi format [the first 4 bytes do not have the value 348]. Assuming big-endian data.'); exit; end; if (lHdr.NIFTIhdr.dim[0] > 7) or (lHdr.NIFTIhdr.dim[0] < 1) then begin //only 1..7 dims, so this Showmessage('Illegal NIfTI Format Header: this header does not specify 1..7 dimensions, but '+inttostr(lHdr.NIFTIhdr.dim[0])); exit; end; FixDataType(lHdr); result := true; if IsNifTiMagic(lHdr.niftiHdr) then begin //must match MAGMA in nifti_img lOri[1] := (lHdr.NIFTIhdr.dim[1]+1) div 2; lOri[2] := (lHdr.NIFTIhdr.dim[2]+1) div 2; lOri[3] := (lHdr.NIFTIhdr.dim[3]+1) div 2; if (not HasQuat(lHdr.NiftiHdr)) {3/2008} and (lHdr.NIFTIhdr.sform_code = 0) and (orthogonalMatrix(lHdr)) then lHdr.NIFTIhdr.sform_code := 1; //ShowHdr(lHdr.NIFTIHdr,3); if emptymatrix(lHdr) then begin if Quat2Mat(lHdr.NiftiHdr) then //HasQuat will specify else begin lHdr.NIFTIhdr.srow_x[0] := lHdr.NIFTIhdr.pixdim[1]; lHdr.NIFTIhdr.srow_y[1] := lHdr.NIFTIhdr.pixdim[2]; lHdr.NIFTIhdr.srow_z[2] := lHdr.NIFTIhdr.pixdim[3]; lHdr.NIFTIhdr.srow_x[3] := -lHdr.NIFTIhdr.srow_x[3]; lHdr.NIFTIhdr.srow_y[3] := -lHdr.NIFTIhdr.srow_y[3]; lHdr.NIFTIhdr.srow_z[3] := -lHdr.NIFTIhdr.srow_z[3]; lHdr.NIFTIhdr.sform_code := 1; end; end; if (lHdr.NIFTIhdr.srow_x[0] > 0) and (lHdr.NIFTIhdr.srow_y[1] > 0) and (lHdr.NIFTIhdr.srow_z[2] > 0) and (lHdr.NIFTIhdr.srow_x[3] > 0) and (lHdr.NIFTIhdr.srow_y[3] > 0) and (lHdr.NIFTIhdr.srow_z[3] > 0) then begin lHdr.NIFTIhdr.srow_x[3] := -lHdr.NIFTIhdr.srow_x[3]; lHdr.NIFTIhdr.srow_y[3] := -lHdr.NIFTIhdr.srow_y[3]; lHdr.NIFTIhdr.srow_z[3] := -lHdr.NIFTIhdr.srow_z[3]; lHdr.NIFTIhdr.sform_code := 1; end; //added 4Mar2006 -> corrects for improperly signed offset values... end else begin //not NIFT: Analyze lHdr.NIfTItransform := false; if not lHdr.DiskDataNativeEndian then begin NIFTIhdr_SwapBytes (lHdr.niftiHdr); move(lHdr.niftiHdr,lAHdr,sizeof(lAHdr)); NIFTIhdr_SwapBytes (lHdr.niftiHdr); lAHdr.Originator[1] := swap(lAHdr.Originator[1]); lAHdr.Originator[2] := swap(lAHdr.Originator[2]); lAHdr.Originator[3] := swap(lAHdr.Originator[3]); end else move(lHdr.niftiHdr,lAHdr,sizeof(lAHdr)); lOri[1] :=lAHdr.Originator[1]; lOri[2] := lAHdr.Originator[2]; lOri[3] := lAHdr.Originator[3]; if ((lOri[1]<1) or (lOri[1]> lHdr.NIFTIhdr.dim[1])) and ((lOri[2]<1) or (lOri[2]> lHdr.NIFTIhdr.dim[2])) and ((lOri[3]<1) or (lOri[3]> lHdr.NIFTIhdr.dim[3])) then begin lOri[1] := (lHdr.NIFTIhdr.dim[1]+1) div 2; lOri[2] := (lHdr.NIFTIhdr.dim[2]+1) div 2; lOri[3] := (lHdr.NIFTIhdr.dim[3]+1) div 2; end; //showmessage(inttostr(sizeof(lAHdr))+' '+realtostr(lHdr.Ori[1],1)+' '+ realtostr(lHdr.Ori[2],1)+' '+realtostr(lHdr.Ori[3],1) ); //DANGER: This header was from ANALYZE format, not NIFTI: make sure the rotation matrix is switched off //NIFTIhdr_SetIdentityMatrix(lHdr); NII_SetIdentityMatrix (lHdr.NIFTIhdr); lHdr.NIFTIhdr.qform_code := kNIFTI_XFORM_UNKNOWN; lHdr.NIFTIhdr.sform_code := kNIFTI_XFORM_UNKNOWN; //test - input estimated orientation matrix lHdr.NIFTIhdr.sform_code := kNIFTI_XFORM_SCANNER_ANAT ; lHdr.NIFTIhdr.srow_x[0] := lHdr.NIFTIhdr.pixdim[1]; lHdr.NIFTIhdr.srow_y[1] := lHdr.NIFTIhdr.pixdim[2]; lHdr.NIFTIhdr.srow_z[2] := lHdr.NIFTIhdr.pixdim[3]; lHdr.NIFTIhdr.srow_x[3] := (lOri[1]-1)*-lHdr.NIFTIhdr.pixdim[1]; lHdr.NIFTIhdr.srow_y[3] := (lOri[2]-1)*-lHdr.NIFTIhdr.pixdim[2]; lHdr.NIFTIhdr.srow_z[3] := (lOri[3]-1)*-lHdr.NIFTIhdr.pixdim[3]; //Warning: some of the NIFTI float values that do exist as integer values in Analyze may have bizarre values like +INF, -INF, NaN lHdr.NIFTIhdr.toffset := 0; lHdr.NIFTIhdr.intent_code := kNIFTI_INTENT_NONE; lHdr.NIFTIhdr.dim_info := kNIFTI_SLICE_SEQ_UNKNOWN + (kNIFTI_SLICE_SEQ_UNKNOWN shl 2) + (kNIFTI_SLICE_SEQ_UNKNOWN shl 4); //Freq, Phase and Slie all unknown lHdr.NIFTIhdr.xyzt_units := kNIFTI_UNITS_UNKNOWN; lHdr.NIFTIhdr.slice_duration := 0; //avoid +inf/-inf, NaN lHdr.NIFTIhdr.intent_p1 := 0; //avoid +inf/-inf, NaN lHdr.NIFTIhdr.intent_p2 := 0; //avoid +inf/-inf, NaN lHdr.NIFTIhdr.intent_p3 := 0; //avoid +inf/-inf, NaN lHdr.NIFTIhdr.pixdim[0] := 1; //QFactor should be 1 or -1 end; if (lHdr.NIFTIhdr.sform_code > kNIFTI_XFORM_UNKNOWN) and (lHdr.NIFTIhdr.sform_code <= kNIFTI_XFORM_MNI_152) then begin //DEC06 lHdr.Mat:= Matrix3D( lHdr.NIFTIhdr.srow_x[0],lHdr.NIFTIhdr.srow_x[1],lHdr.NIFTIhdr.srow_x[2],lHdr.NIFTIhdr.srow_x[3], lHdr.NIFTIhdr.srow_y[0],lHdr.NIFTIhdr.srow_y[1],lHdr.NIFTIhdr.srow_y[2],lHdr.NIFTIhdr.srow_y[3], lHdr.NIFTIhdr.srow_z[0],lHdr.NIFTIhdr.srow_z[1],lHdr.NIFTIhdr.srow_z[2],lHdr.NIFTIhdr.srow_z[3]); //ReportMatrix(lHdr.Mat); end else begin lHdr.Mat:= Matrix3D( lHdr.NIFTIhdr.pixdim[1],0,0,(lOri[1]-1)*-lHdr.NIFTIhdr.pixdim[1], 0,lHdr.NIFTIhdr.pixdim[2],0,(lOri[2]-1)*-lHdr.NIFTIhdr.pixdim[2], 0,0,lHdr.NIFTIhdr.pixdim[3],(lOri[3]-1)*-lHdr.NIFTIhdr.pixdim[3]); end; FixCrapMat(lHdr.Mat); if (lFlipYZ) then MatFlipYZ(lHdr.Mat, lHdr.NIFTIhdr) else Mat2Hdr(lHdr.Mat, lHdr.NIFTIhdr); end; //func NIFTIhdr_LoadHdr procedure NIFTIhdr_SetIdentityMatrix (var lHdr: TMRIcroHdr); //create neutral rotation matrix var lInc: integer; begin with lHdr.NIFTIhdr do begin for lInc := 0 to 3 do srow_x[lInc] := 0; for lInc := 0 to 3 do srow_y[lInc] := 0; for lInc := 0 to 3 do srow_z[lInc] := 0; for lInc := 1 to 16 do intent_name[lInc] := chr(0); //next: create identity matrix: if code is switched on there will not be a problem srow_x[0] := 1; srow_y[1] := 1; srow_z[2] := 1; end; end; //proc NIFTIhdr_IdentityMatrix (*procedure NIFTIhdr_ClearHdr (var lHdr: TNIfTIHdr); overload;//put sensible default values into header var lInc: byte; begin with lHdr do begin {set to 0} HdrSz := sizeof(TNIFTIhdr); for lInc := 1 to 10 do Data_Type[lInc] := chr(0); for lInc := 1 to 18 do db_name[lInc] := chr(0); extents:=0; session_error:= 0; regular:='r'{chr(0)}; dim_info:=(0); dim[0] := 4; for lInc := 1 to 7 do dim[lInc] := 0; intent_p1 := 0; intent_p2 := 0; intent_p3 := 0; intent_code:=0; datatype:=0 ; bitpix:=0; slice_start:=0; for lInc := 1 to 7 do pixdim[linc]:= 1.0; vox_offset:= 0.0; scl_slope := 1.0; scl_inter:= 0.0; slice_end:= 0; slice_code := 0; xyzt_units := 10; cal_max:= 0.0; cal_min:= 0.0; slice_duration:=0; toffset:= 0; glmax:= 0; glmin:= 0; for lInc := 1 to 80 do descrip[lInc] := chr(0);{80 spaces} for lInc := 1 to 24 do aux_file[lInc] := chr(0);{80 spaces} {below are standard settings which are not 0} bitpix := 16;//vc16; {8bits per pixel, e.g. unsigned char 136} DataType := 4;//vc4;{2=unsigned char, 4=16bit int 136} Dim[0] := 3; Dim[1] := 256; Dim[2] := 256; Dim[3] := 128; Dim[4] := 1; {n vols} Dim[5] := 1; Dim[6] := 1; Dim[7] := 1; glMin := 0; glMax := 255; qform_code := kNIFTI_XFORM_UNKNOWN; sform_code:= kNIFTI_XFORM_UNKNOWN; quatern_b := 0; quatern_c := 0; quatern_d := 0; qoffset_x := 0; qoffset_y := 0; qoffset_z := 0; magic := kNIFTI_MAGIC_SEPARATE_HDR; end; //with the NIfTI header... end; //proc NIFTIhdr_ClearHdr *) procedure NIFTIhdr_ClearHdr (out lHdr: TMRIcroHdr); overload;//put sensible default values into header begin lHdr.UsesCustomPalette := false; lHdr.RGB := false; //lHdr.NativeMM3:= 0; lHdr.DiskDataNativeEndian:= true; lHdr.NIfTItransform := true; lHdr.LutVisible := true; lHdr.LutFromZero := false; NII_Clear(lHdr.NIFTIHdr); //NIFTIhdr_ClearHdr(lHdr.NIFTIHdr); lHdr.gzBytes := K_gzBytes_headerAndImageuncompressed; NIFTIhdr_SetIdentityMatrix(lHdr); with lHdr do begin ScrnBufferItems := 0; ImgBufferItems := 0; ImgBufferBPP := 0; RenderBufferItems := 0; ScrnBuffer:= nil; ImgBuffer := nil; end; end; //proc NIFTIhdr_ClearHdr function NIFTIhdr_SaveHdr (var lFilename: string; var lHdr: TMRIcroHdr; lAllowOverwrite: boolean): boolean; overload; var lOutHdr: TNIFTIhdr; lExt: string; lF: File; lOverwrite: boolean; begin lOverwrite := false; //will we overwrite existing file? result := false; //assume failure if lHdr.NIFTIhdr.magic = kNIFTI_MAGIC_EMBEDDED_HDR then begin lExt := UpCaseExt(lFileName); if (lExt = '.GZ') or (lExt = '.NII.GZ') then begin showmessage('Unable to save .nii.gz headers (first ungzip your image if you wish to edit the header)'); exit; end; lFilename := changefileext(lFilename,'.nii') end else begin lFilename := changefileext(lFilename,'.hdr'); lHdr.NIFTIhdr.magic := kNIFTI_MAGIC_SEPARATE_HDR; end; if ((sizeof(TNIFTIhdr))> DiskFreeEx(lFileName)) then begin ShowMessage('There is not enough free space on the destination disk to save the header. '+kCR+ lFileName+ kCR+' Bytes Required: '+inttostr(sizeof(TNIFTIhdr)) ); exit; end; if Fileexists(lFileName) then begin if lAllowOverwrite then begin case MessageDlg('Do you wish to modify the existing file '+lFilename+'?', mtConfirmation,[mbYes, mbNo], 0) of { produce the message dialog box } 6: lOverwrite := true; //6= mrYes, 7=mrNo... not sure what this is for unix. Hardcoded as we do not include Form values end;//case end else showmessage('Error: the file '+lFileName+' already exists.'); if not lOverwrite then Exit; end; if lHdr.NIFTIhdr.magic = kNIFTI_MAGIC_EMBEDDED_HDR then if lHdr.NIFTIhdr.vox_offset < sizeof(TNIFTIHdr) then lHdr.NIFTIhdr.vox_offset := sizeof(TNIFTIHdr); //embedded images MUST start after header if lHdr.NIFTIhdr.magic = kNIFTI_MAGIC_SEPARATE_HDR then lHdr.NIFTIhdr.vox_offset := 0; //embedded images MUST start after header result := true; move(lHdr.NIFTIhdr, lOutHdr, sizeof(lOutHdr)); if lHdr.DiskDataNativeEndian= false then NIFTIhdr_SwapBytes (lOutHdr);{swap to big-endianformat} Filemode := 1; AssignFile(lF, lFileName); {WIN} if lOverwrite then //this allows us to modify just the 348byte header of an existing NII header without touching image data Reset(lF,sizeof(TNIFTIhdr)) else Rewrite(lF,sizeof(TNIFTIhdr)); BlockWrite(lF,lOutHdr, 1 {, NumWritten}); CloseFile(lF); Filemode := 2; end; //func NIFTIhdr_SaveHdr procedure NIFTIhdr_SwapBytes (var lAHdr: TNIFTIhdr); //Swap Byte order for the Analyze type var lInc: integer; begin with lAHdr do begin swap4(hdrsz); swap4(extents); session_error := swap2(session_error); for lInc := 0 to 7 do dim[lInc] := swap2(dim[lInc]);//666 Xswap4r(intent_p1); Xswap4r(intent_p2); Xswap4r(intent_p3); intent_code:= swap2(intent_code); datatype:= swap2(datatype); bitpix := swap2(bitpix); slice_start:= swap2(slice_start); for lInc := 0 to 7 do Xswap4r(pixdim[linc]); Xswap4r(vox_offset); {roi scale = 1} Xswap4r(scl_slope); Xswap4r(scl_inter); slice_end := swap2(slice_end); Xswap4r(cal_max); Xswap4r(cal_min); Xswap4r(slice_duration); Xswap4r(toffset); swap4(glmax); swap4(glmin); qform_code := swap2(qform_code); sform_code:= swap2(sform_code); Xswap4r(quatern_b); Xswap4r(quatern_c); Xswap4r(quatern_d); Xswap4r(qoffset_x); Xswap4r(qoffset_y); Xswap4r(qoffset_z); for lInc := 0 to 3 do //alpha Xswap4r(srow_x[lInc]); for lInc := 0 to 3 do //alpha Xswap4r(srow_y[lInc]); for lInc := 0 to 3 do //alpha Xswap4r(srow_z[lInc]); end; //with NIFTIhdr end; //proc NIFTIhdr_SwapBytes end.
unit Main; interface uses System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms, Winapi.Windows, Winapi.Messages, Vcl.StdCtrls, DirectShow9, DXSUtil, DSPack, Vcl.ExtCtrls, AdvPanel, dxGDIPlusClasses; type TfrmMain = class(TForm) shMain: TShape; pnlMain: TPanel; VideoSourceFilter: TFilter; CaptureGraph: TFilterGraph; SampleGrabber: TSampleGrabber; VideoWindow: TVideoWindow; lbImageDevice: TLabel; pnlTitle: TAdvPanel; lblTitle: TLabel; imgClose: TImage; ListBox: TListBox; ListBox2: TListBox; imgSnapshot: TImage; lblStatus: TLabel; Shape1: TShape; pnlCapture: TPanel; pnlClose: TPanel; shCapture: TShape; shClose: TShape; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure pnlTitleMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure pnlCaptureClick(Sender: TObject); procedure pnlCloseClick(Sender: TObject); procedure imgCloseClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); private { Private declarations } procedure SetImageDevice; procedure StartCapture; procedure GetSnapShot; public { Public declarations } end; var frmMain: TfrmMain; VideoDevice: TSysDevEnum; VideoMediaTypes: TEnumMediaType; implementation {$R *.dfm} procedure TfrmMain.GetSnapShot; var path: string; filename: string; begin path := ''; SampleGrabber.GetBitmap(imgSnapShot.Picture.Bitmap); path := ParamStr(1); filename := ParamStr(2) + '.bmp'; //save file if not DirectoryExists(path) then CreateDir(path); imgSnapShot.Picture.SaveToFile(path + filename); self.Close; end; procedure TfrmMain.imgCloseClick(Sender: TObject); begin Close; end; procedure TfrmMain.pnlCaptureClick(Sender: TObject); begin GetSnapshot; end; procedure TfrmMain.pnlCloseClick(Sender: TObject); begin self.Close; end; procedure TfrmMain.pnlTitleMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); const SC_DRAGMOVE = $F012; begin if Button = mbLeft then begin ReleaseCapture; Perform(WM_SYSCOMMAND, SC_DRAGMOVE, 0); end; end; procedure TfrmMain.FormCreate(Sender: TObject); var i: integer; begin VideoDevice := TSysDevEnum.Create(CLSID_VideoInputDeviceCategory); for i := 0 to VideoDevice.CountFilters - 1 do ListBox.Items.Add(VideoDevice.Filters[i].FriendlyName); VideoMediaTypes := TEnumMediaType.Create; end; procedure TfrmMain.FormKeyPress(Sender: TObject; var Key: Char); begin // escape key if Key = #27 then ModalResult := mrClose; end; procedure TfrmMain.FormShow(Sender: TObject); begin ListBox.ItemIndex := 0; SetImageDevice; end; procedure TfrmMain.SetImageDevice; var PinList: TPinList; i: integer; begin if ListBox.Items.Count = 0 then begin lblStatus.Visible := true; exit; end; VideoDevice.SelectGUIDCategory(CLSID_VideoInputDeviceCategory); if ListBox.ItemIndex <> -1 then begin // Set the device which we work with VideoSourceFilter.BaseFilter.Moniker := VideoDevice.GetMoniker(ListBox.ItemIndex); VideoSourceFilter.FilterGraph := CaptureGraph; CaptureGraph.Active := true; PinList := TPinList.Create(VideoSourceFilter as IBaseFilter); ListBox2.Clear; VideoMediaTypes.Assign(PinList.First); // Adding permission to ListBox2, which supports device for i := 0 to VideoMediaTypes.Count - 1 do ListBox2.Items.Add(VideoMediaTypes.MediaDescription[i]); CaptureGraph.Active := false; PinList.Free; ListBox2.ItemIndex := 0; StartCapture; end; end; procedure TfrmMain.StartCapture; var PinList: TPinList; begin // Activating graph filter, at this stage the source filter is added to the graph CaptureGraph.Active := true; // The configuration of the output device if VideoSourceFilter.FilterGraph <> nil then begin PinList := TPinList.Create(VideoSourceFilter as IBaseFilter); if ListBox2.ItemIndex <> -1 then with (PinList.First as IAMStreamConfig) do SetFormat(VideoMediaTypes.Items[ListBox2.ItemIndex].AMMediaType^); PinList.Free; end; // now render streams with CaptureGraph as IcaptureGraphBuilder2 do begin // Hooking up a preview video (VideoWindow) if VideoSourceFilter.BaseFilter.DataLength > 0 then RenderStream(@PIN_CATEGORY_PREVIEW, nil, VideoSourceFilter as IBaseFilter, SampleGrabber as IBaseFilter , VideoWindow as IBaseFilter); end; //Launch video CaptureGraph.Play; end; end.
unit ncaTermID; interface uses SysUtils, Classes, ncGuidUtils, Windows, ncDebug, ShlObj; procedure GetTermID; procedure RenewTermID; var gTermID: String; implementation function GetSpecialFolderPath(Folder: Integer; CanCreate: Boolean): string; // Gets path of special system folders // // Call this routine as follows: // GetSpecialFolderPath (CSIDL_PERSONAL, false) // returns folder as result // var FilePath: array [0..1024] of widechar; begin SHGetSpecialFolderPath(0, @FilePath[0], FOLDER, CanCreate); Result := FilePath; end; function NomeArq: String; begin Result := GetSpecialFolderPath(CSIDL_COMMON_APPDATA, True) + '\nex.ini'; end; function LeIni: String; var sl : TStrings; begin Result := ''; if not FileExists(NomeArq) then Exit; sl := TStringList.Create; try sl.LoadFromFile(NomeArq); Result := sl.Values['TermID']; finally sl.Free; end; end; procedure SaveIni; var sl : TStrings; begin sl := TStringList.Create; try sl.Values['TermID'] := gTermID; sl.SaveToFile(NomeArq); finally sl.Free; end; end; procedure GetTermID; begin gTermID := ''; try gTermID := LeIni; if gTermID = '' then RenewTermID; except on E: Exception do DebugMsgEsp('GetTermID - Exception: '+E.Message, False, True); end; end; procedure RenewTermID; begin gTermID := TGuidEx.ToString(TGuidEx.New); try SaveIni; except on E: Exception do DebugMsgEsp('RenewTermID - Exception: '+E.Message, False, True); end; end; initialization gTermID := ''; if SameText('novoterminal', paramstr(1)) then RenewTermID else GetTermID; end.
unit uWindows; interface uses Vcl.FileCtrl, System.SysUtils, Winapi.Windows, Vcl.Forms, ShellAPI, System.Classes, Variants, Controls, Dialogs, ComObj, ExtCtrls; procedure barraDeTarefasEsconder; procedure barraDeTarefasMostrar; //////////////////////////////////////////////////////////////////////////////// /// ARQUIVO //////////////////////////////////////////////////////////////////////////////// {Abre o Arquivo} procedure abrirArquivo(fileName: String); {Mover Arquivo} procedure moverArquivo(AFileOrigem, APathDestino: String); {Copiar Arquivo} procedure copiarArquivo(AFileOrigem, APathDestino: string); {Lista Arquivos do diretório passado} function listarArquivos(ADiretorio: String; AExtensao: string = ''): TStringList; {Abre Diálogo para selecionar um arquivo} function selecionarArquivo(AFilterText, AFilter, AExtensaoDefault, ATitulo: String; AInitialDir: string = ''; AFileName: string = ''): string; function salvarArquivo(AFilterText, AFilter, AExtensaoDefault: string; ATitulo: String = 'Salvar Como...'; AFileName: string = ''): string; function selecionarDiretorio(APath: String): string; implementation {Abre o Arquivo} procedure abrirArquivo(fileName: String); begin ShellExecute(0, 'open', PChar(fileName), nil, nil, SW_SHOW); end; {Lista Arquivos do diretório passado} function listarArquivos(ADiretorio: String; AExtensao: string = ''): TStringList; var arquivos : TStringList; search : TSearchRec; ret : Integer; begin if AExtensao = '' then AExtensao := '*'; ret := FindFirst(ADiretorio + '\*.' + AExtensao, faAnyFile, search); arquivos := TStringList.Create; try while ret = 0 do begin if (search.Name <> '.') And (search.Name <> '..') then arquivos.Add(ADiretorio + '\' + search.Name); Ret := FindNext(search); end; result := arquivos; finally //FindClose(search); end; end; {Copiar Arquivo} procedure copiarArquivo(AFileOrigem, APathDestino: string); var fileDestino: string; begin fileDestino := APathDestino + '\' + ExtractFileName(AFileOrigem); CopyFile( PChar (AFileOrigem), PChar ( fileDestino ), true); end; {Recortar Arquivo} procedure moverArquivo(AFileOrigem, APathDestino: String); var fileDestino: string; begin fileDestino := APathDestino + '\' + ExtractFileName(AFileOrigem); MoveFile( PChar( AFileOrigem ), PChar ( fileDestino ) ); // CopyFile( PChar (AFileOrigem), PChar ( fileDestino ), true); //if FileExists(fileDestino) then //DeleteFile(AFileOrigem); end; procedure barraDeTarefasMostrar; begin ShowWindow(Application.Handle, SW_HIDE); SetWindowLong(Application.Handle, GWL_EXSTYLE, WS_EX_WINDOWEDGE); ShowWindow(Application.Handle, SW_SHOW); end; procedure barraDeTarefasEsconder; begin ShowWindow(Application.Handle, SW_HIDE); SetWindowLong(Application.Handle, GWL_EXSTYLE, WS_EX_TOOLWINDOW); ShowWindow(Application.Handle, SW_SHOW); end; {Abre Diálogo para selecionar um arquivo} function selecionarArquivo(AFilterText, AFilter, AExtensaoDefault, ATitulo: String; AInitialDir: string = ''; AFileName: string = ''): string; var openDialog: TOpenDialog; begin openDialog := TOpenDialog.Create(nil); with openDialog do begin Filter := AFilterText + '|' + AFilter; Title := ATitulo; DefaultExt := AExtensaoDefault; FileName := AFileName; InitialDir := AInitialDir; end; if openDialog.Execute then AFileName := openDialog.FileName else AFileName := ''; Result := AFileName; openDialog.Free; end; function salvarArquivo(AFilterText, AFilter, AExtensaoDefault: string; ATitulo: String = 'Salvar Como...'; AFileName: string = ''): string; var saveDialog : TSaveDialog; begin saveDialog := TSaveDialog.Create(nil); with saveDialog do begin Filter := AFilterText + '|' + AFilter; Title := ATitulo; DefaultExt := AExtensaoDefault; FileName := AFileName; end; if saveDialog.Execute then AFileName := saveDialog.FileName else AFileName := ''; Result := AFileName; saveDialog.Free; end; function selecionarDiretorio(APath: String): string; var path: string; begin path := APath; SelectDirectory('Selecionar Diretório', '', path); result := path; end; end.
{**********************************************************************} {* Иллюстрация к книге "OpenGL в проектах Delphi" *} {* Краснов М.В. softgl@chat.ru *} {**********************************************************************} {/* * (c) Copyright 1993, Silicon Graphics, Inc. * 1993-1995 Microsoft Corporation * * ALL RIGHTS RESERVED */} unit frmMain; interface uses Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus, Controls, Dialogs, OpenGL; type TfrmGL = class(TForm) procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private DC: HDC; hrc: HGLRC; procedure Init; procedure SetDCPixelFormat; protected procedure WMPaint(var Msg: TWMPaint); message WM_PAINT; end; var frmGL: TfrmGL; implementation {$R *.DFM} {======================================================================= Инициализация} procedure TfrmGL.Init; begin glClearColor(0.0, 0.0, 0.0, 0.0); glClearStencil(0); glStencilMask(1); glEnable(GL_STENCIL_TEST); end; {======================================================================= Перерисовка окна} procedure TfrmGL.WMPaint(var Msg: TWMPaint); var ps : TPaintStruct; begin BeginPaint(Handle, ps); glClear( GL_COLOR_BUFFER_BIT or GL_STENCIL_BUFFER_BIT ); glStencilFunc(GL_ALWAYS, 1, 1); glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); glColor3ub(200, 0, 0); glBegin(GL_POLYGON); glVertex3i(-4, -4, 0); glVertex3i( 4, -4, 0); glVertex3i( 0, 4, 0); glEnd; glStencilFunc(GL_EQUAL, 1, 1); glStencilOp(GL_INCR, GL_KEEP, GL_DECR); glColor3ub(0, 200, 0); glBegin(GL_POLYGON); glVertex3i(3, 3, 0); glVertex3i(-3, 3, 0); glVertex3i(-3, -3, 0); glVertex3i(3, -3, 0); glEnd; glStencilFunc(GL_EQUAL, 1, 1); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); glColor3ub(0, 0, 200); glBegin(GL_POLYGON); glVertex3i(3, 3, 0); glVertex3i(-3, 3, 0); glVertex3i(-3, -3, 0); glVertex3i(3, -3, 0); glEnd; SwapBuffers(DC); EndPaint(Handle, ps); end; {======================================================================= Создание окна} procedure TfrmGL.FormCreate(Sender: TObject); begin DC := GetDC(Handle); SetDCPixelFormat; hrc := wglCreateContext(DC); wglMakeCurrent(DC, hrc); Init; end; {======================================================================= Изменение размеров окна} procedure TfrmGL.FormResize(Sender: TObject); begin glViewport(0, 0, ClientWidth, ClientHeight ); glMatrixMode(GL_PROJECTION); glLoadIdentity; glOrtho(-5.0, 5.0, -5.0, 5.0, -5.0, 5.0); glMatrixMode(GL_MODELVIEW); InvalidateRect(Handle, nil, False); end; {======================================================================= Конец работы программы} procedure TfrmGL.FormDestroy(Sender: TObject); begin wglMakeCurrent(0, 0); wglDeleteContext(hrc); ReleaseDC(Handle, DC); DeleteDC (DC); end; {======================================================================= Обработка нажатия клавиши} procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_ESCAPE then Close; end; {======================================================================= Устанавливаем формат пикселей} procedure TfrmGL.SetDCPixelFormat; var nPixelFormat: Integer; pfd: TPixelFormatDescriptor; begin FillChar(pfd, SizeOf(pfd), 0); pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; nPixelFormat := ChoosePixelFormat(DC, @pfd); SetPixelFormat(DC, nPixelFormat, @pfd); end; end.
UNIT ZugriffszahlenUnit; INTERFACE const IP4MAX = 4; type IpAddr = array[1..IP4MAX] of byte; IPAddrNodePtr = ^IPAddrNode; IPAddrNode = record prev, next: IPAddrNodePtr; addr: IpAddr; count: integer; end; (* RECORD *) IPAddrList = IPAddrNodePtr; PROCEDURE ReadIP(ipStr: string; var ip: IpAddr); PROCEDURE WriteIP(ip: IpAddr); PROCEDURE Append(var l: IpAddrList; n: IPAddrNodePtr); PROCEDURE Prepend(var l: IpAddrList; n: IPAddrNodePtr); FUNCTION FindNode(l: IpAddrList; x: IpAddr): IPAddrNodePtr; PROCEDURE InsertSorted(var l: IpAddrList; n: IPAddrNodePtr); PROCEDURE InitList(var l: IpAddrList); FUNCTION NewNode(x: IpAddr): IPAddrNodePtr; PROCEDURE NewAccess(var l: IPAddrList; x: IpAddr); PROCEDURE WriteList(l: IPAddrList); IMPLEMENTATION FUNCTION IsSmaller(a, b: IPAddr): boolean; BEGIN if a[1] < b[1] then begin IsSmaller := true; end else if a[1] = b[1] then begin if a[2] < b[2] then begin IsSmaller := true; end else if a[2] = b[2] then begin if a[3] < b[3] then begin IsSmaller := true; end else if a[3] = b[3] then begin if a[4] < b[4] then IsSmaller := true else IsSmaller := false; end else begin IsSmaller := false; end; (* IF [3] *) end else begin IsSmaller := false; end; (* IF [2] *) end else begin IsSmaller := false; end; (* IF [1] *) END; FUNCTION IsEqual(a, b: IPAddr): boolean; BEGIN if a[1] = b[1] then begin if a[2] = b[2] then begin if a[3] = b[3] then begin if a[4] = b[4] then IsEqual := true else IsEqual := false; end else begin IsEqual := false; end; (* IF [3] *) end else begin IsEqual := false; end; (* IF [2] *) end else begin IsEqual := false; end; (* IF [1] *) END; PROCEDURE Append(var l: IPAddrList; n: IPAddrNodePtr); BEGIN n^.prev := l^.prev; n^.next := l; l^.prev^.next := n; l^.prev := n; END; PROCEDURE Prepend(var l: IPAddrList; n: IPAddrNodePtr); BEGIN n^.next := l^.next; n^.prev := l; l^.next^.prev := n; l^.next := n; END; FUNCTION FindNode(l: IPAddrList; x: IpAddr): IPAddrNodePtr; var cur: IPAddrNodePtr; BEGIN cur := l^.next; l^.addr := x; while ((cur <> l) AND (NOT IsEqual(cur^.addr, x))) do cur := cur^.next; if cur = l then FindNode := NIL else FindNode := cur; END; PROCEDURE InitList(var l: IpAddrList); BEGIN New(l); l^.prev := l; l^.next := l; ReadIP('0.0.0.0', l^.addr); l^.count := 0; END; PROCEDURE ReadIP(ipStr: string; var ip: IpAddr); var i: integer; endIdx: integer; BEGIN endIdx := Pos('.', ipStr); for i := 1 to 4 do begin Val(Copy(ipStr, 1, endIdx-1), ip[i]); Delete(ipStr, 1, endIdx); endIdx := Pos('.', ipStr); if endIdx <= 0 then endIdx := Length(ipStr) + 1; end; (* FOR *) END; (* READIP *) PROCEDURE WriteIP(ip: IpAddr); BEGIN Write(ip[1], '.', ip[2], '.', ip[3], '.', ip[4]); END; PROCEDURE InsertSorted(var l: IpAddrList; n: IPAddrNodePtr); var succ: IPAddrNodePtr; BEGIN succ := l^.next; l^.addr := n^.addr; while IsSmaller(succ^.addr, n^.addr) do succ := succ^.next; n^.next := succ; n^.prev := succ^.prev; succ^.prev := n; n^.prev^.next := n; END; FUNCTION NewNode(x: IpAddr): IPAddrNodePtr; var n: IPAddrNodePtr; BEGIN New(n); n^.prev := NIL; n^.addr := x; n^.count := 1; n^.next := NIL; NewNode := n; END; PROCEDURE NewAccess(var l: IPAddrList; x: IpAddr); var node: IPAddrNodePtr; BEGIN node := FindNode(l, x); if node = NIL then InsertSorted(l, NewNode(x)) else Inc(node^.count); END; PROCEDURE WriteList(l: IPAddrList); var cur: IPAddrNodePtr; BEGIN cur := l^.next; while cur <> l do begin Write('->'); WriteIp(cur^.addr); WriteLn(', ', cur^.count, ' Time(s) Accessed'); cur := cur^.next; end; END; BEGIN END.
{------------------------------------------------------------------------------- // EasyComponents For Delphi 7 // 一轩软研第三方开发包 // @Copyright 2010 hehf // ------------------------------------ // // 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何 // 人不得外泄,否则后果自负. // // 使用权限以及相关解释请联系何海锋 // // // 网站地址:http://www.YiXuan-SoftWare.com // 电子邮件:hehaifeng1984@126.com // YiXuan-SoftWare@hotmail.com // QQ :383530895 // MSN :YiXuan-SoftWare@hotmail.com //------------------------------------------------------------------------------} unit untEasySQLEditor; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ecSyntMemo, ecSyntAnal, StdCtrls, DB, ExtCtrls, dbtables, ComCtrls, ecSyntTree, ecPopupCtrl, Buttons, Grids, DBGrids, untEasyPlateDBBaseForm , ecExtHighlight, ecSpell, ImgList, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxLookAndFeels, cxLookAndFeelPainters; //插件导出函数 function ShowBplForm(var AParamList: TStrings): TForm; stdcall; exports ShowBplForm; type TfrmEasySQLEditor = class(TfrmEasyPlateDBBaseForm) Label1: TLabel; SyntAnalyzer1: TSyntAnalyzer; AutoCompletePopup1: TAutoCompletePopup; AutoCompletePopup2: TAutoCompletePopup; TableHighlighter: TecSpellChecker; AliasHighloghter: TecSpellChecker; Panel1: TPanel; SyntaxMemo1: TSyntaxMemo; Splitter1: TSplitter; SyntaxTreeView1: TSyntaxTreeView; Splitter2: TSplitter; Query1: TQuery; DataSource1: TDataSource; BitBtn1: TBitBtn; ImageList1: TImageList; cxGrid1DBTableView1: TcxGridDBTableView; cxGrid1Level1: TcxGridLevel; cxGrid1: TcxGrid; procedure FormCreate(Sender: TObject); procedure AutoCompletePopup1GetAutoCompleteList(Sender: TObject; Pos: TPoint; List, Display: TStrings); procedure AutoCompletePopup2GetAutoCompleteList(Sender: TObject; Pos: TPoint; List, Display: TStrings); procedure SyntaxMemo1TextChanged(Sender: TObject; Pos, Count, LineChange: Integer); procedure TableHighlighterCheckWord(Sender: TObject; const AWord: String; APos: integer; var Valid: Boolean); procedure AliasHighloghterCheckWord(Sender: TObject; const AWord: String; APos: integer; var Valid: Boolean); procedure SyntaxMemo1FinishAnalysis(Sender: TObject); private procedure GetTables(List: TStrings); procedure GetAliases(List: TStrings; Tables: TStrings = nil); procedure GetFields(TableName: string; List, Display: TStrings); function IsIdentifier(APos: integer): Boolean; public { Public declarations } end; var frmEasySQLEditor: TfrmEasySQLEditor; implementation uses ecStrUtils; {$R *.dfm} //引出函数实现 function ShowBplForm(var AParamList: TStrings): TForm; begin frmEasySQLEditor := TfrmEasySQLEditor.Create(Application); if frmEasySQLEditor.FormStyle <> fsMDIChild then frmEasySQLEditor.FormStyle := fsMDIChild; if frmEasySQLEditor.WindowState <> wsMaximized then frmEasySQLEditor.WindowState := wsMaximized; frmEasySQLEditor.FormId := '{B21F94ED-1579-4C40-9851-376DDBF8FEAF}'; Result := frmEasySQLEditor; end; // Extracting databases procedure TfrmEasySQLEditor.FormCreate(Sender: TObject); begin end; // Extracting tables procedure TfrmEasySQLEditor.GetTables(List: TStrings); begin end; // Extracting aliases using parsing results procedure TfrmEasySQLEditor.GetAliases(List, Tables: TStrings); var i: integer; r: TTagBlockCondition; begin with SyntaxMemo1.SyntObj do begin r := TTagBlockCondition(Owner.BlockRules.ItemByName('alias')); if r <> nil then for i := 0 to RangeCount - 1 do if Ranges[i].Rule = r then // lloking for all text ranges of 'alias' rule begin List.Add(TagStr[Ranges[i].StartIdx + 1]); if Tables <> nil then Tables.Add(TagStr[Ranges[i].StartIdx]); end; end; end; // Extracting fields procedure TfrmEasySQLEditor.GetFields(TableName: string; List, Display: TStrings); begin end; // Fill tables name auto-completion list procedure TfrmEasySQLEditor.AutoCompletePopup1GetAutoCompleteList(Sender: TObject; Pos: TPoint; List, Display: TStrings); var range: TTextRange; p, idx: integer; r: TTagBlockCondition; function IsInRule(Range: TTextRange; Rule: TTagBlockCondition): Boolean; begin Result := (Range <> nil) and ((Range.Rule = Rule) or IsInRule(Range.Parent, Rule)); end; begin p := SyntaxMemo1.CaretPosToStrPos(Pos); with SyntaxMemo1.SyntObj do begin r := TTagBlockCondition(Owner.BlockRules.ItemByName('from')); idx := PriorTokenAt(p); if idx < 1 then Exit; Range := NearestRangeAtPos(p); if IsInRule(Range, r) then begin if Tags[idx].EndPos > p then Dec(idx); if Tags[idx].TokenType = 2 then // Identifier Exit; GetTables(List); end; end; end; // Fill fields name auto-completion list procedure TfrmEasySQLEditor.AutoCompletePopup2GetAutoCompleteList(Sender: TObject; Pos: TPoint; List, Display: TStrings); var range: TTextRange; p, idx: integer; Al, Tables: TStringList; S: string; begin p := SyntaxMemo1.CaretPosToStrPos(Pos); if p < 3 then Exit; if SyntaxMemo1.Lines.Chars[p] = '.' then begin idx := SyntaxMemo1.SyntObj.TokenAtPos(p - 2); // get index of table/alias name token if idx <> -1 then begin S := SyntaxMemo1.SyntObj.TagStr[idx]; // table/alias name Al := TStringList.Create; Tables := TStringList.Create; try GetAliases(Al, Tables); idx := Al.IndexOf(S); if idx = -1 then begin // it is not alias Tables.Clear; GetTables(Tables); idx := Tables.IndexOf(S); end; if idx <> -1 then begin GetFields(Tables[idx], List, Display); // get fields list if List.Count > 0 then begin List.Insert(0, '*'); Display.Insert(0, '<ALL>'); end; end; finally Al.Free; Tables.Free; end; end; end; end; // Run table name auto-completion after first letter inputing procedure TfrmEasySQLEditor.SyntaxMemo1TextChanged(Sender: TObject; Pos, Count, LineChange: Integer); begin with SyntaxMemo1 do if (Count = 1) and IsWordChar(Lines.Chars[Pos + 1]) and ((Pos = 0) or IsSpaceChar(Lines.Chars[Pos])) then begin AutoCompletePopup1.Execute; end; end; // Check type of token at given position function TfrmEasySQLEditor.IsIdentifier(APos: integer): Boolean; var idx: integer; begin idx := SyntaxMemo1.SyntObj.TokenAtPos(APos); Result := (idx <> -1) and (SyntaxMemo1.SyntObj.Tags[idx].TokenType = 2); end; // Using ecSpellChecker to highlight valid tables procedure TfrmEasySQLEditor.TableHighlighterCheckWord(Sender: TObject; const AWord: String; APos: integer; var Valid: Boolean); var sl: TStringList; begin if not IsIdentifier(APos) then begin Valid := True; Exit; end; sl := TStringList.Create; GetTables(sl); Valid := sl.IndexOf(AWord) = -1; sl.Free; end; // Using ecSpellChecker to highlight aliases procedure TfrmEasySQLEditor.AliasHighloghterCheckWord(Sender: TObject; const AWord: String; APos: integer; var Valid: Boolean); var sl: TStringList; begin if not IsIdentifier(APos) then begin Valid := True; Exit; end; sl := TStringList.Create; GetAliases(sl); Valid := sl.IndexOf(AWord) = -1; sl.Free; end; procedure TfrmEasySQLEditor.SyntaxMemo1FinishAnalysis(Sender: TObject); begin // Clear previous results TableHighlighter.Clear; AliasHighloghter.Clear; // Analyze (not background) TableHighlighter.Analyze(False); AliasHighloghter.Analyze(False); end; end.
//Nama: Morgen Sudyanto //NIM: 16518380 { Lengkapi dengan identitas } Program ProsesLingkaran; { Input: 2 buah Lingkaran } { Output: luas, keliling, dan hubungan lingkaran A dan B } { KAMUS } const PI : real = 3.1415; type { Definisi Type Koordinat } Koordinat = record x,y: real { lengkapi dengan komponen type Koordinat } end; { Definisi Type Lingkaran } Lingkaran = record c : Koordinat; { titik pusat lingkaran } r : real; { jari-jari, > 0 } end; var A, B : Lingkaran; { variabel untuk lingkaran A dan B } hubungan : integer; { lengkapi dengan variabel yang dibutuhkan } { FUNGSI DAN PROSEDUR } function IsRValid (r:real):boolean; begin IsRValid:=(r>0); end; procedure InputLingkaranA (); { I.S.: A sembarang } { F.S.: A terdefinisi sesuai dengan masukan pengguna. Pemasukan jari-jari diulangi sampai didapatkan jari-jari yang benar yaitu r > 0. Pemeriksaan apakah jari- jari valid menggunakan fungsi IsRValid. Jika jari-jari tidak valid, dikeluarkan pesan kesalahan “Jari-jari harus > 0”. } { lengkapi kamus dan algoritma procedure InputLingkaran } begin readln(A.c.x,A.c.y,A.r); while (not (IsRValid(A.r))) do begin writeln('Jari-jari harus > 0'); readln(A.r); end; end; procedure InputLingkaranB (); { I.S.: A sembarang } { F.S.: A terdefinisi sesuai dengan masukan pengguna. Pemasukan jari-jari diulangi sampai didapatkan jari-jari yang benar yaitu r > 0. Pemeriksaan apakah jari- jari valid menggunakan fungsi IsRValid. Jika jari-jari tidak valid, dikeluarkan pesan kesalahan “Jari-jari harus > 0”. } { lengkapi kamus dan algoritma procedure InputLingkaran } begin readln(B.c.x,B.c.y,B.r); while (not (IsRValid(B.r))) do begin writeln('Jari-jari harus > 0'); readln(B.r); end; end; function KelilingLingkaran (A:Lingkaran) : real; { lengkapi parameter dan type hasil } { Menghasilkan keliling lingkaran A = 2 * PI * A.r } { Lengkapi kamus lokal dan algoritma fungsi KelilingLingkaran } begin KelilingLingkaran:=2*PI*A.r; end; function LuasLingkaran (A:Lingkaran) : real; { lengkapi parameter dan type hasil } { Menghasilkan luas lingkaran A = PI * A.r * A.r } { Lengkapi kamus lokal dan algoritma fungsi LuasLingkaran } begin LuasLingkaran:=PI*A.r*A.r; end; function Jarak (A,B:Lingkaran) : real; { Menghasilkan jarak antara P1 dan P2 } { Lengkapi kamus lokal dan algoritma fungsi Jarak } begin Jarak:=Sqrt((B.c.x-A.c.x)*(B.c.x-A.c.x)+(B.c.y-A.c.y)*(B.c.y-A.c.y)); end; function HubunganLingkaran (A,B:Lingkaran) : integer; { Menghasilkan integer yang menyatakan hubungan lingkaran A dan B, yaitu: 1 = A dan B sama; 2 = A dan B berimpit; 3 = A dan B beririsan; 4 = A dan B bersentuhan; 5 = A dan B saling lepas } { Lengkapi kamus lokal dan algoritma fungsi HubunganLingkaran } begin if ((A.c.x=B.c.x) and (A.c.y=B.c.y) and (A.r=B.r)) then begin HubunganLingkaran:=1; end else if ((A.c.x=B.c.x) and (A.c.y=B.c.y) and (A.r<>B.r)) then begin HubunganLingkaran:=2; end else if ((Jarak(A,B)<(A.r+B.r))) then begin HubunganLingkaran:=3; end else if ((Jarak(A,B)=(A.r+B.r))) then begin HubunganLingkaran:=4; end else begin HubunganLingkaran:=5; end; end; { ALGORITMA PROGRAM UTAMA } begin writeln('Masukkan lingkaran A:'); A.c.x:=0; A.c.y:=0; A.r:=0; InputLingkaranA(); { Lengkapi dengan pemanggilan prosedur InputLingkaran untuk lingkaran A } writeln('Masukkan lingkaran B:'); B.c.x:=0; B.c.y:=0; B.r:=0; InputLingkaranB(); { Lengkapi dengan pemanggilan prosedur InputLingkaran untuk lingkaran B } writeln('Keliling lingkaran A = ', KelilingLingkaran(A):0:2); { Lengkapi dengan pemanggilan fungsi KelilingLingkaran untuk A } writeln('Luas lingkaran A = ', LuasLingkaran(A):0:2); { Lengkapi dengan pemanggilan fungsi LuasLingkaran untuk A } writeln('Keliling lingkaran B = ', KelilingLingkaran(B):0:2); { Lengkapi dengan pemanggilan fungsi KelilingLingkaran untuk B } writeln('Luas lingkaran B = ', LuasLingkaran(B):0:2); { Lengkapi dengan pemanggilan fungsi LuasLingkaran untuk B } write('A dan B adalah '); hubungan:=HubunganLingkaran(A,B); if (hubungan=1) then begin writeln('sama'); end else if (hubungan=2) then begin writeln('berimpit'); end else if (hubungan=3) then begin writeln('beririsan'); end else if (hubungan=4) then begin writeln('bersentuhan'); end else begin writeln('saling lepas'); end; { Lengkapi dengan pemanggilan fungsi HubunganLingkaran dan mengkonversi integer hasil fungsi menjadi kata-kata sbb.: 1 = ‘sama’ 2 = ‘berimpit’ 3 = ‘beririsan’ 4 = ‘bersentuhan’ 5 = ‘saling lepas’ } end.
UNIT ControladorPokedex; {$mode objfpc}{$H+} INTERFACE USES DT_Pokedex, GUI_Pokedex, Crt, SysUtils; CONST TECLA_ESC= #27; TECLA_ENTER= #13; //Comandos teclas especiales. TECLA_ESPECIAL_PRESIONADA= #0; //Al presionar una tecla especial primero se lanza este caracter. TECLA_FLECHA_ARRIBA= #72; //Es una tecla especial. TECLA_FLECHA_ABAJO= #80; //Es una tecla especial. TECLA_FLECHA_DERECHA= #77;//Es una tecla especial. TECLA_FLECHA_IZQUIERDA= #75; //Es una tecla especial. (*Inicia los datos de la pokedex cargando desde la base de datos. Se establece una bandera indicando que la pokedex ya fue iniciada.*) PROCEDURE StartPokedex(); (*Devuelve TRUE si la pokedex ya fue iniciada, FALSE sino.*) FUNCTION PokedexStarted(): BOOLEAN; (*Asigna el control del sistema a la pokedex. Si la pokedex no ha sido iniciada aún mediante 'StartPokedex' entonces la inicializará utilizando esa misma operación. Este procedimiento dibuja la pokedex en pantalla mediante el procedimiento 'DrawPokedex' implementado en la unidad 'GUI_Pokedex'. Además, si se presiona la flecha hacia arriba sube una posición en la lista; si se presiona la flecha hacia abajo se baja una posición en la lista. Al presionar escape (ESC) se devuelve el control al programa principal.*) PROCEDURE ShowPokedex(); IMPLEMENTATION VAR pokedexStart: BOOLEAN; pokedex: DatosPokedex; key: CHAR; (*Inicia los datos de la pokedex cargando desde la base de datos. Se establece una bandera indicando que la pokedex ya fue iniciada.*) PROCEDURE StartPokedex(); Begin IF NOT pokedexStarted THEN Begin IniciarPokedex(pokedex); pokedexStart:= true; End; end; (*Devuelve TRUE si la pokedex ya fue iniciada, FALSE sino.*) FUNCTION PokedexStarted(): BOOLEAN; Begin PokedexStarted:= pokedexStart; end; (*Asigna el control del sistema a la pokedex. Si la pokedex no ha sido iniciada aún mediante 'StartPokedex' entonces la inicializará utilizando esa misma operación. Este procedimiento dibuja la pokedex en pantalla mediante el procedimiento 'DrawPokedex' implementado en la unidad 'GUI_Pokedex'. Además, si se presiona la flecha hacia arriba sube una posición en la lista; si se presiona la flecha hacia abajo se baja una posición en la lista. Al presionar escape (ESC) se devuelve el control al programa principal.*) PROCEDURE ShowPokedex(); VAR especieBuscada: String; indiceEspecieBuscada: INTEGER; BEGIN //IF NOT PokedexStarted THEN StartPokedex; DrawPokedexBackground; DrawPokedex(pokedex); REPEAT key:= ReadKey; IF key=TECLA_ESPECIAL_PRESIONADA THEN Begin key:= ReadKey; CASE key OF TECLA_FLECHA_ARRIBA: Begin AnteriorEspecie(pokedex); DrawPokedex(pokedex); end; TECLA_FLECHA_ABAJO: Begin SiguienteEspecie(pokedex); DrawPokedex(pokedex); end; end; end else if (key='b') OR (key='B') then begin CursorOn; GoToXY(1,22); TextBackGround(Blue); TextColor(White); Write(' '); GoToXY(1,22); Write('Ingresa nombre o numero de especie: '); GoToXY(1,23); Write(' '); GoToXY(3,23); ReadLn(especieBuscada); CursorOff; indiceEspecieBuscada:= BuscarEspecie(especieBuscada,pokedex); IF indiceEspecieBuscada=0 THEN Begin TextBackground(LightRed); TextColor(Yellow); GoToXY(1,23); Write(' '); GoToXY(1,23); Write(' ERROR: No existe la especie buscada. '); TextBackground(Black); end else begin TextBackground(Black); WHILE indiceEspecieBuscada<IndiceEspecieSeleccionada(pokedex) do begin AnteriorEspecie(pokedex); end; WHILE indiceEspecieBuscada>IndiceEspecieSeleccionada(pokedex) do begin SiguienteEspecie(pokedex); end; DrawPokedex(pokedex); end; end; until key=TECLA_ESC; end; BEGIN pokedexStart:= false; END.
unit URepositorioProximaVacina; interface uses UProximaVacina , UEntidade , URepositorioDB , SqlExpr ; type TRepositorioProximaVacina = class(TRepositorioDB<TPROXIMAVACINA>) private public constructor Create; //destructor Destroy; override; procedure AtribuiDBParaEntidade(const coPROXIMAVACINA: TPROXIMAVACINA); override; procedure AtribuiEntidadeParaDB(const coPROXIMAVACINA: TPROXIMAVACINA; const coSQLQuery: TSQLQuery); override; end; implementation uses UDM , SysUtils , StrUtils ; { TRepositorioProximaVacina } constructor TRepositorioPROXIMAVACINA.Create; begin inherited Create(TPROXIMAVACINA, TBL_PROX_VACINA, FLD_ENTIDADE_ID, STR_PROX_VACINA); end; procedure TRepositorioPROXIMAVACINA.AtribuiDBParaEntidade(const coPROXIMAVACINA: TPROXIMAVACINA); begin inherited; with FSQLSelect do begin coPROXIMAVACINA.SUS_CODIGO := FieldByName(FLD_SUS_CODIGO).AsString; //TPACIENTE(FRepositorioPaciente.Retorna(FieldByName(FLD_CODIGO_SUS).AsInteger)); coPROXIMAVACINA.NOME := FieldByName(FLD_NOME).AsString; coPROXIMAVACINA.DATA_RETORNO := FieldByName(FLD_DATA_RETORNO).AsDateTime; coPROXIMAVACINA.VACINA_RETORNO := FieldByName(FLD_VACINA_RETORNO).AsString; coPROXIMAVACINA.DOSE := FieldByName(FLD_DOSE).AsString; end; end; procedure TRepositorioPROXIMAVACINA.AtribuiEntidadeParaDB(const coPROXIMAVACINA: TPROXIMAVACINA; const coSQLQuery: TSQLQuery); begin inherited; with coSQLQuery do begin ParamByName(FLD_SUS_CODIGO).AsString := coPROXIMAVACINA.SUS_CODIGO; ParamByName(FLD_NOME).AsString := coPROXIMAVACINA.NOME ; ParamByName(FLD_DATA_RETORNO).AsDate := coPROXIMAVACINA.DATA_RETORNO ; ParamByName(FLD_VACINA_RETORNO).AsString := coPROXIMAVACINA.VACINA_RETORNO; ParamByName(FLD_DOSE).AsString := coPROXIMAVACINA.DOSE ; end; end; end.
unit ncafbTarifas; { ResourceString: Dario 10/03/13 } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufmFormBase, dxPSGlbl, dxPSUtl, dxPSEngn, dxPrnPg, dxBkgnd, dxWrap, dxPrnDev, dxPSCompsProvider, dxPSFillPatterns, dxPSEdgePatterns, dxPSCore, cxGridCustomPopupMenu, cxGridPopupMenu, dxBar, dxBarExtItems, ExtCtrls, cxControls, cxPC, cxClasses, dxPSPDFExportCore, dxPSPDFExport, cxDrawTextUtils, dxPSPrVwStd, dxPSPrVwAdv, dxPSPrVwRibbon, dxPScxPageControlProducer, dxPScxGridLnk, dxPScxGridLayoutViewLnk, dxPScxEditorProducers, dxPScxExtEditorProducers, cxPCdxBarPopupMenu, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel, dxPScxPivotGridLnk, dxBarBuiltInMenu; type TfbTarifas = class(TFrmBase) Paginas: TcxPageControl; FM: TFormManager; procedure FrmBasePaiCreate(Sender: TObject); procedure FrmBasePaiDestroy(Sender: TObject); private { Private declarations } public procedure AtualizaDireitos; override; procedure FiltraDados; override; class function Descricao: String; override; { Public declarations } end; var fbTarifas: TfbTarifas; implementation uses ncafbTarBasica, ncafbPacotes, ncaFrmPri, ncafbTipoPass, ncafbTiposAcesso, ncaDM, ncafbTiposImp; // START resource string wizard section resourcestring STarifas = 'Tarifas'; // END resource string wizard section {$R *.dfm} { TFrmBase1 } procedure TfbTarifas.AtualizaDireitos; begin inherited; if Dados.tbConfigVariosTiposAcesso.Value then FM.MostrarTab(TfbTiposAcesso) else FM.Esconder(TfbTiposAcesso); end; class function TfbTarifas.Descricao: String; begin Result := STarifas; end; procedure TfbTarifas.FiltraDados; begin inherited; end; procedure TfbTarifas.FrmBasePaiCreate(Sender: TObject); begin BarMgr.Bars[0].Free; FM.RegistraForm(TfbTiposAcesso); FM.RegistraForm(TfbTarBasica); FM.RegistraForm(TfbPacotes); FM.RegistraForm(TfbTiposPass); // FM.RegistraForm(TfbTiposImp); FM.Mostrar(TfbTiposAcesso, 0, 0); FM.Mostrar(TfbTarBasica, 0, 0); FM.Mostrar(TfbPacotes, 0, 0); FM.Mostrar(TfbTiposPass, 0, 0); // FM.Mostrar(TfbTiposImp, 0, 0); Paginas.ActivePageIndex := 0; end; procedure TfbTarifas.FrmBasePaiDestroy(Sender: TObject); begin FM.Clear; inherited; end; end.
unit Resource; interface uses Types; procedure rInit; procedure rDone; procedure rPut(const Name: String; var Data; Size: Longint); {$IFNDEF SOLID}export;{$ENDIF} procedure rGet(const Name: String; var Data); {$IFNDEF SOLID}export;{$ENDIF} procedure rPutStream(const Name: String; S: PStream; Size: Longint); {$IFNDEF SOLID}export;{$ENDIF} procedure rGetStream(const Name: String; S: PStream); {$IFNDEF SOLID}export;{$ENDIF} procedure rDelete(const Name: String); {$IFNDEF SOLID}export;{$ENDIF} function rExist(const Name: String): boolean; {$IFNDEF SOLID}export;{$ENDIF} procedure rGetInfo(const Name: String); {$IFNDEF SOLID}export;{$ENDIF} function rGetSize(const Name: String): longint; {$IFNDEF SOLID}export;{$ENDIF} function rError: Boolean; {$IFNDEF SOLID}export;{$ENDIF} function rGetErrorString: String; {$IFNDEF SOLID}export;{$ENDIF} procedure rReset; {$IFNDEF SOLID}export;{$ENDIF} function rGetIndexSize: longint; {$IFNDEF SOLID}export;{$ENDIF} function rGetIndexName(I: longint): String; {$IFNDEF SOLID}export;{$ENDIF} implementation uses Video, Config, Log, Wizard, FileLib, Vars, Language, Semaphor, Misc; const Lib : PLibrary = Nil; CountKey = 'resource.pack.count'; Count : Longint = 0; var FName : String; TempFName : String; procedure rInit; begin lngPrint('Main', 'resmanager.init'); FName:=cGetParam('Resource.FileName'); TempFName:=cGetParam('Resource.TempFileName'); if (FName = '') or (TempFName = '') then begin lngPrint('Main', 'resmanager.notspec'); sSetExitNow; Exit; end; mCreate(JustPathName(FName)); mCreate(JustPathName(TempFName)); Lib:=New(PLibrary, Init(FName)); if Lib^.Error then begin lngBegin; lngPush(Lib^.ErrorString); lngPrint('Main', 'resmanager.cannotstart'); lngEnd; ErrorLevel:=2; sSetExitNow; Exit; end; lngBegin; lngPush(FExpand(FName)); lngPrint('Main', 'resmanager.info'); lngEnd; Lib^.Debugging:=cGetBoolParam('Debug.Resource'); end; procedure rPut(const Name: String; var Data; Size: Longint); begin if Lib = Nil then Exit; Lib^.AddResourceFromMemory(Name, @Data, Size); end; procedure rGet(const Name: String; var Data); begin if Lib = Nil then Exit; Lib^.GetResourceToMemory(Name, @Data); end; procedure rDelete(const Name: String); begin if Lib = Nil then Exit; Lib^.KillResource(Name); end; function rExist(const Name: String): boolean; begin if Lib = Nil then Exit; rExist:=Lib^.QueryResource(Name) <> Nil; end; procedure rGetInfo(const Name: String); var I: PItem; begin if Lib = Nil then Exit; I:=Lib^.QueryResource(Name); if I = Nil then begin sSetSemaphore('Resource.Info', 'Error'); Exit; end; sSetSemaphore('Resource.Info.ID', Long2Str(I^.ID)); sSetSemaphore('Resource.Info.Offset', Long2Str(I^.Offset)); sSetSemaphore('Resource.Info.Size', Long2Str(I^.Size)); sSetSemaphore('Resource.Info.Name', I^.Name); sSetSemaphore('Resource.Info.ChunkSize', Long2Str(SizeOf(TItem))); end; function rGetSize(const Name: String): longint; begin if Lib = Nil then Exit; rGetSize:=Lib^.GetResourceSize(Name); end; function rError: boolean; begin if Lib = Nil then Exit; rError:=Lib^.Error; end; function rGetErrorString: String; begin if Lib = Nil then Exit; rGetErrorString:=Lib^.ErrorString; end; procedure rReset; begin if Lib = Nil then Exit; Lib^.Reset; end; procedure rDone; var Ok: Boolean; S: TBufStream; F: File; begin if cGetBoolParam('Resource.Pack') and (not sExitNow) then begin Ok:=True; if cGetParam('Resource.Pack.Step') <> '' then begin if not rExist(CountKey) then rPut(CountKey, Count, SizeOf(Count)); rGet(CountKey, Count); Inc(Count); if Count >= cGetNumParam('Resource.Pack.Step') then begin Count:=0; Ok:=True; end else Ok:=False; rPut(CountKey, Count, SizeOf(Count)); end; if Ok then begin lngPrint('Main', 'resmanager.packing'); Lib^.Error:=False; S.Init(TempFName, stCreate, 2048); if S.Status <> stOk then Lib^.DoError('Cannot pack resourcefile, rc#' + Long2Str(S.Status)) else Lib^.Pack(@S); S.Done; if Lib^.Error then begin lngBegin; lngPush(Lib^.ErrorString); lngPrint('Main', 'resmanager.packing.error'); lngEnd; end else begin {$I-} if IOResult <> 0 then; Assign(F, TempFName); Erase(F); if IOResult <> 0 then; end; end else begin lngBegin; lngPush(Long2Str(Count)); lngPush(Long2Str(cGetNumParam('Resource.Pack.Step'))); lngPrint('Main', 'resmanager.packing.notnow'); lngEnd; end; end; if Lib <> Nil then Dispose(Lib, Done); lngPrint('Main', 'resmanager.done'); end; procedure rPutStream(const Name: String; S: PStream; Size: Longint); begin Lib^.AddResource(Name, S, Size); end; procedure rGetStream(const Name: String; S: PStream); begin Lib^.GetResource(Name, S); end; function rGetIndexSize: longint; begin rGetIndexSize:=Lib^.Index^.Count; end; function rGetIndexName(I: Longint): String; var Z: PItem; begin Z:=Lib^.Index^.At(I); if Z = Nil then rGetIndexName:='' else rGetIndexName:=Z^.Name; end; end.
unit untEasyNumeration; interface uses SysUtils, Math; type TEasyNumeration = class public //10 进制 to 2,8,16 进制 class function IntToBin(Value: Integer): string; class function IntToHex(Value: Integer): String;//10 = 2 class function IntToO(Value: Integer): string; //2进制 to 10,8,16 进制 class function BinToHex(Value: String): String; class function BinToO(Value: String): String; class function BinToInt(Value: String): LongInt;// 2 = 10 //16 > 10 2 8 进制 class function HexToBin(Value: string): string; class function HexToInt(Value: string): LongInt; class function HexToO(Value: string): string; //八进制转换成二进制字符串 class function OToBin(Value: string): string; class function OToHex(Value: string): string; class function OToInt(Value: string): LongInt; end; implementation { TEasyNumeration } class function TEasyNumeration.BinToHex(Value: String): String; var vD : Byte; I : Integer; vHextStr : String; vP : PChar; vLen : Integer; begin vLen := Length(Value); if vLen mod 4 > 0 then begin SetLength(vHextStr, vLen div 4 + 1); vLen := vlen div 4 + 1; end else begin SetLength(vHextStr, vLen div 4); vLen := vlen div 4 ; end; //初始化 vD := 0; vP := PChar(Value) + length(Value) - 1; I := 0; //开始计数 while vP^ <> #0 do begin if vp^ = '1' then begin case I of 0: vD :=vd +1 ; 1: vD :=vd + 2; 2: vD :=vd + 4; 3: vD :=vd + 8; end; end; Dec(vP); Inc(I); if I = 4 then begin case vD of 0..9 : vHextStr[vLen] := Chr(vD + $30); 10..15 : vHextStr[vLen] := Chr(vD - 10 + $41); end; Dec(vLen); I := 0; vD := 0; end; end; if I > 0then begin case vD of 0..9 : vHextStr[vLen] := Chr(vD + $30); 10..15 : vHextStr[vLen] := Chr(vD + $41); end; end; Result := vHextStr; end; class function TEasyNumeration.BinToInt(Value: String): LongInt; var i, Size: Integer; begin Result:=0; Size:=Length(Value); for i := Size downto 1 do begin //例如 1010 if Copy(Value,i,1) = '1' then Result := Result + (1 shl (Size - i)); end; end; class function TEasyNumeration.BinToO(Value: String): String; var vD : Byte; I : Integer; vHextStr : String; vP : PChar; vLen : Integer; begin vLen := Length(Value); if vLen mod 3 > 0 then begin SetLength(vHextStr, vLen div 3 + 1); vLen := vlen div 3 + 1; end else begin SetLength(vHextStr, vLen div 3); vLen := vlen div 3 ; end; //初始化 vD := 0; vP := PChar(Value) + length(Value) - 1; I := 0; //开始计数 while vP^ <> #0 do begin if vp^ = '1' then begin case I of 0: vD := vd + 1; 1: vD := vd + 2; 2: vD := vd + 4; end; end; Dec(vP); Inc(I); if I = 3 then begin case vD of 0..9 : vHextStr[vLen] := Chr(vD + $30); end; Dec(vLen); I := 0; vD := 0; end; end; if I > 0then begin case vD of 0..9: vHextStr[vLen] := Chr(vD + $30); end; end; Result := vHextStr; end; class function TEasyNumeration.HexToBin(Value: string): string; const cBitStrings: array[0..15] of string = ( '0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111' ); var I: Integer; begin Result := ''; for I := 1 to Length(Value) do Result := Result + cBitStrings[StrToIntDef('$' + Value[I], 0)]; while Pos('0', Result) = 1 do Delete(Result, 1, 1); end; class function TEasyNumeration.HexToInt(Value: string): LongInt; begin Result := StrToInt('$' + Value); end; class function TEasyNumeration.HexToO(Value: string): string; begin Result := BinToO(HexToBin(Value)); end; class function TEasyNumeration.IntToBin(Value: Integer): string; begin Result := ''; while (Value <> 0) do begin Result := Format('%d' + Result, [Value mod 2]); Value := Value div 2; end; end; class function TEasyNumeration.IntToHex(Value: Integer): String; begin Result := BinToHex(IntToBin(Value)); end; class function TEasyNumeration.IntToO(Value: Integer): string; begin Result := BinToO(IntToBin(Value)); end; class function TEasyNumeration.OToInt(Value: string): LongInt; begin Result := BinToInt(OToBin(Value)); end; class function TEasyNumeration.OToBin(Value: string): string; const cBitStrings: array[0..7] of string = ( '000', '001', '010', '011', '100', '101', '110', '111' ); var i, j: Integer; begin Result := ''; for I := 1 to Length(Value) do begin j:=strtoint(Value[i]); Result := Result + cBitStrings[j]; end; while Pos('0', Result) = 1 do Delete(Result, 1, 1); end; class function TEasyNumeration.OToHex(Value: string): string; begin Result := BinToHex(OToBin(Value)); end; end.