text
stringlengths
14
6.51M
program ej15; function esVocal(c:char): Boolean; begin esVocal:=(c = 'a') or (c = 'e') or (c = 'i') or (c = 'o') or (c = 'u'); end; function letraNoVocal(c:char): Boolean; begin letraNoVocal:= not ((c = 'a') or (c = 'e') or (c = 'i') or (c = 'o') or (c = 'u')); end; procedure cumpleA(var cumple:Boolean); var c:char; begin writeln('Ingrese una vocal: '); readln(c); while(c <> '$') and (cumple) do begin if (not esVocal(c)) then cumple := false else readln(c); end; end; procedure cumpleB(var cumple:Boolean); var c:char; begin writeln('Ingrese una letra no vocal: '); readln(c); while((c <> '#') and (cumple)) do begin if (not letraNoVocal(c)) then cumple:=false else readln(c); end; end; var cumple:Boolean; c:char; begin cumple:=true; cumpleA(cumple); if cumple then begin cumpleB(cumple); if cumple then writeln('Secuencia ingresada correctamente') else writeln('el caracter ingresado fue invalido.') end else writeln('El caracter ingresado no fue invalido.') end.
unit UImageView; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, TMultiP, ComCtrls, StdCtrls, ExtCtrls, UGraphics, UForms; type TImageViewer = class(TAdvancedForm) StatusBar: TStatusBar; WorkImage: TPMultiImage; Panel1: TPanel; rdoImageExt: TRadioGroup; btnSaveAs: TButton; SaveDialog: TSaveDialog; procedure btnSaveAsClick(Sender: TObject); procedure SaveDialogTypeChange(Sender: TObject); private FCurExt: String; FFileName: String; FImgDesc: String; function GetImageExt: String; procedure SetImageExt(const Value: String); procedure SetImageDesc(const Value: String); function GetFilterExt(Index: Integer): String; function GetFilterIndex(ExtStr: String): Integer; public constructor Create(AOwner: TComponent{; prAddress,imgPath,imgDescr: String}); override;{reintroduce;} destructor Destroy; override; procedure LoadImageFromFile(filename: String); procedure LoadImageFromEditor(AImage: TCFImage); property ImageExt: String read GetImageExt write SetImageExt; property ImageDesc: String read FImgDesc write SetImageDesc; end; var ImageViewer: TImageViewer; implementation uses DLLSP96,Dll96v1, UGlobals, UUtil1, UStatus; var ViewerCount: Integer; {$R *.dfm} constructor TImageViewer.Create(AOwner: TComponent); {; imgPath, imgDescr: String} begin inherited Create(AOwner); SettingsName := CFormSettings_ImageViewer; if assigned(AOwner) and AOwner.ClassNameIs('TPicScrollBox') then begin self.top := (ViewerCount * 20) + 170; self.Left := (ViewerCount * 20); end else position := poDesktopCenter; FCurExt := ''; FFileName := ''; btnSaveAs.Enabled := False; inc(ViewerCount); end; procedure TImageViewer.LoadImageFromFile(filename: String); begin FCurExt := ExtractFileExt(filename); Delete(FCurExt,1,1); //delete the '.' ImageExt := FCurExt; //set the users' option FFileName := GetNameOnly(filename); //get just the name Caption := FFileName; StatusBar.SimpleText := filename; Hint := filename; try WorkImage.ImageName := filename; //load the image btnSaveAs.Enabled := True; except ShowAlert(atWarnAlert, 'The image could not be loaded. You may be low on memory.'); end; end; procedure TImageViewer.LoadImageFromEditor(AImage: TCFImage); var BMap: TBitmap; begin if assigned(AImage) and AImage.HasGraphic then try if AImage.FStorage.Size > 0 then begin WorkImage.LoadFromStream(AImage.ILImageType, AImage.FStorage); FCurExt := Uppercase(AImage.ILImageType); end else begin BMap := AImage.BitMap; //creates bitmap from DIB try WorkImage.Picture.Bitmap.Assign(BMap); FCurExt := 'BMP'; finally BMap.Free; end; end; ImageExt := FCurExt; //preselect user option FFileName := 'Untitled'; Caption := 'Untitled Image'; StatusBar.SimpleText := Caption; Hint := Caption; btnSaveAs.Enabled := True; except ShowAlert(atWarnAlert, 'The image could not be loaded. You may be low on memory.'); end; end; function TImageViewer.GetFilterExt(Index: Integer): String; begin case Index of 2: result := 'BMP'; 3: result := 'GIF'; 4: result := 'JPG'; 5: result := 'PCX'; 6: result := 'PNG'; 7: result := 'TIF'; else result := 'BMP'; end; end; function TImageViewer.GetFilterIndex(ExtStr: String): Integer; begin if Uppercase(extStr) = 'BMP' then result := 2 else if Uppercase(extStr) = 'PNG' then result := 6 else if Uppercase(extStr) = 'GIF' then result := 3 else if Uppercase(extStr) = 'PCX' then result := 5 else if Uppercase(extStr) = 'JPG' then result := 4 else if Uppercase(extStr) = 'EPS' then result := 8 else if Uppercase(extStr) = 'TIF' then result := 7 else result := 2; end; procedure TImageViewer.SaveDialogTypeChange(Sender: TObject); var fname: String; begin fname := SaveDialog.FileName; fname := ChangeFileExt(fname, GetFilterExt(SaveDialog.FilterIndex)); SaveDialog.FileName := fName; end; procedure TImageViewer.btnSaveAsClick(Sender: TObject); var ext,fPath: String; aFormStyle: TFormStyle; //github #82 begin // ext := 'bmp'; //TPhotoInfo(FPhotoList.Items[FCurPhotoIndex]).FType; aFormStyle := self.FormStyle; //save form style self.FormStyle := fsNormal; //set to normal so the child can pop up (opendialog) to the front try SaveDialog.InitialDir := appPref_DirPhotoLastSave; SaveDialog.DefaultExt := ImageExt; SaveDialog.FilterIndex := GetFilterIndex(ImageExt); SaveDialog.FileName := FFileName + '.' + ImageExt; SaveDialog.Options := [ofOverwritePrompt, ofEnableSizing]; if SaveDialog.Execute then try fPath := SaveDialog.FileName; ext := ExtractFileExt(fPath); Delete(ext,1,1); //delete the '.' if Uppercase(ext) = 'BMP' then begin WorkImage.SaveAsBMP(fPath); end else if Uppercase(ext) = 'PNG' then begin WorkImage.SaveAsPNG(fPath); end else if Uppercase(ext) = 'GIF' then begin WorkImage.SaveAsGIF(fPath); end else if Uppercase(ext) = 'PCX' then begin WorkImage.SaveAsPCX(fPath); end else if Uppercase(ext) = 'JPG' then begin WorkImage.JPegSaveQuality := 100; WorkImage.JPegSaveSmooth := 0; WorkImage.SaveAsJpg(fPath); end else if Uppercase(ext) = 'EPS' then begin WorkImage.SaveAsEPS(fPath); end else if Uppercase(ext) = 'TIF' then begin WorkImage.TifSaveCompress := sLZW; WorkImage.SaveAsTIF(fPath); end; appPref_DirPhotoLastSave := ExtractFileDir(fPath); Close; except ShowAlert(atWarnAlert, 'A problem was encountered saving the image.'); end; finally self.FormStyle := aFormStyle; end; end; destructor TImageViewer.Destroy; begin dec(ViewerCount); inherited; end; function TImageViewer.GetImageExt: String; begin case rdoImageExt.ItemIndex of 0: result := 'BMP'; 1: result := 'JPG'; 2: result := 'TIF'; 3: result := 'GIF'; 4: result := 'PCX'; 5: result := 'EPS'; 6: result := 'PNG'; else rdoImageExt.ItemIndex := 0; result := 'BMP'; end; end; procedure TImageViewer.SetImageExt(const Value: String); begin if Uppercase(Value) = 'BMP' then rdoImageExt.ItemIndex := 0 else if Uppercase(Value) = 'JPG' then rdoImageExt.ItemIndex := 1 else if Uppercase(Value) = 'JPEG' then rdoImageExt.ItemIndex := 1 else if Uppercase(Value) = 'TIF' then rdoImageExt.ItemIndex := 2 else if Uppercase(Value) = 'TIFF' then rdoImageExt.ItemIndex := 2 else if Uppercase(Value) = 'GIF' then rdoImageExt.ItemIndex := 3 else if Uppercase(Value) = 'PCX' then rdoImageExt.ItemIndex := 4 else if Uppercase(Value) = 'EPS' then rdoImageExt.ItemIndex := 5 else if Uppercase(Value) = 'PNG' then rdoImageExt.ItemIndex := 6 end; procedure TImageViewer.SetImageDesc(const Value: String); begin FImgDesc := Value; Caption := Value; end; initialization ViewerCount := 0; end.
//Copyright 2015 Andrey S. Ionisyan (anserion@gmail.com) // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //===================================================================== //функции расчета компонент цвета в разных цветовых моделях //===================================================================== unit colors_unit; {$mode objfpc}{$H+} interface uses Classes, SysUtils, utils_unit; type TFullColor=record red,green,blue:real; hue,saturation,value,lightness:real; cyan,magenta,yellow,black:real; Y,Cr,Cb,U,V: real; XX,YY,ZZ:real; end; //расчет цветовых моделей HSV,HSL,CMYK,YUV,YCrCb,XYZ по известным RGB function ConvertRGBToFull(red,green,blue:real):TFullColor; implementation //расчет цветовых моделей HSV,HSL,CMYK,YUV,YCrCb,XYZ по известным RGB function ConvertRGBToFull(red,green,blue:real):TFullColor; var C:TFullColor; max,min:real; begin C.red:=red; C.green:=green; C.blue:=blue; max:=C.red; if max<C.green then max:=C.green; if max<C.blue then max:=C.blue; min:=C.red; if min>C.green then min:=C.green; if min>C.blue then min:=C.blue; if max=min then C.hue:=0 else begin if (max=C.red) and (C.green>=C.blue) then C.hue:=60*(C.green-C.blue)/(max-min); if (max=C.red) and (C.green<C.blue) then C.hue:=60*(C.green-C.blue)/(max-min)+360; if max=C.green then C.hue:=60*(C.blue-C.red)/(max-min)+120; if max=C.blue then C.hue:=60*(C.red-C.green)/(max-min)+240; end; if max=0 then C.saturation:=0 else C.saturation:=1-min/max; C.value:=max; C.lightness:=0.5*(max+min); C.Y:=0.299*C.red+0.587*C.green+0.114*C.blue; C.U:=-0.14713*C.red-0.28886*C.green+0.436*C.blue; //+128 C.V:=0.615*C.red-0.51499*C.green-0.10001*C.blue; //+128 C.Cb:=C.U; C.Cr:=C.V; C.XX:=0.49*C.red+0.31*C.green+0.1999646*C.blue; C.YY:=0.17695983*C.red+0.81242258*C.green+0.0106175*C.blue; C.ZZ:=0*C.red+0.01008*C.green+0.989913*C.blue; C.black:=1-C.red; if C.black>1-C.green then C.black:=1-C.green; if C.black>1-C.blue then C.black:=1-C.blue; if C.black=1 then begin C.cyan:=0; C.magenta:=0; C.yellow:=0; end else begin C.cyan:=(1-C.red-C.black)/(1-C.black); C.magenta:=(1-C.green-C.black)/(1-C.black); C.yellow:=(1-C.blue-C.black)/(1-C.black); end; ConvertRGBToFull:=C; end; end.
{ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. } // Copyright (c) 2010 - J. Aldo G. de Freitas Junior Unit HTMLParser; Interface Uses Classes, SysUtils, XMLScanner, HTMLNodes; Type THTMLParser = Class Private fOwnsSource : Boolean; fSource : TXMLTokenIterator; fDestination : THTMLNode; Procedure Mark(aNode : THTMLNode); Procedure ParseTagList(Const aPrevious : THTMLNode); Procedure ParseTag(Const aPrevious : THTMLNode); Procedure ParsePropertyList(Const aPrevious : THTMLNode); Procedure ParseProperty(Const aPrevious : THTMLNode); Procedure ParseText(Const aPrevious : THTMLNode); Procedure ParseSpecialTag1(Const aPrevious : THTMLNode); Procedure ParseSpecialTag2(Const aPrevious : THTMLNode); Public Constructor Create(Const aSource : TXMLTokenIterator; aDestination : THTMLNode; Const aOwnsSource : Boolean = True); Virtual; Destructor Destroy; Override; Procedure Parse; End; THTMLRootNode = Class(THTMLNode) Public Procedure DoLoadFromFile(Const aFileName : String); End; Implementation Procedure THTMLParser.Mark(aNode : THTMLNode); Begin aNode.Row := fSource.Row; aNode.Col := fSource.Col; End; Procedure THTMLParser.ParseTagList(Const aPrevious : THTMLNode); Begin // Debug WriteLn('Parsing tag list.'); While Not(fSource.IsEOS Or (fSource.Kind = tkXMLEOF)) Do If fSource.Match([tkXMLText]) Then ParseText(aPrevious) Else If fSource.Match([tkXMLOpenTag, tkXMLIdentifier]) Then ParseTag(aPrevious) Else If fSource.Match([tkXMLOpenTag, tkXMLQuestion]) Then ParseSpecialTag1(aPrevious) Else If fSource.Match([tkXMLOpenTag, tkXMLExclamation]) Then ParseSpecialTag2(aPrevious) Else If fSource.Match([tkXMLOpenTag, tkXMLSlash]) Then Exit Else fSource.RaiseError('Expected tag or text.'); // Debug WriteLn('Done.'); End; Procedure THTMLParser.ParseTag(Const aPrevious : THTMLNode); Var lTag : THTMLNode; Begin // Debug WriteLn('Parsing tag.'); fSource.Consume(tkXMLOpenTag); lTag := HTMLClassFactory.Build(fSource.Literal, aPrevious); Mark(lTag); lTag.Name := fSource.Extract(tkXMLIdentifier); ParsePropertyList(lTag); If HTMLClassFactory.TagHasChilds(lTag.Name) Then Begin fSource.Consume(tkXMLCloseTag); ParseTagList(lTag); fSource.Consume(tkXMLOpenTag); fSource.Consume(tkXMLSlash); fSource.Consume(lTag.Name); fSource.Consume(tkXMLCloseTag); End Else fSource.Consume(tkXMLCloseTag); // Debug WriteLn('Done.'); End; Procedure THTMLParser.ParsePropertyList(Const aPrevious : THTMLNode); Begin // Debug WriteLn('Parsing property list.'); While Not(fSource.Expected([tkXMLExclamation, tkXMLQuestion, tkXMLSlash, tkXMLCloseTag])) Do Begin fSource.Consume(tkXMLWhite, False); ParseProperty(aPrevious); If fSource.Expected(tkXMLEOF) Or fSource.IsEOS Then fSource.RaiseError('Unexpected end of file.'); End; // Debug WriteLn('Done.'); End; Procedure THTMLParser.ParseProperty(Const aPrevious : THTMLNode); Var lName, lValue : String; Begin // Debug WriteLn('Parsing property.'); lName := fSource.Extract(tkXMLIdentifier); fSource.Consume(tkXMLEqual); lValue := fSource.Extract(tkXMLString); aPrevious.Properties.SetValue(lName, lValue); // Debug WriteLn('Done.'); End; Procedure THTMLParser.ParseText(Const aPrevious : THTMLNode); Var lTag : THTMLTextNode; Begin // Debug WriteLn('Parsing text.'); lTag := THTMLTextNode.Create(aPrevious); lTag.Name := ''; lTag.Content := fSource.Extract(tkXMLText); // Debug WriteLn('Done.'); End; Procedure THTMLParser.ParseSpecialTag1(Const aPrevious : THTMLNode); Var lTag : THTMLSpecialTag1Node; Begin // Debug WriteLn('Parsing special tag (<?something?>).'); fSource.Consume(tkXMLOpenTag); fSource.Consume(tkXMLQuestion); lTag := THTMLSpecialTag1Node.Create(aPrevious); Mark(lTag); lTag.Name := fSource.Extract(tkXMLIdentifier); ParsePropertyList(lTag); fSource.Consume(tkXMLQuestion); fSource.Consume(tkXMLCloseTag); // Debug WriteLn('Done.'); End; Procedure THTMLParser.ParseSpecialTag2(Const aPrevious : THTMLNode); Var lTag : THTMLSpecialTag2Node; Begin // Debug WriteLn('Parsing special tag (<!something!>).'); fSource.Consume(tkXMLOpenTag); fSource.Consume(tkXMLExclamation); lTag := THTMLSpecialTag2Node.Create(aPrevious); Mark(lTag); lTag.Name := fSource.Extract(tkXMLIdentifier); ParsePropertyList(lTag); fSource.Consume(tkXMLExclamation); fSource.Consume(tkXMLCloseTag); // Debug WriteLn('Done.'); End; Constructor THTMLParser.Create(Const aSource : TXMLTokenIterator; aDestination : THTMLNode; Const aOwnsSource : Boolean = True); Begin Inherited Create; fOwnsSource := aOwnsSource; fSource := aSource; fDestination := aDestination; End; Destructor THTMLParser.Destroy; Begin If fOwnsSource Then fSource.Free; Inherited Destroy; End; Procedure THTMLParser.Parse; Begin fSource.Start; // Debug WriteLn('Parsing file.'); ParseTagList(fDestination); // Debug WriteLn('Done.'); fSource.Consume(tkXMLEOF); End; Procedure THTMLRootNode.DoLoadFromFile(Const aFileName : String); Var lTokens : TMemoryStream; Begin lTokens := TMemoryStream.Create; With TXMLScanner.Create(TXMLSource.Create(TFileStream.Create(aFileName, fmOpenRead)), lTokens) Do Begin Try Scan; Finally Free; End; End; With THTMLParser.Create(TXMLTokenIterator.Create(lTokens), Self) Do Begin Try Parse; Finally Free; End; End; End; End.
unit Viewer_u; interface uses Classes,ExtCtrls,Advanced,SysUtils,ImageHlp,Windows,Messages_u,dialogs,CRC32; Type TSowFileInfo=procedure (Sender:TObject;Var FileHead:TFileHead)of object; Type TPassQuest=procedure (Sender:TObject;Var Pass:ShortString)of object; Type TError=procedure (Sender:TObject;ErrorMsg:ShortString)of object; Type TMZFViewer=class (TComponent) private FileName:String; fOnSowFileInfo:TSowFileInfo; fOnPassQuest:TPassQuest; fOnError:TError; fOnBegin:TNotifyEvent; fOnEnd:TNotifyEvent; Password:ShortString; Comment:WideString; FileList:TStringList; Directories:TStringList; FilterPath:String; procedure GetPassword; procedure Error(Msg:ShortString); procedure ViewBegin; procedure ViewEnd; procedure ShowFileInformation(Var FileHead:TFileHead); public constructor Create; procedure Free; destructor Destroy; property ArchiveName:String read FileName write FileName; property Files:TStringList read FileList; property OnShowFileINfo:TSowFileInfo read fOnSowFileInfo write fOnSowFileInfo; property OnPassQuest:TPassQuest read fOnPassQuest write fOnPassQuest; property OnError:TError read fOnError write fOnError; property OnBegin:TNotifyEvent read fOnBegin write fOnBegin; property OnEnd:TNotifyEvent read fOnEnd write fOnEnd; property Commentary:WideString read Comment; property DirList:TStringList read Directories; property Path:String read FilterPath write FilterPath; procedure ShowFiles; procedure DeleteFiles(DeleteFileList:TStringList); procedure RenameFile(OldName,NewName:String); protected end; procedure register; //LZMA_StreamCoderDecoder_u implementation procedure register; begin RegisterComponents('M.A.D.M.A.N.', [TMZFViewer]); end; constructor TMZFViewer.Create; Begin FileList:=TStringList.Create; Directories:=TStringList.Create; Password:=''; End; procedure TMZFViewer.ViewBegin; begin If Assigned(fOnBegin) Then fOnBegin(Self); end; procedure TMZFViewer.ShowFiles; var ArchiveStream:TMemoryStream; AConfig:TArcConfig; ArcHead:TArcHead; FileHead:TFileHead; HeadSize:Word; HeadStream:TStream; Temp,CommentStream:TStream; CommentSize:LongWord; LongNameSize:Word; aLongFileName:String; //FileHeadCRC32:Cardinal; Begin If FileName='' Then Exit; If Not FileExists(FileName) Then Begin Error(rsNoFile); Exit; End; ViewBegin; Comment:=''; LongNameSize:=$0; Directories.Clear; ArchiveStream:=TMemoryStream.Create; ArchiveStream.LoadFromFile(FileName); ArchiveStream.Position:=0; ArchiveStream.Read(ArcHead,SizeOf(TArcHead)); ArchiveStream.Read(AConfig,SizeOf(TArcConfig)); //Check head If Not CheckHead(ArcHead) Then Begin Error(rsCorrupt); ArchiveStream.Free; ViewEnd; Exit; End; //Get comment IF AConfig.UseComment Then Begin Try ArchiveStream.Read(CommentSize,SizeOf(LongWord)); CommentStream:=TMemoryStream.Create; CommentStream.CopyFrom(ArchiveStream,CommentSize); Temp:=TMemoryStream.Create; If Not ExpandStream(CommentStream,Temp) Then Begin Error(rsCorrupt); ArchiveStream.Free; Temp.Free; CommentStream.Free; ViewEnd; Exit; End; CommentStream:=TMemoryStream.Create; Temp.Position:=0; CommentStream.CopyFrom(Temp,Temp.Size); CommentStream.Position:=0; Temp.Free; //CommentStream.Read(Comment,CommentStream.Size); Comment:=ReadWideString(CommentStream); CommentStream.Free; Except //Exception.Create('Error'); Error(rsCorrupt); ArchiveStream.Free; //CommentStream.Free; Exit; End; End; While ArchiveStream.Position<>ArchiveStream.Size Do Begin Try ArchiveStream.Read(HeadSize,SizeOf(Word)); HeadStream:=TMemoryStream.Create; HeadStream.CopyFrom(ArchiveStream,HeadSize); //ArchiveStream.Read(FileHeadCRC32,SizeOf(Cardinal)); HeadStream.Position:=0; //Detect encode mode // If Encode And EncodeMode=After ///////////////////////////////////// If (AConfig.EncodeHead) And ((AConfig.EncodeMode=emAfterCompress)Or ((AConfig.EncodeMode=emBeforeAfter))) Then Begin If Password='' Then GetPassword; If Password='' Then Begin HeadStream.Free; ArchiveStream.Free; ViewEnd; Exit; End; Temp:=TMemoryStream.Create; HeadStream.Position:=0; DecodeStream(HeadStream,Temp,Password,AConfig.EncodeAlgorithm); Temp.Position:=0; HeadStream:=TMemoryStream.Create; HeadStream.CopyFrom(Temp,Temp.Size); Temp.Free; End; //Extract Head Stream to Temp stream Temp:=TMemoryStream.Create; ///////////////////////////////////// HeadStream.Position:=0; {If StreamCRC32(HeadStream)<>FileHeadCRC32 Then Begin Error(rsInvalidPass); ArchiveStream.Free; HeadStream.Free; Temp.Free; Exit; End; HeadStream.Position:=0; } If Not ExpandStream(HeadStream,Temp) Then Begin Error(rsInvalidPass); ArchiveStream.Free; Temp.Free; HeadStream.Free; ViewEnd; Exit; End; ///////////////////////////////////// HeadStream:=TMemoryStream.Create; Temp.Position:=0; HeadStream.CopyFrom(Temp,Temp.Size); Temp.Free; ///////////////////////////////////// If (AConfig.EncodeHead) And ((AConfig.EncodeMode=emBeforeCompress)Or ((AConfig.EncodeMode=emBeforeAfter))) Then Begin If Password='' Then GetPassword; If Password='' Then Begin HeadStream.Free; ArchiveStream.Free; ViewEnd; Exit; End; Temp:=TMemoryStream.Create; HeadStream.Position:=0; DecodeStream(HeadStream,Temp,Password,AConfig.EncodeAlgorithm); Temp.Position:=0; HeadStream:=TMemoryStream.Create; HeadStream.CopyFrom(Temp,Temp.Size); Temp.Free; End; ///////////////////////////////////// HeadStream.Position:=0; HeadStream.Read(FileHead,SizeOf(TFileHead)-4); FileHead.LongFileName:=''; FileHead.LongFileName:=ReadWideString(HeadStream); FileHead.LongFileName:=Format(RootCaption,[ExtractFileName(FileName)])+FileHead.LongFileName; //End create root If Not TextInList(ExtractFileDir(FileHead.LongFileName),Directories) Then Directories.Add(ExtractFileDir(FileHead.LongFileName)); FileList.Add(FileHead.LongFileName); {If Not TextInList(ExtractFileDir(FileHead.LongFileName),Directories) Then Directories.Add(ExtractFileDir(FileHead.LongFileName));} If ExtractFileDir(FileHead.LongFileName)=FilterPath Then ShowFileInformation(FileHead); ArchiveStream.Seek(FileHead.PackedSize,soFromCurrent); Except //Exception.Create('Error'); Error(rsInvalidPass); ArchiveStream.Free; HeadStream.Free; Exit; End; End; ArchiveStream.Free; ViewEnd; End; procedure TMZFViewer.DeleteFiles(DeleteFileList:TStringList); var ArchiveStream:TMemoryStream; AConfig:TArcConfig; ArcHead:TArcHead; FileHead:TFileHead; HeadSize:Word; HeadStream:TStream; Temp,CommentStream:TStream; CommentSize:LongWord; SaveStream:TMemoryStream; MemPos,ContPos:LongWord; Attr:Word; LongNameSize:Word; aLongFileName:String; //FileHeadCRC32:Cardinal; Begin If FileName='' Then Exit; If Not FileExists(FileName) Then Begin Error(rsNoFile); Exit; End; ViewBegin; LongNameSize:=$0; SaveStream:=TMemoryStream.Create; ArchiveStream:=TMemoryStream.Create; ArchiveStream.LoadFromFile(FileName); ArchiveStream.Position:=0; ArchiveStream.Read(ArcHead,SizeOf(TArcHead)); ArchiveStream.Read(AConfig,SizeOf(TArcConfig)); //Check head If Not CheckHead(ArcHead) Then Begin Error(rsCorrupt); ArchiveStream.Free; ViewEnd; Exit; End; //Get comment If AConfig.UseComment Then Begin ArchiveStream.Read(CommentSize,SizeOf(LongWord)); ArchiveStream.Seek(CommentSize,soFromCurrent); End; MemPos:=ArchiveStream.Position; ArchiveStream.Position:=0; SaveStream.CopyFrom(ArchiveStream,MemPos); While ArchiveStream.Position<>ArchiveStream.Size Do Begin Try MemPos:=ArchiveStream.Position; ArchiveStream.Read(HeadSize,SizeOf(Word)); HeadStream:=TMemoryStream.Create; HeadStream.CopyFrom(ArchiveStream,HeadSize); //ArchiveStream.Read(FileHeadCRC32,SizeOf(Cardinal)); HeadStream.Position:=0; //Detect encode mode // If Encode And EncodeMode=After ///////////////////////////////////// If (AConfig.EncodeHead) And ((AConfig.EncodeMode=emAfterCompress)Or ((AConfig.EncodeMode=emBeforeAfter))) Then Begin If Password='' Then GetPassword; If Password='' Then Begin HeadStream.Free; ArchiveStream.Free; ViewEnd; Exit; End; Temp:=TMemoryStream.Create; HeadStream.Position:=0; DecodeStream(HeadStream,Temp,Password,AConfig.EncodeAlgorithm); Temp.Position:=0; HeadStream:=TMemoryStream.Create; HeadStream.CopyFrom(Temp,Temp.Size); Temp.Free; End; //Extract Head Stream to Temp stream Temp:=TMemoryStream.Create; ///////////////////////////////////// HeadStream.Position:=0; {If StreamCRC32(HeadStream)<>FileHeadCRC32 Then Begin Error(rsInvalidPass); ArchiveStream.Free; HeadStream.Free; Temp.Free; Exit; End; HeadStream.Position:=0; } If Not ExpandStream(HeadStream,Temp) Then Begin ArchiveStream.Free; Temp.Free; HeadStream.Free; Exit; End; ///////////////////////////////////// HeadStream:=TMemoryStream.Create; Temp.Position:=0; HeadStream.CopyFrom(Temp,Temp.Size); Temp.Free; ///////////////////////////////////// If (AConfig.EncodeHead) And ((AConfig.EncodeMode=emBeforeCompress)Or ((AConfig.EncodeMode=emBeforeAfter))) Then Begin If Password='' Then GetPassword; If Password='' Then Begin HeadStream.Free; ArchiveStream.Free; ViewEnd; Exit; End; Temp:=TMemoryStream.Create; HeadStream.Position:=0; DecodeStream(HeadStream,Temp,Password,AConfig.EncodeAlgorithm); Temp.Position:=0; HeadStream:=TMemoryStream.Create; HeadStream.CopyFrom(Temp,Temp.Size); Temp.Free; End; ///////////////////////////////////// HeadStream.Position:=0; HeadStream.Read(FileHead,SizeOf(TFileHead)-4); FileHead.LongFileName:=''; FileHead.LongFileName:=ReadWideString(HeadStream); ArchiveStream.Seek(FileHead.PackedSize,soFromCurrent); ContPos:=ArchiveStream.Position; If Not TextInList(FileHead.LongFileName,DeleteFileList) Then Begin ArchiveStream.Position:=MemPos; SaveStream.CopyFrom(ArchiveStream,ContPos-MemPos); ArchiveStream.Position:=ContPos; End; Except //Exception.Create('Error'); Error(rsCorrupt); ArchiveStream.Free; SaveStream.Free; Exit; End; End; Attr:=FileGetAttr(FileName); ArchiveStream.Clear; ArchiveStream.SaveToFile(FileName); ArchiveStream.Free; FileSetAttr(FileName,0); SaveStream.SaveToFile(FileName); SaveStream.Free; FileSetAttr(FileName,Attr); ViewEnd; End; procedure TMZFViewer.RenameFile(OldName,NewName:String); Var ArchiveStream:TMemoryStream; SaveStream:TMemoryStream; Temp,HeadStream:TStream; FileContainer:TStream; ArcHead:TArcHead; AConfig:TArcConfig; FileHead:TFileHead; MemPos,ContPos:LongWord; HeadSize:Word; CommentSize:LongWord; Attr:Word; //FileHeadCRC32:Cardinal; Begin If FileName='' Then Exit; If Not FileExists(FileName) Then Begin Error(rsNoFile); Exit; End; ViewBegin; ArchiveStream:=TMemoryStream.Create; ArchiveStream.LoadFromFile(FileName); ArchiveStream.Read(ArcHead,SizeOf(TArcHead)); ArchiveStream.Read(AConfig,SizeOf(TArcConfig)); If Not CheckHead(ArcHead) Then Begin Error(rsCorrupt); ArchiveStream.Free; ViewEnd; Exit; End; //Get comment If AConfig.UseComment Then Begin ArchiveStream.Read(CommentSize,SizeOf(LongWord)); ArchiveStream.Seek(CommentSize,soFromCurrent); End; SaveStream:=TMemoryStream.Create; MemPos:=ArchiveStream.Position; ArchiveStream.Position:=0; SaveStream.CopyFrom(ArchiveStream,MemPos); ArchiveStream.Position:=MemPos; While ArchiveStream.Position<>ArchiveStream.Size Do Begin Try MemPos:=ArchiveStream.Position; ArchiveStream.Read(HeadSize,SizeOf(Word)); HeadStream:=TMemoryStream.Create; HeadStream.CopyFrom(ArchiveStream,HeadSize); //ArchiveStream.Read(FileHeadCRC32,SizeOf(Cardinal)); HeadStream.Position:=0; ////////////////////// If AConfig.EncodeHead And ((AConfig.EncodeMode=emBeforeCompress)Or (AConfig.EncodeMode=emBeforeAfter)) Then Begin If Password='' Then GetPassword; If Password='' Then Begin HeadStream.Free; ArchiveStream.Free; ViewEnd; Exit; End; Temp:=TMemoryStream.Create; Temp.CopyFrom(HeadStream,HeadStream.Size); HeadStream:=TMemoryStream.Create; DecodeStream(Temp,HeadStream,Password,AConfig.EncodeAlgorithm); HeadStream.Position:=0; Temp.Free; End; //expand Temp:=TMemoryStream.Create; ///////////////////////////////////// HeadStream.Position:=0; {If StreamCRC32(HeadStream)<>FileHeadCRC32 Then Begin Error(rsInvalidPass); ArchiveStream.Free; HeadStream.Free; Temp.Free; Exit; End; HeadStream.Position:=0;} If Not ExpandStream(HeadStream,Temp) Then Begin ArchiveStream.Free; Temp.Free; HeadStream.Free; Exit; End; HeadStream.Free; HeadStream:=TMemoryStream.Create; Temp.Position:=0; HeadStream.CopyFrom(Temp,Temp.Size); HeadStream.Position:=0; //End expand; If AConfig.EncodeHead And ((AConfig.EncodeMode=emAfterCompress)Or (AConfig.EncodeMode=emBeforeAfter)) Then Begin If Password='' Then GetPassword; If Password='' Then Begin HeadStream.Free; ArchiveStream.Free; ViewEnd; Exit; End; Temp:=TMemoryStream.Create; Temp.CopyFrom(HeadStream,HeadStream.Size); HeadStream:=TMemoryStream.Create; DecodeStream(Temp,HeadStream,Password,AConfig.EncodeAlgorithm); HeadStream.Position:=0; Temp.Free; End; ////////////////////// HeadStream.Read(FileHead,SizeOf(TFileHead)-4); FileHead.LongFileName:=''; FileHead.LongFileName:=ReadWideString(HeadStream); If UpperCase(OldName)=UpperCase(FileHead.LongFileName) Then Begin FileContainer:=TMemoryStream.Create; FIleContainer.CopyFrom(ArchiveStream,FileHead.PackedSize); FileContainer.Position:=0; FileHead.LongFileName:=''; FileHead.LongFileName:=NewName; HeadStream:=TMemoryStream.Create; HeadStream.Write(FileHead,SizeOf(TFileHead)-4); WriteWideString(HeadStream,FileHead.LongFileName); HeadStream.Position:=0; If AConfig.EncodeHead And ((AConfig.EncodeMode=emBeforeCompress)Or (AConfig.EncodeMode=emBeforeAfter)) Then Begin If Password='' Then GetPassword; If Password='' Then Begin HeadStream.Free; ArchiveStream.Free; ViewEnd; Exit; End; Temp:=TMemoryStream.Create; Temp.CopyFrom(HeadStream,HeadStream.Size); Temp.Position:=0; HeadStream:=TMemoryStream.Create; EncodeStream(Temp,HeadStream,Password,AConfig.EncodeAlgorithm); HeadStream.Position:=0; End; Temp:=TMemoryStream.Create; Temp.CopyFrom(HeadStream,HeadStream.Size); Temp.Position:=0; HeadStream.Free; HeadStream:=TMemoryStream.Create; CompressStream(Temp,HeadStream); HeadStream.Position:=0; //// If AConfig.EncodeHead And ((AConfig.EncodeMode=emAfterCompress)Or (AConfig.EncodeMode=emBeforeAfter)) Then Begin If Password='' Then GetPassword; If Password='' Then Begin HeadStream.Free; ArchiveStream.Free; ViewEnd; Exit; End; Temp:=TMemoryStream.Create; Temp.CopyFrom(HeadStream,HeadStream.Size); Temp.Position:=0; HeadStream:=TMemoryStream.Create; EncodeStream(Temp,HeadStream,Password,AConfig.EncodeAlgorithm); HeadStream.Position:=0; End; HeadSize:=HeadStream.Size; SaveStream.Write(HeadSize,SizeOf(Word)); SaveStream.CopyFrom(HeadStream,HeadSize); SaveStream.CopyFrom(FileContainer,FileContainer.Size); End Else Begin ArchiveStream.Seek(FileHead.PackedSize,soFromCurrent); ContPos:=ArchiveStream.Position; ArchiveStream.Position:=MemPos; SaveStream.CopyFrom(ArchiveStream,ContPos-MemPos); ArchiveStream.Position:=ContPos; End; Except //Exception.Create('Error'); Error(rsCorrupt); ArchiveStream.Free; SaveStream.Free; Exit; End; End; Attr:=FileGetAttr(FileName); ArchiveStream.Clear; ArchiveStream.SaveToFile(FileName); ArchiveStream.Free; FileSetAttr(FileName,0); SaveStream.SaveToFile(FileName); SaveStream.Free; FileSetAttr(FileName,Attr); ViewEnd; End; procedure TMZFViewer.ViewEnd; begin If Assigned(fOnEnd) Then fOnEnd(Self); end; procedure TMZFViewer.GetPassword; begin If Assigned(fOnPassQuest) Then fOnPassQuest(Self,Password); end; procedure TMZFViewer.Error(Msg:ShortString); begin If Assigned(fOnError) Then fOnError(Self,Msg); end; procedure TMZFViewer.ShowFileInformation(Var FileHead:TFileHead); begin If Assigned(fOnSowFileInfo) Then fOnSowFileInfo(Self,FileHead); end; procedure TMZFViewer.Free; begin If Self<>Nil Then Begin FileList.Free; Directories.Free; Destroy; End; end; destructor TMZFViewer.Destroy; Begin End; end.
unit GfdFrame; interface uses GrfPrim,GrEPS, Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls; type TGfdBox = class(TFrame) DrawBox: TPaintBox; Roman: TLabel; RomanItal: TLabel; RomanBold: TLabel; Symbol: TLabel; Helvetica: TLabel; HelvItal: TLabel; HelvBold: TLabel; Courier: TLabel; CourierItal: TLabel; CourierBold: TLabel; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DrawBoxPaint(Sender: TObject); private { Private declarations } Items : TStringList; procedure AddPrim(Prim : TGraphPrim); procedure ClearList; public { Public declarations } procedure SaveEPS(FileName : String); procedure SaveGED(FileName : String); procedure ReadGED(FileName : String); procedure geClear; procedure geLine(X1,Y1,X2,Y2 : Number; Color : TColor; Width : Number = 1; Style : TPenStyle = psSolid); procedure geArrow(X1,Y1,X2,Y2 : Number; Color : TColor; Width : Number = 1; Style : TPenStyle = psSolid); procedure geRect(X1,Y1,X2,Y2 : Number; Color : TColor; Width : Number = 1; Style : TPenStyle=psSolid); procedure geBar(X1,Y1,X2,Y2 : Number; Color : TColor); procedure geFillRect(X1,Y1,X2,Y2 : Number; PenColor,BrushColor : TColor; PenWidth : Number; PenStyle : TPenStyle; BrushStyle : TBrushStyle; BrushKind : TBrushKind = bkTransparent); procedure geCircle(X,Y,R : Number; Color : TColor; Width : Number = 1; Style : TPenStyle = psSolid); procedure geDisk(X,Y,R : Number; Color : TColor); procedure geFillCircle(X,Y,R : Number; PenColor,BrushColor : TColor; PenWidth : Number; PenStyle : TPenStyle; BrushStyle : TBrushStyle; BrushKind : TBrushKind = bkTransparent); procedure geEllipse(X1,Y1,X2,Y2 : Number; Color : TColor; Width : Number = 1; Style : TPenStyle = psSolid); procedure geFillEllipse(X1,Y1,X2,Y2 : Number; PenColor,BrushColor : TColor; PenWidth : Number; PenStyle : TPenStyle; BrushStyle : TBrushStyle; BrushKind : TBrushKind = bkTransparent); procedure gePolyLine(Points : TFPoints; Color : TColor; Width : Number = 1; Style : TPenStyle = psSolid); procedure gePolyGon(Points : TFPoints; PenColor,BrushColor : TColor; PenWidth : Number; PenStyle : TPenStyle; BrushStyle : TBrushStyle; BrushKind : TBrushKind = bkTransparent); procedure geText(sText : string; X,Y,H : Number; Color : TColor; fnt : epsFonts = efRoman); procedure geTextRot(sText : string; X,Y,H,Angle : Number; Color : TColor; fnt : epsFonts); procedure geBitmap(X1,Y1,X2,Y2 : Number; const FileName : String); end; {TODO Image: see PRLM2.PDF pp 224,225} implementation {$R *.dfm} constructor TGfdBox.Create(AOwner: TComponent); begin inherited; Items := TStringList.Create; WinFonts[efRoman] := Roman.Font; WinFonts[efRomanItal] := RomanItal.Font; WinFonts[efRomanBold] := RomanBold.Font; WinFonts[efSymbol] := Symbol.Font; WinFonts[efHelvetica] := Helvetica.Font; WinFonts[efHelvItal] := HelvItal.Font; WinFonts[efHelvBold] := HelvBold.Font; WinFonts[efCourier] := Courier.Font; WinFonts[efCourierItal] := CourierItal.Font; WinFonts[efCourierBold] := CourierBold.Font; end; destructor TGfdBox.Destroy; begin ClearList; Items.Free; inherited end; procedure TGfdBox.ClearList; var i : integer; begin if Items <> nil then begin with Items do for i := 0 to Count-1 do Objects[i].Free; Items.Clear; end; end; procedure TGfdBox.AddPrim(Prim : TGraphPrim); begin Items.AddObject(Prim.PrimCaption,Prim); end; procedure TGfdBox.SaveEPS(FileName : String); var i : integer; fo : TextFile; begin AssignFile(fo,FileName); Rewrite(fo); with DrawBox do epsWriteHeader(fo,Width,Height,''); if Items <> nil then with Items do begin for i := 0 to Count-1 do with Objects[i] as TGraphPrim do WriteEps(fo); end; epsWriteFooter(fo); CloseFile(fo); end; procedure TGfdBox.SaveGED(FileName : String); var i : integer; fo : TextFile; begin AssignFile(fo,FileName); Rewrite(fo); Writeln(fo,Width,' ',Height); if Items <> nil then with Items do begin for i := 0 to Count-1 do with Objects[i] as TGraphPrim do WriteText(fo); end; CloseFile(fo); end; procedure TGfdBox.ReadGED(FileName : String); var fi : TextFile; PrimRef : TGrPrimRef; W,H : Integer; PName : String; Prim : TGraphPrim; begin AssignFile(fi,FileName); reset(fi); readln(fi,W,H); with DrawBox do begin Width := W; Height := H; end; repeat Readln(fi,PName); if PName = 'Line' then PrimRef := TPrimLine else if PName = 'Rectangle' then PrimRef := TPrimRect else if PName = 'Ellipse' then PrimRef := TPrimEllipse else if PName = 'Text' then PrimRef := TPrimRotText else if PName = 'SimpleArrow' then PrimRef := TPrimArrow1 else if PName = 'WavyLine' then PrimRef := TWavyLine else if PName = 'PolyLine' then PrimRef := TPolyLine else if PName = 'Polygon' then PrimRef := TPolyGon else if PName = 'Bitmap' then PrimRef := TPrimBitmap else PrimRef := nil; if PrimRef <> nil then begin Prim := PrimRef.ReadFromFile(fi); AddPrim(Prim); end until eof(fi); CloseFile(fi); DrawBoxPaint(Self); end; procedure TGfdBox.DrawBoxPaint(Sender: TObject); var i : integer; begin with DrawBox.Canvas do begin Brush.Color := clWhite; Brush.Style := bsSolid; FillRect(Classes.Rect(0,0,Width,Height)); if Items <> nil then with Items do for i := 0 to Count-1 do with Items.Objects[i] as TGraphPrim do Draw(DrawBox.Canvas,false); end; end; procedure TGfdBox.geClear; begin ClearList; DrawBoxPaint(Self); end; procedure TGfdBox.geLine(X1,Y1,X2,Y2 : Number; Color : TColor; Width : Number; Style : TPenStyle); begin AddPrim(TPrimLine.Create(X1,Y1,X2,Y2,Color,0,Width,Style, bsSolid,bkTransparent)); DrawBoxPaint(Self); end; procedure TGfdBox.geArrow(X1,Y1,X2,Y2 : Number; Color : TColor; Width : Number; Style : TPenStyle); begin AddPrim(TPrimArrow1.Create(X1,Y1,X2,Y2,Color,0,Width,Style, bsSolid,bkTransparent)); DrawBoxPaint(Self); end; procedure TGfdBox.geRect(X1,Y1,X2,Y2 : Number; Color : TColor; Width : Number; Style : TPenStyle); begin AddPrim(TPrimRect.Create(X1,Y1,X2,Y2,Color,0,Width,Style, bsClear,bkTransparent)); DrawBoxPaint(Self); end; procedure TGfdBox.geBar(X1,Y1,X2,Y2 : Number; Color : TColor); begin AddPrim(TPrimRect.Create(X1,Y1,X2,Y2,Color,Color,1,psClear, bsSolid,bkTransparent)); DrawBoxPaint(Self); end; procedure TGfdBox.geFillRect(X1,Y1,X2,Y2 : Number; PenColor,BrushColor : TColor; PenWidth : Number; PenStyle : TPenStyle; BrushStyle : TBrushStyle; BrushKind : TBrushKind); begin AddPrim(TPrimRect.Create(X1,Y1,X2,Y2,PenColor,BrushColor,PenWidth, PenStyle,BrushStyle,BrushKind)); DrawBoxPaint(Self); end; procedure TGfdBox.geCircle(X,Y,R : Number; Color : TColor; Width : Number; Style : TPenStyle); begin AddPrim(TPrimCircle.Create(X-R,Y-R,X+R,Y+R,Color,Color,Width, Style,bsClear,bkTransparent)); DrawBoxPaint(Self); end; procedure TGfdBox.geDisk(X,Y,R : Number; Color : TColor); begin AddPrim(TPrimCircle.Create(X-R,Y-R,X+R,Y+R,Color,Color,1,psClear, bsSolid,bkTransparent)); DrawBoxPaint(Self); end; procedure TGfdBox.geFillCircle(X,Y,R : Number; PenColor,BrushColor : TColor; PenWidth : Number; PenStyle : TPenStyle; BrushStyle : TBrushStyle; BrushKind : TBrushKind); begin AddPrim(TPrimCircle.Create(X-R,Y-R,X+R,Y+R,PenColor,BrushColor,PenWidth, PenStyle,BrushStyle,BrushKind)); DrawBoxPaint(Self); end; procedure TGfdBox.geEllipse(X1,Y1,X2,Y2 : Number; Color : TColor; Width : Number; Style : TPenStyle); begin AddPrim(TPrimEllipse.Create(X1,Y1,X2,Y2,Color,0,Width,Style, bsClear,bkTransparent)); DrawBoxPaint(Self); end; procedure TGfdBox.geFillEllipse(X1,Y1,X2,Y2 : Number; PenColor,BrushColor : TColor; PenWidth : Number; PenStyle : TPenStyle; BrushStyle : TBrushStyle; BrushKind : TBrushKind); begin AddPrim(TPrimEllipse.Create(X1,Y1,X2,Y2,PenColor,BrushColor,PenWidth, PenStyle,BrushStyle,BrushKind)); DrawBoxPaint(Self); end; procedure TGfdBox.gePolyLine(Points : TFPoints; Color : TColor; Width : Number; Style : TPenStyle); var PLine : TPolyLine; i : integer; begin PLine := TPolyLine.Create(Points[0].X,Points[0].Y,Points[1].X,Points[1].Y, Color,0,Width,Style,bsSolid,bkTransparent); for i := 2 to Length(Points)-1 do PLine.SetInt(Points[i].X,Points[i].Y); AddPrim(PLine); DrawBoxPaint(Self); end; procedure TGfdBox.gePolyGon(Points : TFPoints; PenColor,BrushColor : TColor; PenWidth : Number; PenStyle : TPenStyle; BrushStyle : TBrushStyle; BrushKind : TBrushKind); var PGon : TPolyGon; i : integer; begin PGon := TPolyGon.Create(Points[0].X,Points[0].Y,Points[1].X,Points[1].Y, PenColor,BrushColor,PenWidth,PenStyle,BrushStyle,BrushKind); for i := 2 to Length(Points)-1 do PGon.SetInt(Points[i].X,Points[i].Y); AddPrim(PGon); DrawBoxPaint(Self); end; procedure TGfdBox.geText(sText : string; X,Y,H : Number; Color : TColor; fnt : epsFonts); var PrText : TPrimText; begin PrText := TPrimText.Create(X,Y,X+H,Y+H,Color,0,1,psSolid, bsSolid,bkTransparent); PrText.Text := sText; PrText.FntN := fnt; AddPrim(PrText); DrawBoxPaint(Self); end; procedure TGfdBox.geTextRot(sText : string; X,Y,H,Angle : Number; Color : TColor; fnt : epsFonts); var PrText : TPrimRotText; begin PrText := TPrimRotText.Create(X,Y,X+H,Y+H,Color,0,1,psSolid, bsSolid,bkTransparent); PrText.Text := sText; PrText.FntN := fnt; PrText.Rot := Angle; AddPrim(PrText); DrawBoxPaint(Self); end; procedure TGfdBox.geBitmap(X1,Y1,X2,Y2 : Number; const FileName : String); var PrBmp : TPrimBitmap; begin PrBmp := TPrimBitMap.Create(X1,Y1,X2,Y2,clBlack,clWhite,1, psSolid,bsClear,bkTransparent); PrBmp.LoadImage(FileName); AddPrim(PrBmp); DrawBoxPaint(Self); end; end.
unit SpecifierTests; // The contents of this file are subject to the Mozilla Public License // Version 1.1 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // http://www.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the // License for the specific language governing rights and limitations // under the License. // // The Original Code is DUnitLite. // // The Initial Developer of the Original Code is Joe White. // Portions created by Joe White are Copyright (C) 2007 // Joe White. All Rights Reserved. // // Contributor(s): // // Alternatively, the contents of this file may be used under the terms // of the LGPL license (the "LGPL License"), in which case the // provisions of LGPL License are applicable instead of those // above. If you wish to allow use of your version of this file only // under the terms of the LGPL License and not to allow others to use // your version of this file under the MPL, indicate your decision by // deleting the provisions above and replace them with the notice and // other provisions required by the LGPL License. If you do not delete // the provisions above, a recipient may use your version of this file // under either the MPL or the LGPL License. interface uses Constraints, Specifications, TestValues, Values; type TestSpecify = class(TRegisterableSpecification) strict private FBase: TBase; procedure SpecifyShouldFail(AValue: TValue; SatisfiesCondition: IConstraint; AExpectedExceptionMessage: string); procedure SpecifyShouldFailGivenMessage(AValue: TValue; SatisfiesCondition: IConstraint; AMessage: string; AExpectedExceptionMessage: string); strict protected procedure SetUp; override; procedure TearDown; override; published // All specifications support messages procedure TestPassingWithMessage; procedure TestFailingWithMessage; // Equality: Should.Equal, including "ToWithin" and "Exactly" procedure TestPassingShouldEqual; procedure TestFailingShouldEqual; procedure TestPassingShouldEqualToWithin; procedure TestFailingShouldEqualToWithin; procedure TestPassingShouldEqualExactly; procedure TestFailingShouldEqualExactly; procedure TestPassingShouldNotEqual; procedure TestFailingShouldNotEqual; procedure TestPassingShouldNotEqualToWithin; procedure TestFailingShouldNotEqualToWithin; procedure TestPassingShouldNotEqualExactly; procedure TestFailingShouldNotEqualExactly; procedure TestFailingLongStringsShouldEqual; // Equality: Should.Be.True procedure TestPassingShouldBeTrue; procedure TestFailingShouldBeTrue; procedure TestPassingShouldNotBeTrue; procedure TestFailingShouldNotBeTrue; // Equality: Should.Be.False procedure TestPassingShouldBeFalse; procedure TestFailingShouldBeFalse; procedure TestPassingShouldNotBeFalse; procedure TestFailingShouldNotBeFalse; // Class: Should.Be.OfType procedure TestPassingShouldBeOfType; procedure TestFailingShouldBeOfType; procedure TestFailingShouldBeOfTypeWhenNil; procedure TestPassingShouldNotBeOfType; procedure TestPassingShouldNotBeOfTypeWhenNil; procedure TestFailingShouldNotBeOfType; // Reference: Should.ReferTo procedure TestPassingShouldReferTo; procedure TestFailingShouldReferTo; procedure TestPassingShouldNotReferTo; procedure TestFailingShouldNotReferTo; // Reference: Should.Be.Assigned procedure TestPassingShouldBeAssigned; procedure TestFailingShouldBeAssigned; procedure TestPassingShouldNotBeAssigned; procedure TestFailingShouldNotBeAssigned; // Reference: Should.Be.Nil procedure TestPassingShouldBeNull; procedure TestFailingShouldBeNull; procedure TestPassingShouldNotBeNull; procedure TestFailingShouldNotBeNull; // Inequality: Should.Be.AtLeast procedure TestPassingShouldBeAtLeast; procedure TestFailingShouldBeAtLeast; procedure TestPassingShouldNotBeAtLeast; procedure TestFailingShouldNotBeAtLeast; // Inequality: Should.Be.AtMost procedure TestPassingShouldBeAtMost; procedure TestFailingShouldBeAtMost; procedure TestPassingShouldNotBeAtMost; procedure TestFailingShouldNotBeAtMost; // Inequality: Should.Be.Between procedure TestPassingShouldBeBetween; procedure TestFailingShouldBeBetween; procedure TestPassingShouldNotBeBetween; procedure TestFailingShouldNotBeBetween; // Inequality: Should.Be.GreaterThan procedure TestPassingShouldBeGreaterThan; procedure TestFailingShouldBeGreaterThan; procedure TestPassingShouldNotBeGreaterThan; procedure TestFailingShouldNotBeGreaterThan; // Inequality: Should.Be.InRange procedure TestPassingShouldBeInRange; procedure TestFailingShouldBeInRange; procedure TestPassingShouldNotBeInRange; procedure TestFailingShouldNotBeInRange; // Inequality: Should.Be.LessThan procedure TestPassingShouldBeLessThan; procedure TestFailingShouldBeLessThan; procedure TestPassingShouldNotBeLessThan; procedure TestFailingShouldNotBeLessThan; end; implementation uses SysUtils, TestFramework; { TestSpecify } procedure TestSpecify.SetUp; begin inherited; FBase := TBase.Create; end; procedure TestSpecify.SpecifyShouldFail(AValue: TValue; SatisfiesCondition: IConstraint; AExpectedExceptionMessage: string); begin SpecifyShouldFailGivenMessage(AValue, SatisfiesCondition, '', AExpectedExceptionMessage); end; procedure TestSpecify.SpecifyShouldFailGivenMessage(AValue: TValue; SatisfiesCondition: IConstraint; AMessage, AExpectedExceptionMessage: string); var ExceptionMessage: string; begin // can't use ExpectedException, because it doesn't work for ETestFailure ExceptionMessage := 'no exception'; try Specify.That(AValue, SatisfiesCondition, AMessage); except on E: ETestFailure do ExceptionMessage := E.Message; end; CheckEquals(AExpectedExceptionMessage, ExceptionMessage); end; procedure TestSpecify.TearDown; begin FreeAndNil(FBase); inherited; end; procedure TestSpecify.TestFailingLongStringsShouldEqual; begin SpecifyShouldFail(StringOfChar('<', 100) + '1' + StringOfChar('>', 100), Should.Equal(StringOfChar('<', 100) + '2' + StringOfChar('>', 100)), 'Expected: ...''<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<2>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>''...'#13#10 + ' but was: ...''<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<1>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>''...'); end; procedure TestSpecify.TestFailingShouldBeAssigned; begin SpecifyShouldFail(nil, Should.Be.Assigned, 'Expected: not nil object'#13#10' but was: nil object'); end; procedure TestSpecify.TestFailingShouldBeAtLeast; begin SpecifyShouldFail(1, Should.Be.AtLeast(2), 'Expected: >= 2'#13#10' but was: 1'); end; procedure TestSpecify.TestFailingShouldBeAtMost; begin SpecifyShouldFail(2, Should.Be.AtMost(1), 'Expected: <= 1'#13#10' but was: 2'); end; procedure TestSpecify.TestFailingShouldBeBetween; begin SpecifyShouldFail(0, Should.Be.Between(1, 3), 'Expected: in range (1, 3)'#13#10' but was: 0'); end; procedure TestSpecify.TestFailingShouldBeFalse; begin SpecifyShouldFail(True, Should.Be.False, 'Expected: False'#13#10' but was: True'); end; procedure TestSpecify.TestFailingShouldBeGreaterThan; begin SpecifyShouldFail(2, Should.Be.GreaterThan(2), 'Expected: > 2'#13#10' but was: 2'); end; procedure TestSpecify.TestFailingShouldBeInRange; begin SpecifyShouldFail(4, Should.Be.InRange(1, 3), 'Expected: in range [1, 3]'#13#10' but was: 4'); end; procedure TestSpecify.TestFailingShouldBeLessThan; begin SpecifyShouldFail(3, Should.Be.LessThan(3), 'Expected: < 3'#13#10' but was: 3'); end; procedure TestSpecify.TestFailingShouldBeNull; begin SpecifyShouldFail(FBase, Should.Be.Null, Format('Expected: nil object'#13#10' but was: TBase($%.8x)', [Integer(FBase)])); end; procedure TestSpecify.TestFailingShouldBeOfType; begin SpecifyShouldFail(FBase, Should.Be.OfType(TObject), 'Expected: TObject'#13#10' but was: TBase'); end; procedure TestSpecify.TestFailingShouldBeOfTypeWhenNil; begin SpecifyShouldFail(nil, Should.Be.OfType(TObject), 'Expected: TObject'#13#10' but was: nil object'); end; procedure TestSpecify.TestFailingShouldBeTrue; begin SpecifyShouldFail(False, Should.Be.True, 'Expected: True'#13#10' but was: False'); end; procedure TestSpecify.TestFailingShouldEqual; begin SpecifyShouldFail(1, Should.Equal(2), 'Expected: 2'#13#10' but was: 1'); end; procedure TestSpecify.TestFailingShouldEqualExactly; begin SpecifyShouldFail(EpsilonTestValues.BaseValue, Should.Equal(EpsilonTestValues.BarelyDifferent).Exactly, 'Expected: 42 (exactly)'#13#10' but was: 42'); end; procedure TestSpecify.TestFailingShouldEqualToWithin; begin SpecifyShouldFail(1.0, Should.Equal(1.75).ToWithin(0.5), 'Expected: 1.75 (to within 0.5)'#13#10' but was: 1'); end; procedure TestSpecify.TestFailingShouldNotBeAssigned; begin SpecifyShouldFail(FBase, Should.Not.Be.Assigned, Format('Expected: nil object'#13#10' but was: TBase($%.8x)', [Integer(FBase)])); end; procedure TestSpecify.TestFailingShouldNotBeAtLeast; begin SpecifyShouldFail(1, Should.Not.Be.AtLeast(1), 'Expected: not >= 1'#13#10' but was: 1'); SpecifyShouldFail(2, Should.Not.Be.AtLeast(1), 'Expected: not >= 1'#13#10' but was: 2'); end; procedure TestSpecify.TestFailingShouldNotBeAtMost; begin SpecifyShouldFail(1, Should.Not.Be.AtMost(1), 'Expected: not <= 1'#13#10' but was: 1'); SpecifyShouldFail(1, Should.Not.Be.AtMost(2), 'Expected: not <= 2'#13#10' but was: 1'); end; procedure TestSpecify.TestFailingShouldNotBeBetween; begin SpecifyShouldFail(2, Should.Not.Be.Between(1, 3), 'Expected: not in range (1, 3)'#13#10' but was: 2'); end; procedure TestSpecify.TestFailingShouldNotBeFalse; begin SpecifyShouldFail(False, Should.Not.Be.False, 'Expected: not False'#13#10' but was: False'); end; procedure TestSpecify.TestFailingShouldNotBeGreaterThan; begin SpecifyShouldFail(3, Should.Not.Be.GreaterThan(2), 'Expected: not > 2'#13#10' but was: 3'); end; procedure TestSpecify.TestFailingShouldNotBeInRange; begin SpecifyShouldFail(3, Should.Not.Be.InRange(1, 3), 'Expected: not in range [1, 3]'#13#10' but was: 3'); end; procedure TestSpecify.TestFailingShouldNotBeLessThan; begin SpecifyShouldFail(2, Should.Not.Be.LessThan(3), 'Expected: not < 3'#13#10' but was: 2'); end; procedure TestSpecify.TestFailingShouldNotBeNull; begin SpecifyShouldFail(nil, Should.Not.Be.Null, 'Expected: not nil object'#13#10' but was: nil object'); end; procedure TestSpecify.TestFailingShouldNotBeOfType; begin SpecifyShouldFail(FBase, Should.Not.Be.OfType(TBase), 'Expected: not TBase'#13#10' but was: TBase'); end; procedure TestSpecify.TestFailingShouldNotBeTrue; begin SpecifyShouldFail(True, Should.Not.Be.True, 'Expected: not True'#13#10' but was: True'); end; procedure TestSpecify.TestFailingShouldNotEqual; begin SpecifyShouldFail(1, Should.Not.Equal(1), 'Expected: not 1'#13#10' but was: 1'); end; procedure TestSpecify.TestFailingShouldNotEqualExactly; begin SpecifyShouldFail(1.0, Should.Not.Equal(1.0).Exactly, 'Expected: not 1 (exactly)'#13#10' but was: 1'); end; procedure TestSpecify.TestFailingShouldNotEqualToWithin; begin SpecifyShouldFail(1.0, Should.Not.Equal(1.25).ToWithin(0.5), 'Expected: not 1.25 (to within 0.5)'#13#10' but was: 1'); end; procedure TestSpecify.TestFailingShouldNotReferTo; begin SpecifyShouldFail(FBase, Should.Not.ReferTo(FBase), Format('Expected: not TBase($%.8x)'#13#10' but was: TBase($%0:.8x)', [Integer(FBase)])); end; procedure TestSpecify.TestFailingShouldReferTo; begin SpecifyShouldFail(FBase, Should.ReferTo(nil), Format('Expected: nil object'#13#10' but was: TBase($%.8x)', [Integer(FBase)])); end; procedure TestSpecify.TestFailingWithMessage; begin SpecifyShouldFailGivenMessage(2, Should.Equal(1), 'One', 'One'#13#10'Expected: 1'#13#10' but was: 2'); end; procedure TestSpecify.TestPassingShouldBeAssigned; begin Specify.That(FBase, Should.Be.Assigned); end; procedure TestSpecify.TestPassingShouldBeAtLeast; begin Specify.That(1, Should.Be.AtLeast(1)); Specify.That(2, Should.Be.AtLeast(1)); end; procedure TestSpecify.TestPassingShouldBeAtMost; begin Specify.That(1, Should.Be.AtMost(1)); Specify.That(1, Should.Be.AtMost(2)); end; procedure TestSpecify.TestPassingShouldBeBetween; begin Specify.That(2, Should.Be.Between(1, 3)); end; procedure TestSpecify.TestPassingShouldBeFalse; begin Specify.That(False, Should.Be.False); end; procedure TestSpecify.TestPassingShouldBeGreaterThan; begin Specify.That(3, Should.Be.GreaterThan(2)); end; procedure TestSpecify.TestPassingShouldBeInRange; begin Specify.That(3, Should.Be.InRange(1, 3)); end; procedure TestSpecify.TestPassingShouldBeLessThan; begin Specify.That(2, Should.Be.LessThan(3)); end; procedure TestSpecify.TestPassingShouldBeNull; begin Specify.That(nil, Should.Be.Null); end; procedure TestSpecify.TestPassingShouldBeOfType; begin Specify.That(FBase, Should.Be.OfType(TBase)); end; procedure TestSpecify.TestPassingShouldBeTrue; begin Specify.That(True, Should.Be.True); end; procedure TestSpecify.TestPassingShouldEqual; begin Specify.That(1, Should.Equal(1)); end; procedure TestSpecify.TestPassingShouldEqualExactly; begin Specify.That(1.0, Should.Equal(1.0).Exactly); end; procedure TestSpecify.TestPassingShouldEqualToWithin; begin Specify.That(1.0, Should.Equal(1.25).ToWithin(0.5)); end; procedure TestSpecify.TestPassingShouldNotBeAssigned; begin Specify.That(nil, Should.Not.Be.Assigned); end; procedure TestSpecify.TestPassingShouldNotBeAtLeast; begin Specify.That(1, Should.Not.Be.AtLeast(2)); end; procedure TestSpecify.TestPassingShouldNotBeAtMost; begin Specify.That(2, Should.Not.Be.AtMost(1)); end; procedure TestSpecify.TestPassingShouldNotBeBetween; begin Specify.That(0, Should.Not.Be.Between(1, 3)); end; procedure TestSpecify.TestPassingShouldNotBeFalse; begin Specify.That(True, Should.Not.Be.False); end; procedure TestSpecify.TestPassingShouldNotBeGreaterThan; begin Specify.That(2, Should.Not.Be.GreaterThan(2)); end; procedure TestSpecify.TestPassingShouldNotBeInRange; begin Specify.That(4, Should.Not.Be.InRange(1, 3)); end; procedure TestSpecify.TestPassingShouldNotBeLessThan; begin Specify.That(3, Should.Not.Be.LessThan(3)); end; procedure TestSpecify.TestPassingShouldNotBeNull; begin Specify.That(FBase, Should.Not.Be.Null); end; procedure TestSpecify.TestPassingShouldNotBeOfType; begin Specify.That(FBase, Should.Not.Be.OfType(TObject)); end; procedure TestSpecify.TestPassingShouldNotBeOfTypeWhenNil; begin Specify.That(nil, Should.Not.Be.OfType(TObject)); end; procedure TestSpecify.TestPassingShouldNotBeTrue; begin Specify.That(False, Should.Not.Be.True); end; procedure TestSpecify.TestPassingShouldNotEqual; begin Specify.That(1, Should.Not.Equal(2)); end; procedure TestSpecify.TestPassingShouldNotEqualExactly; begin Specify.That(EpsilonTestValues.BaseValue, Should.Not.Equal(EpsilonTestValues.BarelyDifferent).Exactly); end; procedure TestSpecify.TestPassingShouldNotEqualToWithin; begin Specify.That(1.0, Should.Not.Equal(1.75).ToWithin(0.5)); end; procedure TestSpecify.TestPassingShouldNotReferTo; begin Specify.That(FBase, Should.Not.ReferTo(nil)); end; procedure TestSpecify.TestPassingShouldReferTo; begin Specify.That(FBase, Should.ReferTo(FBase)); end; procedure TestSpecify.TestPassingWithMessage; begin Specify.That(1, Should.Equal(1), 'Message'); end; initialization TestSpecify.Register; end.
{ @abstrcat ( Basic foundation class definition ) @author ( Joonhae.lee@gmail.com ) @created ( 2014.12 ) @lastmod ( 2014.12 ) } unit NBaseClass; interface uses System.Classes, System.SysUtils, System.Generics.Collections; type { Base ancestor of data class } TNData = class(TPersistent) private fTagObject: TObject; public constructor Create; virtual; destructor Destroy; override; procedure ResetValues; virtual; function Clone(ASource: TPersistent; AResetBeforeCopy: Boolean = false): TNData; virtual; procedure PrintDebug(AStrings: TStrings; Indent: String = ' '); property TagObject: TObject read fTagObject write fTagObject; end; TNDataClass = class of TNData; { Base ancestor for database data object } TNSqlData = class(TNData) public TotalRecordCount: Integer; Page: Integer; RecordsPerPage: Integer; // FromRec: Integer; // RecCount: Integer; SortFields: String; end; { TNList : Conainer for TNData } TNList = class(TObjectList<TNData>) public destructor Destroy; override; procedure Clone(ASrc: TNList; AnItemClass: TNDataClass); procedure Clear; virtual; procedure FreeItems; virtual; procedure PrintDebug(AStrings: TStrings; Indent: String = ''); virtual; function Find(APropName: String; AValue: Variant): TNData; overload; end; implementation uses DateUtils, NBaseRtti, NBasePerf, TypInfo; { TNData } constructor TNData.Create; begin inherited create; fTagObject := nil; TNPerf.Done(format('Class.Counter.%s', [ClassName])); end; destructor TNData.Destroy; begin TNPerf.Done(format('Class.Counter.%s', [ClassName]), -1); inherited; end; procedure TNData.ResetValues; begin TNRtti.ClearObjectFields(Self, true); end; function TNData.Clone(ASource: TPersistent; AResetBeforeCopy: Boolean = false): TNData; begin if Self <> ASource then begin if ASource = nil then ResetValues else TNRtti.CloneObjectFields(ASource, Self, true, AResetBeforeCopy); end; Exit(Self); end; procedure TNData.PrintDebug(AStrings: TStrings; Indent: String = ' '); begin TNRtti.PrintObjectValues(Self, AStrings, Indent); end; { TNList } function TNList.Find(APropName: String; AValue: Variant): TNData; var i: Integer; begin result := nil; for i:=0 to Count-1 do begin if GetPropValue(Items[i], APropName) = AValue then begin result := Items[i]; Exit; end; end; end; procedure TNList.FreeItems; var i: Integer; begin for i:=Count-1 downto 0 do Items[i].Free; Clear; end; procedure TNList.Clear; begin inherited Clear; end; procedure TNList.Clone(ASrc: TNList; AnItemClass: TNDataClass); var s, n: TNData; begin Clear; if ASrc = nil then Exit; for s in ASrc do begin n := AnItemClass.Create; n.Clone(s); Add(n); end; end; destructor TNList.Destroy; begin inherited; end; procedure TNList.PrintDebug(AStrings: TStrings; Indent: String = ''); var i: Integer; begin for i:=0 to Count-1 do begin AStrings.Add(Indent + format('%d''th item: %s', [i, Items[i].ClassName])); TNRtti.PrintObjectValues(Items[i], AStrings, Indent + Indent, false); end; end; end.
edit stringpack.pas c TYPE StopperType = SET OF Character; FUNCTION GetString(VAR S: String; Stoppers: Stoppertype; F: Filedesc): boolean; {Gets a string from file F until a stopper is reached. Returns True if a string/stopper combination is encountered. Returns False if no stopper is encountered before maxstr (256) or ENDFILE} VAR I,I2: Integer; C: Character; Junk: String; BEGIN {GetString} I:=1; S[I] := Getcf(C,F); IF (S[I] IN Stoppers) OR (S[I] = ENDFILE) THEN BEGIN {IF} S[1] := ENDSTR; GetString := False; END; {if} ELSE BEGIN {ELSE} REPEAT I := I + 1; S[I] := Getcf(c,f) UNTIL (S[I] IN Stoppers) OR (I = MAXSTR) OR (S[I] = ENDFILE) IF I = MAXSTR THEN BEGIN {IF} I2 := 1; REPEAT Junk[I2] := Getcf(c,f); I2 := I2+1 UNTIL (Junk[I2] IN Stoppers) OR (I2 = MAXSTR) OR (Junk[I2] = ENDFILE) END; {IF} S[I] := ENDSTR; GetString := True; IF S[I] := ENDFILE THEN BEGIN S[1] := ENDSTR; GetString := False; END; {if} END; {IF-ELSE} END; {Getstring} (*********************************************************************) PROCEDURE Print (VAR S: String; F: Filedesc); {Puts contents of S out to file F} VAR Counter: integer; BEGIN {PRINT} Counter := 1; WHILE S[Counter] <> ENDSTR DO BEGIN {WHILE} Putcf(S[Counter],F); Counter := Counter + 1; END; {WHILE} END; {PRINT} (********************************************************************) (*FUNCTION Length (VAR S: String): integer; {returns number of significant characters in S (not ENDSTR)} VAR Counter: Integer; BEGIN {Length} Counter := 1; WHILE (S[Counter] <> ENDSTR) DO Counter := Counter + 1; Length := N - 1; END; {Length} *) (********************************************************************) 
{ Description: vPlot sketcher class. Copyright (C) 2017-2019 Melchiorre Caruso <melchiorrecaruso@gmail.com> This source is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy of the GNU General Public License is available on the World Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit vpsketcher; {$mode objfpc} interface uses bgrabitmap, classes, math, fpimage, sysutils, vpdriver, vpmath, vppaths; type tvpsketcher = class private fbit: tbgrabitmap; fdotsize: vpfloat; fpatternh: vpfloat; fpatternw: vpfloat; fpatternbh: longint; fpatternbw: longint; function getdarkness(x, y, heigth, width: longint): vpfloat; public constructor create(bit: tbgrabitmap); destructor destroy; override; procedure update(elements: tvpelementlist); virtual abstract; public property dotsize: vpfloat read fdotsize write fdotsize; property patternh: vpfloat read fpatternh write fpatternh; property patternw: vpfloat read fpatternw write fpatternw; property patternbh: longint read fpatternbh write fpatternbh; property patternbw: longint read fpatternbw write fpatternbw; end; tvpsketchersquare = class(tvpsketcher) private function step1(n, heigth, width: vpfloat): tvpelementlist; virtual; public procedure update(elements: tvpelementlist); override; end; tvpsketcherroundedsquare = class(tvpsketchersquare) private function step1(n, heigth, width: vpfloat): tvpelementlist; override; function step2(elements: tvpelementlist; radius: vpfloat): tvpelementlist; end; tvpsketchertriangular = class(tvpsketcher) private function step1(n, heigth, width: vpfloat): tvpelementlist; virtual; public procedure update(elements: tvpelementlist); override; end; implementation // tvpsketcher constructor tvpsketcher.create(bit: tbgrabitmap); begin inherited create; fbit := bit; fdotsize := 0.5; fpatternh := 10; fpatternw := 10; fpatternbh := 10; fpatternbw := 10; end; destructor tvpsketcher.destroy; begin inherited destroy; end; function tvpsketcher.getdarkness(x, y, heigth, width: longint): vpfloat; var i: longint; j: longint; c: tfpcolor; begin result := 0; for j := 0 to heigth -1 do for i := 0 to width -1 do begin c := fbit.colors[x+i, y+j]; result := result + c.blue; result := result + c.green; result := result + c.red; end; result := 1 - result/(3*$FFFF*(heigth*width)); end; // tvpsketchersquare function tvpsketchersquare.step1(n, heigth, width: vpfloat): tvpelementlist; var line: tvpline; begin result := tvpelementlist.create; if n > 0 then begin line.p0.x := 0; line.p0.y := 0; line.p1.x := width/(n*2); line.p1.y := 0; result.add(line); while line.p1.x < width do begin if line.p1.x - line.p0.x > 0 then begin line.p0 := line.p1; if line.p1.y = 0 then line.p1.y := line.p1.y + heigth else line.p1.y := 0 end else begin line.p0 := line.p1; line.p1.x := line.p1.x + width/n; if line.p1.x > width then line.p1.x := width; end; result.add(line); end; end else begin line.p0.x := 0; line.p0.y := 0; line.p1.x := width; line.p1.y := 0; result.add(line); end; result.interpolate(0.5); end; procedure tvpsketchersquare.update(elements: tvpelementlist); var i, j, k: longint; aw, ah: longint; dark: vpfloat; list1: tvpelementlist; list2: tvpelementlist; mx: boolean; begin list1 := tvpelementlist.create; aw := (fbit.width div fpatternbw); ah := (fbit.height div fpatternbh); mx := false; j := 0; while j < ah do begin i := 0; while i < aw do begin dark := getdarkness(fpatternbw*i, fpatternbh*j, fpatternbw, fpatternbh); list2 := step1(round((fpatternw/dotsize)*dark), fpatternh, fpatternw); if mx then begin list2.mirrorx; list2.move(0, patternw); end; mx := list2.items[list2.count -1].last^.y > 0; for k := 0 to list2.count -1 do begin list2.items[k].move(patternw*i, patternw*j); list2.items[k].layer := j; end; list1.merge(list2); list2.destroy; inc(i, 1); end; if j mod 2 = 1 then list1.invert; elements.merge(list1); inc(j, 1); end; list1.destroy; elements.mirrorx; elements.movetoorigin; elements.interpolate(0.5); end; // tvpsketcherroundedsquare function tvpsketcherroundedsquare.step1(n, heigth, width: vpfloat): tvpelementlist; begin if n > 0 then result := step2(inherited step1(n, heigth, width), width/(2*n)) else result := inherited step1(n, heigth, width) end; function tvpsketcherroundedsquare.step2(elements: tvpelementlist; radius: vpfloat): tvpelementlist; var i: longint; l0: tvpline; l1: tvpline; a0: tvpcirclearc; begin result := tvpelementlist.create; if elements.count = 1 then begin result.add(elements.extract(0)); end else begin l0.p0 := tvpelementline(elements.items[0]).first^; l0.p1 := tvpelementline(elements.items[0]).last^; for i := 1 to elements.count -1 do begin l1.p0 := tvpelementline(elements.items[i]).first^; l1.p1 := tvpelementline(elements.items[i]).last^; if (l0.p1.y = 0) and (l1.p1.y > 0) then // left-bottom corner begin a0.radius := radius; a0.center.x := l0.p1.x - radius; a0.center.y := l0.p1.y + radius; a0.startangle := 270; a0.endangle := 360; l0.p1.x := a0.center.x; l1.p0.y := a0.center.y; result.add(a0); end else if (l0.p1.y > 0) and (l1.p1.y > 0) then // left-top corner begin a0.radius := radius; a0.center.x := l0.p1.x + radius; a0.center.y := l0.p1.y - radius; a0.startangle := 180; a0.endangle := 90; l1.p0.x := a0.center.x; l0.p1.y := a0.center.y; result.add(l0); result.add(a0); end else if (l0.p1.y > 0) and (l1.p1.y = 0) then // right-top corner begin a0.radius := radius; a0.center.x := l0.p1.x - radius; a0.center.y := l0.p1.y - radius; a0.startangle := 90; a0.endangle := 0; l0.p1.x := a0.center.x; l1.p0.y := a0.center.y; result.add(a0); end else if (l0.p1.y = 0) and (l1.p1.y = 0) then // right-bottom corner begin a0.radius := radius; a0.center.x := l0.p1.x + radius; a0.center.y := l0.p1.y + radius; a0.startangle := 180; a0.endangle := 270; l1.p0.x := a0.center.x; l0.p1.y := a0.center.y; result.add(l0); result.add(a0); end; l0 := l1; end; end; elements.destroy; result.interpolate(0.5); end; // tvpsketchertriangular function tvpsketchertriangular.step1(n, heigth, width: vpfloat): tvpelementlist; var line: tvpline; begin result := tvpelementlist.create; if n > 0 then begin line.p0.x := 0; line.p0.y := 0; line.p1.x := width/(n*2); line.p1.y := heigth; result.add(line); while line.p1.x < width do begin if line.p1.y > line.p0.y then begin line.p0 := line.p1; line.p1.x := min(line.p1.x + width/(n), width); line.p1.y := 0; end else begin line.p0 := line.p1; line.p1.x := min(line.p1.x + width/(n), width); line.p1.y := heigth; end; result.add(line); end; end else begin line.p0.x := 0; line.p0.y := 0; line.p1.x := width; line.p1.y := 0; result.add(line); end; result.interpolate(0.5); end; procedure tvpsketchertriangular.update(elements: tvpelementlist); var i, j, k: longint; aw, ah: longint; dark: vpfloat; list1: tvpelementlist; list2: tvpelementlist; mx: boolean; begin list1 := tvpelementlist.create; aw := (fbit.width div fpatternbw); ah := (fbit.height div fpatternbw); mx := false; j := 0; while j < ah do begin i := 0; while i < aw do begin dark := getdarkness(fpatternbw*i, fpatternbh*j, fpatternbw, fpatternbh); list2 := step1(round((fpatternw/dotsize)*dark), fpatternh, fpatternw); if mx then begin list2.mirrorx; list2.move(0, patternw); end; mx := list2.items[list2.count -1].last^.y > 0; for k := 0 to list2.count -1 do begin list2.items[k].move(patternw*i, patternw*j); list2.items[k].layer := j; end; list1.merge(list2); list2.destroy; inc(i, 1); end; if j mod 2 = 1 then list1.invert; elements.merge(list1); inc(j, 1); end; list1.destroy; elements.mirrorx; elements.movetoorigin; elements.interpolate(0.5); end; end.
unit UPrefFDocOperation; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. } { This is the Frame that contains the Document Operation Preferences} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, UGlobals, UContainer, ExtCtrls; type TPrefDocOperation = class(TFrame) chkAutoComplete: TCheckBox; ckbAutoTrans: TCheckBox; ckbAutoCalc: TCheckBox; chkAddEditMenus: TCheckBox; chkEMAddUndo: TCheckBox; chkEMAddCut: TCheckBox; chkEMAddCopy: TCheckBox; chkEMAddCellPref: TCheckBox; chkEMAddClear: TCheckBox; chkEMAddPaste: TCheckBox; edtStartPage: TEdit; edtTotalPages: TEdit; ChkAutoNumPages: TCheckBox; chkDisplayPgNums: TCheckBox; ckbUseEnterAsX: TCheckBox; ckbAutoSelect: TCheckBox; chkTxUpper: TCheckBox; chkAutoRunReviewer: TCheckBox; Panel1: TPanel; lblPgStart: TStaticText; lblPgTotal: TStaticText; fldCommentsForm: TComboBox; lblCommentsForm: TStaticText; ckbLinkComments: TCheckBox; chkOptimizeImage: TCheckBox; ImageQualityGroup: TGroupBox; rdoImgQualHigh: TRadioButton; rdoImgQualMed: TRadioButton; rdoImgQualLow: TRadioButton; rdoImgQualVeryLow: TRadioButton; ckbAutoFitFont: TCheckBox; procedure chkAddEditMenusClick(Sender: TObject); procedure chkDisplayPgNumsClick(Sender: TObject); procedure ChkAutoNumPagesClick(Sender: TObject); procedure edtStartPageExit(Sender: TObject); procedure NumberFilter(Sender: TObject; var Key: Char); //procedure chkOptimizeImageClick(Sender: TObject); private FDoc: TContainer; private procedure PopulateCommentsFormList; public constructor CreateFrame(AOwner: TComponent; ADoc: TContainer); procedure LoadPrefs; //loads in the prefs from the app procedure SavePrefs; //saves the changes function CheckCompliance: Boolean; end; implementation uses ComCtrls, UInit, UUtil1, UStatus, UMain, UFormsLib, UBase; {$R *.dfm} procedure TPrefDocOperation.PopulateCommentsFormList; var formID: Integer; index: Integer; node: TTreeNode; begin node := nil; if assigned(FormsLib) then //avoid crash if FormsLibrary folder not found begin for index := 0 to FormsLib.FormLibTree.Items.Count - 1 do if SameText(FormsLib.FormLibTree.Items[index].Text, 'Comments') then begin node := FormsLib.FormLibTree.Items[index]; break; end; if Assigned(node) then for index := 0 to node.Count - 1 do begin formID := TFormIDInfo(node.Item[index].Data).fFormUID; fldCommentsForm.Items.AddObject(node.Item[index].Text, Pointer(formID)); end; end; end; constructor TPrefDocOperation.CreateFrame(AOwner: TComponent; ADoc: TContainer); begin inherited Create(AOwner); FDoc := ADoc; chkAutoRunReviewer.visible := True; //not IsStudentVersion; PopulateCommentsFormList; LoadPrefs; end; procedure TPrefDocOperation.LoadPrefs; var index: Integer; begin //Operations chkAutoComplete.Checked := IsAppPrefSet(bAutoComplete); ckbAutoTrans.Checked := IsAppPrefSet(bAutoTransfer); ckbAutoCalc.checked := IsAppPrefSet(bAutoCalc); ckbAutoSelect.checked := IsAppPrefSet(bAutoSelect); chkTxUpper.checked := LongBool(appPref_PrefFlags and (1 shl bUpperCase)); //IsAppPrefSet(bUpperCase); chkTxUpper.Enabled := not main.ActiveDocIsUAD; ckbUseEnterAsX.checked := IsAppPrefSet(bUseEnterKeyAsX); ckbLinkComments.Checked := IsAppPrefSet(bLinkComments); //Operations - adding Edit Menus chkAddEditMenus.checked := appPref_AddEditM2Popups; chkEMAddUndo.Enabled := appPref_AddEditM2Popups; chkEMAddCut.Enabled := appPref_AddEditM2Popups; chkEMAddCopy.Enabled := appPref_AddEditM2Popups; chkEMAddPaste.Enabled := appPref_AddEditM2Popups; chkEMAddClear.Enabled := appPref_AddEditM2Popups; chkEMAddCellPref.Enabled := appPref_AddEditM2Popups; //set previous settings chkEMAddUndo.Checked := IsBitSet(appPref_AddEM2PUpPref, bAddEMUndo); chkEMAddCut.checked := IsBitSet(appPref_AddEM2PUpPref, bAddEMCut); chkEMAddCopy.checked := IsBitSet(appPref_AddEM2PUpPref, bAddEMCopy); chkEMAddPaste.Checked := IsBitSet(appPref_AddEM2PUpPref, bAddEMPaste); chkEMAddClear.Checked := IsBitSet(appPref_AddEM2PUpPref, bAddEMClear); chkEMAddCellPref.checked := IsBitSet(appPref_AddEM2PUpPref, bAddEMCellPref); //reviewer - moved from Appraiser Prefs chkAutoRunReviewer.checked := appPref_AppraiserAutoRunReviewer; // Set Document Prefs; if have Active use those, else use defaults if FDoc = nil then begin //page numbering chkDisplayPgNums.Checked := true; chkAutoNumPages.checked := true; chkAutoNumPages.enabled := true; lblPgStart.Enabled := False; lblPgTotal.Enabled := False; edtStartPage.Enabled := False; edtTotalPages.Enabled := False; end else begin //if doc <> nil then //Page numbering chkDisplayPgNums.checked := FDoc.DisplayPgNums; //appPref_DisplayPgNumbers; if chkDisplayPgNums.checked then chkAutoNumPages.Enabled := True else chkAutoNumPages.Enabled := False; chkAutoNumPages.checked := FDoc.AutoPgNumber; //appPref_AutoPageNumber; edtStartPage.text := ''; edtTotalPages.Text := ''; if FDoc.ManualStartPg > 0 then edtStartPage.text := IntToStr(FDoc.ManualStartPg); if FDoc.ManualTotalPg > 0 then edtTotalPages.Text := IntToStr(FDoc.ManualTotalPg); end; // appPref_DefaultCommentsForm for index := 0 to fldCommentsForm.Items.Count - 1 do if (Integer(fldCommentsForm.Items.Objects[index]) = appPref_DefaultCommentsForm) then fldCommentsForm.ItemIndex := index; chkOptimizeImage.Checked := appPref_ImageAutoOptimization; //github 71 ckbAutoFitFont.Checked := appPref_AutoFitTextToCell; rdoImgQualHigh.Checked := False; //reset to False before we read from ini rdoImgQualMed.Checked := false; rdoImgQualLow.Checked := False; rdoImgQualVeryLow.Checked := False; case appPref_ImageOptimizedQuality of imgQualHigh: rdoImgQualHigh.Checked := True; imgQualMed: rdoImgQualMed.Checked := True; imgQualLow: rdoImgQualLow.Checked := True; imgQualVeryLow: rdoImgQualVeryLow.Checked := True; end; end; procedure TPrefDocOperation.SavePrefs; var startPg, TotalPg: Integer; begin If CheckCompliance then //Operations SetAppPref(bAutoComplete, chkAutoComplete.Checked); SetAppPref(bAutoTransfer, ckbAutoTrans.Checked); SetAppPref(bAutoCalc, ckbAutoCalc.Checked); SetAppPref(bAutoSelect, ckbAutoSelect.Checked); SetAppPref(bUpperCase, chkTxUpper.Checked); SetAppPref(bUseEnterKeyAsX, ckbUseEnterAsX.checked); SetAppPref(bLinkComments, ckbLinkComments.checked); appPref_AddEditM2Popups := chkAddEditMenus.checked; appPref_AddEM2PUpPref := SetBit2Flag(appPref_AddEM2PUpPref, bAddEMUndo, chkEMAddUndo.Checked); appPref_AddEM2PUpPref := SetBit2Flag(appPref_AddEM2PUpPref, bAddEMCut, chkEMAddCut.checked); appPref_AddEM2PUpPref := SetBit2Flag(appPref_AddEM2PUpPref, bAddEMCopy, chkEMAddCopy.checked); appPref_AddEM2PUpPref := SetBit2Flag(appPref_AddEM2PUpPref, bAddEMPaste, chkEMAddPaste.Checked); appPref_AddEM2PUpPref := SetBit2Flag(appPref_AddEM2PUpPref, bAddEMClear, chkEMAddClear.Checked); appPref_AddEM2PUpPref := SetBit2Flag(appPref_AddEM2PUpPref, bAddEMCellPref, chkEMAddCellPref.checked); //reviewer - moved from Appraiser appPref_AppraiserAutoRunReviewer := chkAutoRunReviewer.checked; //Active Document Preferences if (FDoc <> nil) then begin //Operations - immediate change to editor if FDoc.docEditor <> nil then FDoc.docEditor.FUpperCase := chkTxUpper.checked; //Page numbering FDoc.DisplayPgNums := chkDisplayPgNums.checked; startPg := StrToIntDef(edtStartPage.text, 0); TotalPg := StrToIntDef(edtTotalPages.Text, 0); if (FDoc.AutoPgNumber <> chkAutoNumPages.checked) or (startPg <>FDoc.ManualStartPg) or (TotalPg<>FDoc.ManualTotalPg) then begin FDoc.ManualStartPg := startPg; FDoc.ManualTotalPg := TotalPg; FDoc.AutoPgNumber := chkAutoNumPages.checked; //save this last to reset doc pages end; end; // appPref_DefaultCommentsForm if (fldCommentsForm.ItemIndex >= 0) then appPref_DefaultCommentsForm := Integer(fldCommentsForm.Items.Objects[fldCommentsForm.ItemIndex]); //github 71: appPref_ImageAutoOptimization := chkOptimizeImage.Checked; appPref_AutoFitTextToCell := ckbAutoFitFont.Checked; if rdoImgQualHigh.Checked then appPref_ImageOptimizedQuality := imgQualHigh //High else if rdoImgQualMed.Checked then appPref_ImageOptimizedQuality := imgQualMed else if rdoImgQualLow.Checked then appPref_ImageOptimizedQuality := imgQualLow else if rdoImgQualVeryLow.Checked then appPref_ImageOptimizedQuality := imgQualVeryLow; end; procedure TPrefDocOperation.chkAddEditMenusClick(Sender: TObject); var EnableOK: Boolean; begin EnableOK := chkAddEditMenus.checked; chkEMAddUndo.Enabled := EnableOK; chkEMAddCut.Enabled := EnableOK; chkEMAddCopy.Enabled := EnableOK; chkEMAddPaste.Enabled := EnableOK; chkEMAddClear.Enabled := EnableOK; chkEMAddCellPref.Enabled := EnableOK; end; procedure TPrefDocOperation.chkDisplayPgNumsClick(Sender: TObject); begin if chkDisplayPgNums.Checked then begin chkAutoNumPages.Enabled := True; if not chkAutoNumPages.checked then begin lblPgStart.Enabled := True; lblPgTotal.Enabled := True; edtStartPage.Enabled := True; edtTotalPages.Enabled := True; end; end else begin chkAutoNumPages.Enabled := False; lblPgStart.Enabled := False; lblPgTotal.Enabled := False; edtStartPage.Enabled := False; edtTotalPages.Enabled := False; end; end; procedure TPrefDocOperation.ChkAutoNumPagesClick(Sender: TObject); begin if chkAutoNumPages.checked then begin lblPgStart.Enabled := False; lblPgTotal.Enabled := False; edtStartPage.Enabled := False; edtTotalPages.Enabled := False; end else begin lblPgStart.Enabled := True; lblPgTotal.Enabled := True; edtStartPage.Enabled := True; edtTotalPages.Enabled := True; end; end; procedure TPrefDocOperation.edtStartPageExit(Sender: TObject); var start, total: Integer; begin if assigned(FDoc) and (length(edtTotalPages.text) = 0) then begin start := StrToIntDef(edtStartPage.text, 0); total := start + FDoc.docForm.TotalReportPages + 1; edtTotalPages.text := IntToStr(total); end; end; procedure TPrefDocOperation.NumberFilter(Sender: TObject; var Key: Char); begin if not (Key in [#08, '0'..'9']) then key := char(#0); end; function TPrefDocOperation.CheckCompliance: Boolean; var start, total: Integer; begin result := True; if chkAutoNumPages.Enabled and not chkAutoNumPages.checked then //if not auto-number, check for page number compliance begin start := StrToIntDef(edtStartPage.text, 0); total := StrToIntDef(edtTotalPages.Text, 0); result := (start > 0) and (start <= total); if not result then ShowNotice('When opting for manual page numbering, a starting page number must be entered and the total number of pages must be greater or equal to the start page number.'); end; end; {procedure TPrefDocOperation.chkOptimizeImageClick(Sender: TObject); var EnableOK: Boolean; begin EnableOK := chkOptimizeImage.checked; ComprQualityGroup.Visible := EnableOK; DPIGroup.Visible := EnableOK; end; } end.
PROGRAM Stat(INPUT, OUTPUT); VAR Min, Max, Sum, Number, CountDigit: INTEGER; Overflow: BOOLEAN; PROCEDURE ReadDigit(VAR F: TEXT; VAR D: INTEGER); VAR Ch: CHAR; BEGIN{ReadDigit} READ(F, Ch); D := -1; IF (Ch = '0') THEN D := 0 ELSE IF (Ch = '1') THEN D := 1 ELSE IF (Ch = '2') THEN D := 2 ELSE IF (Ch = '3') THEN D := 3 ELSE IF (Ch = '4') THEN D := 4 ELSE IF (Ch = '5') THEN D := 5 ELSE IF (Ch = '6') THEN D := 6 ELSE IF (Ch = '7') THEN D := 7 ELSE IF (Ch = '8') THEN D := 8 ELSE IF (Ch = '9') THEN D := 9 END;{ReadDigit} PROCEDURE ReadNumber(VAR F: TEXT; VAR N: INTEGER); {Преобразует строку цифр из файла до первого нецифрового символа, в соответствующее целое число N} VAR Digit: INTEGER; BEGIN{ReadNumber} Digit := 0; N:=0; WHILE (Digit <> -1) AND ( N <> -1) DO BEGIN ReadDigit(INPUT, Digit); IF (Digit <> -1) THEN IF (N < MAXINT DIV 10) OR (( MAXINT MOD 10 > Digit) AND (MAXINT DIV 10 = N)) THEN N := N * 10 + Digit ELSE IF(N > MAXINT DIV 10) THEN N := -1 END END;{ReadNumber} BEGIN{Stat} Max := 0; Min := MAXINT; Sum := 0; Number := 0; CountDigit := 0; Overflow := FALSE; WHILE (NOT Overflow) AND (NOT EOLN) DO BEGIN ReadNumber(INPUT, Number); Overflow := (CountDigit >= MAXINT - 1) OR (Number = -1) OR (Sum > (MAXINT - Number)); IF Overflow THEN WRITELN('Введено неверное значение или переполнение') ELSE BEGIN CountDigit := CountDigit + 1; Sum := Sum + Number; IF (Max < Number) THEN Max := Number; IF (Min > Number) THEN Min := Number; END END; IF (NOT Overflow) THEN BEGIN IF (CountDigit > 0) THEN BEGIN WRITELN('Min= ', Min); WRITELN('Max= ', Max); WRITELN('Average= ', Sum DIV CountDigit, '.', Sum MOD CountDigit * 100 DIV CountDigit); END ELSE WRITELN('Ничего не введено') END END.{Stat}
(***********************************************************) (* Notify My Android Demo *) (* https://www.notifymyandroid.com *) (* *) (* part of the Digital Home Server project *) (* http://www.digitalhomeserver.net *) (* info@digitalhomeserver.net *) (* *) (* This unit is freeware, credits are appreciated *) (***********************************************************) unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, NMAUnit, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP; type TMainForm = class(TForm) APIKeyEdit: TEdit; Label1: TLabel; VerifyButton: TButton; GroupBox1: TGroupBox; SendButton: TButton; SubjectEdit: TEdit; Label2: TLabel; Label3: TLabel; MessageEdit: TMemo; DebugLog: TMemo; Label4: TLabel; DevKeyEdit: TEdit; ApplicationEdit: TEdit; Label5: TLabel; CodeLabel: TLabel; MsgLabel: TLabel; procedure VerifyButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure SendButtonClick(Sender: TObject); private { Private declarations } NMA : TNMA; procedure LogData(LogData : String); public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.dfm} procedure TMainForm.FormCreate(Sender: TObject); begin NMA := TNMA.Create; // Create the Notify My Android object NMA.OnLogData := LogData; // event trigger for logging purposes end; // Verify the api key procedure TMainForm.VerifyButtonClick(Sender: TObject); begin if Trim(APIKeyEdit.Text) = '' then begin ShowMessage('API Key can not be empty'); Exit; end; if NMA.GetInfo(APIKeyEdit.Text) then begin CodeLabel.Caption := 'Success'; MsgLabel.Caption := ''; end else begin CodeLabel.Caption := 'Error'; MsgLabel.Caption := NMA.ErrorInfo.Msg; end; end; // Send a message procedure TMainForm.SendButtonClick(Sender: TObject); begin NMA.SendMessage(APIKeyEdit.Text,SubjectEdit.Text,MessageEdit.Text,ApplicationEdit.Text,0); end; procedure TMainForm.LogData(LogData: string); begin DebugLog.Lines.Add(LogData); end; end.
unit GR32_TestGuiPngDisplay; (* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 or LGPL 2.1 with linking exception * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Alternatively, the contents of this file may be used under the terms of the * Free Pascal modified version of the GNU Lesser General Public License * Version 2.1 (the "FPC modified LGPL License"), in which case the provisions * of this license are applicable instead of those above. * Please see the file LICENSE.txt for additional information concerning this * license. * * The Original Code is Graphics32 * * The Initial Developer of the Original Code is * Christian-W. Budde * * Portions created by the Initial Developer are Copyright (C) 2000-2009 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) interface uses {$IFDEF FPC} LCLIntf, {$ELSE} Windows, Messages, {$ENDIF} SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, GR32, GR32_Image; type TFmDisplay = class(TForm) BtNo: TButton; BtYes: TButton; Image32: TImage32; LbQuestion: TLabel; LbRenderer: TLabel; RbInternal: TRadioButton; RbPngImage: TRadioButton; procedure FormShow(Sender: TObject); procedure RbInternalClick(Sender: TObject); procedure RbPngImageClick(Sender: TObject); private FReference : TBitmap32; FInternal : TBitmap32; procedure ClearImage32; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Reference: TBitmap32 read FReference write FReference; property Internal: TBitmap32 read FInternal write FInternal; end; var FmDisplay: TFmDisplay; implementation {$IFDEF FPC} {$R *.lfm} {$ELSE} {$R *.dfm} {$ENDIF} constructor TFmDisplay.Create(AOwner: TComponent); begin inherited; FInternal := TBitmap32.Create; FInternal.DrawMode := dmBlend; FReference := TBitmap32.Create; FReference.DrawMode := dmBlend; end; destructor TFmDisplay.Destroy; begin FreeAndNil(FInternal); FreeAndNil(FReference); inherited; end; procedure TFmDisplay.FormShow(Sender: TObject); begin RbInternal.Checked := True; RbInternalClick(Sender); end; procedure TFmDisplay.ClearImage32; const Colors: array [Boolean] of TColor32 = ($FFFFFFFF, $FFB0B0B0); var R: TRect; I, J: Integer; OddY: Integer; TilesHorz, TilesVert: Integer; TileX, TileY: Integer; TileHeight, TileWidth: Integer; begin Image32.Bitmap.Clear($FFFFFFFF); TileHeight := 8; TileWidth := 8; R := Image32.ClientRect; TilesHorz := (R.Right - R.Left) div TileWidth; TilesVert := (R.Bottom - R.Top) div TileHeight; TileY := 0; for J := 0 to TilesVert do begin TileX := 0; OddY := J and $1; for I := 0 to TilesHorz do begin Image32.Bitmap.FillRectS(TileX, TileY, TileX + TileWidth, TileY + TileHeight, Colors[I and $1 = OddY]); Inc(TileX, TileWidth); end; Inc(TileY, TileHeight); end end; procedure TFmDisplay.RbInternalClick(Sender: TObject); begin with Image32 do begin ClearImage32; Bitmap.Draw(0, 0, FInternal); end; end; procedure TFmDisplay.RbPngImageClick(Sender: TObject); begin with Image32 do begin ClearImage32; Bitmap.Draw(0, 0, FReference); end; end; end.
unit Fplayer; { La Classe Tplayer créé par vizi le 22/03/2008 contient les information d'un joueur, notamment ses ressources, son ID serveur, son pseudo, équipe etc... défini également les classes Tcolor et Trace. } interface uses FDisplay; const TeamColor : array[0..7] of TCoords3c = ( (x : 0.00; y : 1.00; z : 1.00), // Cyan (x : 1.00; y : 0.00; z : 1.00), // Magenta (x : 1.00; y : 0.00; z : 0.00), // Red (x : 0.00; y : 1.00; z : 0.00), // Green (x : 0.00; y : 0.00; z : 1.00), // Blue (x : 1.00; y : 1.00; z : 0.00), // Yellow (x : 1.00; y : 1.00; z : 1.00), // White (x : 0.50; y : 0.50; z : 0.50) // Gray ); DEFAULT_GOLD = 2500; DEFAULT_WOOD = 0; type Tplayer = class private _Res1 : double; _Res2 : double; _color : integer; _team : integer; _race : integer; _id : integer; _unitcount : integer; _nick : string; public constructor Create(); //only allowed before playing procedure init_nick(n : string); procedure init_color(c : integer); procedure init_race(r : integer); procedure init_team(t : integer); procedure init_id(id : integer); //allowed in game procedure add_res1(n : double); procedure add_res2(n : double); procedure add_unit(); procedure kill_unit(); procedure set_team(n : integer); property res1 : double read _res1 write _res1; property res2 : double read _res2 write _res2; property nick : string read _nick write _nick; property color : integer read _color write _color; property team : integer read _team write _team; property race : integer read _race write _race; property id : integer read _id; property unitcount : integer read _unitcount; // Les write des fonctions ci dessus sont pas tres secure mais bon // on fais avec temporairement... end; TPublicPlayerInfo = class Public isYou : boolean; color : integer; team : integer; race : integer; nick : string; ip : string; constructor create; procedure refresh(color, team, race : Integer; nick, ip: string); end; TPublicPlayerList = class Public tab : array[0..7] of TPublicPlayerInfo; count : integer; constructor create; procedure refresh(id, color, team, race : integer ; nick, ip : string); procedure add(id, color, team, race : integer ; nick, ip : string ; isYou : boolean); procedure remove(id : integer); end; implementation uses FLogs, sysutils, Fredirect, FLuaFunctions, Fserver, FInterfaceDraw; constructor Tplayer.Create(); begin self._id := 0; self._res1 := DEFAULT_GOLD; self._res2 := DEFAULT_WOOD; self._color := 0; self._unitcount := 0; self._team := 1; self._race := 1; self._nick := 'Error_noNick'; end; procedure TPlayer.init_id(id : integer); begin end; procedure Tplayer.add_res1(n : double); begin self._res1 := self._res1 + n; end; procedure Tplayer.add_res2(n : double); begin self._res2 := self._res2 + n; end; procedure Tplayer.add_unit(); begin inc(self._unitcount); TriggerEvent(EVENT_POPCHANGE); end; procedure Tplayer.kill_unit(); begin dec(self._unitcount); TriggerEvent(EVENT_POPCHANGE); end; procedure Tplayer.init_color(c : integer); begin //FIX ME { Server_request(PLAYER, INIT, COLOR, sizeof(c), c); } end; procedure Tplayer.init_nick(n : string); begin //FIX ME { Server_request(PLAYER, INIT, NICK, length(n), format_string(n)); } end; procedure Tplayer.set_team(n : integer); begin //FIX ME { Server_request(PLAYER, UPDATE, TEAM, length(n), n); } end; procedure Tplayer.init_race(r : integer); begin //FIX ME { Server_request(PLAYER, INIT, RACE, sizeof(r), r); } end; procedure Tplayer.init_team(T : integer); begin //FIX ME { Server_request(PLAYER, INIT, RACE, sizeof(r), r); } end; constructor TPublicPlayerInfo.create; begin self.color := -1; self.race := -1; self.team := -1; self.nick := 'Error FPlayer l. 163'; self.isYou := false; self.ip := 'Error IP'; end; procedure TPublicPlayerInfo.refresh(color, team, race : Integer; nick, ip: string); begin //Set value to -1 or '' if you don't want to modify it... if color <> -1 then self.color := color; if race <> -1 then self.race := race; if team <> -1 then self.team := team; if nick <> '' then self.nick := nick; if ip <> '' then self.ip := ip; // If in MENU, reload displayed informations. if CurrentScreen = SCREEN_MENU then begin RefreshPlayerList(L); end; end; constructor TPublicPlayerList.create; begin self.count := 0; end; procedure TPublicPlayerList.refresh(id, color, team, race : integer ; nick, ip : string); begin self.tab[id].refresh(color, team, race, nick, ip); // If you are the server, update your basic ClientTab info too : if GlobalServerIP = '127.0.0.1' then begin ClientTab.tab[id].info.color := color; ClientTab.tab[id].info.team := team; ClientTab.tab[id].info.race := race; ClientTab.tab[id].info.nick := nick; end; end; procedure TPublicPlayerList.add(id, color, team, race : integer ; nick, ip : string ; isYou : boolean); begin inc(self.count); self.tab[id] := TPublicPlayerInfo.create; self.refresh(id, color, team, race, nick, ip); self.tab[id].isYou := isYou; log('Public player list added' + intToStr(self.count)); end; procedure TPublicPlayerList.remove(id : integer); begin self.tab[id].Destroy; dec(self.count); end; end.
unit zDPF; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, RxVerInf, Registry, zSharedFunctions, zAVKernel, zAVZKernel, zLogSystem; type // Информация о DPF TDPFInfo = record RegKey : string; // Ключ реестра CLSID : string; // CLSID BinFile : string; // Бинарный файл Descr : string; // Описание LegalCopyright : string; // Копирайты CheckResult : integer; // Результат проверки по базе безопасных программ CodeBase : string; // Источник end; TDPFInfoArray = array of TDPFInfo; // Менеджер DPF TDPFList = class DPFInfoArray : TDPFInfoArray; constructor Create; destructor Destroy; override; function RefresDPFList : boolean; function ScanDPFKeys(APrefix : string) : boolean; function GetItemEnabledStatus(DPFInfo : TDPFInfo) : integer; function DeleteItem(DPFInfo : TDPFInfo) : boolean; function SetItemEnabledStatus(var DPFInfo : TDPFInfo; NewStatus : boolean) : boolean; function AddDPF(DPFInfo : TDPFInfo) : boolean; end; implementation uses zScriptingKernel; { TDPFList } function TDPFList.AddDPF(DPFInfo: TDPFInfo): boolean; var VersionInfo : TVersionInfo; begin DPFInfo.BinFile := NTFileNameToNormalName(DPFInfo.BinFile); DPFInfo.CheckResult := FileSignCheck.CheckFile(DPFInfo.BinFile); try VersionInfo := TVersionInfo.Create(DPFInfo.BinFile); DPFInfo.Descr := VersionInfo.FileDescription; DPFInfo.LegalCopyright := VersionInfo.LegalCopyright; VersionInfo.Free; except end; SetLength(DPFInfoArray, Length(DPFInfoArray)+1); DPFInfoArray[Length(DPFInfoArray)-1] := DPFInfo; end; constructor TDPFList.Create; begin DPFInfoArray := nil; end; destructor TDPFList.Destroy; begin DPFInfoArray := nil; inherited; end; function TDPFList.DeleteItem(DPFInfo: TDPFInfo): boolean; var Reg : TRegistry; begin Result := false; Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; Reg.DeleteKey(DPFInfo.RegKey+'\'+DPFInfo.CLSID); except end; Result := true; Reg.Free; end; function TDPFList.GetItemEnabledStatus(DPFInfo: TDPFInfo): integer; begin Result := 1; if copy(DPFInfo.RegKey, length(DPFInfo.RegKey), 1) = '-' then Result := 0; end; function TDPFList.RefresDPFList: boolean; begin DPFInfoArray := nil; ScanDPFKeys(''); ScanDPFKeys('-'); end; function TDPFList.ScanDPFKeys(APrefix: string): boolean; var Reg : TRegistry; List : TStrings; Tmp : TDPFInfo; i : integer; BaseKey, S : string; begin Reg := TRegistry.Create; List := TStringList.Create; Reg.RootKey := HKEY_LOCAL_MACHINE; // Поиск DPF BaseKey := 'SOFTWARE\Microsoft\Code Store Database\Distribution Units'+APrefix; if Reg.OpenKey(BaseKey, false) then begin Reg.GetKeyNames(List); Reg.CloseKey; ZProgressClass.AddProgressMax(List.Count); for i := 0 to List.Count - 1 do begin ZProgressClass.ProgressStep; Tmp.RegKey := BaseKey; Tmp.CLSID := Trim(List[i]); Tmp.CodeBase := ''; if Reg.OpenKey(BaseKey + '\'+List[i]+'\DownloadInformation', false) then begin try Tmp.CodeBase := Reg.ReadString('CODEBASE'); except end; Reg.CloseKey; end; S := copy(Tmp.CLSID, 2, length(Tmp.CLSID)-2); Tmp.BinFile := CLSIDFileName(S); AddDPF(Tmp); end; end; List.Free; Reg.Free; end; function TDPFList.SetItemEnabledStatus(var DPFInfo: TDPFInfo; NewStatus: boolean): boolean; var Reg : TRegistry; S : string; begin Result := false; // Лог. защита - блокирования активации активного и выключения неактивного if NewStatus and (GetItemEnabledStatus(DPFInfo) <> 0) then exit; if not(NewStatus) and (GetItemEnabledStatus(DPFInfo) <> 1) then exit; // Блокировка if not(NewStatus) then begin Reg := TRegistry.Create; Reg.RootKey := HKEY_LOCAL_MACHINE; Reg.MoveKey(DPFInfo.RegKey+'\'+DPFInfo.CLSID, DPFInfo.RegKey+'-\'+DPFInfo.CLSID, true); DPFInfo.RegKey := DPFInfo.RegKey + '-'; Result := true; end; // Разблокировка if NewStatus then begin Reg := TRegistry.Create; Reg.RootKey := HKEY_LOCAL_MACHINE; Reg.MoveKey(DPFInfo.RegKey+'\'+DPFInfo.CLSID, copy(DPFInfo.RegKey, 1, length(DPFInfo.RegKey)-1)+'\'+DPFInfo.CLSID, true); DPFInfo.RegKey := copy(DPFInfo.RegKey, 1, length(DPFInfo.RegKey)-1); Result := true; end; end; end.
unit Especificacao; interface type TEspecificacao = class public function SatisfeitoPor(Objeto :TObject) :Boolean; virtual; end; implementation uses ExcecaoMetodoNaoImplementado; { TEspecificacao } function TEspecificacao.SatisfeitoPor(Objeto: TObject): Boolean; begin raise TExcecaoMetodoNaoImplementado.Create(self.ClassName, 'SatisfeitoPor(Objeto: TObject): Boolean;'); end; end.
{***************************************************************************} { } { DUnitX } { } { Copyright (C) 2015 Vincent Parrett & Contributors } { } { vincent@finalbuilder.com } { http://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DUnitX.StackTrace.MadExcept3; interface {$I DUnitX.inc} uses {$IFDEF USE_NS} System.SysUtils, System.Classes, {$ELSE} SysUtils, Classes, {$ENDIF} {$IFDEF USE_MADEXCEPT3} madStackTrace, {$ENDIF} DUnitX.TestFramework; type TMadExcept3StackTraceProvider = class(TInterfacedObject,IStacktraceProvider) public function GetStackTrace(const ex: Exception; const exAddressAddress: Pointer): string; function PointerToLocationInfo(const Addrs: Pointer): string; function PointerToAddressInfo(Addrs: Pointer): string; end; implementation uses DUnitX.IoC; { TJCLStackTraceProvider } function TMadExcept3StackTraceProvider.GetStackTrace(const ex: Exception; const exAddressAddress: Pointer): string; begin result := ''; {$IFDEF USE_MADEXCEPT3} Result := string(madStackTrace.StackTrace( false, false, false, nil, exAddressAddress, false, false, 0, 0, nil, @exAddressAddress)); {$ENDIF} end; function TMadExcept3StackTraceProvider.PointerToAddressInfo(Addrs: Pointer): string; begin {$IFDEF USE_MADEXCEPT3} Result := String(StackAddrToStr(Addrs)); {$ELSE} Result := ''; {$ENDIF} end; function TMadExcept3StackTraceProvider.PointerToLocationInfo(const Addrs: Pointer): string; begin {$IFDEF USE_MADEXCEPT3} Result := String(StackAddrToStr(Addrs)); {$ELSE} Result := ''; {$ENDIF} end; initialization {$IFDEF USE_MADEXCEPT3} {$IFDEF DELPHI_XE_UP} TDUnitXIoC.DefaultContainer.RegisterType<IStacktraceProvider,TMadExcept3StackTraceProvider>(true); {$ELSE} //D2010 bug prevents using above method. TDUnitXIoC.DefaultContainer.RegisterType<IStacktraceProvider>(true, function : IStacktraceProvider begin result := TMadExcept3StackTraceProvider.Create; end ); {$ENDIF} {$ENDIF} end.
unit BFA.Helper.MemTable; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Memo.Types, System.Rtti, FMX.Grid.Style, FMX.Grid, FMX.ScrollBox, FMX.Memo, FMX.Edit, FMX.Controls.Presentation, FMX.StdCtrls, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, System.Net.URLClient, System.Net.HttpClient, System.Net.HttpClientComponent, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, System.JSON, System.Net.Mime; type TFDMemTableHelper = class helper for TFDMemTable procedure FillError(FMessage, FError : String); function FillDataFromString(FJSON : String) : Boolean; //ctrl + shift + C function FillDataFromURL(FURL : String; FMultiPart : TMultipartFormData = nil) : Boolean; //ctrl + shift + C end; implementation { TFDMemTableHelper } function TFDMemTableHelper.FillDataFromString(FJSON: String): Boolean; var JObjectData : TJSONObject; JArrayJSON : TJSONArray; isArray : Boolean; begin try Self.Active := False; Self.Close; Self.FieldDefs.Clear; if TJSONObject.ParseJSONValue(FJSON) is TJSONObject then begin JObjectData := TJSONObject.ParseJSONValue(FJSON) as TJSONObject; end else if TJSONObject.ParseJSONValue(FJSON) is TJSONArray then begin isArray := True; JArrayJSON := TJSONObject.ParseJSONValue(FJSON) as TJSONArray; JObjectData := TJSONObject(JArrayJSON.Get(0)); end else begin Result := False; Self.FillError('Gagal Parsing JSON', 'Ini Bukan JSON'); Exit; end; for var i := 0 to JObjectData.Size - 1 do Self.FieldDefs.Add( StringReplace(JObjectData.Get(i).JsonString.ToString, '"', '', [rfReplaceAll, rfIgnoreCase]), ftString, 10000, False ); Self.CreateDataSet; Self.Active := True; Self.Open; try if isArray then begin for var i := 0 to JArrayJSON.Size - 1 do begin JObjectData := TJSONObject(JArrayJSON.Get(i)); Self.Append; for var ii := 0 to JObjectData.Size - 1 do begin if TJSONObject.ParseJSONValue(JObjectData.GetValue(Self.FieldDefs[ii].Name).ToJSON) is TJSONObject then Self.Fields[ii].AsString := JObjectData.GetValue(Self.FieldDefs[ii].Name).ToJSON else if TJSONObject.ParseJSONValue(JObjectData.GetValue(Self.FieldDefs[ii].Name).ToJSON) is TJSONArray then Self.Fields[ii].AsString := JObjectData.GetValue(Self.FieldDefs[ii].Name).ToJSON else Self.Fields[ii].AsString := JObjectData.Values[Self.FieldDefs[ii].Name].Value; end; Self.Post; end; end else begin Self.Append; for var ii := 0 to JObjectData.Size - 1 do begin if TJSONObject.ParseJSONValue(JObjectData.GetValue(Self.FieldDefs[ii].Name).ToJSON) is TJSONObject then Self.Fields[ii].AsString := JObjectData.GetValue(Self.FieldDefs[ii].Name).ToJSON else if TJSONObject.ParseJSONValue(JObjectData.GetValue(Self.FieldDefs[ii].Name).ToJSON) is TJSONArray then Self.Fields[ii].AsString := JObjectData.GetValue(Self.FieldDefs[ii].Name).ToJSON else Self.Fields[ii].AsString := JObjectData.Values[Self.FieldDefs[ii].Name].Value; end; Self.Post; end; Result := True; except on E : Exception do begin Result := False; Self.FillError('Error Parsing JSON', E.Message); end; end; finally Self.First; if isArray then JArrayJSON.DisposeOf; end; end; function TFDMemTableHelper.FillDataFromURL(FURL: String; FMultiPart : TMultipartFormData = nil): Boolean; var FNetHTTP : TNetHTTPClient; FNetRespon : IHTTPResponse; begin FNetHTTP := TNetHTTPClient.Create(nil); try try if Assigned(FMultiPart) then FNetRespon := FNetHTTP.Post(FURL, FMultiPart) else FNetRespon := FNetHTTP.Get(FURL); Result := Self.FillDataFromString(FNetRespon.ContentAsString()); except on E : Exception do begin Result := False; Self.FillError('Gagal Load JSON From URL', E.Message); end; end; finally FNetHTTP.DisposeOf; end; end; procedure TFDMemTableHelper.FillError(FMessage, FError : String); begin Self.Active := False; Self.Close; Self.FieldDefs.Clear; Self.FieldDefs.Add('message', ftString, 200, False); Self.FieldDefs.Add('error', ftString, 200, False); Self.CreateDataSet; Self.Active := True; Self.Open; Self.Append; Self.Fields[0].AsString := FMessage; Self.Fields[1].AsString := FError; Self.Post; end; end.
unit uPrincipal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, Vcl.Buttons, Vcl.ExtCtrls, Vcl.ComCtrls; type TfrmPrincipal = class(TForm) mnPrincipal: TMainMenu; mnuCadastro: TMenuItem; mniFuncionario: TMenuItem; N1: TMenuItem; mniSair: TMenuItem; Ajuda1: TMenuItem; mniSobre: TMenuItem; pnTop: TPanel; btnFuncionario: TSpeedButton; btnSobre: TSpeedButton; btnSair: TSpeedButton; stbPrincipal: TStatusBar; procedure FormCreate(Sender: TObject); procedure mniSobreClick(Sender: TObject); procedure mniFuncionarioClick(Sender: TObject); procedure btnFuncionarioClick(Sender: TObject); procedure btnSobreClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnSairClick(Sender: TObject); procedure mniSairClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmPrincipal: TfrmPrincipal; implementation uses uSobre, uCadFuncionario, uConexaoController, uDmPrincipal, uVisualControl; {$R *.dfm} procedure TfrmPrincipal.btnFuncionarioClick(Sender: TObject); begin mniFuncionario.Click; end; procedure TfrmPrincipal.btnSairClick(Sender: TObject); begin Close; end; procedure TfrmPrincipal.btnSobreClick(Sender: TObject); begin mniSobre.Click; end; procedure TfrmPrincipal.FormClose(Sender: TObject; var Action: TCloseAction); begin if (Application.MessageBox('Deseja realmente sair do Sistema?', 'Encerrar Aplicação', MB_ICONQUESTION + MB_YESNO) = mrYes) then Action := caFree else Action := caNone; end; procedure TfrmPrincipal.FormCreate(Sender: TObject); var ConexaoCto : TConexaoController; criouDados : Boolean; begin //Setando o Caption do Form Caption := Application.Title; //Criando o Banco de Dados ConexaoCto := TConexaoController.Create; try ConexaoCto.createData; criouDados := ConexaoCto.criouDados; finally ConexaoCto.Free; end; //Encerrando a Aplicação caso haja erros na criação das tabelas. if not(criouDados) then Application.Terminate; end; procedure TfrmPrincipal.FormDestroy(Sender: TObject); begin TdmPrincipal.Destroy; end; procedure TfrmPrincipal.FormShow(Sender: TObject); begin stbPrincipal.Panels[0].Text := Application.Title; stbPrincipal.Panels[1].Text := dayOfWeek + ', ' + dataExtenso; end; procedure TfrmPrincipal.mniFuncionarioClick(Sender: TObject); var frmCadFuncionario : TfrmCadFuncionario; begin frmCadFuncionario := TfrmCadFuncionario.Create(Self); try frmCadFuncionario.ShowModal; finally frmCadFuncionario.Free; end; end; procedure TfrmPrincipal.mniSairClick(Sender: TObject); begin Close; end; procedure TfrmPrincipal.mniSobreClick(Sender: TObject); var frmSobre : TfrmSobre; begin frmSobre := TfrmSobre.Create(Self); try frmSobre.ShowModal; finally frmSobre.Free; end; end; end.
Unit GraphicsSpeedButtonEx; Interface Uses System.SysUtils, System.Classes, Vcl.Controls, Vcl.Buttons, Vcl.Graphics, Vcl.Themes, Winapi.GDIPAPI, Winapi.GDIPOBJ, GraphicsUtils; Type TGraphicsSpeedButtonEx = Class(TSpeedButton) Private { Private declarations } FImage : TGPBitmap; FImageGrey : TGPBitmap; FTitle : String; FImageWidth, FImageHeight: Integer; Protected { Protected declarations } Procedure Paint; Override; Private FGPFont: TGPFont; Public { Public declarations } Constructor Create(AOwner: TComponent); Override; Destructor Destroy; Override; Procedure SetImage(Image: TGPBitmap); Procedure SetTitle(Title: String); Published { Published declarations } End; Procedure Register; Implementation Const TITLE_FONT_NAME = 'Tahoma'; TITLE_FONT_SIZE = 9; Procedure Register; Begin RegisterComponents('Samples', [TGraphicsSpeedButtonEx]); End; Constructor TGraphicsSpeedButtonEx.Create(AOwner: TComponent); Begin Inherited; Self.Flat := Not(csDesigning In ComponentState); End; Destructor TGraphicsSpeedButtonEx.Destroy; Begin If FImageGrey <> Nil Then FImageGrey.Free(); If FGPFont <> Nil Then FGPFont.Free(); Inherited; End; Procedure TGraphicsSpeedButtonEx.Paint(); Var x, y : Integer; Image : TGPBitmap; Graphics : TGPGraphics; layoutRect : TGPRectF; stringFormat: TGPStringFormat; brush : TGPBrush; Begin Inherited; If Self.Enabled Then Begin Image := FImage; End Else Begin If (FImage <> Nil) And (FImageGrey = Nil) Then Begin FImageGrey := CreateGreyImage(FImage); End; Image := FImageGrey; End; Graphics := TGPGraphics.Create(Self.Canvas.Handle); If Image <> Nil Then Begin x := 5; y := (Height - Image.GetHeight()) Div 2; Graphics.DrawImage(Image, x, y, FImageWidth, FImageHeight); End; If FTitle <> '' Then Begin If Self.Enabled Then Begin brush := TGPSolidBrush.Create(GetButtonTextBGR() Or $FF000000); End Else Begin brush := TGPSolidBrush.Create(GetButtonTextBGR() Or $7F000000); End; layoutRect := MakeRect(5 + FImageWidth, 0.0, Width - 5 - FImageWidth, Height - 1); stringFormat := TGPStringFormat.Create(); stringFormat.SetLineAlignment(StringAlignmentCenter); Graphics.SetTextRenderingHint(TextRenderingHintClearTypeGridFit); Graphics.DrawString(FTitle, -1, FGPFont, layoutRect, stringFormat, brush); stringFormat.Free(); brush.Free(); End; Graphics.Free(); End; Procedure TGraphicsSpeedButtonEx.SetImage(Image: TGPBitmap); Begin FImage := Image; If FImageGrey <> Nil Then Begin FImageGrey.Free(); FImageGrey := Nil; End; If FImage <> Nil Then Begin FImageWidth := FImage.GetWidth(); FImageHeight := FImage.GetHeight(); End; Self.Invalidate(); End; Procedure TGraphicsSpeedButtonEx.SetTitle(Title: String); Begin FTitle := Title; If (FTitle <> '') And (FGPFont = Nil) Then Begin FGPFont := TGPFont.Create(Self.font.Name, Self.font.Size, FontStyleRegular); End; Self.Invalidate(); End; End.
unit KM_HTTPClientLNet; {$I KaM_Remake.inc} interface uses Classes, SysUtils, lNet, URLUtils, lHTTP; type TKMHTTPClientLNet = class private fHTTPClient: TLHTTPClient; HTTPBuffer: AnsiString; fOnError: TGetStrProc; fOnGetCompleted: TGetStrProc; fIsUTF8: Boolean; procedure HTTPClientDoneInput(ASocket: TLHTTPClientSocket); procedure HTTPClientError(const msg: string; aSocket: TLSocket); function HTTPClientInput(ASocket: TLHTTPClientSocket; ABuffer: PChar; ASize: Integer): Integer; public constructor Create; destructor Destroy; override; procedure GetURL(aURL: string; aIsUTF8: Boolean); procedure UpdateStateIdle; property OnError: TGetStrProc write fOnError; property OnGetCompleted: TGetStrProc write fOnGetCompleted; end; implementation constructor TKMHTTPClientLNet.Create; begin inherited Create; fHTTPClient := TLHTTPClient.Create(nil); fHTTPClient.Timeout := 0; fHTTPClient.OnInput := HTTPClientInput; fHTTPClient.OnError := HTTPClientError; fHTTPClient.OnDoneInput := HTTPClientDoneInput; end; destructor TKMHTTPClientLNet.Destroy; begin fHTTPClient.Free; inherited; end; procedure TKMHTTPClientLNet.GetURL(aURL: string; aIsUTF8: Boolean); var Proto, User, Pass, Host, Port, Path: string; begin fIsUTF8 := aIsUTF8; fHTTPClient.Disconnect(true); //If we were doing something, stop it HTTPBuffer := ''; ParseURL(aURL, Proto, User, Pass, Host, Port, Path); fHTTPClient.Host := Host; fHTTPClient.URI := Path; fHTTPClient.Port := StrToIntDef(Port, 80); fHTTPClient.SendRequest; end; procedure TKMHTTPClientLNet.HTTPClientDoneInput(ASocket: TLHTTPClientSocket); var ReturnString: UnicodeString; begin aSocket.Disconnect; if fIsUTF8 then ReturnString := UTF8Decode(HTTPBuffer) else ReturnString := UnicodeString(HTTPBuffer); if Assigned(fOnGetCompleted) then fOnGetCompleted(ReturnString); HTTPBuffer := ''; end; procedure TKMHTTPClientLNet.HTTPClientError(const msg: string; aSocket: TLSocket); begin if Assigned(fOnError) then fOnError(msg); end; function TKMHTTPClientLNet.HTTPClientInput(ASocket: TLHTTPClientSocket; ABuffer: PChar; ASize: Integer): Integer; var oldLength: dword; begin if ASize > 0 then begin oldLength := Length(HTTPBuffer); setlength(HTTPBuffer, oldLength + ASize); move(ABuffer^, HTTPBuffer[oldLength + 1], ASize); end; Result := aSize; // tell the http buffer we read it all end; procedure TKMHTTPClientLNet.UpdateStateIdle; begin fHTTPClient.CallAction; //Process network events end; end.
{ MIT License Copyright (c) 2020 Paulo Henrique de Freitas Passella Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Copyright: (c) 2020, Paulo Henrique de Freitas Passella (passella@gmail.com) } unit untAnonymousInterface; interface uses System.SysUtils, System.Rtti, System.TypInfo, System.Generics.Collections; type TAnonymousInterfaceBuilder<I: IInvokable> = class private lstAnonymousMethods: TList<Pointer>; public constructor Create(); destructor Destroy; override; function AddMethod(const anonymousMethod: Pointer): TAnonymousInterfaceBuilder<I>; overload; function AddMethod<T>(const anonymousMethod: T): TAnonymousInterfaceBuilder<I>; overload; function Build(): I; end; TAnonymousInterfaceBuilderFactory = class public class function CreateBuilder<I: IInvokable>(): TAnonymousInterfaceBuilder<I>; end; TAnonymousVirtualInterface<I: IInvokable> = class(TVirtualInterface) private builder: TAnonymousInterfaceBuilder<I>; public constructor Create(const builder: TAnonymousInterfaceBuilder<I>); destructor Destroy; override; end; TAnonymousInterface = class public class function Wrap<D: IInvokable; O>(const event: O): D; overload; class function Wrap<D: IInvokable>(const event: Pointer): D; overload; end; implementation { TAnonymousInterface } class function TAnonymousInterface.Wrap<D, O>(const event: O): D; type TVtable = array [0 .. 3] of Pointer; PVtable = ^TVtable; PPVtable = ^PVtable; begin if not Supports(TVirtualInterface.Create(TypeInfo(D), procedure(Method: TRttiMethod; const Args: TArray<TValue>; out Result: TValue) begin var nArgs: TArray<TValue> := [Pointer((@event)^)] + Copy(Args, 1, Length(Args) - 1); var Handle: PTypeInfo := nil; if Assigned(Method.ReturnType) then Handle := Method.ReturnType.Handle; Result := Invoke(PPVtable((@event)^)^^[3], nArgs, Method.CallingConvention, Handle, Method.IsStatic, Method.IsConstructor); end), GetTypeData(TypeInfo(D))^.GUID, Result) then Result := nil; end; class function TAnonymousInterface.Wrap<D>(const event: Pointer): D; type TVtable = array [0 .. 3] of Pointer; PVtable = ^TVtable; PPVtable = ^PVtable; begin if not Supports(TVirtualInterface.Create(TypeInfo(D), procedure(Method: TRttiMethod; const Args: TArray<TValue>; out Result: TValue) begin var nArgs: TArray<TValue> := [Pointer((@event)^)] + Copy(Args, 1, Length(Args) - 1); var Handle: PTypeInfo := nil; if Assigned(Method.ReturnType) then Handle := Method.ReturnType.Handle; Result := Invoke(PPVtable((@event)^)^^[3], nArgs, Method.CallingConvention, Handle, Method.IsStatic, Method.IsConstructor); end), GetTypeData(TypeInfo(D))^.GUID, Result) then Result := nil; end; { TAnonymousInterfaceBuilderFactory } class function TAnonymousInterfaceBuilderFactory.CreateBuilder<I>: TAnonymousInterfaceBuilder<I>; begin Result := TAnonymousInterfaceBuilder<I>.Create(); end; { TAnonymousInterfaceBuilder<I> } function TAnonymousInterfaceBuilder<I>.AddMethod( const anonymousMethod: Pointer): TAnonymousInterfaceBuilder<I>; begin lstAnonymousMethods.Add(anonymousMethod); Result := Self; end; function TAnonymousInterfaceBuilder<I>.AddMethod<T>( const anonymousMethod: T): TAnonymousInterfaceBuilder<I>; begin var ptrMethod: PPointer := @anonymousMethod; lstAnonymousMethods.Add(ptrMethod^); Result := Self; end; function TAnonymousInterfaceBuilder<I>.Build: I; begin var intF := TAnonymousVirtualInterface<I>.Create(Self); Supports(intF, GetTypeData(TypeInfo(I))^.GUID, Result); end; constructor TAnonymousInterfaceBuilder<I>.Create; begin inherited Create(); lstAnonymousMethods := TList<Pointer>.Create; end; destructor TAnonymousInterfaceBuilder<I>.Destroy; begin if Assigned(lstAnonymousMethods) then FreeAndNil(lstAnonymousMethods); inherited Destroy; end; { TAnonymousVirtualInterface<I> } constructor TAnonymousVirtualInterface<I>.Create( const builder: TAnonymousInterfaceBuilder<I>); type TVtable = array [0 .. 3] of Pointer; PVtable = ^TVtable; PPVtable = ^PVtable; begin inherited Create(TypeInfo(I)); Self.builder := builder; Self.OnInvoke := procedure(Method: TRttiMethod; const Args: TArray<TValue>; out Result: TValue) begin var anonymousMethod: Pointer := builder.lstAnonymousMethods[Method.VirtualIndex - 3]; var nArgs: TArray<TValue> := [Pointer((@anonymousMethod)^)] + Copy(Args, 1, Length(Args) - 1); var Handle: PTypeInfo := nil; if Assigned(Method.ReturnType) then Handle := Method.ReturnType.Handle; Result := Invoke(PPVtable((@anonymousMethod)^)^^[3], nArgs, Method.CallingConvention, Handle, Method.IsStatic, Method.IsConstructor); end; end; destructor TAnonymousVirtualInterface<I>.Destroy; begin if Assigned(builder) then FreeAndNil(builder); inherited Destroy; end; end.
unit QApplication.Application; interface uses Generics.Collections, SyncObjs, QuadEngine, QCore.Input, QCore.Types, QApplication.Window, QApplication.Input, QGame.Game, Strope.Math; type TQApplicationParameters = class strict private FGame: TQGame; FTimerDelta: Word; FResolution: TVectorI; FIsFullscreen: Boolean; public constructor Create(AGame: TQGame; AResolution: TVectorI; AIsFullscreen: Boolean; ATimerDelta: Word = 16); property Game: TQGame read FGame; property TimerDelta: Word read FTimerDelta; property Resolution: TVectorI read FResolution; property IsFullscreen: Boolean read FIsFullscreen; end; ///<summary>Класс приложения, организующий работу окна, игры и игроого таймера.</summary> TQApplication = class sealed (TComponent) strict private FWindow: TWindow; FGame: TQGame; FControlState: IControlState; FIsStoped: Boolean; FMainTimer: IQuadTimer; FCriticalSection: TCriticalSection; FMessages: TList<TEventMessage>; FResolution: TVectorI; FIsFullscreen: Boolean; FIsAltPressed: Boolean; procedure SetupWindow; procedure SetupTimer(ATimerDelta: Word); procedure ProcessMessages; function GetFPS(): Single; private procedure MainTimerUpdate(const ADeltaTime: Double); public constructor Create; destructor Destroy; override; ///<summary>Метод вызывается для инициализации приложения.</summary> ///<param name="AParameter">Объект-параметр для инициализации.</param> procedure OnInitialize(AParameter: TObject = nil); override; ///<summary>Метод служит для активации или деактивации приложения.</summary> ///<param name="AIsActivate">Значение True служит для активации, /// значение False - для деактивации.</param> procedure OnActivate(AIsActivate: Boolean); override; ///<summary>Метод вызывается для отрисовки игры.</summary> ///<param name="ALayer">Слой сцены для отрисовки.</param> procedure OnDraw(const ALayer: Integer); override; ///<summary>Метод вызывается таймером для обновления состояния приложения.</summary> ///<param name="ADelta">Промежуток времены в секундах, /// прошедший с предыдущего обновления состояния.</param> procedure OnUpdate(const ADelta: Double); override; ///<summary>Метод вызываеся для прекращения работы приложения.</summary> procedure OnDestroy; override; ///<summary>Метод вызывается для реакции на событие "движение мышки"</summary> ///<param name="AMousePosition">Текущие координаты мыши, /// относительно левого верхнего края рабочего окна.</param> ///<returns>Возвращенное логическое значение сигнализирует о том, /// было ли событие обработано.</returns> function OnMouseMove(const AMousePosition: TVectorF): Boolean; override; ///<summary>Метод вызывается для реакции на событие <b><i>нажатие кнопки мыши</i></b></summary> ///<param name="AButton">Нажатая кнопка мыши.</param> ///<param name="AMousePosition">Координаты мыши в момент нажатие кнопки, /// относительно левого верхнего края рабочего окна.</param> ///<returns>Возвращенное логическое значение сигнализирует о том, ///было ли событие обработано.</returns> ///<remarks>Значения перечисления <see creg="QCore.Input|TMouseButton" /> /// можно узать в модуле QCore.Input.</remarks> function OnMouseButtonDown( AButton: TMouseButton; const AMousePosition: TVectorF): Boolean; override; ///<summary>Метод вызывается для реакции на событие <b><i>отпускание кнопки мыши</i></b></summary> ///<param name="AButton">Отпущенная кнопка мыши.</param> ///<param name="AMousePosition">Координаты мыши в момент отпускания кнопки, /// относительно левого верхнего края рабочего окна.</param> ///<returns>Возвращенное логическое значение сигнализирует о том, ///было ли событие обработано.</returns> ///<remarks>Значения перечисления <see creg="QCore.Input|TMouseButton" /> /// можно узать в модуле QCore.Input.</remarks> function OnMouseButtonUp( AButton: TMouseButton; const AMousePosition: TVectorF): Boolean; override; ///<summary>Метод вызывается для реакции на событие <b><i>прокрутка колеса мыши вниз</i></b></summary> ///<param name="ADirection">Напревление прокрутки колеса. /// Значение +1 соответствует прокрутке вверх, -1 - вниз.</param> ///<returns>Возвращенное логическое значение сигнализирует о том, ///было ли событие обработано.</returns> function OnMouseWheel(ADirection: Integer): Boolean; override; ///<summary>Метод вызывается для рекции на событие <b><i>нажатие кнопки на клавиатуре</i></b></summary> ///<param name="AKey">Нажатая кнопка на клавиатуре.</param> ///<returns>Возвращенное логическое значение сигнализирует о том, ///было ли событие обработано.</returns> ///<remarks>Значения констант TKeyButton можно узать в модуле uInput.</remarks> function OnKeyDown(AKey: TKeyButton): Boolean; override; ///<summary>Метод вызывается для рекции на событие <b><i>отпускание кнопки на клавиатуре</i></b></summary> ///<param name="AKey">Отпущенная кнопка на клавиатуре.</param> ///<returns>Возвращенное логическое значение сигнализирует о том, ///было ли событие обработано.</returns> ///<remarks>Значения констант TKeyButton можно узать в модуле uInput.</remarks> function OnKeyUp(AKey: TKeyButton): Boolean; override; ///<summary>Метод запускает обработку событий приложением.</summary> procedure Loop; procedure Stop; ///<summary>Экземпляр окна типа <see cref="QApplication.Window|TWindow" /> /// принадлежащий приложению.</summary> property Window: TWindow read FWindow; ///<summary>Экземпляр класса игры типа <see cref="QGame.Game|TQGame" /> /// или производного от него.</summary> property Game: TQGame read FGame; ///<summary>Интерфейс, позволяющий проверять состояние клавиатуры и мыши.</summary> property ControlState: IControlState read FControlState; ///<summary>Рабочее разрешение приложение и размер клиентской области окна.</summary> property Resolution: TVectorI read FResolution; ///<summary>Среднее количество обновлений (и кадров) за последнюю секунду.</summary> property FPS: Single read GetFPS; property IsFullscreen: Boolean read FIsFullscreen; end; var TheApplication: TQApplication = nil; TheControlState: IControlState = nil; TheMouseState: IMouseState = nil; TheKeyboardState: IKeyboardState = nil; implementation uses Windows, Messages, SysUtils, QEngine.Core; type TControlState = class sealed (TBaseObject, IControlState, IMouseState, IKeyboardState) strict private FMousePosition: TVectorF; FButtonsState: array [0..2] of Boolean; FKeysState: array [0..KEYBOARD_KEYS] of Boolean; FWheelState: TMouseWheelState; function GetMouseState(): IMouseState; function GetKeyboardState(): IKeyboardState; function GetX(): Single; function GetY(): Single; function GetPosition(): TVectorF; function GetIsButtonPressed(AButton: TMouseButton): Boolean; function GetWheelState(): TMouseWheelState; function GetIsKeyPressed(AKey: TKeyButton): Boolean; private procedure ClearWheelState; procedure SetWheelState(ADirection: Integer); procedure SetButtonState(AButton: TMouseButton; AState: Boolean); procedure SetMousePosition(const APosition: TVectorF); procedure SetKeyState(AKey: TKeyButton; AState: Boolean); public constructor Create; property Mouse: IMouseState read GetMouseState; property Keyboard: IKeyboardState read GetKeyboardState; property X: Single read GetX; property Y: Single read GetY; property Position: TVectorF read GetPosition; property IsButtonPressed[AButton: TMouseButton]: Boolean read GetIsButtonPressed; property WheelState: TMouseWheelState read GetWheelState; property IsKeyPressed[AKey: TKeyButton]: Boolean read GetIsKeyPressed; end; {$REGION ' TControlState '} constructor TControlState.Create; var I: Integer; begin FMousePosition.Create(0, 0); for I := 0 to 2 do FButtonsState[I] := False; for I := 0 to KEYBOARD_KEYS do FKeysState[I] := False; FWheelState := mwsNone; end; function TControlState.GetIsButtonPressed(AButton: TMouseButton): Boolean; begin Result := FButtonsState[Integer(AButton)]; end; function TControlState.GetIsKeyPressed(AKey: TKeyButton): Boolean; begin if AKey < KEYBOARD_KEYS then Result := FKeysState[AKey] else Result := False; end; function TControlState.GetKeyboardState: IKeyboardState; begin Result := Self; end; function TControlState.GetMouseState: IMouseState; begin Result := Self; end; function TControlState.GetPosition: TVectorF; begin Result := FMousePosition; end; function TControlState.GetWheelState: TMouseWheelState; begin Result := FWheelState; end; function TControlState.GetX: Single; begin Result := FMousePosition.X; end; function TControlState.GetY: Single; begin Result := FMousePosition.Y; end; procedure TControlState.ClearWheelState; begin FWheelState := mwsNone; end; procedure TControlState.SetWheelState; begin if ADirection > 0 then FWheelState := mwsUp else FWheelState := mwsDown; end; procedure TControlState.SetButtonState; begin FButtonsState[Integer(AButton)] := AState; end; procedure TControlState.SetMousePosition; begin FMousePosition := APosition; end; procedure TControlState.SetKeyState; begin if (AKey < KEYBOARD_KEYS) then FKeysState[AKey] := AState; end; {$ENDREGION} {$REGION ' TQApplicationParameters '} constructor TQApplicationParameters.Create( AGame: TQGame; AResolution: TVector2I; AIsFullscreen: Boolean; ATimerDelta: Word = 16); begin if not Assigned(AGame) then raise EArgumentException.Create( 'Не указан объект игры. ' + '{11946C86-12FC-4907-9E74-F3C844A372CD}'); FGame := AGame; FResolution := AResolution; FIsFullscreen := AIsFullscreen; FTimerDelta := ATimerDelta; end; {$ENDREGION} {$REGION ' TQApplication '} procedure MainTimerCallback(var ADelta: Double); stdcall; begin if Assigned(TheApplication) then TheApplication.MainTimerUpdate(ADelta); end; constructor TQApplication.Create; begin Inc(FRefCount); FIsStoped := True; FWindow := TWindow.Create(Self); FControlState := TControlState.Create; FCriticalSection := TCriticalSection.Create; FMessages := TList<TEventMessage>.Create; TheControlState := ControlState; TheMouseState := TheControlState.Mouse; TheKeyboardState := TheControlState.Keyboard; end; destructor TQApplication.Destroy; begin FMainTimer := nil; if Assigned(FGame) then FGame.OnDestroy; FreeAndNil(FGame); if Assigned(FWindow) then FreeAndNil(FWindow); FreeAndNil(FCriticalSection); FreeAndNil(FMessages); FControlState := nil; TheControlState := nil; TheMouseState := nil; TheKeyboardState := nil; FMainTimer := nil; inherited; end; function TQApplication.GetFPS; begin if Assigned(FMainTimer) then Result := FMainTimer.GetFPS else Result := 0; end; procedure TQApplication.SetupWindow; var AWindowCaption: string; begin AWindowCaption := FGame.Name + ' (' + FGame.Version + ')'; FWindow.CreateWindow(AWindowCaption, Resolution.X, Resolution.Y); end; procedure TQApplication.SetupTimer(ATimerDelta: Word); begin TheDevice.CreateTimer(FMainTimer); FMainTimer.SetState(False); FMainTimer.SetCallBack(@MainTimerCallback); FMainTimer.SetInterval(ATimerDelta); end; procedure TQApplication.ProcessMessages; var AMessage: TEventMessage; begin for AMessage in FMessages do begin case AMessage.MessageType of emtMouseEvent: if Assigned(FGame) then FGame.OnMouseMove(AMessage.MousePosition); emtMouseButtonEvent: if AMessage.IsMouseButtonPressed then begin if Assigned(FGame) then FGame.OnMouseButtonDown(AMessage.MouseButton, AMessage.MousePosition); end else begin if Assigned(FGame) then FGame.OnMouseButtonUp(AMessage.MouseButton, AMessage.MousePosition); end; emtMouseWheelEvent: if Assigned(FGame) then FGame.OnMouseWheel(AMessage.MouseWheelDirection); emtKeyEvent: if AMessage.IsKeyPressed then begin if Assigned(FGame) then FGame.OnKeyDown(AMessage.KeyButton); end else begin if Assigned(FGame) then FGame.OnKeyUp(AMessage.KeyButton); end; end; end; FMessages.Clear; end; procedure TQApplication.Loop; var AMessage: TMsg; begin FIsStoped := False; while GetMessageA(AMessage, FWindow.Handle, 0, 0) do// and FIsRuning do begin if AMessage.message = 0 then Break; TranslateMessage(AMessage); DispatchMessageA(AMessage); if FIsStoped then DestroyWindow(FWindow.Handle); end; FCriticalSection.Enter; FCriticalSection.Leave; end; procedure TQApplication.Stop; begin FIsStoped := True; end; procedure TQApplication.MainTimerUpdate(const ADeltaTime: Double); begin FCriticalSection.Enter; ProcessMessages; OnUpdate(ADeltaTime); OnDraw(0); (FControlState as TControlState).ClearWheelState; if FIsStoped then FMainTimer.SetState(False); if FIsStoped then FMainTimer.SetState(False); FCriticalSection.Leave; end; procedure TQApplication.OnInitialize(AParameter: TObject = nil); var AOptions: TQApplicationParameters; begin if not Assigned(AParameter) then raise EArgumentException.Create( 'Не указаны параметры для инициализации приложения. ' + '{4B5CB812-602E-4713-8581-B59B35576786}'); if not (AParameter is TQApplicationParameters) then raise EArgumentException.Create( 'Неправильный формат параметров инициализации. ' + '{DDAF7AF1-9673-4344-93F9-D61D2DA43133}'); AOptions := AParameter as TQApplicationParameters; FGame := AOptions.Game; FResolution := AOptions.Resolution; FIsFullscreen := AOptions.IsFullscreen; SetupWindow; SetupTimer(AOptions.TimerDelta); TheRender.Initialize(Window.Handle, Resolution.X, Resolution.Y, FIsFullscreen); FreeAndNil(AOptions); FGame.OnInitialize; end; procedure TQApplication.OnActivate(AIsActivate: Boolean); begin if Assigned(FMainTimer) then FMainTimer.SetState(AIsActivate); end; procedure TQApplication.OnDraw(const ALayer: Integer); begin if Assigned(FGame) then begin TheRender.BeginRender; FGame.OnDraw(0); TheRender.EndRender; end; end; procedure TQApplication.OnUpdate(const ADelta: Double); begin if Assigned(FGame) then FGame.OnUpdate(ADelta); end; procedure TQApplication.OnDestroy; begin FMainTimer.SetState(False); end; function TQApplication.OnMouseMove; begin Result := True; FCriticalSection.Enter; (FControlState as TControlState).SetMousePosition(AMousePosition); FMessages.Add(TEventMessage.CreateAsMouseEvent(AMousePosition)); FCriticalSection.Leave; end; function TQApplication.OnMouseButtonDown; begin Result := True; FCriticalSection.Enter; (FControlState as TControlState).SetMousePosition(AMousePosition); (FControlState as TControlState).SetButtonState(AButton, True); FMessages.Add( TEventMessage.CreateAsMouseButtonEvent(AMousePosition, AButton, True)); FCriticalSection.Leave; end; function TQApplication.OnMouseButtonUp; begin Result := True; FCriticalSection.Enter; (FControlState as TControlState).SetMousePosition(AMousePosition); (FControlState as TControlState).SetButtonState(AButton, False); FMessages.Add( TEventMessage.CreateAsMouseButtonEvent(AMousePosition, AButton, False)); FCriticalSection.Leave; end; function TQApplication.OnMouseWheel; begin Result := True; FCriticalSection.Enter; (FControlState as TControlState).SetWheelState(ADirection); FMessages.Add( TEventMessage.CreateAsMouseWheelEvent(ADirection)); FCriticalSection.Leave; end; function TQApplication.OnKeyDown; begin Result := True; FCriticalSection.Enter; (FControlState as TControlState).SetKeyState(AKey, True); FMessages.Add( TEventMessage.CreateAsKeyEvent(AKey, True)); FCriticalSection.Leave; if AKey = KB_ALT then FIsAltPressed := True; if (AKey = KB_F4) and FIsAltPressed then Stop; end; function TQApplication.OnKeyUp; begin Result := True; FCriticalSection.Enter; (FControlState as TControlState).SetKeyState(AKey, False); FMessages.Add( TEventMessage.CreateAsKeyEvent(AKey, False)); FCriticalSection.Leave; if AKey = KB_ALT then FIsAltPressed := False; end; {$ENDREGION} end.
unit AT.Vcl.Actions.Types; interface type TATBoolDataAfterChangedEvent = procedure(Sender: TObject; const Value: Boolean) of object; TATDataAfterChangedEvent = procedure(Sender: TObject; const Value: Variant) of object; TATDateTimeDataAfterChangedEvent = procedure(Sender: TObject; const Value: TDateTime) of object; TATInt32DataAfterChangedEvent = procedure(Sender: TObject; const Value: Int32) of object; TATInt64DataAfterChangedEvent = procedure(Sender: TObject; const Value: Int64) of object; TATStrDataAfterChangedEvent = procedure(Sender: TObject; const Value: String) of object; TATBoolDataBeforeChangedEvent = procedure(Sender: TObject; const OldValue: Boolean; const NewValue: Boolean) of object; TATDataBeforeChangedEvent = procedure(Sender: TObject; const OldValue: Variant; const NewValue: Variant) of object; TATDateTimeDataBeforeChangedEvent = procedure(Sender: TObject; const OldValue: TDateTime; const NewValue: TDateTime) of object; TATInt32DataBeforeChangedEvent = procedure(Sender: TObject; const OldValue: Integer; const NewValue: Integer) of object; TATInt64DataBeforeChangedEvent = procedure(Sender: TObject; const OldValue: Int64; const NewValue: Int64) of object; TATStrDataBeforeChangedEvent = procedure(Sender: TObject; const OldValue: String; const NewValue: String) of object; implementation end.
unit Materials; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls, Project, Menus; type TMaterialsForm = class(TForm) Panel1: TPanel; PageControl: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; ComponentsTMemo: TMemo; WiresTMemo: TMemo; CloseTButton: TButton; RefreshTButton: TButton; TabSheet3: TTabSheet; TabSheet4: TTabSheet; LinksTMemo: TMemo; BOMTMemo: TMemo; CopyTButton: TButton; TabSheet5: TTabSheet; StatisticsTMemo: TMemo; TabSheet6: TTabSheet; BreaksTMemo: TMemo; PrintTButton: TButton; procedure FormResize(Sender: TObject); procedure CloseTButtonClick(Sender: TObject); procedure RefreshTButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure CopyTButtonClick(Sender: TObject); procedure PrintTButtonClick(Sender: TObject); private { Private declarations } Created : boolean; function ActiveMemo : TMemo; public { Public declarations } Project : TveProject; procedure UpdateInfo; end; var MaterialsForm: TMaterialsForm; implementation {$R *.DFM} uses Outlines, CelledOutlines, SizeableOutlines, OtherOutlines, SortCompare, Connective, PrintReport, Globals, Netlist, Contnrs; procedure TMaterialsForm.FormCreate(Sender: TObject); begin // show last page in tabbed page control PageControl.ActivePageIndex := 3; end; procedure TMaterialsForm.FormShow(Sender: TObject); var MainForm : TForm; begin if not Created then begin // Position page so it is slightly to right and down of center position // This means this form is not obscured by netlist form which does live // exactly at centre of main form. MainForm := Application.MainForm; Left := MainForm.Left + (MainForm.Width div 2) - (Width div 2) + (2 * GetSystemMetrics(SM_CXHTHUMB) ); Top := MainForm.Top + (MainForm.Height div 2) - (Height div 2) + (2 * GetSystemMetrics( SM_CYVTHUMB) ); Created := True; PageControl.ActivePage := TabSheet1; end; end; // ************************************************ // REPOSITION BUTTONS AFTER FORM RESIZE // ************************************************ procedure TMaterialsForm.FormResize(Sender: TObject); var Spacing : integer; begin Spacing := CloseTButton.Width div 6; // Position Close Button at left CloseTButton.Left := Spacing * 2; // Position Print Button at right, with Copy, Refresh buttons nearby PrintTButton.Left := Panel1.Width - PrintTButton.Width - (Spacing * 2); CopyTButton.Left := PrintTButton.Left - CopyTButton.Width - Spacing; RefreshTButton.Left := CopyTButton.Left - RefreshTButton.Width - Spacing; end; procedure TMaterialsForm.CloseTButtonClick(Sender: TObject); begin Hide; end; procedure TMaterialsForm.RefreshTButtonClick(Sender: TObject); begin UpdateInfo; end; procedure DisplayComponents( Project : TveProject; Memo : TMemo ); var S : TStringList; i : integer; Item : TveBoardItem; Outline : TveOutline; Components : TList; const HeadingFormat = '%8s%20s%18s (%3s,%3s)-(%3s,%3s) %5s'; DataFormat = '%8s%20s%18s (%3d,%3d)'; DataLeadedFormat = '%8s%20s%18s (%3d,%3d)-(%3d,%3d) %5s'; begin S := TStringList.Create; try Components := TList.Create; try // fill list with components for i := 0 to Project.BoardItemCount -1 do begin Item := Project.BoardItems[i]; Outline := Item.Outline; if Outline.UserDefined then begin Components.Add( Item ); end; end; // sort list so same part type are grouped Components.Sort( CompareItemsForComponents ); // print column headings S.Add( Format(HeadingFormat, ['Item', 'Value', 'Outline', 'X', 'Y', 'X2', 'X2', 'Length']) ); S.Add( '' ); for i := 0 to Components.Count -1 do begin Item := TveBoardItem(Components[i]); Outline := Item.Outline; if Outline.UserDefined then begin if Outline is TveSizeableOutline then begin S.Add( Format( DataLeadedFormat, [Item.Designator, Item.Value, Outline.Name, Item.X, Item.Y, Item.X+Item.EndDeltaX, Item.Y+Item.EndDeltaY, Item.DisplayLength] ) ); end else begin S.Add( Format( DataFormat, [Item.Designator, Item.Value, Outline.Name, Item.X, Item.Y] ) ); end; end; end; Memo.Lines := S; finally Components.Free; end finally S.Free; end; end; function CompareItemsByValue( P1, P2 : pointer ) : integer; begin result := AnsiCompareStr( TveBoardItem(P1).Value, TveBoardItem(P2).Value ); if result = 0 then begin if TveBoardItem(P1).X > TveBoardItem(P2).X then begin result := 1; end else if TveBoardItem(P1).X < TveBoardItem(P2).X then begin result := -1; end else if TveBoardItem(P1).Y > TveBoardItem(P2).Y then begin result := 1; end else if TveBoardItem(P1).Y < TveBoardItem(P2).Y then begin result := -1; end end; end; procedure DisplayWires( Project : TveProject; Memo : TMemo ); var Connectivity : TConnectivity; S : TStringList; Wires : TList; i : integer; Item : TveBoardItem; Node : TneNode; Outline : TveOutline; LastItem : TveBoardItem; const HeadingFormat = '%17s %10s, (%3s,%3s)'; DataFormat = '%17s %10s, (%3d,%3d)'; begin // get hold of connectivity object that provides net information Connectivity := TConnectivity( Project.ConnectivityObject ); S := TStringList.Create; try Wires := TList.Create; try // print column headings S.Add( Format( HeadingFormat, ['Net', 'Value', 'X', 'Y'] ) ); S.Add(''); // build list of wires for i := 0 to Project.BoardItemCount -1 do begin Item := Project.BoardItems[i]; Outline := Item.Outline; if (Outline is TveWireOutline) then begin Wires.Add( Item ); end; end; // sort wires so connected wires are adjacent in list Wires.Sort( CompareItemsByValue ); // print out list of wires LastItem := nil; for i := 0 to Wires.Count -1 do begin Item := TveBoardItem( Wires[i] ); // blank line before each interconnected group of wires if (LastItem <> nil) and (Item.Value <> LastItem.Value) then begin S.Add( '' ); end; LastItem := Item; Node := Connectivity.NodeByWire( Item ); if Node = nil then begin S.Add( Format( DataFormat, [ '', Item.Value, Item.X, Item.Y] ) ); end else begin S.Add( Format( DataFormat, [ Node.Name, Item.Value, Item.X, Item.Y] ) ); end; end; finally Wires.Free; end; // display wires in memo Memo.Lines := S; finally S.Free; end; end; // Compare Items So Sort Produces Leftmost items first. // If two items have same X position, then put topmost item first function CompareItemsByPosition( P1, P2 : pointer ) : integer; var Item1, Item2 : TveBoardItem; begin Item1 := TveBoardItem(P1); Item2 := TveBoardItem(P2); if (Item1.X < Item2.X) then begin result := -1; end else if Item1.X > Item2.X then begin result := 1; end else begin if Item1.Y < Item2.Y then begin result := -1; end else if Item1.Y > Item2.Y then begin result := 1; end else begin result := 0; end; end; end; type TLinkData = class public Link : TveBoardItem; Net : TneNode; end; function CompareLinkDataByNetName( P1, P2 : pointer ) : integer; var Net1, Net2 : TneNode; begin // compare first by net name Net1 := TLinkData( P1 ).Net; Net2 := TLinkData( P2 ).Net; // if no net names involved, compare by position if (Net1 = nil) and (Net2 = nil) then begin result := CompareItemsByPosition( TLinkData(P1).Link, TlinkData(P2).Link ); exit; end; // if one link has no net, put it last if Net1 = nil then begin result := 1; exit; end; if Net2 = nil then begin result := -1; exit; end; // both links have a net result := AnsiCompareStr( Net1.Name, Net2.Name ); end; procedure DisplayLinks( Project : TveProject; Memo : TMemo ); var Connectivity : TConnectivity; S : TStringList; Links : TObjectList; LinkData : TLinkData; i : integer; Item : TveBoardItem; Outline : TveOutline; NetName : string; const HeadingFormat = '%15s (%3s,%3s)-(%3s,%3s) %5s'; DataFormat = '%15s (%3d,%3d)-(%3d,%3d) %5s'; begin // get hold of connectivity object that provides net information Connectivity := TConnectivity( Project.ConnectivityObject ); S := TStringList.Create; try Links := TObjectList.Create; try // print column headings S.Add( Format(HeadingFormat, [ 'Net', 'X', 'Y', 'X2', 'Y2', 'Length' ]) ); S.Add(''); // build list of links for i := 0 to Project.BoardItemCount -1 do begin Item := Project.BoardItems[i]; Outline := Item.Outline; if (Outline is TveLinkOutline) then begin LinkData := TLinkData.Create; LinkData.Link := Item; LinkData.Net := Connectivity.NodeByLink( Item ); Links.Add( LinkData ); end; end; // sort wires so connected wires are adjacent in list Links.Sort( CompareLinkDataByNetName ); // print out list of wires for i := 0 to Links.Count -1 do begin LinkData := TLinkData( Links[i] ); Item := LinkData.Link; if LinkData.Net <> nil then begin NetName := LinkData.Net.Name; end else begin NetName := ''; end; S.Add( Format( DataFormat, [ NetName, Item.X, Item.Y, Item.X+Item.EndDeltaX, Item.Y+Item.EndDeltaY, Item.DisplayLength ] ) ); end; finally Links.Free; end; // display wires in memo Memo.Lines := S; finally S.Free; end; end; // Compare Items So Sort Produces grouping of items with same // alphabetical prefix of designator (C11 C3 etc), same outline // and same value. function CompareItemsForBOM( P1, P2 : pointer ) : integer; var Item1, Item2 : TveBoardItem; begin Item1 := TveBoardItem(P1); Item2 := TveBoardItem(P2); // Same Outline - no two outlines will ever have the same name, // so we can compare by name without having to worry about // outline object references being to same object. result := AnsiCompareStr( Item1.Outline.Name, Item2.Outline.Name ); // same outline - so compare Value ( 100K vs 22K etc ) if result = 0 then begin result := AnsiCompareStr( Item1.Value, Item2.Value ); end; // same outline & value - so compare designator - "Item" column if result = 0 then begin // result := AnsiCompareStr( Item1.Designator, Item2.Designator ); result := CompareDesignators( Item1.Designator, Item2.Designator ); end; end; procedure DisplayBOM( Project : TveProject; Memo : TMemo ); var S : TStringList; i : integer; Item : TveBoardItem; Outline : TveOutline; Components : TList; LastComponent : TveBoardItem; const HeadingFormat = '%8s%20s%18s (%3s,%3s)'; DataFormat = '%8s%20s%18s (%3d,%3d)'; begin S := TStringList.Create; try Components := TList.Create; try // print column headings S.Add( Format( HeadingFormat, ['Item', 'Value', 'Outline', 'X', 'Y'] ) ); S.Add( '' ); // fill list with components for i := 0 to Project.BoardItemCount -1 do begin Item := Project.BoardItems[i]; Outline := Item.Outline; if Outline.UserDefined then begin Components.Add( Item ); end; end; // sort list so same part type are grouped Components.Sort( CompareItemsForBOM ); // print out list of components in groups LastComponent := nil; for i := 0 to Components.Count -1 do begin Item := TveBoardItem( Components[i] ); // blank line before each interconnected group of wires if (LastComponent <> nil) and ( (Item.Value <> LastComponent.Value) or (Item.Outline <> LastComponent.Outline) ) then begin S.Add( '' ); end; LastComponent := Item; S.Add( Format( DataFormat, [Item.Designator, Item.Value, Item.Outline.Name, Item.X, Item.Y] ) ); end; finally Components.Free; end; Memo.Lines := S; finally S.Free; end; end; procedure DisplayStatistics( Project : TveProject; Memo : TMemo ); var S : TStringList; i : integer; Outline : TveOutline; ComponentCount : integer; LinkCount : integer; WireCount : integer; BreakCount : integer; Connectivity : TConnectivity; x, y : integer; SolderPointCount : integer; begin S := TStringList.Create; try // info on board items available from Components list. ComponentCount := 0; LinkCount := 0; WireCount := 0; BreakCount := 0; for i := 0 to Project.BoardItemCount - 1 do begin Outline := Project.BoardItems[i].Outline; if Outline.UserDefined then begin inc( ComponentCount ); end else if( Outline is TveLinkOutline ) then begin inc( LinkCount ); end else if( Outline is TveWireOutline ) then begin inc( WireCount ); end else if( Outline is TveBreakOutline ) then begin inc( BreakCount ); end; end; S.Add( Format('Components : %d', [ComponentCount]) ); S.Add( '' ); S.Add( Format('Links : %d', [LinkCount]) ); S.Add( '' ); S.Add( Format('Wires : %d', [WireCount]) ); S.Add( '' ); S.Add( Format('Breaks : %d', [BreakCount]) ); S.Add( '' ); // solder point info available from Design Rule Checker SolderPointCount := 0; Connectivity := TConnectivity( Project.ConnectivityObject ); for x := 0 to Project.BoardWidth - 1 do begin for y := 0 to Project.BoardHeight -1 do begin if Connectivity.Cells[x, y].PinCount > 0 then begin inc( SolderPointCount ); end; end; end; S.Add( Format('Solder Points : %d', [SolderPointCount]) ); // display information Memo.Lines := S; finally S.Free; end; end; (* function CompareItemsByBreakPosition( P1, P2 : pointer ) : integer; var Item1, Item2 : TveBoardItem; begin Item1 := TveBoardItem(P1); Item2 := TveBoardItem(P2); // sort by Y ( across board ) if Item1.X < Item2.X then begin result := -1; end else if Item1.X > Item2.X then begin result := 1; end else if Item1.Y < Item2.Y then begin result := -1; end else if Item2.Y > Item2.Y then begin result := 1; end else begin result := 0; end; end; *) procedure DisplayBreaks( Project : TveProject; Memo : TMemo ); var S : TStringList; i : integer; Item : TveBoardItem; List : TList; begin List := nil; S := TStringList.Create; try // fill list with references to items with break outlines List := TList.Create; for i := 0 to Project.BoardItemCount - 1 do begin Item := Project.BoardItems[i]; if Item.Outline is TveBreakOutline then begin List.Add( Item ); end; end; // sort list by break position // List.Sort( CompareItemsByBreakPosition ); List.Sort( CompareItemsByPosition ); // put outline (break) locations into report S.Add( ' X, Y' ); S.Add( '' ); for i := 0 to List.Count - 1 do begin Item := TveBoardItem( List[i] ); case Item.Shift of shNone: begin S.Add( Format('%4d ,%4d', [Item.X, Item.Y]) ); end; shRight: begin S.Add( Format('%4d.5,%4d', [Item.X, Item.Y]) ); end; shDown: begin S.Add( Format('%4d ,%4d.5', [Item.X, Item.Y]) ); end; end; end; // display information Memo.Lines := S; finally S.Free; List.Free; end; end; // ************************************************ // REFRESH ALL TABS // ************************************************ procedure TMaterialsForm.UpdateInfo; begin Screen.Cursor := crHourGlass; try DisplayComponents( Project, ComponentsTMemo ); DisplayWires( Project, WiresTMemo ); DisplayLinks( Project, LinksTMemo ); DisplayBOM( Project, BOMTMemo ); DisplayStatistics( Project, StatisticsTMemo ); DisplayBreaks( Project, BreaksTMemo ); finally Screen.Cursor := crDefault; end; end; // ************************************************ // FIND CURRENTLY SHOWING MEMO // ************************************************ function TMaterialsForm.ActiveMemo : TMemo; var ActivePage : TTabSheet; begin ActivePage := PageControl.ActivePage; if ActivePage = TabSheet1 then begin result := ComponentsTMemo; end else if ActivePage = TabSheet2 then begin result := WiresTMemo; end else if ActivePage = TabSheet3 then begin result := LinksTMemo; end else if ActivePage = TabSheet4 then begin result := BOMTMemo; end else if ActivePage = TabSheet5 then begin result := StatisticsTMemo; end else if ActivePage = TabSheet6 then begin result := BreaksTMemo; end // we never get here, but stops "Undefined result" compiler warning else begin result := nil; end; end; // ************************************************ // COPY TO CLIPBOARD CURRENTLY SHOWING MEMO // ************************************************ procedure TMaterialsForm.CopyTButtonClick(Sender: TObject); begin ActiveMemo.SelectAll; ActiveMemo.CopyToClipboard; end; // ************************************************ // PRINT THE CURRENTLY SHOWING MEMO // ************************************************ procedure TMaterialsForm.PrintTButtonClick(Sender: TObject); var ReportPrinter : TPrintReportForm; begin // This form has position = poOwnerFormCenter, do must have AOwner // param set to this form, not to nil ReportPrinter := TPrintReportForm.Create(self); try ReportPrinter.HKEY_CURRENT_USER_key := Globals.HKEY_CURRENT_USER_KEY; ReportPrinter.ReportStrings := ActiveMemo.Lines; ReportPrinter.PrinterTitle := 'VeeCAD Report'; ReportPrinter.Caption := 'Print: ' + PageControl.ActivePage.Caption; // title for each page, including page number at %d format ReportPrinter.PageTitle := 'Materials : ' + PageControl.ActivePage.Caption + '. Page %d'; ReportPrinter.Execute; finally ReportPrinter.Free; end; end; end.
unit UnCEGIDCrypt; {$mode objfpc}{$H+} interface function IsValidHex(Str : string) : Boolean; function GetNextMysteriousNumber(MysteriousNumber : Longint) : Longint; function Encrypt(DecryptStr : string) : string; function Decrypt(EncryptStr : string) : string; implementation uses SysUtils, LConvEncoding; function IsValidHex(Str : string) : Boolean; var Index : Integer; BoolTmp : Boolean; begin BoolTmp := True; for Index := 1 to Length(Str) do begin BoolTmp := BoolTmp and (Str[Index] in ['0'..'9','a'..'f','A'..'F']); end; IsValidHex := BoolTmp; end; function GetNextMysteriousNumber(MysteriousNumber : Longint) : Longint; begin if MysteriousNumber < 0 then begin MysteriousNumber := $74D99E; end; MysteriousNumber := ((MysteriousNumber mod $01F31D) * $41A7) - ((MysteriousNumber div $01F31D) * $0B14); if MysteriousNumber < 0 then begin MysteriousNumber := MysteriousNumber + $7FFFFFFF; end; GetNextMysteriousNumber := MysteriousNumber; end; function Encrypt(DecryptStr : string) : string; var Index : Integer; CharTmp : Byte; EncryptStr : string; MysteriousNumber : Longint; begin DecryptStr := UTF8ToISO_8859_15(DecryptStr); EncryptStr := ''; MysteriousNumber := $02BA4CB5; for Index := Length(DecryptStr) downto 1 do begin MysteriousNumber := GetNextMysteriousNumber(MysteriousNumber); CharTmp := Byte(DecryptStr[Index]); CharTmp := CharTmp xor (MysteriousNumber div 65536); EncryptStr := EncryptStr + IntToHex(CharTmp, 2); MysteriousNumber := MysteriousNumber xor CharTmp; end; Encrypt := EncryptStr; end; function Decrypt(EncryptStr : string) : string; var Index : Integer; CharTmp, HexTmp : Byte; DecryptStr : string; MysteriousNumber : Longint; begin DecryptStr := ''; MysteriousNumber := $02BA4CB5; for Index := 1 to (Length(EncryptStr) div 2) do begin MysteriousNumber := GetNextMysteriousNumber(MysteriousNumber); HexTmp := StrToInt('$' + EncryptStr[(Index * 2) - 1] + EncryptStr[Index * 2]); CharTmp := HexTmp xor (MysteriousNumber div 65536); MysteriousNumber := MysteriousNumber xor HexTmp; DecryptStr := ISO_8859_15ToUTF8(Char(CharTmp)) + DecryptStr; end; Decrypt := DecryptStr; end; end.
unit at.ShortName.Vcl.Forms.Generic.TabForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls; type TfrmGenericTabForm = class(TForm) pnlContents: TPanel; strict protected property Align; property AlignWithMargins; property BorderIcons; property BorderStyle; property FormStyle; property GlassFrame; property Margins; property OnActivate; property OnDeactivate; property WindowState; strict protected function GetContents: TPanel; function GetText: TCaption; /// <summary> /// IsNonClosing property getter. /// </summary> function GetIsNonClosing: Boolean; procedure SetText(const Value: TCaption); procedure _InitControls; procedure _InitFields; procedure _InitLiveBindings; procedure _LoadFormState; procedure _NotifyVM; procedure _SaveFormState; procedure _SetFormCaption; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function CloseQuery: Boolean; override; property Caption read GetText write SetText; property Contents: TPanel read GetContents; property IsNonClosing: Boolean read GetIsNonClosing; end; TfrmGenericTabFormClass = class of TfrmGenericTabForm; var frmGenericTabForm: TfrmGenericTabForm; implementation uses AT.GarbageCollector, System.Rtti, AT.ShortName.Attribs, AT.ShortName.DM.Services.Application, AT.ShortName.Intf; {$R *.dfm} constructor TfrmGenericTabForm.Create(AOwner: TComponent); begin inherited Create(AOwner); inherited WindowState := wsNormal; inherited BorderIcons := []; inherited BorderStyle := bsNone; inherited FormStyle := fsNormal; inherited GlassFrame.Enabled := False; _SetFormCaption; _LoadFormState; _InitFields; _InitControls; _InitLiveBindings; _NotifyVM; end; destructor TfrmGenericTabForm.Destroy; begin _SaveFormState; inherited Destroy; end; function TfrmGenericTabForm.CloseQuery: Boolean; var AIntf: IATMainCloseQuery; begin Result := inherited CloseQuery; if (NOT IsNonClosing) then Exit; if (NOT AppServices.MainFormSupports(IATMainCloseQuery, AIntf)) then Exit; Result := ( (AIntf.WantsToClose OR AIntf.IsClosing) AND Result ); end; function TfrmGenericTabForm.GetContents: TPanel; begin Result := pnlContents; end; function TfrmGenericTabForm.GetIsNonClosing: Boolean; var AGC: IATGarbageCollector; AContext: TRttiContext; AType: TRttiType; AAttr: TCustomAttribute; ANCAttr: ATNonClosingFormAttribute; begin AContext := TRttiContext.Create; TATGC.Cleanup( procedure begin AContext.Free; end, AGC); AType := AContext.GetType(Self.ClassType); Result := False; ANCAttr := NIL; for AAttr in AType.GetAttributes do begin Result := (AAttr is ATNonClosingFormAttribute); if (Result) then begin ANCAttr := (AAttr as ATNonClosingFormAttribute); Break; end; end; if (Result and (Assigned(ANCAttr))) then Result := ANCAttr.Value; end; function TfrmGenericTabForm.GetText: TCaption; var Len: Integer; begin Len := GetTextLen; SetString(Result, PChar(nil), Len); if Len <> 0 then begin Len := Len - GetTextBuf(PChar(Result), Len + 1); if Len > 0 then SetLength(Result, Length(Result) - Len); end; end; procedure TfrmGenericTabForm.SetText(const Value: TCaption); var AIntf: IATFormCaptionChanged; begin if (GetText <> Value) then SetTextBuf(PChar(Value)); if (Supports(Parent, IATFormCaptionChanged, AIntf)) then AIntf.FormCaptionChanged(Value) else if (Supports(Owner, IATFormCaptionChanged, AIntf)) then AIntf.FormCaptionChanged(Value); end; procedure TfrmGenericTabForm._InitControls; var AIntf: IATInitControls; begin if (not Supports(Self, IATInitControls, AIntf)) then Exit; AIntf.InitControls; end; procedure TfrmGenericTabForm._InitFields; var AIntf: IATInitFields; begin if (not Supports(Self, IATInitFields, AIntf)) then Exit; AIntf.InitFields; end; procedure TfrmGenericTabForm._InitLiveBindings; var AIntf: IATLiveBindings; begin if (not Supports(Self, IATLiveBindings, AIntf)) then Exit; AIntf.InitLiveBindings; end; procedure TfrmGenericTabForm._LoadFormState; var AIntf: IATPersistentForm; begin if (not Supports(Self, IATPersistentForm, AIntf)) then Exit; AIntf.LoadFormState; end; procedure TfrmGenericTabForm._NotifyVM; var AIntf: IATLiveBindings; begin if (not Supports(Self, IATLiveBindings)) then Exit; AIntf.NotifyVM; end; procedure TfrmGenericTabForm._SaveFormState; var AIntf: IATPersistentForm; begin if (not Supports(Self, IATPersistentForm, AIntf)) then Exit; AIntf.SaveFormState; end; procedure TfrmGenericTabForm._SetFormCaption; var AIntf: IATInitFormCaption; begin if (not Supports(Self, IATInitFormCaption, AIntf)) then Exit; AIntf.SetFormCaption; end; end.
Unit SteamworksProcessor; {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} Interface Type FunctionArgumentDecl = Class IsVar:Boolean; Name:TERRAString; InitVal:TERRAString; ArgumentType:TERRAString; End; FunctionDecl = Class Name:TERRAString; EntryPoint:TERRAString; ReturnType:TERRAString; Arguments:Array Of FunctionArgumentDecl; ArgumentCount:Integer; Function AddArgument():FunctionArgumentDecl; End; EnumFieldDecl = Class Name:TERRAString; Value:TERRAString; Comment:TERRAString; End; EnumDecl = Class Name:TERRAString; Decls:Array Of EnumFieldDecl; DeclCount:Integer; Constructor Create(Const Name:TERRAString); Function AddDecl():EnumFieldDecl; End; StructFieldDecl = Class Name:TERRAString; FieldType:TERRAString; Comment:TERRAString; Count:TERRAString; End; StructDecl = Class Public Name:TERRAString; Fields:Array Of StructFieldDecl; FieldCount:Integer; Constructor Create(Const Name:TERRAString); Function AddField():StructFieldDecl; End; ConstDecl = Record Name:TERRAString; ConstType:TERRAString; Value:TERRAString; End; RegionDecl = Class Name:TERRAString; Functions:Array Of FunctionDecl; FunctionCount:Integer; Constructor Create(Const Name:TERRAString); Procedure AddFunction(Func:FunctionDecl); End; SteamDeclarations = Class Protected Procedure LoadConsts(Const SrcName:TERRAString); Procedure LoadEnums(Const SrcName:TERRAString); Procedure LoadStructs(Const SrcName:TERRAString); Procedure LoadRegion(Var Lines:TERRAString); Function ReadNextDecl(Var Lines:TERRAString):FunctionDecl; Public Consts:Array Of ConstDecl; ConstCount:Integer; Enums:Array Of EnumDecl; EnumCount:Integer; Structs:Array Of StructDecl; StructCount:Integer; Regions:Array Of RegionDecl; RegionCount:Integer; Constructor Create(); Function AddRegion(Const Name:TERRAString):RegionDecl; Function AddEnum(Const Name:TERRAString):EnumDecl; End; Implementation Uses SysUtils, GenUtilities; Function IsPointer(Const TypeName:TERRAString):Boolean; Begin Result := (Copy(TypeName, Length(TypeName) - 3, 3) = 'Ptr'); End; { SteamDeclarations } Constructor SteamDeclarations.Create; Var Src, Output:Stream; Tag, Tag2, Lines, S, S2, Def:TERRAString; I,J:Integer; Begin ConstCount := 0; EnumCount := 0; StructCount := 0; LoadConsts('SteamConstants.cs'); LoadEnums('SteamEnums.cs'); LoadStructs('SteamStructs.cs'); Src := Stream.Create('NativeMethods.cs'); Src.ReadLines(Lines); Src.Release; Tag := '#if '; Tag2 := '#endif'; I := Pos(Tag, Lines); While I>0 Do Begin S := Copy(Lines, 1, Pred(I)); Lines := Copy(Lines, I+Length(Tag), MaxInt); I := Pos(CrLf, Lines); J := Pos(' ', Lines); If (J>0) And ((J<I) Or (I<=0)) Then I := J; Def := Copy(Lines, 1, Pred(I)); Lines := Copy(Lines, Succ(I), MaxInt); I := Pos(Tag2, Lines); Lines := Copy(Lines, I+Length(Tag2), MaxInt); Lines := S + CrLf + Lines; I := Pos(Tag, Lines); End; Tag := '#region '; Repeat I := Pos(Tag, Lines); If I<=0 Then Break; Lines := Copy(Lines, I + Length(Tag), MaxInt); LoadRegion(Lines); Until False; End; Procedure SteamDeclarations.LoadConsts(Const SrcName:TERRAString); Var Tag, Lines:TERRAString; S, S2, S3:TERRAString; Src:Stream; I,J:Integer; ConstType,Name, Value:TERRAString; Begin Src := Stream.Create(SrcName); Src.ReadLines(Lines); Src.Release; Tag := 'public const '; I := Pos(Tag, Lines); While I>0 Do Begin Lines := Copy(Lines, I + Length(Tag), MaxInt); ConstType := TrimLeft(TrimRight(StringExtractNextWord(Lines, ' '))); Name := StringExtractNextWord(Lines, '='); Value := StringExtractNextWord(Lines, ';'); Inc(ConstCount); SetLength(Consts, ConstCount); Consts[Pred(ConstCount)].Name := TrimLeft(TrimRight(Name)); Consts[Pred(ConstCount)].ConstType := ConstType; Consts[Pred(ConstCount)].Value := Value; I := Pos(Tag, Lines); End; End; Procedure SteamDeclarations.LoadEnums(Const SrcName:TERRAString); Var Tag, Lines:TERRAString; S, S2, S3:TERRAString; Src:Stream; I,J:Integer; CurrentEnum:EnumDecl; CurrentDecl:EnumFieldDecl; Begin Src := Stream.Create(SrcName); Src.ReadLines(Lines); Src.Release; CurrentEnum := Nil; Tag := 'public enum '; I := Pos(Tag, Lines); While I>0 Do Begin Lines := Copy(Lines, I + Length(Tag), MaxInt); S := StringExtractNextWord(Lines, ' '); If S[1] = 'E' Then S := Copy(S, 2, MaxInt); If Pos('Steam', S)<=0 Then S := 'Steam' + S; { If S = 'MatchMakingServerResponse' Then IntToString(2);} CurrentEnum := Self.AddEnum(S); CurrentDecl := Nil; StringExtractNextWord(Lines, '{'); I := Pos('}', Lines); S := Copy(Lines, 1, Pred(I)); Lines := Copy(Lines, I + 1, MaxInt); S := TrimLeft(S); While S<>'' Do Begin S2 := Copy(S, 1, 2); If (S2='//') Then Begin I := Pos(CrLf, S); S2 := Copy(S, 1, Pred(I)); S := Copy(S, Succ(I), MaxInt); S2 := TrimLeft(S2); StringExtractNextWord(S2, ' '); If Assigned(CurrentDecl) Then CurrentDecl.Comment := S2; End Else Begin I := Pos(',', S); J := Pos('//', S); If (J>0) And (J<I) Then Begin S2 := Copy(S, 1, Pred(J)); S := TrimLeft(Copy(S, J, MaxInt)); End Else If (I<=0) Then Begin S2 := S; S := ''; End Else Begin S2 := Copy(S, 1, Pred(I)); S := TrimLeft(Copy(S, Succ(I), MaxInt)); End; S3 := StringExtractNextWord(S2, '='); ReplaceText('k_E', 'Steam', S3); ReplaceText('k_E', 'Steam', S2); S2 := TrimRight(TrimLeft(S2)); If S2 = '' Then S2 := IntToString(EnumCount); CurrentDecl := CurrentEnum.AddDecl(); CurrentDecl.Name := TrimRight(TrimLeft(S3)); CurrentDecl.Value := TrimRight(TrimLeft(S2)); End; S := TrimLeft(S); End; I := Pos(Tag, Lines); End; End; Procedure SteamDeclarations.LoadStructs(Const SrcName:TERRAString); Var Tag, Lines:TERRAString; S, S2, S3:TERRAString; Src:Stream; I,J,K,W:Integer; NextCount:TERRAString; Struct:StructDecl; CurrentField:StructFieldDecl; Begin Src := Stream.Create(SrcName); Src.ReadLines(Lines); Src.Release; Tag := 'public struct '; I := Pos(Tag, Lines); While I>0 Do Begin Lines := Copy(Lines, I + Length(Tag), MaxInt); S := StringExtractNextWord(Lines, ' '); If Pos('_t', S)>Length(S)-2 Then S := Copy(S, 1, Length(S)-2); If Pos('Steam', S)<=0 Then S := 'Steam' + S; {If S='SteamMatchMakingKeyValuePair' Then IntToString(2);} Inc(StructCount); SetLength(Structs, StructCount); Struct := StructDecl.Create(S); Structs[Pred(StructCount)] := Struct; CurrentField := Nil; StringExtractNextWord(Lines, '{'); I := Pos(Tag, Lines); If I<=0 Then Begin S := Lines; Lines := ''; End Else Begin S := Copy(Lines, 1, Pred(I)); Lines := Copy(Lines, I, MaxInt); End; NextCount := ''; S := TrimLeft(S); While S<>'' Do Begin S2 := Copy(S, 1, 2); If (Pos('}', S2)>0) Then Break; If (S2='//') Then Begin I := Pos(CrLf, S); S2 := Copy(S, 1, Pred(I)); S := Copy(S, Succ(I), MaxInt); S2 := TrimLeft(S2); StringExtractNextWord(S2, ' '); If Assigned(CurrentField) Then CurrentField.Comment := S2; End Else Begin I := Pos(';', S); J := Pos('//', S); K := Pos(CrLf, S); W := Pos('{', S); If (W>0) And ((W<I) Or (I<=0)) And ((W<J) Or (J<=0)) And ((W<K) Or (K<=0)) Then Begin I := Pos('}', S); S := TrimLeft(Copy(S, Succ(I), MaxInt)); Continue; End Else If (K>0) And ((K<I) Or (I<=0)) And ((K<J) Or (J<=0)) Then Begin S2 := Copy(S, 1, Pred(K)); S := TrimLeft(Copy(S, K, MaxInt)); End Else If (J>0) And (J<I) Then Begin S2 := Copy(S, 1, Pred(J)); S := TrimLeft(Copy(S, J, MaxInt)); End Else If (I<=0) Then Begin S2 := S; S := ''; End Else Begin S2 := Copy(S, 1, Pred(I)); S := TrimLeft(Copy(S, Succ(I), MaxInt)); End; S2 := TrimLeft(S2); If Pos('[Marshal',S2)>0 Then Begin If Pos('ByValTStr', S2)>0 Then Begin StringExtractNextWord(S2, '='); NextCount := StringExtractNextWord(S2, ')'); ReplaceText('Constants.', '', NextCount); End; End Else If Pos('{',S2)>0 Then Begin StringExtractNextWord(S, '}'); End Else Begin StringExtractNextWord(S2, ' '); // public CurrentField := Struct.AddField(); CurrentField.FieldType := TrimRight(TrimLeft(StringExtractNextWord(S2, ' '))); // get type CurrentField.Name := TrimRight(TrimLeft(StringExtractNextWord(S2, ';'))); // get name CurrentField.Count := NextCount; NextCount := ''; If CurrentField.Name[2] = '_' Then Begin ReplaceText('m_un', '', CurrentField.Name); ReplaceText('m_us', '', CurrentField.Name); ReplaceText('m_', '', CurrentField.Name); End; End; End; S := TrimLeft(S); End; I := Pos(Tag, Lines); End; End; Function SteamDeclarations.ReadNextDecl(Var Lines:TERRAString):FunctionDecl; Var S, S2, S3, Tag:TERRAString; I,J,K:Integer; EntryPoint:TERRAString; CurrentArg:FunctionArgumentDecl; Begin Tag := 'EntryPoint = "'; I := Pos(Tag, Lines); If I<=0 Then Begin EntryPoint := ''; End Else Begin Lines := Copy(Lines, I + Length(Tag), MaxInt); EntryPoint := StringExtractNextWord(Lines, '"'); End; Tag := 'public static extern '; I := Pos(Tag, Lines); If I<=0 Then Begin Result := Nil; Exit; End; Lines := Copy(Lines, I + Length(Tag), MaxInt); I := Pos(';', Lines); If I<=0 Then Begin S := Lines; Lines := ''; End Else Begin S := Copy(Lines, 1, Pred(I)); Lines := Copy(Lines, I, MaxInt); End; Result := FunctionDecl.Create(); Result.ReturnType := StringExtractNextWord(S, ' '); Result.Name := StringExtractNextWord(S, '('); If EntryPoint<>'' Then Result.EntryPoint := EntryPoint Else Result.EntryPoint := Result.Name; I := Pos('[MarshalAs', S); While (I>0) Do Begin S2 := Copy(S, 1, Pred(I)); S := Copy(S, I+5, MaxInt); StringExtractNextWord(S, ']'); S := S2+' '+S; I := Pos('[MarshalAs', S); End; S2 := StringExtractNextWord(S, ')'); Result.ArgumentCount := 0; While S2<>'' Do Begin S3 := StringExtractNextWord(S2, ','); CurrentArg := Result.AddArgument(); CurrentArg.ArgumentType := StringExtractNextWord(S3, ' '); CurrentArg.IsVar := (CurrentArg.ArgumentType='out'); If (CurrentArg.IsVar) Then CurrentArg.ArgumentType := StringExtractNextWord(S3, ' '); CurrentArg.Name := TrimLeft(TrimRight(StringExtractNextWord(S3, '='))); If Pos('"', S3)>0 Then S3 := ''; //ReplaceText('"', '''', S3); CurrentArg.InitVal := S3; End; Result.ReturnType := TrimLeft(TrimRight(Result.ReturnType)); If (Result.ArgumentCount=0) And (Pos('_', Result.Name)<=0) And (IsPointer(Result.ReturnType)) Then Result.Name := 'Get'+Result.Name; End; Procedure SteamDeclarations.LoadRegion(Var Lines:TERRAString); Var Tag:TERRAString; S, RegionName:TERRAString; I,J,K:Integer; Func:FunctionDecl; CurrentRegion:RegionDecl; Begin I := Pos(CrLf, Lines); J := Pos(' ', Lines); If (J>0) And ((J<I) Or (I<=0)) Then I := J; RegionName := Copy(Lines, 1, Pred(I)); Lines := Copy(Lines, Succ(I), MaxInt); Tag := '#endregion'; I := Pos(Tag, Lines); S := Copy(Lines, 1, Pred(I)); Lines := Copy(Lines, I + Length(Tag), MaxInt); CurrentRegion := Self.AddRegion(RegionName); Repeat Func := ReadNextDecl(S); If Func = Nil Then Break Else CurrentRegion.AddFunction(Func); Until False; End; Function SteamDeclarations.AddRegion(const Name: TERRAString):RegionDecl; Begin Result := RegionDecl.Create(Name); Inc(RegionCount); SetLength(Regions, RegionCount); Regions[Pred(RegionCount)] := Result; End; Function SteamDeclarations.AddEnum(const Name: TERRAString): EnumDecl; Begin Result := EnumDecl.Create(Name); Inc(EnumCount); SetLength(Enums, EnumCount); Enums[Pred(EnumCount)] := Result; End; { StructDecl } Function StructDecl.AddField: StructFieldDecl; Begin Result := StructFieldDecl.Create(); Inc(FieldCount); SetLength(Fields, FieldCount); Fields[Pred(FieldCount)] := Result End; Constructor StructDecl.Create(const Name: TERRAString); Begin Self.Name := Name; Self.FieldCount := 0; End; { FunctionDecl } Function FunctionDecl.AddArgument:FunctionArgumentDecl; Begin Result := FunctionArgumentDecl.Create(); Inc(ArgumentCount); SetLength(Arguments, ArgumentCount); Arguments[Pred(ArgumentCount)] := Result; End; { RegionDecl } Constructor RegionDecl.Create(const Name: TERRAString); Begin Self.Name := Name; Self.FunctionCount := 0; End; Procedure RegionDecl.AddFunction(Func: FunctionDecl); Begin Inc(FunctionCount); SetLength(Functions, FunctionCount); Functions[Pred(FunctionCount)] := Func; End; { EnumDecl } Constructor EnumDecl.Create(const Name: TERRAString); Begin Self.Name := Name; Self.DeclCount := 0; End; Function EnumDecl.AddDecl: EnumFieldDecl; Begin Result := EnumFieldDecl.Create(); Inc(DeclCount); SetLength(Decls, DeclCount); Decls[Pred(DeclCount)] := Result; End; End.
{*******************************************************} { } { TFacturaElectronica } { } { Copyright (C) 2017 Bambu Code SA de CV } { } {*******************************************************} unit Facturacion.GeneradorSello; interface uses Facturacion.Comprobante, Facturacion.OpenSSL; type /// <summary> /// Instancia base encargada de generar el sello del comprobante /// independientemente de la versión. /// </summary> IGeneradorSello = Interface ['{28111CB2-59C9-4D2C-89F9-09E3CD447668}'] /// <summary> /// Instancia de OpenSSL usada para la encripción. /// </summary> procedure Configurar(const aOpenSSL: IOpenSSL); /// <summary> /// Se encarga de generar el respectivo sello según la encripción de la /// versión implementada /// </summary> /// <param name="aCadenaOriginal"> /// Cadena Original del CFDI previamente generada /// </param> function GenerarSelloDeFactura(const aCadenaOriginal: TCadenaUTF8): TCadenaUTF8; End; implementation end.
unit Helper.DUnitAssert; interface uses System.SysUtils, System.Classes, System.Math, DUnitX.TestFramework; type TAssertHelper = class helper for Assert class procedure AreMemosEqual(const expectedStrings: string; const actualStrings: string); end; implementation function FindDiffrence(const s1: string; const s2: string): integer; var j: integer; begin if s1 = s2 then Exit(0); for j := 1 to Min(s1.Length, s2.Length) do if s1[j] <> s2[j] then Exit(j); Result := Min(s1.Length, s2.Length); end; class procedure TAssertHelper.AreMemosEqual(const expectedStrings: string; const actualStrings: string); var slActual: TStringList; slExpected: TStringList; i: integer; aPos: integer; begin slActual := TStringList.Create; slExpected := TStringList.Create; try slActual.Text := actualStrings; slExpected.Text := expectedStrings; Assert.AreEqual(slExpected.Count, slActual.Count, Format('(diffrent number of lines)', [slExpected.Count, slActual.Count])); for i := 0 to slExpected.Count - 1 do if slExpected[i] <> slActual[i] then begin aPos := FindDiffrence(slExpected[i], slActual[i]); Assert.Fail (Format('in line: %d at pos: %d, expected |%s| is not equal to actual |%s|', [i + 1, aPos, slExpected[i], slActual[i]])); end; finally slActual.Free; slExpected.Free; end; end; end.
unit DialogUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Menus, Dialogs, ELDsgnr, ComCtrls, TypInfo, TypesUnit, FreeBasicRTTI; type TDialog = class(TForm) ELDesigner: TELDesigner; procedure FormShow(Sender: TObject); procedure ELDesignerChangeSelection(Sender: TObject); procedure ELDesignerControlHint(Sender: TObject; AControl: TControl; var AHint: String); procedure ELDesignerControlInserted(Sender: TObject); procedure ELDesignerControlInserting(Sender: TObject; var AControlClass: TControlClass); procedure ELDesignerModified(Sender: TObject); procedure ELDesignerKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ELDesignerDesignFormClose(Sender: TObject; var Action: TCloseAction); procedure FormResize(Sender: TObject); procedure FormCanResize(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean); private { Private declarations } fTyp:TType; fNode:TTreeNode; fMenuItem, fDropdownMenu:TMenuItem; fPage:TTabSheet; fNameChanged:TNotifyEvent; procedure SetPage(v:TTabSheet); procedure SetDropDownMenu(v:TMenuItem); procedure SetTyp(v:TType); protected procedure MenuItemClick(Sender:TObject); procedure SetName(const v:TComponentName);override; procedure WMMoved(var m:TWMMove);message wm_move; procedure WMActivate(var m:TWMActivate);message wm_activate; public { Public declarations } AssignedItems,AssignedEvents:TStrings; Sheet:TTabSheet; constructor Create(AOwner:TComponent); override; destructor Destroy; override; procedure BuildMenu; procedure ActivateDialog; procedure ReadPage; procedure DeleteObjects; procedure Comment(C:TControl); procedure UnComment(C:TControl); property Typ:TType read ftyp write SetTyp; property Page:TTabSheet read fPage write SetPage; property Node:TTreeNode read fNode write fNode; property MenuItem:TMenuItem read fMenuItem; property DropdownMenu:TMenuItem read fDropdownMenu write SetDropDownMenu; property OnNameChanged:TNotifyEvent read fNameChanged write fNameChanged; end; var Dialog: TDialog; Loked,DialogsList:TStringList; CanUpdate:boolean; implementation {$R *.dfm} uses PageSheetUnit, MainUnit, ObjectsTreeUnit, ScannerUnit, ContainerUnit, LauncherUnit, InspectorUnit, MenuEditorUnit; constructor TDialog.Create(AOwner:TComponent); begin inherited; AssignedItems:=TStringList.Create; AssignedEvents:=TStringList.Create; fTyp:=TType.create; fTyp.Extends:=Launcher.Lib.MainTypeName; if fTyp.Extends='' then fTyp.Extends:='QForm'; fTyp.ExtendsType:=Launcher.TypeExists(fTyp.Extends); fTyp.Hosted:=NamesList.AddName(fTyp.Extends); ActiveDialog:=Self; ActiveObject:=ActiveDialog; fMenuItem:=TMenuItem.Create(Self); fMenuItem.RadioItem:=true; fMenuItem.AutoCheck:=true; fMenuItem.OnClick:=MenuItemClick; fMenuItem.Tag:=integer(self); try Name:=''; except end; oldName:=Name; Inspector.Properties.Designer:=ELDesigner; RTTIGetProperties(Typ.Extends,Inspector.Filter,'public'); fMenuItem.Tag:=integer(Self); if DialogsList.IndexOfObject(self)=-1 then DialogsList.AddObject(Name,Self); if fPage<>nil then if TPageSheet(fPage).Scanner.TypExists(Typ.Hosted)<>nil then Typ:=TPageSheet(fPage).Scanner.TypExists(Typ.Hosted); ObjectsTree.Dialog:=self; end; destructor TDialog.Destroy; begin AssignedItems.Free; AssignedEvents.Free; fMenuItem.Free; if fPage<>nil then fPage:=nil; if DialogsList.IndexOfObject(self)>-1 then DialogsList.Delete(DialogsList.IndexOfObject(self)); if fNode<>nil then fNode.Free; if fPage<>nil then TPageSheet(fPage).Dialog:=nil; if ActiveObject=Self then ActiveObject:=nil; if ActiveDialog=Self then ActiveDialog:=nil; inherited; end; procedure TDialog.WMActivate(var m:TWMActivate); begin inherited; if m.ActiveWindow=Handle then ActivateDialog; end; procedure TDialog.SetPage(v:TTabSheet); begin fPage:=v; if v<>nil then v.Caption:=Name; end; procedure TDialog.SetName(const v:TComponentName); var SaveState:boolean; i:integer; begin inherited; if fPage<>nil then begin SaveState:=TPageSheet(fPage).Saved; fPage.Name:=Name; fPage.Caption:=Name; TPageSheet(fPage).Saved:=SaveState; if Sheet<>nil then Sheet.Caption:=Caption; end; if fMenuItem<>nil then fMenuItem.Caption:=Name; if fNode<>nil then fNode.Text:=Name; i:=DialogsList.IndexOfObject(self); if i>-1 then DialogsList[i]:=Name; Caption:=Name; if assigned(fNameChanged) then fNameChanged(self); end; procedure TDialog.SetDropDownMenu(v:TMenuItem); begin fDropDownMenu:=v; if v<>nil then begin fMenuItem.Caption:=Name; v.Add(fMenuItem); end end; procedure TDialog.SetTyp(v:TType); begin ftyp:=v; if v<>nil then begin Tag:=integer(ftyp); Typ.Hosted:=v.Hosted; Typ.Extends:=v.Extends; if width=0 then width:=v.cx; if height=0 then height:=v.cy; RTTIGetProperties(v.Hosted,inspector.Filter,'public'); end end; procedure TDialog.WMMoved(var m:TWMMove); begin inherited; if fPage<>nil then begin TPageSheet(fPage).Saved:=false; TPageSheet(fPage).UpdateControl(self); end end; procedure TDialog.BuildMenu; var i,v,e:integer; s,ident,kind:string; m:TMenu; mi:TMenuItem; L:TList; begin i:=0; L:=TList.Create; repeat s:=trim(Resources.Menus[i]); if pos(' ',s)>0 then begin ident:=copy(s,1,pos(' ',s)-1); kind:=trim(copy(s,pos(' ',s)+1,length(s))); end else begin ident:=s; kind:=''; end; if compareText(ident,'begin')=0 then L.Add(m); if compareText(ident,'end')=0 then L.Delete(L.Count-1); if (CompareText(kind,'menu')=0) or (CompareText(kind,'menuex')=0) then begin menu:=TMainMenu.Create(self); m:=menu; end; if (CompareText(ident,'popup')=0)then begin M:=TMenu(L[L.Count-1]); if m<>nil then begin mi:=TmenuItem.Create(m); mi.Caption:=StringReplace(kind,'"','',[rfreplaceall]); TMainMenu(m).Items.Add(mi); m:=TMenu(mi); end; end; if (CompareText(ident,'menuitem')=0)then begin M:=TMenu(L[L.Count-1]); if m<>nil then begin mi:=TmenuItem.Create(m); if compareText(kind,'separator')=0 then mi.Caption:='-' else begin mi.Caption:=StringReplace(trim(copy(kind,1,pos(',',kind)-1)),'"','',[rfreplaceall]); val(trim(copy(kind,pos(',',kind)+1,length(kind))),v,e); if e=0 then mi.MenuIndex:=v; end; if m.InheritsFrom(TMainMenu) then TMainMenu(m).Items.Add(mi) else TMenuItem(m).Add(mi); end end; inc(i); until i>Resources.Menus.Count-1;L.Free; Resources.Menus.Clear; end; procedure TDialog.ReadPage; var wc:TWndClassEx; s:TScanner; i,j,z,x,e,vl,lx,ly,lcx,lcy,addr:integer; t,cls:TType; v,f:TField; C:array of TContainer; tk,p,u,sv:string; L,Types{}:TStrings; pif:PPropInfo; function GetContainer(v:string):TContainer; var i:integer; begin result:=nil; for i:=low(c) to high(c) do if comparetext(c[i].Name,v)=0 then begin result:=c[i]; exit end end; begin Types:=nil; if fPage=nil then exit; s:=TPageSheet(fPage).Scanner; if s<>nil then s.Scan; if s.Types=nil then exit; if s.Types.Count>0 then for i:=0 to s.Types.Count-1 do begin t:=s.Typ[i]; if Typ.Hosted=t.Hosted then begin typ:=T; for j:=0 to typ.FieldCount-1 do begin v:=typ.Field[j]; x:=Launcher.Lib.Types.IndexOf(v.Return); if x=-1 then begin if Launcher.ReadUnregisterClass then begin x:=Launcher.Types.IndexOf(v.Return); Types:=Launcher.Types end end else Types:=Launcher.Lib.Types; if x>-1 then begin if Types<>nil then cls:=TType(Types.Objects[x]); f:=cls.FieldExists('constructor '+cls.Hosted); if f<>nil then begin SetLength(C,length(C)+1); C[High(C)]:=TContainer.Create(Self); C[High(C)].Parent:=self; C[High(C)].Typ:=cls; try C[High(C)].Hosted:=v.Return; if C[High(C)].Name<>'' then NamesList.RemoveName(C[High(C)].Name); C[High(C)].Name:=v.Hosted; except wc.cbSize:=sizeof(wc); if GetClassInfoEx(hinstance,PChar(C[High(C)].Hosted),wc)=false then begin messageDlg(format('The %s class not exists.'#10'Check on FreeBasic gui library, if that was registered.',[]),mtError,[mbok],0); exit; end else messageDlg('Internal error $3-TContainer: can''t create class.',mtError,[mbok],0); end; for x:=0 to TPageSheet(fPage).Frame.Edit.Lines.Count-1 do begin tk:=TPageSheet(fPage).Frame.Edit.Lines[x]; if pos(lowercase(v.Hosted),lowercase(tk))>0 then TPageSheet(fPage).Frame.Edit.Lines.Objects[x]:=C[High(C)]; if (pos(lowercase(C[High(C)].Name),lowercase(tk))>0) and{} (pos('.setbounds(',lowercase(tk))>0) then begin p:=trim(copy(tk,pos('(',tk)+1,pos(')',tk)-pos('(',tk)-1)); u:=''; for z:=1 to length(p) do if p[z]<>#32 then u:=u+p[z]; L:=TStringList.Create; L.Text:=stringreplace(u,',',#10,[rfreplaceall]); val(L[0],lx,e); val(L[1],ly,e); val(L[2],lcx,e); val(L[3],lcy,e); if e=0 then begin C[High(C)].Left:=lx; C[High(C)].Top:=ly; C[High(C)].Width:=lcx; C[High(C)].Height:=lcy; end; L.Free; end; if (pos(lowercase(C[High(C)].Name),lowercase(tk))>0) and (pos('=',lowercase(tk))>0) then begin u:=''; sv:=''; p:=trim(copy(tk,1,pos('=',tk)-1)); if pos('.',p)>0 then begin u:=trim(copy(p,pos('.',p)+1,length(p))); p:=trim(copy(p,1,pos('.',p)-1)); end; sv:=trim(copy(tk,pos('=',tk)+1,length(tk))); if comparetext(p,C[High(C)].Name)=0 then begin pif:=GetPropInfo(C[High(C)],u); if pif<>nil then begin if comparetext(u,'parent')=0 then begin if comparetext(sv,'this')=0 then C[High(C)].Parent:=self else C[High(C)].Parent:=TWinControl(FindComponent(sv)); end else if comparetext(u,'align')=0 then begin val(sv,vl,e); if e=0 then SetPropValue(C[High(C)],u,TAlign(strtoint(sv))) else if GetPropInfo(C[High(C)],u)<>nil then try typinfo.SetEnumProp(C[High(C)],u,sv); except messageDlg(format('No such kind , wrong property %s.',[u]),mtError,[mbok],0); end end else if comparetext(u,'canvas.color')=0 then begin SetPropValue(C[High(C)],'color',StringToColor(sv){integer()}); end else if comparetext(u,'canvas.textcolor')=0 then begin addr:=GetPropValue(C[High(C)],'font'); if addr>0 then TFont(Addr).Color:=StringToColor(sv); end; end; end; end; end; end; end; end; end; end; for i:=0 to TPageSheet(fPage).Frame.Edit.Lines.Count-1 do begin tk:=TPageSheet(fPage).Frame.Edit.Lines[i]; if pos('.',tk)>0 then begin tk:=trim(copy(tk,1,pos('.',tk)-1)); TPageSheet(fpage).Frame.Edit.Lines.Objects[i]:=GetContainer(tk); end end ; {} for i:=0 to TPageSheet(fPage).Frame.Edit.Lines.Count-1 do begin tk:=TPageSheet(fPage).Frame.Edit.Lines[i]; for x:=low(C) to high(C) do begin if (pos(lowercase(c[x].Name),lowercase(tk))>0) and (pos('setbounds',lowercase(tk))>0) then begin u:=trim(copy(tk,pos('(',tk)+1,pos(')',tk)-pos('(',tk)-1)); p:=''; j:=0;lx:=0;ly:=0;lcx:=0;lcy:=0; for z:=1 to length(u) do begin p:=p+u[z]; if (u[z]=',') or (z=length(u)) then begin if z<length(u) then p:=trim(copy(p,1,length(p)-1)); inc(j); val(p,vl,e); if (j=1) and (e=0) then lx:=vl; if (j=2) and (e=0) then ly:=vl; if (j=3) and (e=0) then lcx:=vl; if (j=4) and (e=0) then lcy:=vl; if j=4 then begin c[x].Left:=lx; c[x].Top:=ly; c[x].Width:=lcx; c[x].Height:=lcy; end; p:=''; end end end; if (pos('this.',lowercase(tk))>0) and (pos('setbounds',lowercase(tk))>0) then begin u:=trim(copy(tk,pos('(',tk)+1,pos(')',tk)-pos('(',tk)-1)); p:=''; j:=0; lx:=0;ly:=0;lcx:=0;lcy:=0; for z:=1 to length(u) do begin p:=p+u[z]; if (u[z]=',') or (z=length(u)) then begin if z<length(u) then p:=trim(copy(p,1,length(p)-1)); inc(j); val(p,vl,e); if (j=1) and (e=0) then lx:=vl; if (j=2) and (e=0) then ly:=vl; if (j=3) and (e=0) then lcx:=vl; if (j=4) and (e=0) then lcy:=vl; if j=4 then begin Left:=lx; Top:=ly; Width:=lcx; Height:=lcy; end; p:=''; end end end; end ; end; Inspector.Dialog:=self; end; procedure TDialog.MenuItemClick(Sender:TObject); begin if not IsWindowVisible(Handle) then ShowWindow(Handle,sw_show); BringToFront; end; procedure TDialog.ActivateDialog; begin ObjectsTree.AddObject(Self); Inspector.Dialog:=self; if typ<>nil then Inspector.ReadEvents(Typ); {} Main.UpdateToolBars; ActiveDialog:=self; ActiveObject:=ActiveDialog end; procedure TDialog.FormShow(Sender: TObject); begin ELDesigner.DesignControl:=self; ELDesigner.Active:=true end; procedure TDialog.ELDesignerChangeSelection(Sender: TObject); var i,j:integer; T:TType; L:TStrings; begin L:=nil; T:=nil; Inspector.Properties.Clear; if ELDesigner.SelectedControls.Count=1 then oldName:=ELDesigner.SelectedControls.DefaultControl.Name else oldName:=''; for i:=0 to ELDesigner.SelectedControls.Count-1 do begin if ELDesigner.SelectedControls.Items[i].InheritsFrom(TDialog) then L:=TDialog(ELDesigner.SelectedControls.Items[i]).AssignedItems else if ELDesigner.SelectedControls.Items[i].InheritsFrom(TContainer) then L:=TContainer(ELDesigner.SelectedControls.Items[i]).AssignedItems; Inspector.Properties.Add(ELDesigner.SelectedControls.Items[i]); Inspector.ObjectsBox.ItemIndex:=Inspector.ObjectsBox.Items.IndexOfObject(ELDesigner.SelectedControls.Items[i]); ObjectsTree.TreeView.Selected:=ObjectsTree.Find(ELDesigner.SelectedControls.Items[i]); ELDesigner.SelectedControls.Items[i].Refresh; if ELDesigner.SelectedControls.Items[i].InheritsFrom(TDialog) then T:=TDialog(ELDesigner.SelectedControls.Items[i]).Typ else if ELDesigner.SelectedControls.Items[i].InheritsFrom(TContainer) then T:=TContainer(ELDesigner.SelectedControls.Items[i]).Typ; if t<>nil then if T<>nil then begin Inspector.ReadEvents(T); for j:=0 to Inspector.ListView.Items.Count-1 do begin if L.IndexOf(Inspector.ListView.Items[j].Caption)<>-1 then ; end {} end end; end; procedure TDialog.ELDesignerControlHint(Sender: TObject; AControl: TControl; var AHint: String); begin if AControl.InheritsFrom(TContainer) then AHint:=Format('Origin: Left: %d, Top: %d'#10'Size: Width: %d, Height: %d'#10'Name: %s, ClassName: %s'#10'Module: %s',[Acontrol.Left,AControl.Top,AControl.Width,AControl.Height,AControl.Name,TContainer(AControl).Hosted,GetModuleName(hinstance)]) end; procedure TDialog.ELDesignerControlInserted(Sender: TObject); begin try TContainer(ELDesigner.SelectedControls.DefaultControl).Typ:=Launcher.SelType; if Launcher.SelType.Hosted='' then TContainer(ELDesigner.SelectedControls.DefaultControl).Hosted:=Launcher.SelClass; Launcher.ResetPalette; CanUpdate:=false; if fPage<>nil then TPageSheet(fPage).InsertControl(ELDesigner.SelectedControls.DefaultControl); ObjectsTree.UpdateDialog; Inspector.ReadObject(ELDesigner.SelectedControls.DefaultControl); Inspector.UpdateItems; oldName:=ELDesigner.SelectedControls.DefaultControl.Name; except Launcher.ResetPalette end; if ELDesigner.SelectedControls.Count>0 then ELDesigner.SelectedControls.DefaultControl.Invalidate; ELDesigner.DesignControl.Invalidate; if fPage<>nil then begin ActiveEditor:=TPageSheet(fPage); TPageSheet(fPage).Scanner.Execute; end end; procedure TDialog.ELDesignerControlInserting(Sender: TObject; var AControlClass: TControlClass); begin if Launcher.SelType<>nil then AControlClass:=TContainer else AControlClass:=nil; end; procedure TDialog.ELDesignerModified(Sender: TObject); var i:integer; begin Inspector.ReadObjects(self); Inspector.UpdateItems; if Page<>nil then begin for i:=0 to ELDesigner.SelectedControls.Count-1 do with TPageSheet(Page) do begin UpdateControl(ELDesigner.SelectedControls.Items[i]); end; TPageSheet(fPage).Saved:=false; end end; procedure TDialog.DeleteObjects; var i:integer; begin if fPage<>nil then begin for i:=ELDesigner.SelectedControls.Count-1 downto 0 do TPageSheet(fPage).DeleteControl(ELDesigner.SelectedControls.Items[i]); TPageSheet(fPage).Scanner.Execute; end ; ELDesigner.DeleteSelectedControls; end; procedure TDialog.ELDesignerKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var i:integer; begin if ssCtrl in shift then if key=ord('M') then begin MenuEditorDlg.EditMenu:=Menu; Menu:=nil; MenuEditorDlg.Menu:=MenuEditorDlg.EditMenu; MenuEditorDlg.Show end; if key=vk_delete then begin if fPage<>nil then begin for i:=ELDesigner.SelectedControls.Count-1 downto 0 do begin TPageSheet(fPage).DeleteControl(ELDesigner.SelectedControls.Items[i]); ObjectsTree.DeleteObject(ELDesigner.SelectedControls.Items[i]); end; TPageSheet(fPage).Scanner.Execute; end end; end; procedure TDialog.Comment(C:TControl); begin if C=nil then exit; if ELDesigner.SelectedControls.IndexOf(C)>-1 then begin ELDesigner.LockControl(C,[lmNoReSize]+[lmNoMove]); Update; Loked.AddObject(C.Name,C) end end; procedure TDialog.UnComment(C:TControl); var i:integer; begin if C=nil then exit; if ELDesigner.SelectedControls.IndexOf(C)>-1 then begin ELDesigner.LockControl(C,[]); Update ; i:=Loked.IndexOfObject(C); if i>-1 then Loked.Delete(i); end end; procedure TDialog.ELDesignerDesignFormClose(Sender: TObject; var Action: TCloseAction); begin Action:=caHide; end; procedure TDialog.FormResize(Sender: TObject); begin if fPage<>nil then begin TPageSheet(fPage).Saved:=false; TPageSheet(fPage).UpdateControl(self); end end; procedure TDialog.FormCanResize(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean); begin if Visible then Resize:=true else Resize:=false; end; initialization Loked:=TStringList.Create; DialogsList:=TStringList.Create; DialogsList.OnChange:=Main.DialogsListChange; finalization DialogsList.Free; Loked.Free; end.
{***************************************************************************} { } { DUnitX } { } { Copyright (C) 2015 Vincent Parrett & Contributors } { } { vincent@finalbuilder.com } { http://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DUnitX.StackTrace.JCL; interface {$I DUnitX.inc} uses {$IFDEF USE_NS} System.SysUtils, System.Classes, {$ELSE} SysUtils, Classes, {$ENDIF} {$IFDEF USE_JCL} JclDebug, {$ENDIF} DUnitX.TestFramework; type TJCLStackTraceProvider = class(TInterfacedObject,IStacktraceProvider) protected function GetStackTrace(const ex: Exception; const exAddressAddress: Pointer): string; function PointerToLocationInfo(const Addrs: Pointer): string; function PointerToAddressInfo(Addrs: Pointer): string; end; implementation uses DUnitX.IoC; { TJCLStackTraceProvider } function TJCLStackTraceProvider.GetStackTrace(const ex: Exception; const exAddressAddress: Pointer): string; {$IFDEF USE_JCL} var traceList: TStrings; {$ENDIF} begin result := ''; {$IFDEF USE_JCL} traceList := TStringList.Create; try JclDebug.JclLastExceptStackListToStrings(traceList, true); Result := traceList.Text; finally traceList.Free; end; {$ENDIF} end; function TJCLStackTraceProvider.PointerToAddressInfo(Addrs: Pointer): string; {$IFDEF USE_JCL} var _file, _module, _proc: string; _line: integer; {$ENDIF} begin Result := ''; {$IFDEF USE_JCL} JclDebug.MapOfAddr(Addrs, _file, _module, _proc, _line); Result := Format('%s$%p', [_proc, Addrs]); {$ENDIF} end; //Borrowed from DUnit. function TJCLStackTraceProvider.PointerToLocationInfo(const Addrs: Pointer): string; {$IFDEF USE_JCL} var _file, _module, _proc: string; _line: integer; {$ENDIF} begin Result := ''; {$IFDEF USE_JCL} JclDebug.MapOfAddr(Addrs, _file, _module, _proc, _line); if _file <> '' then Result := Format('%s:%d', [_file, _line]) else Result := _module; {$ENDIF} end; initialization {$IFDEF USE_JCL} {$IFDEF DELPHI_XE_UP} TDUnitXIoC.DefaultContainer.RegisterType<IStacktraceProvider,TJCLStackTraceProvider>(true); {$ELSE} //D2010 bug prevents using above method. TDUnitXIoC.DefaultContainer.RegisterType<IStacktraceProvider>(true, function : IStacktraceProvider begin result := TJCLStackTraceProvider.Create; end ); {$ENDIF} {$ENDIF} end.
unit fmBaseBuscar; interface uses Windows, SysUtils, Classes, Graphics, fmBase, StdCtrls, Grids, DBGrids, DB, JvDBUltimGrid, dmBaseBuscar, Controls, JvExDBGrids, JvDBGrid; type TfBaseBuscar = class(TfBase) dsValores: TDataSource; GridValores: TJvDBUltimGrid; eFiltrada: TEdit; procedure eBusquedaKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormCreate(Sender: TObject); procedure eFiltradaChange(Sender: TObject); procedure GridValoresDrawDataCell(Sender: TObject; const Rect: TRect; Field: TField; State: TGridDrawState); procedure GridValoresCellClick(Column: TColumn); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private BaseBuscar: TBaseBuscar; FDataSet: TDataSet; FieldOIDMercado: TIntegerField; FCloseOnSelect: boolean; Selected: boolean; protected function GetData: TBaseBuscar; virtual; function GetOID_VALOR: integer; virtual; public procedure AddChar(const c: char); property OID_VALOR: integer read GetOID_VALOR; property CloseOnSelect: boolean read FCloseOnSelect write FCloseOnSelect; end; const VALOR_NO_SELECTED: integer = Low(Integer); implementation uses dmDataComun, UtilGrid; {$R *.dfm} procedure TfBaseBuscar.GridValoresCellClick(Column: TColumn); begin inherited; Selected := true; if FCloseOnSelect then Close; end; procedure TfBaseBuscar.GridValoresDrawDataCell(Sender: TObject; const Rect: TRect; Field: TField; State: TGridDrawState); var valor, resultado: string; desde, num, i: integer; DefColor: TColor; gCanvas: TCanvas; procedure NormalText; begin gCanvas.Font.Style := []; if gdSelected in State then gCanvas.Font.Color := clWhite else gCanvas.Font.Color := clBlack; end; begin if not Field.IsNull then begin gCanvas := GridValores.Canvas; gCanvas.FillRect(Rect); valor := Field.AsString; if field.Tag = TAG_BANDERA then begin DataComun.DibujarBandera(FieldOIDMercado.Value, gCanvas, Rect.Left + 2, Rect.Top + 2, gCanvas.Brush.Color); NormalText; gCanvas.TextOut(Rect.Left + 23, Rect.Top + 2, valor); end else begin if Field.Tag = TAG_BUSQUEDA then begin if gdSelected in State then gCanvas.Font.Color := clWhite else gCanvas.Font.Color := clBlack; desde := Pos(UpperCase(eFiltrada.Text), UpperCase(valor)); num := length(eFiltrada.Text); if desde >= 1 then begin resultado := Copy(valor, 1, desde - 1); gCanvas.TextOut(Rect.Left + 2, Rect.Top + 2, resultado); i := gCanvas.TextWidth(resultado); resultado := Copy(valor, desde, num); DefColor := gCanvas.Brush.Color; gCanvas.Brush.Color := $008000FF; gCanvas.Font.Style := [fsBold]; gCanvas.Font.Color := clWhite; gCanvas.TextOut(Rect.Left + i + 2, Rect.Top + 2, resultado); gCanvas.Brush.Color := DefColor; if num < length(valor) then begin i := i + gCanvas.TextWidth(resultado); resultado := Copy(valor, desde + num, length(valor)); NormalText; gCanvas.TextOut(Rect.Left + i + 2, Rect.Top + 2, resultado); end; end else begin NormalText; gCanvas.TextOut(Rect.Left + 2, Rect.Top + 2, valor); end; end else begin NormalText; gCanvas.TextOut(Rect.Left + 2, Rect.Top + 2, valor); end; end; end; end; procedure TfBaseBuscar.AddChar(const c: char); begin eFiltrada.Text := eFiltrada.Text + c; eFiltrada.SelStart := length(eFiltrada.Text); eFiltrada.SelLength := 0; end; procedure TfBaseBuscar.eBusquedaKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; case Key of VK_DOWN: begin GridValores.SetFocus; FDataSet.Next; end; VK_UP: begin GridValores.SetFocus; FDataSet.Prior; end; VK_PRIOR: begin GridValores.SetFocus; FDataSet.MoveBy(-16); end; VK_NEXT: begin GridValores.SetFocus; FDataSet.MoveBy(16); end; end; end; procedure TfBaseBuscar.eFiltradaChange(Sender: TObject); begin inherited; BaseBuscar.BuscarFiltrado(eFiltrada.Text); end; procedure TfBaseBuscar.FormCreate(Sender: TObject); begin inherited; FCloseOnSelect := true; BaseBuscar := GetData; dsValores.DataSet := BaseBuscar.Valores; FDataSet := dsValores.DataSet; FieldOIDMercado := BaseBuscar.ValoresOID_MERCADO; TUtilGridSort.Create(GridValores); ActiveControl := eFiltrada end; procedure TfBaseBuscar.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = VK_RETURN then begin Selected := true; if FCloseOnSelect then Close; end; end; function TfBaseBuscar.GetData: TBaseBuscar; begin result := TBaseBuscar.Create(Self); end; function TfBaseBuscar.GetOID_VALOR: integer; begin if Selected then result := FDataSet.FieldByName('OID_VALOR').AsInteger else result := VALOR_NO_SELECTED; end; end.
PROGRAM ex_disable_screensaver; (* Copyright (c) 2012-2019 Guillermo Martínez J. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. *) {$IFDEF FPC} {$IFDEF WINDOWS}{$R 'manifest.rc'}{$ENDIF} {$ENDIF} USES Common, allegro5, al5font; VAR Display: ALLEGRO_DISPLAYptr; Font: ALLEGRO_FONTptr; Events: ALLEGRO_EVENT_QUEUEptr; Event: ALLEGRO_EVENT; Done, Active, FullScreen: BOOLEAN; BEGIN Done := FALSE; Active := TRUE; FullScreen := FALSE; IF ParamCount = 2 THEN IF ParamStr (1) = '-fullscreen' THEN FullScreen := TRUE; IF NOT al_init THEN AbortExample ('Could not init Allegro.'); al_install_keyboard; al_init_font_addon; IF FullScreen THEN al_set_new_display_flags (ALLEGRO_GENERATE_EXPOSE_EVENTS OR ALLEGRO_FULLSCREEN) ELSE al_set_new_display_flags (ALLEGRO_GENERATE_EXPOSE_EVENTS); Display := al_create_display (640, 480); IF Display = NIL THEN AbortExample ('Could not create display.'); Font := al_create_builtin_font; IF Font = NIL THEN AbortExample ('Error creating builtin font.'); Events := al_create_event_queue; al_register_event_source (Events, al_get_keyboard_event_source); { For expose events } al_register_event_source (Events, al_get_display_event_source (Display)); REPEAT al_clear_to_color (al_map_rgb (0, 0, 0)); IF Active THEN al_draw_text (Font, al_map_rgb_f (1, 1, 1), 0, 0, 0, 'Screen saver: Normal') ELSE al_draw_text (Font, al_map_rgb_f (1, 1, 1), 0, 0, 0, 'Screen saver: Inhibited'); al_flip_display; al_wait_for_event (Events, @Event); IF Event.ftype = ALLEGRO_EVENT_KEY_DOWN THEN CASE Event.keyboard.keycode OF ALLEGRO_KEY_ESCAPE: Done := TRUE; ALLEGRO_KEY_SPACE: IF al_inhibit_screensaver (Active) THEN Active := NOT Active; END UNTIL Done; al_destroy_font (Font); al_destroy_event_queue (Events) END.
unit IDEDlgs; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExptIntf,TypUtils,ExtDialogs,ToolIntf; procedure InstallDlgs; procedure UnInstallDlgs; function isInstalled : boolean; procedure TestDlg; //procedure InstallEditorDlg(Editor : TCustomForm); implementation const MainFormClassName = 'TAppBuilder'; OpenDialogName = 'OpenFileDialog'; SaveDialogName = 'SaveFileDialog'; EditorOpenDialogName = 'OpenFileDlg'; EditorSaveDialogName = 'SaveFileDlg'; EditorClassName = 'TEditWindow'; var MainForm : TCustomForm; OldOpenDialog : TOpenDialog; OldSaveDialog : TSaveDialog; NewOpenDialog : TOpenDialogEx; NewSaveDialog : TOpenDialogEx; (*OldEditorOpenDialog : TOpenDialog; OldEditorSaveDialog : TSaveDialog;*) type TObjectPointer = ^TObject; (*TDebugDialog = class public class procedure DoShow(sender : TObject); end; *) function FindMainForm : TCustomForm; var i : integer; begin // Find Main Form result := nil; for i:=0 to Screen.FormCount-1 do if Screen.Forms[i].ClassNameIs(MainFormClassName) then begin result := Screen.Forms[i]; break; end; end; (* procedure CheckEditorDlg; var i : integer; Editor : TCustomForm; begin showMessage('Check'); for i:=0 to Screen.FormCount-1 do if Screen.Forms[i].ClassNameIs(EditorClassName) then begin Editor := Screen.Forms[i]; showMessage('Find Editor!'); InstallEditorDlg(Editor); end; end; *) procedure InstallDlgs; var Address1,Address2 : TObjectPointer; begin UninstallDlgs; OldOpenDialog:=nil; OldSaveDialog:=nil; MainForm := nil; MainForm := FindMainForm; if MainForm<>nil then begin {OldOpenDialog:=TOpenDialog(GetClassProperty(MainForm,OpenDialogName)); OldSaveDialog:=TSaveDialog(GetClassProperty(MainForm,SaveDialogName));} Address1 := TObjectPointer(MainForm.FieldAddress(OpenDialogName)); Address2 := TObjectPointer(MainForm.FieldAddress(SaveDialogName)); //if (OldOpenDialog<>nil) and (OldSaveDialog<>nil) then if (Address1<>nil) and (Address2<>nil) then begin OldOpenDialog:=TOpenDialog(Address1^); OldSaveDialog:=TSaveDialog(Address2^); NewOpenDialog := TOpenDialogEx.Create(nil); NewSaveDialog := TOpenDialogEx.Create(nil); with NewOpenDialog do begin NewStyle := true; IsSaveDialog := false; Name := OpenDialogName; Options := OldOpenDialog.Options; DefaultExt:=OldOpenDialog.DefaultExt; Title := OldOpenDialog.Title; FileName := OldOpenDialog.FileName; FileEditStyle := OldOpenDialog.FileEditStyle; Filter := OldOpenDialog.Filter; FilterIndex := OldOpenDialog.FilterIndex; end; with NewSaveDialog do begin NewStyle := true; IsSaveDialog := true; Name := SaveDialogName; Options := OldSaveDialog.Options; DefaultExt:=OldSaveDialog.DefaultExt; Title := OldSaveDialog.Title; FileName := OldSaveDialog.FileName; FileEditStyle := OldSaveDialog.FileEditStyle; Filter := OldSaveDialog.Filter; FilterIndex := OldSaveDialog.FilterIndex; end; //SetClassProperty(MainForm,OpenDialogName,NewOpenDialog); //SetClassProperty(MainForm,SaveDialogName,NewSaveDialog); Address1^ := NewOpenDialog; Address2^ := NewSaveDialog; //ShowMessage('Installed!'); //OldOpenDialog.Options := OldOpenDialog.Options-[ofShowHelp]; //OldSaveDialog.Options := OldSaveDialog.Options-[ofShowHelp]; (*CheckEditorDlg;*) end; end; end; procedure UnInstallDlgs; var Address1,Address2 : TObjectPointer; begin if isInstalled then if MainForm=FindMainForm then begin Address1 := TObjectPointer(MainForm.FieldAddress(OpenDialogName)); Address2 := TObjectPointer(MainForm.FieldAddress(SaveDialogName)); if (Address1<>nil) and (Address2<>nil) then begin Address1^ := OldOpenDialog; Address2^ := OldSaveDialog; NewOpenDialog.free; NewSaveDialog.free; //ShowMessage('UnInstalled!'); end; end; MainForm:=nil; OldOpenDialog:=nil; OldSaveDialog:=nil; end; function isInstalled : boolean; begin result := (MainForm<>nil) and (OldOpenDialog<>nil) and (OldSaveDialog<>nil); end; procedure TestDlg; begin if isInstalled then begin OldOpenDialog.Execute; OldSaveDialog.Execute; (*if OldEditorOpenDialog<>nil then begin OldEditorOpenDialog.Execute; OldEditorSaveDialog.Execute; end;*) end; end; (* type TFileOperationNotifier = class(TIAddInNotifier) public procedure FileNotification(NotifyCode: TFileNotification; const FileName: string; var Cancel: Boolean); override; stdcall; procedure EventNotification(NotifyCode: TEventNotification; var Cancel: Boolean); override; stdcall; end; var FileOperationNotifier : TFileOperationNotifier=nil; *) (* procedure InstallEditorDlg(Editor : TCustomForm); var Address1,Address2 : TObjectPointer; NewEditorSaveDialog : TOpenDialogEx; NewEditorOpenDialog : TOpenDialogEx; begin Address2 := TObjectPointer(Editor.FieldAddress(EditorSaveDialogName)); Address1 := TObjectPointer(Editor.FieldAddress(EditorOpenDialogName)); if (Address1<>nil) and (Address2<>nil) then begin //ShowMessage('Find Addr'); OldEditorOpenDialog:=TOpenDialog(Address1^); OldEditorSaveDialog:=TSaveDialog(Address2^); //if OldEditorSaveDialog is TOpenDialogEx then exit; if OldEditorSaveDialog.ClassNameIs('TOpenDialogEx') then begin ShowMessage('Has Installed'); exit; end; NewEditorOpenDialog := TOpenDialogEx.Create(nil); NewEditorSaveDialog := TOpenDialogEx.Create(nil); with NewEditorOpenDialog do begin NewStyle := true; IsSaveDialog := true; Name := EditorOpenDialogName; Options := OldEditorOpenDialog.Options; DefaultExt:=OldEditorOpenDialog.DefaultExt; Title := OldEditorOpenDialog.Title; FileName := OldEditorOpenDialog.FileName; FileEditStyle := OldEditorOpenDialog.FileEditStyle; Filter := OldEditorOpenDialog.Filter; FilterIndex := OldEditorOpenDialog.FilterIndex; end; with NewEditorSaveDialog do begin NewStyle := true; IsSaveDialog := true; Name := EditorSaveDialogName; Options := OldEditorSaveDialog.Options; DefaultExt:=OldEditorSaveDialog.DefaultExt; Title := OldEditorSaveDialog.Title; FileName := OldEditorSaveDialog.FileName; FileEditStyle := OldEditorSaveDialog.FileEditStyle; Filter := OldEditorSaveDialog.Filter; FilterIndex := OldEditorSaveDialog.FilterIndex; end; //ShowMessage('Create'); //OldEditorSaveDialog.FileEditStyle := fsComboBox; OldEditorOpenDialog.Options := OldEditorOpenDialog.Options-[ofShowHelp]; OldEditorSaveDialog.Options := OldEditorSaveDialog.Options-[ofShowHelp]; //OldEditorSaveDialog.free; //Address1^ := NewEditorSaveDialog; //NewEditorSaveDialog.Name := EditorSaveDialogName; //NewEditorSaveDialog.Name := EditorOpenDialogName; ShowMessage('Editor Dialog Installed!'); end; end; *) { TFileOperationNotifier } (* procedure TFileOperationNotifier.EventNotification( NotifyCode: TEventNotification; var Cancel: Boolean); begin // end; procedure TFileOperationNotifier.FileNotification( NotifyCode: TFileNotification; const FileName: string; var Cancel: Boolean); begin if (NotifyCode=fnFileOpened) and isInstalled then CheckEditorDlg; end; { TDebugDialog } class procedure TDebugDialog.DoShow(sender: TObject); begin ShowMessage('OK'); end; *) initialization InstallDlgs; (*if ToolServices<>nil then begin FileOperationNotifier := TFileOperationNotifier.Create; ToolServices.AddNotifier(FileOperationNotifier); end;*) finalization (*if (ToolServices<>nil) and (FileOperationNotifier<>nil) then begin ToolServices.RemoveNotifier(FileOperationNotifier); FileOperationNotifier.free; end;*) UNInstallDlgs; end.
object Form3: TForm3 Left = 0 Top = 0 Width = 794 Height = 506 BorderIcons = [biSystemMenu] BorderStyle = bsSizeToolWin Caption = 'Camera View' Color = clBtnFace Constraints.MaxHeight = 508 Constraints.MaxWidth = 794 Constraints.MinHeight = 250 Constraints.MinWidth = 400 Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False OnClose = FormClose OnCreate = FormCreate PixelsPerInch = 96 TextHeight = 13 object VideoBox: TPaintBox Left = 146 Top = 0 Width = 640 Height = 480 Color = clCream ParentColor = False end object BtnCamIsAtZero: TSpeedButton Left = 8 Top = 228 Width = 129 Height = 25 Hint = 'Camera center is above workpiece zero; set offsets accordingly' Caption = 'Cam is at Part Zero' Font.Charset = ANSI_CHARSET Font.Color = 2925325 Font.Height = -12 Font.Name = 'Arial' Font.Style = [fsBold] ParentFont = False ParentShowHint = False ShowHint = True OnClick = BtnCamIsAtZeroClick end object Label1: TLabel Left = 280 Top = 224 Width = 5 Height = 19 Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -16 Font.Name = 'Tahoma' Font.Style = [fsBold] ParentFont = False end object BtnCamAtHilite: TSpeedButton Left = 8 Top = 260 Width = 129 Height = 25 Hint = 'Camera center is above hilited point; set offsets accordingly' Caption = 'Cam is at Hilite Point' Font.Charset = ANSI_CHARSET Font.Color = clFuchsia Font.Height = -12 Font.Name = 'Arial' Font.Style = [fsBold] ParentFont = False ParentShowHint = False ShowHint = True OnClick = BtnCamAtHiliteClick end object RadioGroupCam: TRadioGroup Left = 8 Top = 8 Width = 129 Height = 73 Hint = 'Spinde view camera control' Caption = 'Spindle Cam' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -12 Font.Name = 'MS Sans Serif' Font.Style = [] ItemIndex = 0 Items.Strings = ( 'Off' 'Crosshair') ParentFont = False TabOrder = 0 OnClick = RadioGroupCamClick end object TrackBar1: TTrackBar Left = 8 Top = 128 Width = 129 Height = 20 Hint = 'Crosshair circle diameter' Max = 100 Min = 1 Position = 10 TabOrder = 1 TabStop = False TickStyle = tsNone end object StaticText1: TStaticText Left = 76 Top = 98 Width = 29 Height = 17 Caption = 'Color' TabOrder = 2 end object StaticText6: TStaticText Left = 31 Top = 160 Width = 76 Height = 17 Caption = 'Circle Diameter' TabOrder = 3 end object OverlayColor: TPanel Left = 32 Top = 96 Width = 33 Height = 17 Hint = 'Crosshair overlay color' BevelWidth = 2 Color = clRed Ctl3D = True ParentBackground = False ParentCtl3D = False TabOrder = 4 OnClick = OverlayColorClick end object ColorDialog1: TColorDialog Left = 16 Top = 296 end end
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2013 Embarcadero Technologies, Inc. } { } {*******************************************************} unit Androidapi.JNI.Hardware; interface uses Androidapi.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.GraphicsContentViewText; type {Class forward declarations} JCamera_Face = interface;//android.hardware.Camera$Face JCamera_ErrorCallback = interface;//android.hardware.Camera$ErrorCallback JCamera_CameraInfo = interface;//android.hardware.Camera$CameraInfo JCamera_Size = interface;//android.hardware.Camera$Size JCamera_FaceDetectionListener = interface;//android.hardware.Camera$FaceDetectionListener JCamera_ShutterCallback = interface;//android.hardware.Camera$ShutterCallback JCamera_PreviewCallback = interface;//android.hardware.Camera$PreviewCallback JCamera = interface;//android.hardware.Camera JCamera_Parameters = interface;//android.hardware.Camera$Parameters JCamera_AutoFocusMoveCallback = interface;//android.hardware.Camera$AutoFocusMoveCallback JCamera_AutoFocusCallback = interface;//android.hardware.Camera$AutoFocusCallback JCamera_PictureCallback = interface;//android.hardware.Camera$PictureCallback JCamera_OnZoomChangeListener = interface;//android.hardware.Camera$OnZoomChangeListener JCamera_FaceClass = interface(JObjectClass) ['{3926BFB1-9866-403B-A24E-7FCB9251F1A5}'] {Methods} function init: JCamera_Face; cdecl; end; [JavaSignature('android/hardware/Camera$Face')] JCamera_Face = interface(JObject) ['{4FBCBB16-3A6B-493C-952F-55AC60C75DE9}'] {Property Methods} function _Getid: Integer; procedure _Setid(Value: Integer); function _GetleftEye: JPoint; procedure _SetleftEye(Value: JPoint); function _Getmouth: JPoint; procedure _Setmouth(Value: JPoint); function _Getrect: JRect; procedure _Setrect(Value: JRect); function _GetrightEye: JPoint; procedure _SetrightEye(Value: JPoint); function _Getscore: Integer; procedure _Setscore(Value: Integer); {Properties} property id: Integer read _Getid write _Setid; property leftEye: JPoint read _GetleftEye write _SetleftEye; property mouth: JPoint read _Getmouth write _Setmouth; property rect: JRect read _Getrect write _Setrect; property rightEye: JPoint read _GetrightEye write _SetrightEye; property score: Integer read _Getscore write _Setscore; end; TJCamera_Face = class(TJavaGenericImport<JCamera_FaceClass, JCamera_Face>) end; JCamera_ErrorCallbackClass = interface(IJavaClass) ['{5AAEF0D6-153A-481B-8A54-527D810352D2}'] end; [JavaSignature('android/hardware/Camera$ErrorCallback')] JCamera_ErrorCallback = interface(IJavaInstance) ['{45CC94C4-4AEC-43B6-861D-A7AC2392CB2D}'] {Methods} procedure onError(error: Integer; camera: JCamera); cdecl; end; TJCamera_ErrorCallback = class(TJavaGenericImport<JCamera_ErrorCallbackClass, JCamera_ErrorCallback>) end; JCamera_CameraInfoClass = interface(JObjectClass) ['{4D9A2405-77B3-4828-B7F5-AF756B98D6B5}'] {Property Methods} function _GetCAMERA_FACING_BACK: Integer; function _GetCAMERA_FACING_FRONT: Integer; {Methods} function init: JCamera_CameraInfo; cdecl; {Properties} property CAMERA_FACING_BACK: Integer read _GetCAMERA_FACING_BACK; property CAMERA_FACING_FRONT: Integer read _GetCAMERA_FACING_FRONT; end; [JavaSignature('android/hardware/Camera$CameraInfo')] JCamera_CameraInfo = interface(JObject) ['{D7A9C455-C629-40F6-BCAE-E20195C6069B}'] {Property Methods} function _GetcanDisableShutterSound: Boolean; procedure _SetcanDisableShutterSound(Value: Boolean); function _Getfacing: Integer; procedure _Setfacing(Value: Integer); function _Getorientation: Integer; procedure _Setorientation(Value: Integer); {Properties} property canDisableShutterSound: Boolean read _GetcanDisableShutterSound write _SetcanDisableShutterSound; property facing: Integer read _Getfacing write _Setfacing; property orientation: Integer read _Getorientation write _Setorientation; end; TJCamera_CameraInfo = class(TJavaGenericImport<JCamera_CameraInfoClass, JCamera_CameraInfo>) end; JCamera_SizeClass = interface(JObjectClass) ['{23FA6E4F-E2F1-4FDF-9892-A56C71EEA6D4}'] {Methods} function init(w: Integer; h: Integer): JCamera_Size; cdecl; end; [JavaSignature('android/hardware/Camera$Size')] JCamera_Size = interface(JObject) ['{2D2A15A6-C3ED-4B61-8276-214F497A766A}'] {Property Methods} function _Getheight: Integer; procedure _Setheight(Value: Integer); function _Getwidth: Integer; procedure _Setwidth(Value: Integer); {Methods} function equals(obj: JObject): Boolean; cdecl; function hashCode: Integer; cdecl; {Properties} property height: Integer read _Getheight write _Setheight; property width: Integer read _Getwidth write _Setwidth; end; TJCamera_Size = class(TJavaGenericImport<JCamera_SizeClass, JCamera_Size>) end; JCamera_FaceDetectionListenerClass = interface(IJavaClass) ['{2C26C033-6093-440C-8B6F-E0E8632CE495}'] end; [JavaSignature('android/hardware/Camera$FaceDetectionListener')] JCamera_FaceDetectionListener = interface(IJavaInstance) ['{F5A3CD35-3B25-41A8-9B69-6EC00C39A0BF}'] {Methods} procedure onFaceDetection(faces: TJavaObjectArray<JCamera_Face>; camera: JCamera); cdecl; end; TJCamera_FaceDetectionListener = class(TJavaGenericImport<JCamera_FaceDetectionListenerClass, JCamera_FaceDetectionListener>) end; JCamera_ShutterCallbackClass = interface(IJavaClass) ['{D658141F-9627-4E2E-8B23-CDF1814F02FB}'] end; [JavaSignature('android/hardware/Camera$ShutterCallback')] JCamera_ShutterCallback = interface(IJavaInstance) ['{50F23354-86CD-4B59-9CC8-E647BDF98EC2}'] {Methods} procedure onShutter; cdecl; end; TJCamera_ShutterCallback = class(TJavaGenericImport<JCamera_ShutterCallbackClass, JCamera_ShutterCallback>) end; JCamera_PreviewCallbackClass = interface(IJavaClass) ['{C6836D36-1914-4DB8-8458-D6AEC71A7257}'] end; [JavaSignature('android/hardware/Camera$PreviewCallback')] JCamera_PreviewCallback = interface(IJavaInstance) ['{6F2F0374-DCFF-43EC-B8BF-DB2F72574EBB}'] {Methods} procedure onPreviewFrame(data: TJavaArray<Byte>; camera: JCamera); cdecl; end; TJCamera_PreviewCallback = class(TJavaGenericImport<JCamera_PreviewCallbackClass, JCamera_PreviewCallback>) end; JCameraClass = interface(JObjectClass) ['{EC7FA230-96BA-4ED6-9328-CAC5F459C235}'] {Property Methods} function _GetACTION_NEW_PICTURE: JString; function _GetACTION_NEW_VIDEO: JString; function _GetCAMERA_ERROR_SERVER_DIED: Integer; function _GetCAMERA_ERROR_UNKNOWN: Integer; {Methods} procedure getCameraInfo(cameraId: Integer; cameraInfo: JCamera_CameraInfo); cdecl; function getNumberOfCameras: Integer; cdecl; function open(cameraId: Integer): JCamera; cdecl; overload; function open: JCamera; cdecl; overload; {Properties} property ACTION_NEW_PICTURE: JString read _GetACTION_NEW_PICTURE; property ACTION_NEW_VIDEO: JString read _GetACTION_NEW_VIDEO; property CAMERA_ERROR_SERVER_DIED: Integer read _GetCAMERA_ERROR_SERVER_DIED; property CAMERA_ERROR_UNKNOWN: Integer read _GetCAMERA_ERROR_UNKNOWN; end; [JavaSignature('android/hardware/Camera')] JCamera = interface(JObject) ['{40A86A47-3393-4E33-8884-C33107CD903B}'] {Methods} procedure addCallbackBuffer(callbackBuffer: TJavaArray<Byte>); cdecl; procedure autoFocus(cb: JCamera_AutoFocusCallback); cdecl; procedure cancelAutoFocus; cdecl; function enableShutterSound(enabled: Boolean): Boolean; cdecl; function getParameters: JCamera_Parameters; cdecl; procedure lock; cdecl; procedure reconnect; cdecl; procedure release; cdecl; procedure setAutoFocusMoveCallback(cb: JCamera_AutoFocusMoveCallback); cdecl; procedure setDisplayOrientation(degrees: Integer); cdecl; procedure setErrorCallback(cb: JCamera_ErrorCallback); cdecl; procedure setFaceDetectionListener(listener: JCamera_FaceDetectionListener); cdecl; procedure setOneShotPreviewCallback(cb: JCamera_PreviewCallback); cdecl; procedure setParameters(params: JCamera_Parameters); cdecl; procedure setPreviewCallback(cb: JCamera_PreviewCallback); cdecl; procedure setPreviewCallbackWithBuffer(cb: JCamera_PreviewCallback); cdecl; procedure setPreviewDisplay(holder: JSurfaceHolder); cdecl; procedure setPreviewTexture(surfaceTexture: JSurfaceTexture); cdecl; procedure setZoomChangeListener(listener: JCamera_OnZoomChangeListener); cdecl; procedure startFaceDetection; cdecl; procedure startPreview; cdecl; procedure startSmoothZoom(value: Integer); cdecl; procedure stopFaceDetection; cdecl; procedure stopPreview; cdecl; procedure stopSmoothZoom; cdecl; procedure takePicture(shutter: JCamera_ShutterCallback; raw: JCamera_PictureCallback; jpeg: JCamera_PictureCallback); cdecl; overload; procedure takePicture(shutter: JCamera_ShutterCallback; raw: JCamera_PictureCallback; postview: JCamera_PictureCallback; jpeg: JCamera_PictureCallback); cdecl; overload; procedure unlock; cdecl; end; TJCamera = class(TJavaGenericImport<JCameraClass, JCamera>) end; JCamera_ParametersClass = interface(JObjectClass) ['{519157BE-F3CB-41ED-90A0-239A67F07E7C}'] {Property Methods} function _GetANTIBANDING_50HZ: JString; function _GetANTIBANDING_60HZ: JString; function _GetANTIBANDING_AUTO: JString; function _GetANTIBANDING_OFF: JString; function _GetEFFECT_AQUA: JString; function _GetEFFECT_BLACKBOARD: JString; function _GetEFFECT_MONO: JString; function _GetEFFECT_NEGATIVE: JString; function _GetEFFECT_NONE: JString; function _GetEFFECT_POSTERIZE: JString; function _GetEFFECT_SEPIA: JString; function _GetEFFECT_SOLARIZE: JString; function _GetEFFECT_WHITEBOARD: JString; function _GetFLASH_MODE_AUTO: JString; function _GetFLASH_MODE_OFF: JString; function _GetFLASH_MODE_ON: JString; function _GetFLASH_MODE_RED_EYE: JString; function _GetFLASH_MODE_TORCH: JString; function _GetFOCUS_DISTANCE_FAR_INDEX: Integer; function _GetFOCUS_DISTANCE_NEAR_INDEX: Integer; function _GetFOCUS_DISTANCE_OPTIMAL_INDEX: Integer; function _GetFOCUS_MODE_AUTO: JString; function _GetFOCUS_MODE_CONTINUOUS_PICTURE: JString; function _GetFOCUS_MODE_CONTINUOUS_VIDEO: JString; function _GetFOCUS_MODE_EDOF: JString; function _GetFOCUS_MODE_FIXED: JString; function _GetFOCUS_MODE_INFINITY: JString; function _GetFOCUS_MODE_MACRO: JString; function _GetPREVIEW_FPS_MAX_INDEX: Integer; function _GetPREVIEW_FPS_MIN_INDEX: Integer; function _GetSCENE_MODE_ACTION: JString; function _GetSCENE_MODE_AUTO: JString; function _GetSCENE_MODE_BARCODE: JString; function _GetSCENE_MODE_BEACH: JString; function _GetSCENE_MODE_CANDLELIGHT: JString; function _GetSCENE_MODE_FIREWORKS: JString; function _GetSCENE_MODE_HDR: JString; function _GetSCENE_MODE_LANDSCAPE: JString; function _GetSCENE_MODE_NIGHT: JString; function _GetSCENE_MODE_NIGHT_PORTRAIT: JString; function _GetSCENE_MODE_PARTY: JString; function _GetSCENE_MODE_PORTRAIT: JString; function _GetSCENE_MODE_SNOW: JString; function _GetSCENE_MODE_SPORTS: JString; function _GetSCENE_MODE_STEADYPHOTO: JString; function _GetSCENE_MODE_SUNSET: JString; function _GetSCENE_MODE_THEATRE: JString; function _GetWHITE_BALANCE_AUTO: JString; function _GetWHITE_BALANCE_CLOUDY_DAYLIGHT: JString; function _GetWHITE_BALANCE_DAYLIGHT: JString; function _GetWHITE_BALANCE_FLUORESCENT: JString; function _GetWHITE_BALANCE_INCANDESCENT: JString; function _GetWHITE_BALANCE_SHADE: JString; function _GetWHITE_BALANCE_TWILIGHT: JString; function _GetWHITE_BALANCE_WARM_FLUORESCENT: JString; {Properties} property ANTIBANDING_50HZ: JString read _GetANTIBANDING_50HZ; property ANTIBANDING_60HZ: JString read _GetANTIBANDING_60HZ; property ANTIBANDING_AUTO: JString read _GetANTIBANDING_AUTO; property ANTIBANDING_OFF: JString read _GetANTIBANDING_OFF; property EFFECT_AQUA: JString read _GetEFFECT_AQUA; property EFFECT_BLACKBOARD: JString read _GetEFFECT_BLACKBOARD; property EFFECT_MONO: JString read _GetEFFECT_MONO; property EFFECT_NEGATIVE: JString read _GetEFFECT_NEGATIVE; property EFFECT_NONE: JString read _GetEFFECT_NONE; property EFFECT_POSTERIZE: JString read _GetEFFECT_POSTERIZE; property EFFECT_SEPIA: JString read _GetEFFECT_SEPIA; property EFFECT_SOLARIZE: JString read _GetEFFECT_SOLARIZE; property EFFECT_WHITEBOARD: JString read _GetEFFECT_WHITEBOARD; property FLASH_MODE_AUTO: JString read _GetFLASH_MODE_AUTO; property FLASH_MODE_OFF: JString read _GetFLASH_MODE_OFF; property FLASH_MODE_ON: JString read _GetFLASH_MODE_ON; property FLASH_MODE_RED_EYE: JString read _GetFLASH_MODE_RED_EYE; property FLASH_MODE_TORCH: JString read _GetFLASH_MODE_TORCH; property FOCUS_DISTANCE_FAR_INDEX: Integer read _GetFOCUS_DISTANCE_FAR_INDEX; property FOCUS_DISTANCE_NEAR_INDEX: Integer read _GetFOCUS_DISTANCE_NEAR_INDEX; property FOCUS_DISTANCE_OPTIMAL_INDEX: Integer read _GetFOCUS_DISTANCE_OPTIMAL_INDEX; property FOCUS_MODE_AUTO: JString read _GetFOCUS_MODE_AUTO; property FOCUS_MODE_CONTINUOUS_PICTURE: JString read _GetFOCUS_MODE_CONTINUOUS_PICTURE; property FOCUS_MODE_CONTINUOUS_VIDEO: JString read _GetFOCUS_MODE_CONTINUOUS_VIDEO; property FOCUS_MODE_EDOF: JString read _GetFOCUS_MODE_EDOF; property FOCUS_MODE_FIXED: JString read _GetFOCUS_MODE_FIXED; property FOCUS_MODE_INFINITY: JString read _GetFOCUS_MODE_INFINITY; property FOCUS_MODE_MACRO: JString read _GetFOCUS_MODE_MACRO; property PREVIEW_FPS_MAX_INDEX: Integer read _GetPREVIEW_FPS_MAX_INDEX; property PREVIEW_FPS_MIN_INDEX: Integer read _GetPREVIEW_FPS_MIN_INDEX; property SCENE_MODE_ACTION: JString read _GetSCENE_MODE_ACTION; property SCENE_MODE_AUTO: JString read _GetSCENE_MODE_AUTO; property SCENE_MODE_BARCODE: JString read _GetSCENE_MODE_BARCODE; property SCENE_MODE_BEACH: JString read _GetSCENE_MODE_BEACH; property SCENE_MODE_CANDLELIGHT: JString read _GetSCENE_MODE_CANDLELIGHT; property SCENE_MODE_FIREWORKS: JString read _GetSCENE_MODE_FIREWORKS; property SCENE_MODE_HDR: JString read _GetSCENE_MODE_HDR; property SCENE_MODE_LANDSCAPE: JString read _GetSCENE_MODE_LANDSCAPE; property SCENE_MODE_NIGHT: JString read _GetSCENE_MODE_NIGHT; property SCENE_MODE_NIGHT_PORTRAIT: JString read _GetSCENE_MODE_NIGHT_PORTRAIT; property SCENE_MODE_PARTY: JString read _GetSCENE_MODE_PARTY; property SCENE_MODE_PORTRAIT: JString read _GetSCENE_MODE_PORTRAIT; property SCENE_MODE_SNOW: JString read _GetSCENE_MODE_SNOW; property SCENE_MODE_SPORTS: JString read _GetSCENE_MODE_SPORTS; property SCENE_MODE_STEADYPHOTO: JString read _GetSCENE_MODE_STEADYPHOTO; property SCENE_MODE_SUNSET: JString read _GetSCENE_MODE_SUNSET; property SCENE_MODE_THEATRE: JString read _GetSCENE_MODE_THEATRE; property WHITE_BALANCE_AUTO: JString read _GetWHITE_BALANCE_AUTO; property WHITE_BALANCE_CLOUDY_DAYLIGHT: JString read _GetWHITE_BALANCE_CLOUDY_DAYLIGHT; property WHITE_BALANCE_DAYLIGHT: JString read _GetWHITE_BALANCE_DAYLIGHT; property WHITE_BALANCE_FLUORESCENT: JString read _GetWHITE_BALANCE_FLUORESCENT; property WHITE_BALANCE_INCANDESCENT: JString read _GetWHITE_BALANCE_INCANDESCENT; property WHITE_BALANCE_SHADE: JString read _GetWHITE_BALANCE_SHADE; property WHITE_BALANCE_TWILIGHT: JString read _GetWHITE_BALANCE_TWILIGHT; property WHITE_BALANCE_WARM_FLUORESCENT: JString read _GetWHITE_BALANCE_WARM_FLUORESCENT; end; [JavaSignature('android/hardware/Camera$Parameters')] JCamera_Parameters = interface(JObject) ['{EFDE0CD6-C9EB-4DE2-B903-A61589549842}'] {Methods} function flatten: JString; cdecl; function &get(key: JString): JString; cdecl; function getAntibanding: JString; cdecl; function getAutoExposureLock: Boolean; cdecl; function getAutoWhiteBalanceLock: Boolean; cdecl; function getColorEffect: JString; cdecl; function getExposureCompensation: Integer; cdecl; function getExposureCompensationStep: Single; cdecl; function getFlashMode: JString; cdecl; function getFocalLength: Single; cdecl; function getFocusAreas: JList; cdecl; procedure getFocusDistances(output: TJavaArray<Single>); cdecl; function getFocusMode: JString; cdecl; function getHorizontalViewAngle: Single; cdecl; function getInt(key: JString): Integer; cdecl; function getJpegQuality: Integer; cdecl; function getJpegThumbnailQuality: Integer; cdecl; function getJpegThumbnailSize: JCamera_Size; cdecl; function getMaxExposureCompensation: Integer; cdecl; function getMaxNumDetectedFaces: Integer; cdecl; function getMaxNumFocusAreas: Integer; cdecl; function getMaxNumMeteringAreas: Integer; cdecl; function getMaxZoom: Integer; cdecl; function getMeteringAreas: JList; cdecl; function getMinExposureCompensation: Integer; cdecl; function getPictureFormat: Integer; cdecl; function getPictureSize: JCamera_Size; cdecl; function getPreferredPreviewSizeForVideo: JCamera_Size; cdecl; function getPreviewFormat: Integer; cdecl; procedure getPreviewFpsRange(range: TJavaArray<Integer>); cdecl; function getPreviewFrameRate: Integer; cdecl;//Deprecated function getPreviewSize: JCamera_Size; cdecl; function getSceneMode: JString; cdecl; function getSupportedAntibanding: JList; cdecl; function getSupportedColorEffects: JList; cdecl; function getSupportedFlashModes: JList; cdecl; function getSupportedFocusModes: JList; cdecl; function getSupportedJpegThumbnailSizes: JList; cdecl; function getSupportedPictureFormats: JList; cdecl; function getSupportedPictureSizes: JList; cdecl; function getSupportedPreviewFormats: JList; cdecl; function getSupportedPreviewFpsRange: TJavaObjectArray<JList>; cdecl; function getSupportedPreviewFrameRates: JList; cdecl;//Deprecated function getSupportedPreviewSizes: JList; cdecl; function getSupportedSceneModes: JList; cdecl; function getSupportedVideoSizes: JList; cdecl; function getSupportedWhiteBalance: JList; cdecl; function getVerticalViewAngle: Single; cdecl; function getVideoStabilization: Boolean; cdecl; function getWhiteBalance: JString; cdecl; function getZoom: Integer; cdecl; function getZoomRatios: JList; cdecl; function isAutoExposureLockSupported: Boolean; cdecl; function isAutoWhiteBalanceLockSupported: Boolean; cdecl; function isSmoothZoomSupported: Boolean; cdecl; function isVideoSnapshotSupported: Boolean; cdecl; function isVideoStabilizationSupported: Boolean; cdecl; function isZoomSupported: Boolean; cdecl; procedure remove(key: JString); cdecl; procedure removeGpsData; cdecl; procedure &set(key: JString; value: JString); cdecl; overload; procedure &set(key: JString; value: Integer); cdecl; overload; procedure setAntibanding(antibanding: JString); cdecl; procedure setAutoExposureLock(toggle: Boolean); cdecl; procedure setAutoWhiteBalanceLock(toggle: Boolean); cdecl; procedure setColorEffect(value: JString); cdecl; procedure setExposureCompensation(value: Integer); cdecl; procedure setFlashMode(value: JString); cdecl; procedure setFocusAreas(focusAreas: JList); cdecl; procedure setFocusMode(value: JString); cdecl; procedure setGpsAltitude(altitude: Double); cdecl; procedure setGpsLatitude(latitude: Double); cdecl; procedure setGpsLongitude(longitude: Double); cdecl; procedure setGpsProcessingMethod(processing_method: JString); cdecl; procedure setGpsTimestamp(timestamp: Int64); cdecl; procedure setJpegQuality(quality: Integer); cdecl; procedure setJpegThumbnailQuality(quality: Integer); cdecl; procedure setJpegThumbnailSize(width: Integer; height: Integer); cdecl; procedure setMeteringAreas(meteringAreas: JList); cdecl; procedure setPictureFormat(pixel_format: Integer); cdecl; procedure setPictureSize(width: Integer; height: Integer); cdecl; procedure setPreviewFormat(pixel_format: Integer); cdecl; procedure setPreviewFpsRange(min: Integer; max: Integer); cdecl; procedure setPreviewFrameRate(fps: Integer); cdecl;//Deprecated procedure setPreviewSize(width: Integer; height: Integer); cdecl; procedure setRecordingHint(hint: Boolean); cdecl; procedure setRotation(rotation: Integer); cdecl; procedure setSceneMode(value: JString); cdecl; procedure setVideoStabilization(toggle: Boolean); cdecl; procedure setWhiteBalance(value: JString); cdecl; procedure setZoom(value: Integer); cdecl; procedure unflatten(flattened: JString); cdecl; end; TJCamera_Parameters = class(TJavaGenericImport<JCamera_ParametersClass, JCamera_Parameters>) end; JCamera_AutoFocusMoveCallbackClass = interface(IJavaClass) ['{901C04AC-438E-4233-A469-A3A53EA3A5E3}'] end; [JavaSignature('android/hardware/Camera$AutoFocusMoveCallback')] JCamera_AutoFocusMoveCallback = interface(IJavaInstance) ['{3F071E3E-4BE6-4DFF-A5C9-458E91DD4204}'] {Methods} procedure onAutoFocusMoving(start: Boolean; camera: JCamera); cdecl; end; TJCamera_AutoFocusMoveCallback = class(TJavaGenericImport<JCamera_AutoFocusMoveCallbackClass, JCamera_AutoFocusMoveCallback>) end; JCamera_AutoFocusCallbackClass = interface(IJavaClass) ['{624541C8-C3C3-4A09-8367-4C3237E658D0}'] end; [JavaSignature('android/hardware/Camera$AutoFocusCallback')] JCamera_AutoFocusCallback = interface(IJavaInstance) ['{2E9C9152-C3B7-43EE-98BD-04189FBE43A7}'] {Methods} procedure onAutoFocus(success: Boolean; camera: JCamera); cdecl; end; TJCamera_AutoFocusCallback = class(TJavaGenericImport<JCamera_AutoFocusCallbackClass, JCamera_AutoFocusCallback>) end; JCamera_PictureCallbackClass = interface(IJavaClass) ['{45CCC52F-A446-40A5-BA95-A16D17A11415}'] end; [JavaSignature('android/hardware/Camera$PictureCallback')] JCamera_PictureCallback = interface(IJavaInstance) ['{307615DE-4EFD-4290-A113-CCE958C0C8C2}'] {Methods} procedure onPictureTaken(data: TJavaArray<Byte>; camera: JCamera); cdecl; end; TJCamera_PictureCallback = class(TJavaGenericImport<JCamera_PictureCallbackClass, JCamera_PictureCallback>) end; JCamera_OnZoomChangeListenerClass = interface(IJavaClass) ['{7D8BC2A6-9164-48A0-B14F-D65D3642D2BA}'] end; [JavaSignature('android/hardware/Camera$OnZoomChangeListener')] JCamera_OnZoomChangeListener = interface(IJavaInstance) ['{8083D248-A911-4752-8C17-5F3C9F26CB33}'] {Methods} procedure onZoomChange(zoomValue: Integer; stopped: Boolean; camera: JCamera); cdecl; end; TJCamera_OnZoomChangeListener = class(TJavaGenericImport<JCamera_OnZoomChangeListenerClass, JCamera_OnZoomChangeListener>) end; implementation begin end.
{*******************************************************} { } { Delphi FireMonkey Notification Service } { } { Helpers for MacOS implementations } { } { Copyright(c) 2013 Embarcadero Technologies, Inc. } { } {*******************************************************} // Reference on programm guide in Apple developer center: // https://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Introduction/Introduction.html unit FMX.Notification.Mac; interface procedure RegisterNotificationService; procedure UnregisterNotificationService; implementation uses System.Classes, System.SysUtils, FMX.Notification, FMX.Platform, FMX.Helpers.Mac, FMX.Types, Macapi.Foundation, Macapi.ObjectiveC, Macapi.CocoaTypes, FMX.Messages; type { TNotificationCenterCocoa } TNotificationCenterDelegate = class; TNotificationCenterCocoa = class (TInterfacedObject, IFMXNotificationCenter) strict private FNotificationCenter: NSUserNotificationCenter; FNotificationCenterDelegate: TNotificationCenterDelegate; function CreateNativeNotification(const ANotification: TNotification): NSUserNotification; function ConverNativeToDelphiNotification(const ANotification: NSUserNotification): TNotification; function FindNativeNotification(const AID: string; ANotification: NSUserNotification): Boolean; public constructor Create; destructor Destroy; override; procedure ReceiveNotification(const ANotification: NSUserNotification); { IFMXNotificationCenter } function GetCurrentNotifications: TNotifications; function FindNotification(const AName: string): TNotification; procedure ScheduleNotification(const ANotification: TNotification); procedure PresentNotification(const ANotification: TNotification); procedure CancelNotification(const AName: string); overload; procedure CancelNotification(const ANotification: TNotification); overload; procedure CancelAllNotifications; { Not supported in Mountain Lion } procedure SetIconBadgeNumber(const ACount: Integer); function GetIconBadgeNumber: Integer; procedure ResetIconBadgeNumber; end; { Notification Center Delegate } TNotificationCenterDelegate = class (TOCLocal, NSUserNotificationCenterDelegate) strict private FNotificationCenter: TNotificationCenterCocoa; public constructor Create(ANotificationCenter: TNotificationCenterCocoa); procedure userNotificationCenter(center: NSUserNotificationCenter; didActivateNotification: NSUserNotification); cdecl; end; var NotificationCenter: TNotificationCenterCocoa; procedure RegisterNotificationService; begin if TOSVersion.Check(10, 8) then begin NotificationCenter := TNotificationCenterCocoa.Create; TPlatformServices.Current.AddPlatformService(IFMXNotificationCenter, NotificationCenter); end; end; procedure UnregisterNotificationService; begin TPlatformServices.Current.RemovePlatformService(IFMXNotificationCenter); NotificationCenter := nil; end; { TNotificationCenterCocoa } procedure TNotificationCenterCocoa.CancelAllNotifications; var Notifications: NSArray; NativeNotification: NSUserNotification; I: NSUInteger; begin Notifications := FNotificationCenter.scheduledNotifications; for I := 0 to Notifications.count - 1 do begin NativeNotification := TNSUserNotification.Wrap(Notifications.objectAtIndex(I)); FNotificationCenter.removeScheduledNotification(NativeNotification); end; FNotificationCenter.removeAllDeliveredNotifications; end; procedure TNotificationCenterCocoa.CancelNotification(const AName: string); var NativeNotification: NSUserNotification; begin if FindNativeNotification(AName, NativeNotification) then begin FNotificationCenter.removeScheduledNotification(NativeNotification); FNotificationCenter.removeDeliveredNotification(NativeNotification); end; end; procedure TNotificationCenterCocoa.CancelNotification( const ANotification: TNotification); begin if Assigned(ANotification) then CancelNotification(ANotification.Name); end; constructor TNotificationCenterCocoa.Create; begin FNotificationCenter := TNSUserNotificationCenter.Wrap(TNSUserNotificationCenter.OCClass.defaultUserNotificationCenter); FNotificationCenter.retain; FNotificationCenterDelegate := TNotificationCenterDelegate.Create(Self); FNotificationCenter.setDelegate(FNotificationCenterDelegate); end; function TNotificationCenterCocoa.CreateNativeNotification( const ANotification: TNotification): NSUserNotification; var NativeNotification: NSUserNotification; UserInfo: NSDictionary; GMTDateTime: TDateTime; begin NativeNotification := TNSUserNotification.Create; if not ANotification.Name.IsEmpty then begin // Set unique identificator UserInfo := TNSDictionary.Wrap(TNSDictionary.OCClass.dictionaryWithObject( (NSSTR(ANotification.Name) as ILocalObject).GetObjectID, (NSSTR('id') as ILocalObject).GetObjectID)); NativeNotification.setUserInfo(UserInfo); end; // Get GMT time and set notification fired date GMTDateTime := GetGMTDateTime(ANotification.FireDate); NativeNotification.setDeliveryTimeZone(TNSTimeZone.Wrap(TNSTimeZone.OCClass.defaultTimeZone)); NativeNotification.setDeliveryDate(DateTimeToNSDate(GMTDateTime)); NativeNotification.setInformativeText(NSSTR(ANotification.AlertBody)); NativeNotification.setHasActionButton(ANotification.HasAction); if ANotification.HasAction then NativeNotification.setActionButtonTitle(NSSTR(ANotification.AlertAction)); if ANotification.EnableSound then NativeNotification.setSoundName(NSUserNotificationDefaultSoundName) else NativeNotification.setSoundName(nil); Result := NativeNotification; end; function TNotificationCenterCocoa.ConverNativeToDelphiNotification( const ANotification: NSUserNotification): TNotification; var UserInfo: NSDictionary; NotificationTmp: TNotification; begin NotificationTmp := TNotification.Create; UserInfo := ANotification.userInfo; if Assigned(UserInfo) then NotificationTmp.Name := UTF8ToString(TNSString.Wrap(UserInfo.valueForKey(NSSTR('id'))).UTF8String); if Assigned(ANotification.informativeText) then NotificationTmp.AlertBody := UTF8ToString(ANotification.informativeText.UTF8String); if Assigned(ANotification.actionButtonTitle) then NotificationTmp.AlertAction := UTF8ToString(ANotification.actionButtonTitle.UTF8String);; NotificationTmp.FireDate := NSDateToDateTime(ANotification.deliveryDate); NotificationTmp.EnableSound := Assigned(ANotification.SoundName); NotificationTmp.HasAction := ANotification.hasActionButton; Result := NotificationTmp; end; destructor TNotificationCenterCocoa.Destroy; begin FNotificationCenter.release; inherited Destroy; end; function TNotificationCenterCocoa.FindNativeNotification( const AID: string; ANotification: NSUserNotification): Boolean; var Notifications: NSArray; NativeNotification: NSUserNotification; Found: Boolean; I: NSUInteger; UserInfo: NSDictionary; begin Notifications := FNotificationCenter.scheduledNotifications; Found := False; I := 0; while (I < Notifications.count) and not Found do begin NativeNotification := TNSUserNotification.Wrap(Notifications.objectAtIndex(I)); UserInfo := NativeNotification.userInfo; if Assigned(UserInfo) and (UTF8ToString(TNSString.Wrap(UserInfo.valueForKey(NSSTR('id'))).UTF8String) = AID) then Found := True else Inc(I); end; if Found then ANotification := NativeNotification else ANotification := nil; Result := Found; end; function TNotificationCenterCocoa.FindNotification(const AName: string): TNotification; var NativeNotification: NSUserNotification; begin if FindNativeNotification(AName, NativeNotification) then Result := ConverNativeToDelphiNotification(NativeNotification) else Result := nil; end; function TNotificationCenterCocoa.GetCurrentNotifications: TNotifications; var Notifications: NSArray; NativeNotification: NSUserNotification; I: Integer; begin Notifications := FNotificationCenter.scheduledNotifications; SetLength(Result, Notifications.count); for I := 0 to Integer(Notifications.count) - 1 do begin NativeNotification := TNSUserNotification.Wrap(Notifications.objectAtIndex(I)); Result[I] := ConverNativeToDelphiNotification(NativeNotification); end; end; procedure TNotificationCenterCocoa.PresentNotification( const ANotification: TNotification); var NativeNotification: NSUserNotification; begin CancelNotification(ANotification); NativeNotification := CreateNativeNotification(ANotification); FNotificationCenter.deliverNotification(NativeNotification); end; procedure TNotificationCenterCocoa.ScheduleNotification(const ANotification: TNotification); var NativeNotification: NSUserNotification; begin CancelNotification(ANotification); NativeNotification := CreateNativeNotification(ANotification); FNotificationCenter.scheduleNotification(NativeNotification); end; procedure TNotificationCenterCocoa.ReceiveNotification(const ANotification: NSUserNotification); begin TMessageManager.DefaultManager.SendMessage(Self, TMessage<TNotification>.Create(ConverNativeToDelphiNotification(ANotification))); end; procedure TNotificationCenterCocoa.SetIconBadgeNumber(const ACount: Integer); begin // Nop supported; end; function TNotificationCenterCocoa.GetIconBadgeNumber: Integer; begin Result := 0; // Not supported; end; procedure TNotificationCenterCocoa.ResetIconBadgeNumber; begin // Not supported; end; { TNotificationCenterDelegate } constructor TNotificationCenterDelegate.Create(ANotificationCenter: TNotificationCenterCocoa); begin FNotificationCenter := ANotificationCenter; end; procedure TNotificationCenterDelegate.userNotificationCenter(center: NSUserNotificationCenter; didActivateNotification: NSUserNotification); begin if Assigned(FNotificationCenter) then FNotificationCenter.ReceiveNotification(didActivateNotification); end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Winapi.ActiveX, Winapi.DirectShow9, DeckLinkAPI, DeckLinkAPI.Discovery, DeckLinkAPI.Modes; Const MAX_DECKLINK = 16; type CVideoDelegate = class; TForm1 = class(TForm) m_CaptureTimeLabel: TLabel; m_CaptureTime: TLabel; Label1: TLabel; Label2: TLabel; Label3: TLabel; m_InputCardCombo: TComboBox; m_OutputCardCombo: TComboBox; m_VideoFormatCombo: TComboBox; m_StartButton: TButton; procedure FormCreate(Sender: TObject); procedure m_StartButtonClick(Sender: TObject); procedure m_VideoFormatComboChange(Sender: TObject); private { Private declarations } public m_pDelegate : CVideoDelegate; m_bRunning : boolean; m_pInputCard : IDeckLinkInput; m_pOutputCard : IDeckLinkOutput; m_pDeckLink : array[0..MAX_DECKLINK-1] of IDeckLink; end; CVideoDelegate = class(TInterfacedObject, IDeckLinkInputCallback) Private m_RefCount : integer; m_pController: TForm1; Public constructor Create(pController : TForm1); protected function QueryInterface(const IID: TGUID; out Obj): HRESULT; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; function VideoInputFormatChanged(notificationEvents: _BMDVideoInputFormatChangedEvents; const newDisplayMode: IDeckLinkDisplayMode; detectedSignalFlags: _BMDDetectedVideoInputFormatFlags): HResult; stdcall; function VideoInputFrameArrived(const videoFrame: IDeckLinkVideoInputFrame; const audioPacket: IDeckLinkAudioInputPacket): HResult; stdcall; end; var Form1: TForm1; implementation {$R *.dfm} (* CVideoDelegate *) function CVideoDelegate._AddRef: Integer; begin Result := InterlockedIncrement(m_RefCount); end; function CVideoDelegate._Release: Integer; begin result := InterlockedDecrement(m_RefCount); if Result = 0 then Destroy; end; constructor CVideoDelegate.Create(pController : TForm1); begin m_pController :=pController; m_RefCount:=1; end; function CVideoDelegate.QueryInterface(const IID: TGUID; out Obj): HRESULT; const IID_IUnknown : TGUID = '{00000000-0000-0000-C000-000000000046}'; begin Result := E_NOINTERFACE; Pointer(Obj):=nil; if IsEqualGUID(IID, IID_IUnknown)then begin Pointer(Obj) := Self; _addRef; Result := S_OK; end else if IsEqualGUID(IID, IDeckLinkInputCallback)then begin //GetInterface(IDeckLinkInputCallback, obj); Pointer(Obj) := Pointer(IDeckLinkInputCallback(self)); _addRef; Result := S_OK; end; end; function CVideoDelegate.VideoInputFormatChanged(notificationEvents: _BMDVideoInputFormatChangedEvents; const newDisplayMode: IDeckLinkDisplayMode; detectedSignalFlags: _BMDDetectedVideoInputFormatFlags): HResult; begin RESULT:=S_OK; end; function CVideoDelegate.VideoInputFrameArrived(const videoFrame: IDeckLinkVideoInputFrame; const audioPacket: IDeckLinkAudioInputPacket): HResult; var frameTime, frameDuration : Int64; hours, minutes, seconds, frames : integer; theResult : HResult; captureString : string; begin if m_pController.m_bRunning then begin videoFrame.GetStreamTime(frameTime, frameDuration, 600); theResult := m_pController.m_pOutputCard.ScheduleVideoFrame(videoFrame, frameTime, frameDuration, 600); if theResult <> S_OK then showmessage(format('Scheduling failed with result 0x%08x',[theResult])); hours:=frametime div (600 * 60 * 60); minutes:=(frametime div (600 * 60)) mod 60; seconds:=(frametime div 600) mod 60; frames:=(frametime div 6) mod 100; captureString:=Format('%02.2d:%02.2d:%02.2d:%02.2d',[hours, minutes, seconds, frames]); m_pController.m_CaptureTime.Caption:=captureString; end; RESULT:=S_OK; end; procedure TForm1.FormCreate(Sender: TObject); var i : integer; cardname : Widestring; find_deckLink : boolean; result : HResult; pIterator : IDeckLinkIterator; begin pIterator := nil; m_pDelegate := CVideoDelegate.create(self); // Setup video format combo m_VideoFormatCombo.Items.AddObject('525i59.94 NTSC', TObject(bmdModeNTSC)); m_VideoFormatCombo.Items.AddObject('625i50 PAL', TObject(bmdModePAL)); m_VideoFormatCombo.Items.AddObject('1080PsF23.98', TObject(bmdModeHD1080p2398)); m_VideoFormatCombo.Items.AddObject('1080PsF24', TObject(bmdModeHD1080p24)); m_VideoFormatCombo.Items.AddObject('1080i50', TObject(bmdModeHD1080i50)); m_VideoFormatCombo.Items.AddObject('1080i59.94', TObject(bmdModeHD1080i5994)); m_VideoFormatCombo.Items.AddObject('720p50', TObject(bmdModeHD720p50)); m_VideoFormatCombo.Items.AddObject('720p59.94', TObject(bmdModeHD720p5994)); m_VideoFormatCombo.Items.AddObject('720p60', TObject(bmdModeHD720p60)); m_VideoFormatCombo.Items.AddObject('2K 23.98p', TObject(bmdMode2k2398)); m_VideoFormatCombo.Items.AddObject('2K 24p', TObject(bmdMode2k24)); m_VideoFormatCombo.ItemIndex:=0; result := CoCreateInstance(CLASS_CDeckLinkIterator, nil, CLSCTX_ALL, IID_IDeckLinkIterator, pIterator); if result<>S_OK then begin showmessage(format('This application requires the DeckLink drivers installed.'+#10#13+'Please install the Blackmagic DeckLink drivers to use the features of this application.'+#10#13+'result = %08x.', [result])); exit; end; for I := 0 to MAX_DECKLINK-1 do begin find_deckLink := true; if pIterator.Next(m_pDeckLink[i])<>S_OK then break; if m_pDeckLink[i].GetModelName(cardName)<>S_OK then cardName:='Unknown DeckLink'; // Add this deckLink instance to the popup menus m_InputCardCombo.Items.AddObject(cardName, Pointer(m_pDeckLink[i])); m_OutputCardCombo.Items.AddObject(cardName, Pointer(m_pDeckLink[i])); end; if not find_deckLink then begin m_InputCardCombo.Items.Add('No DeckLink Cards Found'); m_OutputCardCombo.Items.Add('No DeckLink Cards Found'); m_StartButton.Enabled:=false; end; m_InputCardCombo.ItemIndex:=0; m_OutputCardCombo.ItemIndex:=0; // Hide the timecode m_captureTimeLabel.Visible:=false; m_CaptureTime.Visible:=false; m_bRunning:=false; end; procedure TForm1.m_StartButtonClick(Sender: TObject); var Result : HResult; actualStopTime : int64; displayMode : _BMDDisplayMode; begin actualStopTime:=0; // Obtain the input and output interfaces if not m_bRunning then begin if m_pDeckLink[m_InputCardCombo.ItemIndex].QueryInterface(IID_IDeckLinkInput, m_pInputCard)<>S_OK then exit; if m_pDeckLink[m_OutputCardCombo.ItemIndex].QueryInterface(IID_IDeckLinkOutput, m_pOutputCard)<>S_OK then begin if assigned(m_pInputCard) then m_pInputCard:=nil; exit; end; displayMode:=_BMDDisplayMode(m_videoFormatCombo.Items.Objects[m_videoFormatCombo.ItemIndex]); // Turn on video input Result:=m_pInputCard.SetCallback(m_pDelegate); if Result<>S_OK then showmessage(format('SetDelegate failed with result 0x%08x',[Result])); Result:=m_pInputCard.EnableVideoInput(displayMode, bmdFormat8bitYUV, 0); if Result<>S_OK then showmessage(format('EnableVideoInput failed with result 0x%08x',[Result])); // Turn on video output Result:=m_pOutputCard.EnableVideoOutput(displayMode,bmdVideoOutputFlagDefault); if Result<>S_OK then showmessage(format('EnableVideoOutput failed with result 0x%08x',[Result])); Result:=m_pOutputCard.StartScheduledPlayback(0, 600, 1.0); if Result<>S_OK then showmessage(format('StartScheduledPlayback failed with result 0x%08x',[Result])); // Sart the input stream running Result:=m_pInputCard.StartStreams; if Result<>S_OK then showmessage(format('Input StartStreams failed with result 0x%08x',[Result])); m_bRunning:=true; m_CaptureTimeLabel.Visible:=true; m_CaptureTime.Visible:=true; m_CaptureTime.Caption:=''; m_OutputCardCombo.Enabled:=false; m_InputCardCombo.Enabled:=false; m_StartButton.Caption:='Stop'; end else begin m_bRunning:=false; m_pInputCard.StopStreams; m_pOutputCard.StopScheduledPlayback(0,actualStopTime, 600); m_pOutputCard.DisableVideoOutput; m_pInputCard.DisableVideoInput; m_CaptureTimeLabel.Visible:=false; m_CaptureTime.Visible:=false; m_OutputCardCombo.Enabled:=true; m_InputCardCombo.Enabled:=true; m_StartButton.Caption:='Start'; end; end; procedure TForm1.m_VideoFormatComboChange(Sender: TObject); var displayMode : _BMDDisplayMode; actualStopTime : int64; begin if m_bRunning then begin displayMode:=_BMDDisplayMode(m_videoFormatCombo.Items.Objects[m_videoFormatCombo.ItemIndex]); m_pOutputCard.StopScheduledPlayback(0,actualStopTime, 600); m_pOutputCard.DisableVideoOutput; m_pInputCard.StopStreams; m_pInputCard.EnableVideoInput(displayMode, bmdFormat8bitYUV,0); m_pOutputCard.EnableVideoOutput(displayMode,bmdVideoOutputFlagDefault); m_pOutputCard.StartScheduledPlayback(0, 600, 1.0); m_pInputCard.StartStreams; end; end; end.
{ NIM/Nama : Dhafin Rayhan Ahmad } { Tanggal : 5 April 2019 } Program nilaiekstrim; { Membaca masukan N (integer), kemudian N buah integer ke dalam array, lalu X (integer), kemudian menentukan apakah X minimum/maksimum/N#A/tidak ada. } { FUNGSI DAN PROSEDUR } function findMax (arr : array of integer; Neff : integer) : integer; { menentukan elemen maksimum pada array } { KAMUS LOKAL } var eMax, i : integer; { ALGORITMA FUNGSI findMax } begin eMax := arr[0]; for i := 1 to Neff-1 do begin if eMax < arr[i] then begin eMax := arr[i]; end; end; findMax := eMax; end; function findMin (arr : array of integer; Neff : integer) : integer; { menentukan elemen minimum pada array } { KAMUS LOKAL } var eMin, i : integer; { ALGORITMA FUNGSI findMin } begin eMin := arr[0]; for i := 1 to Neff-1 do begin if eMin > arr[i] then begin eMin := arr[i]; end; end; findMin := eMin; end; function isOnArray (arr : array of integer; Neff : integer; X : integer) : boolean; { menentukan apakan suatu elemen ada pada array } { KAMUS LOKAL } var found : boolean; i : integer; { ALGORITMA FUNGSI isOnArray } begin found := false; i := 0; { INISIALISASI } while (not(found)) and (i < Neff) do { Skema pengulangan berdasarkan kondisi mengulang } begin if X = arr[i] then begin found := true; end; i := i + 1; end; isOnArray := found; end; { KAMUS } var arr : array[1..100] of integer; N, X, i : integer; { ALGORITMA } begin readln(N); { N efektif array 'arr' } for i := 1 to N do { Skema pengulangan berdasarkan pencacah } begin readln(arr[i]); end; readln(X); if X = findMax(arr, N) then begin writeln('maksimum'); if X = findMin(arr, N) then begin writeln('minimum'); end; end else if X = findMin(arr, N) then begin writeln('minimum'); end else if isOnArray(arr, N, X) then begin writeln('N#A'); end else begin writeln(X, ' tidak ada'); end; end.
unit AT.Vcl.Actions.Data; interface uses System.Classes, System.Variants, Vcl.ActnList, AT.Vcl.Actions.Consts, AT.Vcl.Actions.Types; type [ComponentPlatformsAttribute(pidCurrentPlatforms)] TATCustomDataAction = class(TAction) strict private FDescription: String; strict protected function GetDescription: String; procedure SetDescription(const Value: String); published property Description: String read GetDescription write SetDescription; end; [ComponentPlatformsAttribute(pidCurrentPlatforms)] TATBooleanDataAction = class(TATCustomDataAction) strict private FAfterDataChange: TATBoolDataAfterChangedEvent; FBeforeDataChange: TATBoolDataBeforeChangedEvent; FData: Boolean; procedure SetData(Value: Boolean); strict protected procedure _AfterDataChange(const Value: Boolean); procedure _BeforeDataChange(const OldValue: Boolean; const NewValue: Boolean); public constructor Create(AOwner: TComponent); override; published property AfterDataChanged: TATBoolDataAfterChangedEvent read FAfterDataChange write FAfterDataChange; property BeforeDataChanged: TATBoolDataBeforeChangedEvent read FBeforeDataChange write FBeforeDataChange; property Data: Boolean read FData write SetData default False; end; [ComponentPlatformsAttribute(pidCurrentPlatforms)] TATDataAction = class(TATCustomDataAction) strict private FAfterDataChange: TATDataAfterChangedEvent; FBeforeDataChange: TATDataBeforeChangedEvent; FData: Variant; procedure SetData(Value: Variant); strict protected procedure _AfterDataChange(const Value: Variant); procedure _BeforeDataChange(const OldValue: Variant; const NewValue: Variant); public constructor Create(AOwner: TComponent); override; published property AfterDataChanged: TATDataAfterChangedEvent read FAfterDataChange write FAfterDataChange; property BeforeDataChanged: TATDataBeforeChangedEvent read FBeforeDataChange write FBeforeDataChange; property Data: Variant read FData write SetData; end; [ComponentPlatformsAttribute(pidCurrentPlatforms)] TATDateTimeDataAction = class(TATCustomDataAction) strict private FAfterDataChange: TATDateTimeDataAfterChangedEvent; FBeforeDataChange: TATDateTimeDataBeforeChangedEvent; FData: TDateTime; procedure SetData(Value: TDateTime); strict protected procedure _AfterDataChange(const Value: TDateTime); procedure _BeforeDataChange(const OldValue: TDateTime; const NewValue: TDateTime); public constructor Create(AOwner: TComponent); override; published property AfterDataChanged: TATDateTimeDataAfterChangedEvent read FAfterDataChange write FAfterDataChange; property BeforeDataChanged: TATDateTimeDataBeforeChangedEvent read FBeforeDataChange write FBeforeDataChange; property Data: TDateTime read FData write SetData; end; [ComponentPlatformsAttribute(pidCurrentPlatforms)] TATInt32DataAction = class(TATCustomDataAction) strict private FAfterDataChange: TATInt32DataAfterChangedEvent; FBeforeDataChange: TATInt32DataBeforeChangedEvent; FData: Integer; procedure SetData(Value: Integer); strict protected procedure _AfterDataChange(const Value: Integer); procedure _BeforeDataChange(const OldValue: Integer; const NewValue: Integer); public constructor Create(AOwner: TComponent); override; published property AfterDataChanged: TATInt32DataAfterChangedEvent read FAfterDataChange write FAfterDataChange; property BeforeDataChanged: TATInt32DataBeforeChangedEvent read FBeforeDataChange write FBeforeDataChange; property Data: Integer read FData write SetData default 0; end; [ComponentPlatformsAttribute(pidCurrentPlatforms)] TATInt64DataAction = class(TATCustomDataAction) strict private FAfterDataChange: TATInt64DataAfterChangedEvent; FBeforeDataChange: TATInt64DataBeforeChangedEvent; FData: Int64; procedure SetData(Value: Int64); strict protected procedure _AfterDataChange(const Value: Int64); procedure _BeforeDataChange(const OldValue: Int64; const NewValue: Int64); public constructor Create(AOwner: TComponent); override; published property AfterDataChanged: TATInt64DataAfterChangedEvent read FAfterDataChange write FAfterDataChange; property BeforeDataChanged: TATInt64DataBeforeChangedEvent read FBeforeDataChange write FBeforeDataChange; property Data: Int64 read FData write SetData default 0; end; [ComponentPlatformsAttribute(pidCurrentPlatforms)] TATMultiDataAction = class(TATCustomDataAction) strict private FAfterDataChange: TATDataAfterChangedEvent; FBeforeDataChange: TATDataBeforeChangedEvent; FBoolData: Boolean; FDTData: TDateTime; FInt32Data: Integer; FInt64Data: Int64; FStringData: String; FVarData: Variant; procedure SetBoolData(Value: Boolean); procedure SetDTData(Value: TDateTime); procedure SetInt32Data(Value: Integer); procedure SetInt64Data(Value: Int64); procedure SetStringData(Value: String); procedure SetVarData(Value: Variant); strict protected procedure _AfterDataChange(const Value: Variant); procedure _BeforeDataChange(const OldValue: Variant; const NewValue: Variant); public constructor Create(AOwner: TComponent); override; published property AfterDataChanged: TATDataAfterChangedEvent read FAfterDataChange write FAfterDataChange; property BeforeDataChanged: TATDataBeforeChangedEvent read FBeforeDataChange write FBeforeDataChange; property BooleanData: Boolean read FBoolData write SetBoolData; property DateTimeData: TDateTime read FDTData write SetDTData; property Int32Data: Integer read FInt32Data write SetInt32Data; property Int64Data: Int64 read FInt64Data write SetInt64Data; property StringData: String read FStringData write SetStringData; property VariantData: Variant read FVarData write SetVarData; end; [ComponentPlatformsAttribute(pidCurrentPlatforms)] TATStrDataAction = class(TATCustomDataAction) strict private FAfterDataChange: TATStrDataAfterChangedEvent; FBeforeDataChange: TATStrDataBeforeChangedEvent; FData: String; procedure SetData(Value: String); strict protected procedure _AfterDataChange(const Value: String); procedure _BeforeDataChange(const OldValue: String; const NewValue: String); public constructor Create(AOwner: TComponent); override; published property AfterDataChanged: TATStrDataAfterChangedEvent read FAfterDataChange write FAfterDataChange; property BeforeDataChanged: TATStrDataBeforeChangedEvent read FBeforeDataChange write FBeforeDataChange; property Data: String read FData write SetData; end; implementation uses System.SysUtils, System.Actions, AT.Rtti; { TATCustomDataAction } function TATCustomDataAction.GetDescription: String; begin Result := FDescription; end; procedure TATCustomDataAction.SetDescription(const Value: String); var Idx: Integer; ALink: TBasicActionLink; begin if (Value <> FDescription) then begin for Idx := 0 to (ClientCount - 1) do begin ALink := Clients[Idx]; if (HasProperty(ALink, 'Description')) then SetPropertyValue(ALink, 'Description', Value); end; FDescription := Value; Change; end; end; { TATBooleanDataAction } constructor TATBooleanDataAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FData := False; end; procedure TATBooleanDataAction.SetData(Value: Boolean); begin _BeforeDataChange(FData, Value); FData := Value; _AfterDataChange(FData); end; procedure TATBooleanDataAction._AfterDataChange(const Value: Boolean); begin if (NOT Assigned(FAfterDataChange)) then Exit; FAfterDataChange(Self, Value); end; procedure TATBooleanDataAction._BeforeDataChange(const OldValue, NewValue: Boolean); begin if (NOT Assigned(FBeforeDataChange)) then Exit; FBeforeDataChange(Self, OldValue, NewValue); end; { TATDataAction } constructor TATDataAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FData := Unassigned; end; procedure TATDataAction.SetData(Value: Variant); begin _BeforeDataChange(FData, Value); FData := Value; _AfterDataChange(FData); end; procedure TATDataAction._AfterDataChange(const Value: Variant); begin if (NOT Assigned(FAfterDataChange)) then Exit; FAfterDataChange(Self, Value); end; procedure TATDataAction._BeforeDataChange(const OldValue: Variant; const NewValue: Variant); begin if (NOT Assigned(FBeforeDataChange)) then Exit; FBeforeDataChange(Self, OldValue, NewValue); end; { TATDateTimeDataAction } constructor TATDateTimeDataAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FData := Now; end; procedure TATDateTimeDataAction.SetData(Value: TDateTime); begin _BeforeDataChange(FData, Value); FData := Value; _AfterDataChange(FData); end; procedure TATDateTimeDataAction._AfterDataChange( const Value: TDateTime); begin if (NOT Assigned(FAfterDataChange)) then Exit; FAfterDataChange(Self, Value); end; procedure TATDateTimeDataAction._BeforeDataChange( const OldValue: TDateTime; const NewValue: TDateTime); begin if (NOT Assigned(FBeforeDataChange)) then Exit; FBeforeDataChange(Self, OldValue, NewValue); end; { TATInt32DataAction } constructor TATInt32DataAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FData := 0; end; procedure TATInt32DataAction.SetData(Value: Integer); begin _BeforeDataChange(FData, Value); FData := Value; _AfterDataChange(FData); end; procedure TATInt32DataAction._AfterDataChange(const Value: Integer); begin if (NOT Assigned(FAfterDataChange)) then Exit; FAfterDataChange(Self, Value); end; procedure TATInt32DataAction._BeforeDataChange(const OldValue, NewValue: Integer); begin if (NOT Assigned(FBeforeDataChange)) then Exit; FBeforeDataChange(Self, OldValue, NewValue); end; { TATInt64DataAction } constructor TATInt64DataAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FData := 0; end; procedure TATInt64DataAction.SetData(Value: Int64); begin _BeforeDataChange(FData, Value); FData := Value; _AfterDataChange(FData); end; procedure TATInt64DataAction._AfterDataChange(const Value: Int64); begin if (NOT Assigned(FAfterDataChange)) then Exit; FAfterDataChange(Self, Value); end; procedure TATInt64DataAction._BeforeDataChange(const OldValue: Int64; const NewValue: Int64); begin if (NOT Assigned(FBeforeDataChange)) then Exit; FBeforeDataChange(Self, OldValue, NewValue); end; { TATMultiDataAction } constructor TATMultiDataAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FBoolData := False; FDTData := Now; FInt32Data := 0; FInt64Data := 0; FStringData := EmptyStr; FVarData := Unassigned; end; procedure TATMultiDataAction.SetBoolData(Value: Boolean); begin _BeforeDataChange(FBoolData, Value); FBoolData := Value; _AfterDataChange(FBoolData); end; procedure TATMultiDataAction.SetDTData(Value: TDateTime); begin _BeforeDataChange(FDTData, Value); FDTData := Value; _AfterDataChange(FDTData); end; procedure TATMultiDataAction.SetInt32Data(Value: Integer); begin _BeforeDataChange(FInt32Data, Value); FInt32Data := Value; _AfterDataChange(FInt32Data); end; procedure TATMultiDataAction.SetInt64Data(Value: Int64); begin _BeforeDataChange(FInt64Data, Value); FInt64Data := Value; _AfterDataChange(FInt64Data); end; procedure TATMultiDataAction.SetStringData(Value: String); begin _BeforeDataChange(FStringData, Value); FStringData := Value; _AfterDataChange(FStringData); end; procedure TATMultiDataAction.SetVarData(Value: Variant); begin _BeforeDataChange(FVarData, Value); FVarData := Value; _AfterDataChange(FVarData); end; procedure TATMultiDataAction._AfterDataChange(const Value: Variant); begin if (NOT Assigned(FAfterDataChange)) then Exit; FAfterDataChange(Self, Value); end; procedure TATMultiDataAction._BeforeDataChange( const OldValue: Variant; const NewValue: Variant); begin if (NOT Assigned(FBeforeDataChange)) then Exit; FBeforeDataChange(Self, OldValue, NewValue); end; { TATStrDataAction } constructor TATStrDataAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FData := EmptyStr; end; procedure TATStrDataAction.SetData(Value: String); begin _BeforeDataChange(FData, Value); FData := Value; _AfterDataChange(FData); end; procedure TATStrDataAction._AfterDataChange(const Value: String); begin if (NOT Assigned(FAfterDataChange)) then Exit; FAfterDataChange(Self, Value); end; procedure TATStrDataAction._BeforeDataChange(const OldValue, NewValue: String); begin if (NOT Assigned(FBeforeDataChange)) then Exit; FBeforeDataChange(Self, OldValue, NewValue); end; end.
unit Report_GoodsNotSalePastDialog; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ParentForm, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, Vcl.StdCtrls, cxButtons, cxControls, cxContainer, cxEdit, Vcl.ComCtrls, dxCore, cxDateUtils, ChoicePeriod, dsdGuides, cxDropDownEdit, cxCalendar, cxTextEdit, cxMaskEdit, cxButtonEdit, cxPropertiesStore, dsdAddOn, dsdDB, cxLabel, dxSkinsCore, dxSkinsDefaultPainters, cxCheckBox, dsdAction, Vcl.ActnList, cxCurrencyEdit; type TReport_GoodsNotSalePastDialogForm = class(TParentForm) cxButton1: TcxButton; cxButton2: TcxButton; PeriodChoice: TPeriodChoice; dsdUserSettingsStorageAddOn: TdsdUserSettingsStorageAddOn; cxPropertiesStore: TcxPropertiesStore; FormParams: TdsdFormParams; edUnit: TcxButtonEdit; cxLabel3: TcxLabel; UnitGuides: TdsdGuides; ActionList: TActionList; actRefresh: TdsdDataSetRefresh; actGet_UserUnit: TdsdExecStoredProc; spGet_UserUnit: TdsdStoredProc; actRefreshStart: TdsdDataSetRefresh; ceNotSalePastDay: TcxCurrencyEdit; cxLabel6: TcxLabel; private { Private declarations } public { Public declarations } end; implementation {$R *.dfm} initialization RegisterClass(TReport_GoodsNotSalePastDialogForm); end.
unit TarFTP.Utils; interface uses SysUtils; function GetFileSize(const FileName : String) : Int64; function SizeToStr(Size : Int64) : String; implementation function GetFileSize(const FileName : String) : Int64; var SearchRec : TSearchRec; begin if FindFirst( FileName, faAnyFile, SearchRec ) = 0 then try Result := SearchRec.Size; finally FindClose( SearchRec ); end else Result := 0; end; type TSizeOrder = ( soBytes, soKBytes, soMBytes, soGBytes, soTBytes ); const KB = 1024; MB = KB * 1024; GB = MB * Int64(1024); TB = GB * Int64(1024); SIZES : array[ TSizeOrder ] of Int64 = ( 1, KB, MB, GB, TB ); SIZE_STR : array[ TSizeOrder ] of String = ( 'bytes', 'KB', 'MB', 'GB', 'TB' ); function SizeToStr(Size : Int64) : String; var order : TSizeOrder; value : Extended; begin order := soBytes; while order < High( order ) do begin if Size < SIZES[ order ] then begin if order > soBytes then order := Pred( order ); Break; end; order := Succ( order ); end; value := Size / SIZES[ order ]; Result := Format( '%.2f %s', [ value, SIZE_STR[ order ] ] ); end; end.
{***************************************************************************} { } { Delphi.Mocks } { } { Copyright (C) 2011 Vincent Parrett } { } { http://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit Delphi.Mocks; interface {$I 'Delphi.Mocks.inc'} uses System.TypInfo, System.Rtti, System.Sysutils, System.RegularExpressions, System.Generics.Defaults, Delphi.Mocks.WeakReference; type IWhen<T> = interface; //Records the expectations we have when our Mock is used. We can then verify //our expectations later. IExpect<T> = interface ['{8B9919F1-99AB-4526-AD90-4493E9343083}'] function Once : IWhen<T>;overload; procedure Once(const AMethodName : string);overload; function Never : IWhen<T>;overload; procedure Never(const AMethodName : string);overload; function AtLeastOnce : IWhen<T>;overload; procedure AtLeastOnce(const AMethodName : string);overload; function AtLeast(const times : Cardinal) : IWhen<T>;overload; procedure AtLeast(const AMethodName : string; const times : Cardinal);overload; function AtMost(const times : Cardinal) : IWhen<T>;overload; procedure AtMost(const AMethodName : string; const times : Cardinal);overload; function Between(const a,b : Cardinal) : IWhen<T>;overload; procedure Between(const AMethodName : string; const a,b : Cardinal);overload; function Exactly(const times : Cardinal) : IWhen<T>;overload; procedure Exactly(const AMethodName : string; const times : Cardinal);overload; function Before(const AMethodName : string) : IWhen<T>;overload; procedure Before(const AMethodName : string; const ABeforeMethodName : string);overload; function After(const AMethodName : string) : IWhen<T>;overload; procedure After(const AMethodName : string; const AAfterMethodName : string);overload; procedure Clear; end; IWhen<T> = interface ['{A8C2E07B-A5C1-463D-ACC4-BA2881E8419F}'] function When : T; end; /// This is the definition for an anonymous function you can pass into /// WillExecute. The args array will be the arguments passed to the method /// called on the Mock. If the method returns a value then your anon func must /// return that.. and the return type must match. The return type is passed in /// so that you can ensure tha. TExecuteFunc = reference to function (const args : TArray<TValue>; const ReturnType : TRttiType) : TValue; IStubSetup<T> = interface ['{3E6AD69A-11EA-47F1-B5C3-63F7B8C265B1}'] function GetBehaviorMustBeDefined : boolean; procedure SetBehaviorMustBeDefined(const value : boolean); function GetAllowRedefineBehaviorDefinitions : boolean; procedure SetAllowRedefineBehaviorDefinitions(const value : boolean); //set the return value for a method when called with the parameters specified on the When function WillReturn(const value : TValue) : IWhen<T>; overload; //set the return value for a method when called with the parameters specified on the When //AllowNil flag allow to define: returning nil value is allowed or not. function WillReturn(const value : TValue; const AllowNil: Boolean) : IWhen<T>; overload; //set the nil as return value for a method when called with the parameters specified on the When function WillReturnNil : IWhen<T>; //Will exedute the func when called with the specified parameters function WillExecute(const func : TExecuteFunc) : IWhen<T>;overload; //will always execute the func no matter what parameters are specified. procedure WillExecute(const AMethodName : string; const func : TExecuteFunc);overload; //set the default return value for a method when it is called with parameter values we //haven't specified procedure WillReturnDefault(const AMethodName : string; const value : TValue); //set the Exception class that will be raised when the method is called with the parmeters specified function WillRaise(const exceptionClass : ExceptClass; const message : string = '') : IWhen<T>;overload; //This method will always raise an exception.. this behavior will trump any other defined behaviors procedure WillRaise(const AMethodName : string; const exceptionClass : ExceptClass; const message : string = '');overload; //set the Exception class that will be raised when the method is called with the parmeters specified function WillRaiseWhen(const exceptionClass: ExceptClass; const message: string = ''): IWhen<T>; //If true, calls to methods for which we have not defined a behavior will cause verify to fail. property BehaviorMustBeDefined : boolean read GetBehaviorMustBeDefined write SetBehaviorMustBeDefined; //If true, it is possible to overwrite a already defined behaviour. property AllowRedefineBehaviorDefinitions: boolean read GetAllowRedefineBehaviorDefinitions write SetAllowRedefineBehaviorDefinitions; end; //We use the Setup to configure our expected behaviour rules and to verify //that those expectations were met. IMockSetup<T> = interface(IStubSetup<T>) ['{D6B21933-BF51-4937-877E-51B59A3B3268}'] //Set Expectations for methods function Expect : IExpect<T>; end; IStubProxy<T> = interface ['{578BAF90-4155-4C0F-AAED-407057C6384F}'] function Setup : IStubSetup<T>; function Proxy : T; end; {$IFOPT M+} {$M-} {$DEFINE ENABLED_M+} {$ENDIF} IProxy = interface(IWeakReferenceableObject) ['{C97DC7E8-BE99-46FE-8488-4B356DD4AE29}'] function ProxyInterface : IInterface; function ProxyFromType(const ATypeInfo : PTypeInfo) : IProxy; procedure AddImplement(const AProxy : IProxy; const ATypeInfo : PTypeInfo); function QueryImplementedInterface(const IID: TGUID; out Obj): HRESULT; stdcall; procedure SetParentProxy(const AProxy : IProxy); function SupportsIInterface: Boolean; end; {$IFDEF ENABLED_M+} {$M+} {$ENDIF} //used by the mock - need to find another place to put this.. circular references //problem means we need it here for now. IProxy<T> = interface(IProxy) ['{1E3A98C5-78BA-4D65-A4BA-B6992B8B4783}'] function Setup : IMockSetup<T>; function Proxy : T; end; IAutoMock = interface ['{9C7113DF-6F93-496D-A223-61D30782C7D8}'] function Mock(const ATypeInfo : PTypeInfo) : IProxy; procedure Add(const ATypeName : string; const AMock: IProxy); end; TStub<T> = record private FProxy : IStubProxy<T>; FAutomocker : IAutoMock; public class operator Implicit(const Value: TStub<T>): T; function Setup : IStubSetup<T>; function Instance : T; function InstanceAsValue : TValue; class function Create: TStub<T>; overload; static; class function Create(const ACreateObjectFunc: TFunc<T>): TStub<T>; overload; static; // explicit cleanup. Not sure if we really need this. procedure Free; end; //We use a record here to take advantage of operator overloading, the Implicit //operator allows us to use the mock as the interface without holding a reference //to the mock interface outside of the mock. TMock<T> = record private FProxy : IProxy<T>; FCreated : Boolean; FAutomocker : IAutoMock; procedure CheckCreated; public class operator Implicit(const Value: TMock<T>): T; class function Create(const AAutoMock: IAutoMock; const ACreateObjectFunc: TFunc<T>): TMock<T>; overload; static; function Setup : IMockSetup<T>; overload; function Setup<I : IInterface> : IMockSetup<I>; overload; //Verify that our expectations were met. procedure Verify(const message : string = ''); overload; procedure Verify<I : IInterface>(const message : string = ''); overload; procedure VerifyAll(const message : string = ''); procedure ResetCalls; function CheckExpectations: string; procedure Implement<I : IInterface>; overload; function Instance : T; overload; function Instance<I : IInterface> : I; overload; function InstanceAsValue : TValue; overload; function InstanceAsValue<I : IInterface> : TValue; overload; class function Create: TMock<T>; overload; static; class function Create(const ACreateObjectFunc: TFunc<T>): TMock<T>; overload; static; //Explicit cleanup. Not sure if we really need this. procedure Free; end; TAutoMockContainer = record private FAutoMocker : IAutoMock; public function Mock<T> : TMock<T>; overload; procedure Mock(const ATypeInfo : PTypeInfo); overload; class function Create : TAutoMockContainer; static; end; /// Used for defining permissable parameter values during method setup. /// Inspired by Moq ItRec = record private ParamIndex : cardinal; function DefaultComparer<T>: IEqualityComparer<T>; public constructor Create(const AParamIndex : Integer); function IsAny<T>() : T ; function Matches<T>(const predicate: TPredicate<T>) : T; function IsNotNil<T> : T; overload; function IsNotNil<T>(const comparer: IEqualityComparer<T>) : T; overload; function IsEqualTo<T>(const value : T) : T; overload; function IsEqualTo<T>(const value : T; const comparer: IEqualityComparer<T>) : T; overload; function IsInRange<T>(const fromValue : T; const toValue : T) : T; function IsIn<T>(const values : TArray<T>) : T; overload; function IsIn<T>(const values : TArray<T>; const comparer: IEqualityComparer<T>) : T; overload; function IsIn<T>(const values : IEnumerable<T>) : T; overload; function IsIn<T>(const values : IEnumerable<T>; const comparer: IEqualityComparer<T>) : T; overload; function IsNotIn<T>(const values : TArray<T>) : T; overload; function IsNotIn<T>(const values : TArray<T>; const comparer: IEqualityComparer<T>) : T; overload; function IsNotIn<T>(const values : IEnumerable<T>) : T; overload; function IsNotIn<T>(const values : IEnumerable<T>; const comparer: IEqualityComparer<T>) : T; overload; function IsRegex(const regex : string; const options : TRegExOptions = []) : string; function AreSamePropertiesThat<T>(const Value: T): T; function AreSameFieldsThat<T>(const Value: T): T; function AreSameFieldsAndPropertiedThat<T>(const Value: T): T; end; TComparer = class public class function CompareFields<T>(Param1, Param2: T): Boolean; class function CompareMembers<T: TRttiMember; T2>(Members: TArray<T>; Param1, Param2: T2): Boolean; class function CompareProperties<T>(Param1, Param2: T): Boolean; end; //Exception Types that the mocks will raise. EMockException = class(Exception); EMockProxyAlreadyImplemented = class(EMockException); EMockSetupException = class(EMockException); EMockNoRTTIException = class(EMockException); EMockNoProxyException = class(EMockException); EMockVerificationException = class(EMockException); TTypeInfoHelper = record helper for TTypeInfo function NameStr : string; inline; end; function It(const AParamIndx : Integer) : ItRec; function It0 : ItRec; function It1 : ItRec; function It2 : ItRec; function It3 : ItRec; function It4 : ItRec; function It5 : ItRec; function It6 : ItRec; function It7 : ItRec; function It8 : ItRec; function It9 : ItRec; implementation uses System.Classes, Generics.Defaults, Delphi.Mocks.Utils, Delphi.Mocks.Interfaces, Delphi.Mocks.Proxy, Delphi.Mocks.ObjectProxy, Delphi.Mocks.ParamMatcher, Delphi.Mocks.AutoMock, Delphi.Mocks.Validation, Delphi.Mocks.Helpers {$IFDEF DELPHI_XE8_UP} ,System.Hash {$ENDIF}; procedure TMock<T>.CheckCreated; var pInfo : PTypeInfo; begin pInfo := TypeInfo(T); if not FCreated then raise EMockException.CreateFmt('Create for TMock<%s> was not called before use.', [pInfo.Name]); if (FProxy = nil) then raise EMockException.CreateFmt('Internal Error : Internal Proxy for TMock<%s> was nil.', [pInfo.Name]); end; function TMock<T>.CheckExpectations: string; var su : IMockSetup<T>; v : IVerify; begin CheckCreated; if Supports(FProxy.Setup,IVerify,v) then Result := v.CheckExpectations else raise EMockException.Create('Could not cast Setup to IVerify interface!'); end; class function TMock<T>.Create: TMock<T>; begin Result := Create(nil); end; class function TMock<T>.Create(const ACreateObjectFunc: TFunc<T>): TMock<T>; begin Result := Create(nil, ACreateObjectFunc); end; class function TMock<T>.Create(const AAutoMock: IAutoMock; const ACreateObjectFunc: TFunc<T>): TMock<T>; var proxy : IInterface; pInfo : PTypeInfo; begin //Make sure that we start off with a clean mock FillChar(Result, SizeOf(Result), 0); //By default we don't auto mock TMock<T>. It changes when TAutoMock is used. Result.FAutomocker := AAutoMock; pInfo := TypeInfo(T); //Raise exceptions if the mock doesn't meet the requirements. TMocksValidation.CheckMockType(pInfo); case pInfo.Kind of //Create our proxy object, which will implement our object T tkClass : proxy := TObjectProxy<T>.Create(ACreateObjectFunc, Result.FAutomocker, false); //Create our proxy interface object, which will implement our interface T tkInterface : proxy := TProxy<T>.Create(Result.FAutomocker, false); end; //Push the proxy into the result we are returning. if proxy.QueryInterface(GetTypeData(TypeInfo(IProxy<T>)).Guid, Result.FProxy) <> 0 then //TODO: This raise seems superfluous as the only types which are created are controlled by us above. They all implement IProxy<T> raise EMockNoProxyException.Create('Error casting to interface ' + pInfo.NameStr + ' , proxy does not appear to implememnt IProxy<T>'); //The record has been created! Result.FCreated := True; end; procedure TMock<T>.Free; begin CheckCreated; FProxy := nil; FAutomocker := nil; end; procedure TMock<T>.Implement<I>; var proxy : IProxy<I>; pInfo : PTypeInfo; begin CheckCreated; if FProxy is TObjectProxy<T> then raise ENotSupportedException.Create('Adding interface implementation to non interfaced objects not supported at this time'); pInfo := TypeInfo(I); TMocksValidation.CheckMockInterface(pInfo); proxy := TProxy<I>.Create; FProxy.AddImplement(proxy, pInfo); end; class operator TMock<T>.Implicit(const Value: TMock<T>): T; begin Value.CheckCreated; result := Value.FProxy.Proxy; end; function TMock<T>.Instance : T; begin CheckCreated; result := FProxy.Proxy; end; function TMock<T>.Instance<I>: I; var prox : IInterface; proxyI : IProxy<I>; pInfo : PTypeInfo; begin result := nil; CheckCreated; //Does the proxy we have, or any of its children support a proxy for the passed //in interface type? pInfo := TypeInfo(I); prox := FProxy.ProxyFromType(pInfo); if prox = nil then raise EMockException.CreateFmt('Mock does not implement [%s]', [pInfo.NameStr]); if (prox = nil) or (not Supports(prox, IProxy<I>, proxyI)) then raise EMockException.CreateFmt('Proxy for [%s] does not support [IProxy<T>].', [pInfo.NameStr]); //Return the interface for the requested implementation. result := proxyI.Proxy; end; function TMock<T>.InstanceAsValue: TValue; begin CheckCreated; result := TValue.From<T>(Self); end; function TMock<T>.InstanceAsValue<I>: TValue; begin CheckCreated; result := TValue.From<I>(Self.Instance<I>); end; procedure TMock<T>.ResetCalls; var interfaceV : IVerify; begin CheckCreated; if Supports(FProxy.Setup, IVerify, interfaceV) then interfaceV.ResetCalls else raise EMockException.Create('Could not cast Setup to IVerify interface!'); end; function TMock<T>.Setup: IMockSetup<T>; begin CheckCreated; result := FProxy.Setup; end; {$O-} function TMock<T>.Setup<I>: IMockSetup<I>; var setup : IProxy; pInfo : PTypeInfo; pMockSetupInfo : PTypeInfo; begin CheckCreated; //We have to ask for the proxy who owns the implementation of the interface/object //in question. The reason for this it that all proxies implement IProxy<T> and //therefore we will just get the first proxy always. //E.g. IProxy<IInterfaceOne> and IProxy<IInterfaceTwo> have the same GUID. Makes //generic interfaces hard to use. pInfo := TypeInfo(I); //Get the proxy which implements setup := FProxy.ProxyFromType(pInfo); //If nill is returned then we don't implement the defined type. if setup = nil then raise EMockNoProxyException.CreateFmt('[%s] is not implement.', [pInfo.NameStr]); //Now get it as the mocksetup that we requrie. Note that this doesn't ensure //that I is actually implemented as all proxies implment IMockSetup<I>. This //is what we only return the error that IMockSetup isn't implemented. if not Supports(setup, IMockSetup<I>, result) then begin pMockSetupInfo := TypeInfo(IMockSetup<I>); raise EMockNoProxyException.CreateFmt('[%s] Proxy does not implement [%s]', [pInfo.NameStr, pMockSetupInfo.NameStr]); end; end; {$O+} procedure TMock<T>.Verify(const message: string); var v : IVerify; begin CheckCreated; if Supports(FProxy.Setup, IVerify, v) then v.Verify(message) else raise EMockException.Create('Could not cast Setup to IVerify interface!'); end; {$O-} procedure TMock<T>.Verify<I>(const message: string); var prox : IInterface; interfaceV : IVerify; pInfo : PTypeInfo; begin CheckCreated; //Does the proxy we have, or any of its children support a proxy for the passed //in interface type? pInfo := TypeInfo(I); prox := FProxy.ProxyFromType(pInfo); if (prox = nil) or (not Supports(prox, IVerify, interfaceV)) then raise EMockException.Create('Could not cast Setup to IVerify interface!'); interfaceV.Verify(message); end; {$O+} procedure TMock<T>.VerifyAll(const message: string); var interfaceV : IVerify; begin CheckCreated; if Supports(FProxy.Setup, IVerify, interfaceV) then interfaceV.VerifyAll(message) else raise EMockException.Create('Could not cast Setup to IVerify interface!'); end; { TStub<T> } class function TStub<T>.Create(): TStub<T>; begin result := TStub<T>.Create(nil); end; class function TStub<T>.Create(const ACreateObjectFunc: TFunc<T>): TStub<T>; var proxy : IInterface; pInfo : PTypeInfo; begin //Make sure that we start off with a clean mock FillChar(Result, SizeOf(Result), 0); //By default we don't auto mock TMock<T>. It changes when TAutoMock is used. Result.FAutomocker := nil; pInfo := TypeInfo(T); if not (pInfo.Kind in [tkInterface,tkClass]) then raise EMockException.Create(pInfo.NameStr + ' is not an Interface or Class. TStub<T> supports interfaces and classes only'); case pInfo.Kind of //NOTE: We have a weaker requirement for an object proxy opposed to an interface proxy. //NOTE: Object proxy doesn't require more than zero methods on the object. tkClass : begin //Check to make sure we have if not CheckClassHasRTTI(pInfo) then raise EMockNoRTTIException.Create(pInfo.NameStr + ' does not have RTTI, specify {$M+} for the object to enabled RTTI'); //Create our proxy object, which will implement our object T proxy := TObjectProxy<T>.Create(ACreateObjectFunc, Result.FAutomocker, true); end; tkInterface : begin //Check to make sure we have if not CheckInterfaceHasRTTI(pInfo) then raise EMockNoRTTIException.Create(pInfo.NameStr + ' does not have RTTI, specify {$M+} for the interface to enabled RTTI'); //Create our proxy interface object, which will implement our interface T proxy := TProxy<T>.Create(Result.FAutomocker, true); end; else raise EMockException.Create('Invalid type kind T'); end; //Push the proxy into the result we are returning. if proxy.QueryInterface(GetTypeData(TypeInfo(IStubProxy<T>)).Guid, Result.FProxy) <> 0 then //TODO: This raise seems superfluous as the only types which are created are controlled by us above. They all implement IProxy<T> raise EMockNoProxyException.Create('Error casting to interface ' + pInfo.NameStr + ' , proxy does not appear to implememnt IProxy<T>'); end; procedure TStub<T>.Free; begin FProxy := nil; end; class operator TStub<T>.Implicit(const Value: TStub<T>): T; begin result := Value.FProxy.Proxy; end; function TStub<T>.Instance: T; begin result := FProxy.Proxy; end; function TStub<T>.InstanceAsValue: TValue; begin result := TValue.From<T>(Self); end; function TStub<T>.Setup: IStubSetup<T>; begin result := FProxy.Setup; end; { TTypeInfoHelper } function TTypeInfoHelper.NameStr: string; begin {$IFNDEF NEXTGEN} result := string(Self.Name); {$ELSE} result := Self.NameFld.ToString; {$ENDIF} end; { TAutoMockContainer } class function TAutoMockContainer.Create: TAutoMockContainer; begin FillChar(Result, SizeOf(Result), 0); Result.FAutoMocker := TAutoMock.Create; end; procedure TAutoMockContainer.Mock(const ATypeInfo: PTypeInfo); begin FAutoMocker.Mock(ATypeInfo); end; function TAutoMockContainer.Mock<T>: TMock<T>; var mock : TMock<T>; pInfo : PTypeInfo; begin pInfo := TypeInfo(T); mock := TMock<T>.Create(FAutoMocker, nil); FAutoMocker.Add(pInfo.NameStr, mock.FProxy); result := mock; end; { It } function ItRec.AreSameFieldsAndPropertiedThat<T>(const Value: T): T; begin Result := Value; TMatcherFactory.Create<T>(ParamIndex, function(Param: T): Boolean begin Result := TComparer.CompareFields<T>(Param, Value) and TComparer.CompareProperties<T>(Param, Value); end); end; function ItRec.AreSameFieldsThat<T>(const Value: T): T; begin Result := Value; TMatcherFactory.Create<T>(ParamIndex, function(Param: T): Boolean begin Result := TComparer.CompareFields<T>(Param, Value); end); end; function ItRec.AreSamePropertiesThat<T>(const Value: T): T; begin Result := Value; TMatcherFactory.Create<T>(ParamIndex, function(Param: T): Boolean begin Result := TComparer.CompareProperties<T>(Param, Value); end); end; constructor ItRec.Create(const AParamIndex : Integer); begin ParamIndex := AParamIndex; end; function ItRec.DefaultComparer<T>: IEqualityComparer<T>; var LCtx: TRttiContext; LType: TRttiType; LMethod: TRttiMethod; begin Result := TEqualityComparer<T>.Default; LType := LCtx.GetType(TypeInfo(T)); if LType.IsRecord then if LType.TryGetMethod('&op_Equality', LMethod) then begin Result := TEqualityComparer<T>.Construct( function(const Left, Right: T): Boolean begin Result := LMethod.Invoke(nil, [TValue.From<T>(Left), TValue.From<T>(Right)]).AsBoolean; end, function(const Value: T): Integer begin {$IFDEF DELPHI_XE8_UP} Result := THashBobJenkins.GetHashValue(Value, SizeOf(Value)); {$ELSE} Result := BobJenkinsHash(Value, SizeOf(Value), 0); {$ENDIF} end); end; end; function ItRec.IsAny<T>: T; begin result := Default(T); TMatcherFactory.Create<T>(ParamIndex, function(value : T) : boolean begin result := true; end); end; function ItRec.IsEqualTo<T>(const value: T; const comparer: IEqualityComparer<T>): T; begin Result := Value; TMatcherFactory.Create<T>(ParamIndex, function(param : T) : boolean begin result := comparer.Equals(param,value); end); end; function ItRec.IsEqualTo<T>(const value : T) : T; begin Result := IsEqualTo<T>(value, DefaultComparer<T>); end; function ItRec.IsIn<T>(const values: TArray<T>): T; begin Result := IsIn<T>(values, DefaultComparer<T>); end; function ItRec.IsIn<T>(const values: IEnumerable<T>): T; begin Result := IsIn<T>(values, DefaultComparer<T>); end; function ItRec.IsIn<T>(const values: IEnumerable<T>; const comparer: IEqualityComparer<T>): T; begin result := Default(T); TMatcherFactory.Create<T>(ParamIndex, function(param : T) : boolean var value : T; begin result := false; for value in values do begin result := comparer.Equals(param,value); if result then exit; end; end); end; function ItRec.IsIn<T>(const values: TArray<T>; const comparer: IEqualityComparer<T>): T; begin result := Default(T); TMatcherFactory.Create<T>(ParamIndex, function(param : T) : boolean var value : T; begin result := false; for value in values do begin result := comparer.Equals(param,value); if result then exit; end; end); end; function ItRec.IsInRange<T>(const fromValue, toValue: T): T; begin result := Default(T); end; function ItRec.IsNotIn<T>(const values: TArray<T>): T; begin Result := IsNotIn<T>(values, DefaultComparer<T>); end; function ItRec.IsNotIn<T>(const values: IEnumerable<T>): T; begin Result := IsNotIn<T>(values, DefaultComparer<T>); end; function ItRec.IsNotIn<T>(const values: IEnumerable<T>; const comparer: IEqualityComparer<T>): T; begin result := Default(T); TMatcherFactory.Create<T>(ParamIndex, function(param : T) : boolean var value : T; begin result := true; for value in values do begin if comparer.Equals(param,value) then exit(false); end; end); end; function ItRec.IsNotIn<T>(const values: TArray<T>; const comparer: IEqualityComparer<T>): T; begin result := Default(T); TMatcherFactory.Create<T>(ParamIndex, function(param : T) : boolean var value : T; begin result := true; for value in values do begin if comparer.Equals(param,value) then exit(false); end; end); end; function ItRec.IsNotNil<T>: T; begin Result := IsNotNil<T>(DefaultComparer<T>); end; function ItRec.IsNotNil<T>(const comparer: IEqualityComparer<T>): T; begin result := Default(T); TMatcherFactory.Create<T>(ParamIndex, function(param : T) : boolean begin result := not comparer.Equals(param,Default(T)); end); end; function ItRec.Matches<T>(const predicate: TPredicate<T>): T; begin result := Default(T); TMatcherFactory.Create<T>(ParamIndex, predicate); end; //class function It.ParamIndex: integer; //begin // result := 0; //end; function ItRec.IsRegex(const regex : string; const options : TRegExOptions) : string; begin result := ''; TMatcherFactory.Create<string>(ParamIndex, function(param : string) : boolean begin result := TRegEx.IsMatch(param,regex,options) end); end; function It(const AParamIndx : Integer) : ItRec; begin result := ItRec.Create(AParamIndx); end; function It0 : ItRec; begin result := ItRec.Create(0); end; function It1 : ItRec; begin result := ItRec.Create(1); end; function It2 : ItRec; begin result := ItRec.Create(2); end; function It3 : ItRec; begin result := ItRec.Create(3); end; function It4 : ItRec; begin result := ItRec.Create(4); end; function It5 : ItRec; begin result := ItRec.Create(5); end; function It6 : ItRec; begin result := ItRec.Create(6); end; function It7 : ItRec; begin result := ItRec.Create(7); end; function It8 : ItRec; begin result := ItRec.Create(8); end; function It9 : ItRec; begin result := ItRec.Create(9); end; { TComparer } class function TComparer.CompareFields<T>(Param1, Param2: T): Boolean; var RTTI: TRttiContext; begin RTTI := TRttiContext.Create; Result := CompareMembers<TRttiField, T>(RTTI.GetType(TypeInfo(T)).GetFields, Param1, Param2); end; class function TComparer.CompareMembers<T, T2>(Members: TArray<T>; Param1, Param2: T2): Boolean; var PublicMember: TRttiMember; Instance1, Instance2, MemberValue1, MemberValue2: TValue; MemberType: TTypeKind; begin Instance1 := TValue.From<T2>(Param1); Instance2 := TValue.From<T2>(Param2); Result := SameValue(Instance1, Instance2); if not Result and not Instance1.IsEmpty and not Instance2.IsEmpty then begin Result := True; for PublicMember in Members do if PublicMember.Visibility in [mvPublic, mvPublished] then begin if PublicMember is TRttiProperty then begin MemberValue1 := TRttiProperty(PublicMember).GetValue(Instance1.AsPointer); MemberValue2 := TRttiProperty(PublicMember).GetValue(Instance2.AsPointer); MemberType := TRttiProperty(PublicMember).PropertyType.TypeKind; end else begin MemberValue1 := TRttiField(PublicMember).GetValue(Instance1.AsPointer); MemberValue2 := TRttiField(PublicMember).GetValue(Instance2.AsPointer); MemberType := TRttiField(PublicMember).FieldType.TypeKind; end; if MemberType = tkClass then Result := Result and CompareMembers<TRttiField, TObject>(MemberValue1.RttiType.GetFields, MemberValue1.AsObject, MemberValue2.AsObject) and CompareMembers<TRttiProperty, TObject>(MemberValue1.RttiType.GetProperties, MemberValue1.AsObject, MemberValue2.AsObject) else Result := Result and SameValue(MemberValue1, MemberValue2); end; end; end; class function TComparer.CompareProperties<T>(Param1, Param2: T): Boolean; var RTTI: TRttiContext; begin RTTI := TRttiContext.Create; Result := CompareMembers<TRttiProperty, T>(RTTI.GetType(TypeInfo(T)).GetProperties, Param1, Param2); end; end.
unit anysort; {$ifdef fpc}{$mode delphi}{$H+}{$endif} interface type TCompareFunc = function (const elem1, elem2): integer; procedure AnySort(var Arr; Count: Integer; Stride: Integer; CompareFunc: TCompareFunc; start:integer=0); implementation type TByteArray = array [Word] of byte; PByteArray = ^TByteArray; procedure AnyQuickSort(var Arr; idxL, idxH: Integer; Stride: Integer; CompareFunc: TCompareFunc; var SwapBuf, MedBuf); var ls,hs : Integer; //index * stride (width of type being sorted) li,hi : Integer; //index mi : Integer; //middle index: low + high div 2 ms : Integer; //middle index * stride pb : PByteArray;//pointer to byte array begin pb:=@Arr; li:=idxL; hi:=idxH; mi:=(li+hi) div 2; ls:=li*Stride; hs:=hi*Stride; ms:=mi*Stride; Move(pb[ms], medBuf, Stride); //move "stride" bytes from element ms of pb to medBuf repeat while CompareFunc( pb[ls], medBuf) < 0 do begin //while the value of the element at ls is less than the value of the element at medBuf inc(ls, Stride); //move ls by stride inc(li); //move li by 1 end; while CompareFunc( medBuf, pb[hs] ) < 0 do begin //while the value copied to medbuf is less than the value of the element at hs dec(hs, Stride); //move hs down by stride dec(hi); //move hi down by 1 end; //at this point the compare function must have returned 0 or 1 //so as long as the high index is above the low index we need to swap if ls <= hs then begin Move(pb[ls], SwapBuf, Stride); //move the element at ls to the swap buffer Move(pb[hs], pb[ls], Stride); //move the element at hs to ls Move(SwapBuf, pb[hs], Stride); //move the element in the swap buffer to hs // begin fix 11/11/2021: update ms if the reference point is moved if li=mi then ms:=hs; //if low index = mid index then set mid stride to high stride if hi=mi then ms:=ls; //if high index = mid index then set mid stride to low stride // end fix inc(ls, Stride); inc(li); //increase ls by stride and li by 1 dec(hs, Stride); dec(hi); //decrease hs by stride and hi by 1 end; until ls>hs; //continue until ls is greater than hs //idxL and idxH are the start and end points for sorting. For our purposes they're //0 and the length of the array -1 //so, if hi > 0 then call recursively from 0 to hi if hi>idxL then AnyQuickSort(Arr, idxL, hi, Stride, CompareFunc, SwapBuf, MedBuf); //and if li < pred(length(array)) call recursively from li to idxH if li<idxH then AnyQuickSort(Arr, li, idxH, Stride, CompareFunc, SwapBuf, MedBuf); end; procedure AnySort(var Arr; Count: Integer; Stride: Integer; CompareFunc: TCompareFunc; start:integer=0); type TByteArray = array of byte; var buf: TByteArray; begin buf:=TByteArray.create; if Count <= 1 then Exit; // should be more than 1 to be sortable SetLength(buf, Stride*2); //for an integer buf will then have a length of 8/ We pass the first element as //the swap buffer and the 4th element as the medBuf AnyQuickSort(Arr, start, Count-1+start, Stride, compareFunc, buf[0], buf[Stride]); end; end.
unit User; { Trida TUser reprezentuje jednoho uzivatele. Uzivatel se typicky vyznacuje - id (unikatni identifikacni string, napr. "root"), - krestnim jmenem a prijmenim, - flagy opravnujici ho k jednotlivym cinnostem (napr. \root, \regulator), - seznamem oblasti rizeni, ke kterym ma pristup, vcetne nejvyssi pristuppove urovne u kazde oblasti rizeni, kterou je schopen autorizovat. Uzivatel muze dostat ban, v takovem pripad je okamzite odpojen ze serveru a neni mu umoznen dalsi pristup. } interface uses IniFiles, Generics.Collections, DCPsha256, SysUtils, Classes, Generics.Defaults, TOblRizeni, Windows; const _SALT_LEN = 24; type TUser = class // trida reprezentujici uzivatele private fpasswd:string; // heslo - hash SHA256 fban:boolean; // flag urcujici ban uzivate freg:boolean; // flag urcijici moznost autorizovat regulator fid:string; // unikatni id fsalt:string; // sul hesla procedure SetPasswd(passwd:string); // nastavi heslo, viz \passwd procedure SetBan(state:boolean); // nastavi ban, viz \ban procedure SetReg(state:boolean); // nastavi regulator, viz \regulator procedure SetId(new:string); function GetFullName():string; // varti jsmeno uzivatele ve formatu: first_name [mezera] lastname class function GenSalt():string; public firstname:string; // krestni jmeno lastname:string; // prijmeni root:boolean; // flag opravneni root OblR: TDictionary<string, TORControlRights>; // seznam oblasti rizeni vcetne opravneni lastlogin:TDateTime; // cas posledniho loginu class var comparer: TComparison<TUser>; constructor Create(); overload; constructor Create(ini:TMemIniFile; section:string); overload; destructor Destroy(); override; procedure LoadData(ini:TMemIniFile; section:string); procedure SaveData(ini:TMemIniFile; section:string); procedure SaveStat(ini:TMemIniFile; section:string); function GetRights(OblR:string):TORCOntrolRights; // vrati opravneni k dane oblasti rizeni procedure SetRights(OblR:string; rights:TORControlRights); // nastavi opravneni dane oblasti rizeni property id:string read fid write SetId; property password:string read fpasswd write SetPasswd; property ban:boolean read fban write SetBan; property regulator:boolean read freg write SetReg; property fullName:string read GetFullName; property salt:string read fsalt; class function ComparePasswd(plain:string; hash:string; salt:string):boolean; // kontroluje shodu hesel; true poku hesla sedi, jinak false class function GenerateHash(plain:AnsiString):string; // generuje hash hesla end;//class TUser implementation uses TOblsRizeni, TCPServerOR, UserDb; //////////////////////////////////////////////////////////////////////////////// constructor TUser.Create(ini:TMemIniFile; section:string); begin inherited Create(); Self.OblR := TDictionary<string, TORControlRights>.Create(); Self.LoadData(ini, section); end;//ctor constructor TUser.Create(); begin Self.OblR := TDictionary<string, TORControlRights>.Create(); inherited Create(); end;//ctor destructor TUser.Destroy(); begin Self.OblR.Free(); inherited Destroy(); end;//dtor //////////////////////////////////////////////////////////////////////////////// procedure TUser.LoadData(ini:TMemIniFile; section:string); var i:Integer; data:TStrings; begin Self.OblR.Clear(); Self.fid := section; Self.fpasswd := ini.ReadString(section, 'passwd', ''); Self.root := ini.ReadBool(section, 'root', false); Self.firstname := ini.ReadString(section, 'fname', ''); Self.lastname := ini.ReadString(section, 'lname', ''); Self.fsalt := ini.ReadString(section, 'salt', ''); try Self.lastlogin := StrToDateTime(ini.ReadString(section, 'lastlogin', '')); except Self.lastlogin := 0; end; Self.fban := ini.ReadBool(section, 'ban', false); Self.freg := ini.ReadBool(section, 'reg', false); data := TStringList.Create(); ExtractStrings(['(', ')', ',', ';'], [], PChar(ini.ReadString(section, 'ORs', '')), data); for i := 0 to (data.Count div 2)-1 do begin try Self.OblR.Add(data[i*2], TORControlRights(StrToInt(data[i*2 + 1]))); except end; end;//for i data.Free(); end;//procedure procedure TUser.SaveData(ini:TMemIniFile; section:string); var i:Integer; rights:TORControlRights; str:string; begin Self.SaveStat(ini, section); ini.WriteString(section, 'passwd', Self.fpasswd); if (Self.root) then ini.WriteBool(section, 'root', Self.root); if (Self.firstname <> '') then ini.WriteString(section, 'fname', Self.firstname); if (Self.lastname <> '') then ini.WriteString(section, 'lname', Self.lastname); if (Self.ban) then ini.WriteBool(section, 'ban', Self.ban); if (Self.regulator) then ini.WriteBool(section, 'reg', Self.regulator); if (self.salt <> '') then ini.WriteString(section, 'salt', Self.fsalt); str := ''; for i := 0 to ORs.Count-1 do if (Self.OblR.TryGetValue(ORs.GetORIdByIndex(i), rights)) then str := str + '(' + ORs.GetORIdByIndex(i) + ';' + IntToStr(Integer(rights)) + ')'; if (str <> '') then ini.WriteString(section, 'ORs', str); end;//procedure procedure TUser.SaveStat(ini:TMemIniFile; section:string); begin ini.WriteString(section, 'lastlogin', DateTimeToStr(Self.lastlogin)); end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TUser.SetPasswd(passwd:string); begin // heslo je 2x zahashovane Self.fsalt := Self.GenSalt(); Self.fpasswd := TUser.GenerateHash(AnsiString(TUser.GenerateHash(AnsiString(passwd)) + self.fsalt)); end;//procedure //////////////////////////////////////////////////////////////////////////////// function TUser.GetRights(OblR:string):TORCOntrolRights; var rights:TORControlRights; begin if (Self.root) then Exit(TORCOntrolRights.superuser); if (Self.OblR.TryGetValue(OblR, rights)) then Result := rights else Result := null; end;//function //////////////////////////////////////////////////////////////////////////////// class function TUser.ComparePasswd(plain:string; hash:string; salt:string):boolean; begin Result := (hash = TUser.GenerateHash(AnsiString(LowerCase(plain + salt)))); end;//function class function TUser.GenerateHash(plain:AnsiString):string; var hash: TDCP_sha256; Digest: array[0..31] of byte; // RipeMD-160 produces a 160bit digest (20bytes) i:Integer; begin hash := TDCP_sha256.Create(nil); hash.Init(); hash.UpdateStr(plain); hash.Final(digest); hash.Free(); Result := ''; for i := 0 to 31 do Result := Result + IntToHex(Digest[i], 2); Result := LowerCase(Result); end;//function //////////////////////////////////////////////////////////////////////////////// procedure TUser.SetRights(OblR:string; rights:TORControlRights); var OblRRef:TOR; begin Self.OblR.AddOrSetValue(OblR, rights); ORs.GetORByIndex(ORs.GetORIndex(OblR), OblRRef); if (OblRRef <> nil) then OblRRef.UserUpdateRights(Self); end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TUser.SetBan(state:boolean); var oblr:string; OblRRef:TOR; begin if (Self.fban = state) then Exit(); Self.fban := state; if (Self.fban) then begin // user prave dostal BAN -> aktualizovat oblasti rizeni for oblr in Self.OblR.Keys do begin ORs.GetORByIndex(ORs.GetORIndex(oblr), OblRRef); if (OblRRef <> nil) then OblRRef.UserUpdateRights(Self); end; end; end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TUser.SetReg(state:boolean); begin if (Self.freg = state) then Exit(); Self.freg := state; if (not Self.freg) then ORTCPServer.DisconnectRegulatorUser(self); end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TUser.SetId(new:string); begin if (Self.id <> new) then begin Self.fid := new; UsrDB.Sort(); end; end; //////////////////////////////////////////////////////////////////////////////// function TUser.GetFullName():string; begin Result := Self.firstname + ' ' + Self.lastname; end; //////////////////////////////////////////////////////////////////////////////// class function TUser.GenSalt():string; var all:string; i, len:Integer; begin all := 'abcdefghijklmnopqrstuvwxyz0123456789'; len := Length(all); Result := ''; for i := 0 to _SALT_LEN-1 do Result := Result + all[Random(len)+1]; end; //////////////////////////////////////////////////////////////////////////////// initialization TUser.comparer := function (const Left, Right: TUser): Integer begin Result := AnsiCompareStr(Left.id, Right.id); end; finalization end.//unit
{$ifdef license} (* Copyright 2020 ChapmanWorld LLC ( https://chapmanworld.com ) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) {$endif} /// <exclude/> unit cwTest.TestCase.Console; {$ifdef fpc}{$mode delphiunicode}{$endif} interface uses cwTest ; type TStandardConsoleReport = class( TInterfacedObject, ITestReport ) private fCurrentTestSuite: string; fCurrentTestCase: string; fCurrentDepth: nativeuint; private procedure WriteDepth; strict private //- ITestReport -// procedure BeginTestSuite( const TestSuite: string ); procedure EndTestSuite; procedure BeginTestCase( const TestCase: string ); procedure EndTestCase; procedure RecordTestResult( const TestName: string; const TestResultState: TTestResult; const Reason: string ); public constructor Create; reintroduce; end; implementation procedure TStandardConsoleReport.BeginTestCase(const TestCase: string); begin fCurrentTestCase := TestCase; WriteDepth; Writeln('<TestCase name="',fCurrentTestCase,'">'); inc(fCurrentDepth); end; procedure TStandardConsoleReport.BeginTestSuite(const TestSuite: string); begin fCurrentTestSuite := TestSuite; fCurrentTestCase := ''; WriteDepth; Writeln('<TestSuite name="',fCurrentTestSuite,'">'); inc(fCurrentDepth); end; constructor TStandardConsoleReport.Create; begin inherited Create; fCurrentTestCase := ''; fCurrentTestSuite := ''; fCurrentDepth := 0; end; procedure TStandardConsoleReport.EndTestCase; begin WriteDepth; Writeln('<TestCase/>'); fCurrentTestCase := ''; dec(fCurrentDepth); end; procedure TStandardConsoleReport.EndTestSuite; begin WriteDepth; Writeln('<TestSuite/>'); fCurrentTestSuite := ''; fCurrentTestCase := ''; dec(fCurrentDepth); end; procedure TStandardConsoleReport.RecordTestResult(const TestName: string; const TestResultState: TTestResult; const Reason: string); var TestResultStr: string; begin case TestResultState of trSucceeded: TestResultStr := 'SUCCESS'; trFailed: TestResultStr := 'FAILED'; trError: TestResultStr := 'ERROR'; else begin TestResultStr := ''; end; end; WriteDepth; if TestResultState<>trSucceeded then begin Writeln('<Test name="',TestName,'" Result="',TestResultStr,'" Reason="'+Reason+'"/>'); end else begin Writeln('<Test name="',TestName,'" Result="',TestResultStr,'"/>'); end; end; procedure TStandardConsoleReport.WriteDepth; var idx: nativeuint; begin if fCurrentDepth=0 then begin exit; end; for idx := 0 to pred(fCurrentDepth) do begin Write(chr($09)); end; end; end.
{ Invokable interface ICalibrationWS } unit CalibrationWSIntf; interface uses InvokeRegistry, Types, XSBuiltIns, CommunicationObj; type ICalibrationWS = interface(IInvokable) ['{B585A686-C49A-4F5B-AD45-54802E973ECC}'] // ICalibration function Get_Potencia: Integer; safecall; function Get_CRadarPL: Single; safecall; function Get_CRadarPC: Single; safecall; function Get_PotMetPL: Single; safecall; function Get_PotMetPC: Single; safecall; function Get_MPS_Voltage: Double; safecall; function Get_Tx_Pulse_SP: Integer; safecall; function Get_Tx_Pulse_LP: Integer; safecall; function Get_Start_Sample_SP: Integer; safecall; function Get_Final_Sample_SP: Integer; safecall; function Get_Start_Sample_LP: Integer; safecall; function Get_Final_Sample_LP: Integer; safecall; function Get_Tx_Factor: Double; safecall; function Get_Stalo_Delay: Integer; safecall; function Get_Stalo_Step: Integer; safecall; function Get_Stalo_Width: Integer; safecall; function Get_Valid_tx_power: Double; safecall; function Get_Loop_Gain: Double; safecall; // ICalibrationControl procedure Set_Potencia(Value: Integer); safecall; procedure Set_CRadarPL(Value: Single); safecall; procedure Set_CRadarPC(Value: Single); safecall; procedure Set_MPS_Voltage(Value: Double); safecall; procedure Set_Tx_Pulse_SP(Value: Integer); safecall; procedure Set_Tx_Pulse_LP(Value: Integer); safecall; procedure Set_Start_Sample_SP(Value: Integer); safecall; procedure Set_Final_Sample_SP(Value: Integer); safecall; procedure Set_Start_Sample_LP(Value: Integer); safecall; procedure Set_Final_Sample_LP(Value: Integer); safecall; procedure Set_Tx_Factor(Value: Double); safecall; procedure Set_Stalo_Delay(Value: Integer); safecall; procedure Set_Stalo_Step(Value: Integer); safecall; procedure Set_Stalo_Width(Value: Integer); safecall; procedure Set_Valid_tx_power(Value: Double); safecall; procedure Set_Loop_Gain(Value: Double); safecall; procedure SaveDRX; safecall; // properties property Potencia: Integer read Get_Potencia write Set_Potencia; property CRadarPL: Single read Get_CRadarPL write Set_CRadarPL; property CRadarPC: Single read Get_CRadarPC write Set_CRadarPC; property PotMetPL: Single read Get_PotMetPL; property PotMetPC: Single read Get_PotMetPC; property MPS_Voltage: Double read Get_MPS_Voltage write Set_MPS_Voltage; property Tx_Pulse_SP: Integer read Get_Tx_Pulse_SP write Set_Tx_Pulse_SP; property Tx_Pulse_LP: Integer read Get_Tx_Pulse_LP write Set_Tx_Pulse_LP; property Start_Sample_SP: Integer read Get_Start_Sample_SP write Set_Start_Sample_SP; property Final_Sample_SP: Integer read Get_Final_Sample_SP write Set_Final_Sample_SP; property Start_Sample_LP: Integer read Get_Start_Sample_LP write Set_Start_Sample_LP; property Final_Sample_LP: Integer read Get_Final_Sample_LP write Set_Final_Sample_LP; property Tx_Factor: Double read Get_Tx_Factor write Set_Tx_Factor; property Stalo_Delay: Integer read Get_Stalo_Delay write Set_Stalo_Delay; property Stalo_Step: Integer read Get_Stalo_Step write Set_Stalo_Step; property Stalo_Width: Integer read Get_Stalo_Width write Set_Stalo_Width; property Valid_tx_power: Double read Get_Valid_tx_power write Set_Valid_tx_power; property Loop_Gain: Double read Get_Loop_Gain write Set_Loop_Gain; end; implementation end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.5 2004.10.27 9:17:46 AM czhower For TIdStrings Rev 1.4 7/28/04 11:43:32 PM RLebeau Bug fix for CleanupCookieList() Rev 1.3 2004.02.03 5:45:02 PM czhower Name changes Rev 1.2 1/22/2004 7:10:02 AM JPMugaas Tried to fix AnsiSameText depreciation. Rev 1.1 2004.01.21 1:04:54 PM czhower InitComponenet Rev 1.0 11/14/2002 02:16:26 PM JPMugaas 2001-Mar-31 Doychin Bondzhev - Added new method AddCookie2 that is called when we have Set-Cookie2 as response - The common code in AddCookie and AddCookie2 is now in DoAdd 2001-Mar-24 Doychin Bondzhev - Added OnNewCookie event This event is called for every new cookie. Can be used to ask the user program do we have to store this cookie in the cookie collection - Added new method AddCookie This calls the OnNewCookie event and if the result is true it adds the new cookie in the collection } unit IdCookieManager; { Implementation of the HTTP State Management Mechanism as specified in RFC 2109, 2965. Author: Doychin Bondzhev (doychin@dsoft-bg.com) Copyright: (c) Chad Z. Hower and The Indy Team. } interface {$i IdCompilerDefines.inc} uses Classes, IdBaseComponent, IdCookie, IdHeaderList, IdURI; Type TOnNewCookieEvent = procedure(ASender: TObject; ACookie: TIdCookieRFC2109; var VAccept: Boolean) of object; TOnCookieManagerEvent = procedure(ASender: TObject; ACookieCollection: TIdCookies) of object; TOnCookieCreateEvent = TOnCookieManagerEvent; TOnCookieDestroyEvent = TOnCookieManagerEvent; TIdCookieManager = class(TIdBaseComponent) protected FOnCreate: TOnCookieCreateEvent; FOnDestroy: TOnCookieDestroyEvent; FOnNewCookie: TOnNewCookieEvent; FCookieCollection: TIdCookies; procedure CleanupCookieList; procedure DoAddServerCookie(ACookie: TIdCookieRFC2109; ACookieText: String; AURL: TIdURI); procedure DoOnCreate; virtual; procedure DoOnDestroy; virtual; function DoOnNewCookie(ACookie: TIdCookieRFC2109): Boolean; virtual; procedure InitComponent; override; public destructor Destroy; override; // procedure AddServerCookie(const ACookie: String; AURL: TIdURI); procedure AddServerCookie2(const ACookie: String; AURL: TIdURI); procedure AddServerCookies(const ACookies: String; AURL: TIdURI); overload; procedure AddServerCookies(const ACookies: TStrings; AURL: TIdURI); overload; procedure AddServerCookies2(const ACookies: String; AURL: TIdURI); overload; procedure AddServerCookies2(const ACookies: TStrings; AURL: TIdURI); overload; procedure AddCookies(ASource: TIdCookieManager); procedure CopyCookie(ACookie: TIdCookieRFC2109); // procedure GenerateClientCookies(AURL: TIdURI; SecureOnly: Boolean; Headers: TIdHeaderList); // property CookieCollection: TIdCookies read FCookieCollection; published property OnCreate: TOnCookieCreateEvent read FOnCreate write FOnCreate; property OnDestroy: TOnCookieDestroyEvent read FOnDestroy write FOnDestroy; property OnNewCookie: TOnNewCookieEvent read FOnNewCookie write FOnNewCookie; end; //procedure SplitCookies(const ACookie: String; ACookies: TStrings); implementation uses IdAssignedNumbers, IdException, IdGlobal, IdGlobalProtocols, SysUtils; { TIdCookieManager } destructor TIdCookieManager.Destroy; begin CleanupCookieList; DoOnDestroy; FreeAndNil(FCookieCollection); inherited Destroy; end; procedure TIdCookieManager.GenerateClientCookies(AURL: TIdURI; SecureOnly: Boolean; Headers: TIdHeaderList); var I, J: Integer; LCookieList: TIdCookieList; LResultList: TList; LCookie: TIdNetscapeCookie; LRFC2965Needed: Boolean; begin { Per RFC 2109: When it sends a request to an origin server, the user agent sends a Cookie request header to the origin server if it has cookies that are applicable to the request, based on * the request-host; * the request-URI; * the cookie's age. } // check for expired cookies first... CleanupCookieList; LCookieList := CookieCollection.LockCookieList(caRead); try if LCookieList.Count > 0 then begin LResultList := TList.Create; try // Search for cookies for this domain and URI for J := 0 to LCookieList.Count-1 do begin LCookie := LCookieList.Cookies[J]; if LCookie.IsAllowed(AURL, SecureOnly) then begin LResultList.Add(LCookie); end; end; if LResultList.Count > 0 then begin { RLebeau: per RFC 2965: A user agent that supports both this specification and Netscape-style cookies SHOULD send a Cookie request header that follows the older Netscape specification if it received the cookie in a Set-Cookie response header and not in a Set-Cookie2 response header. However, it SHOULD send the following request header as well: Cookie2: $Version="1" The Cookie2 header advises the server that the user agent understands new-style cookies. If the server understands new-style cookies, as well, it SHOULD continue the stateful session by sending a Set- Cookie2 response header, rather than Set-Cookie. A server that does not understand new-style cookies will simply ignore the Cookie2 request header. } LRFC2965Needed := True; for I := 0 to LResultList.Count-1 do begin LCookie := TIdCookieRFC2109(LResultList.Items[I]); if LCookie is TIdCookieRFC2965 then begin Headers.AddValue('Cookie2', LCookie.ClientCookie); {Do not Localize} LRFC2965Needed := False; end else begin Headers.AddValue('Cookie', LCookie.ClientCookie); {Do not Localize} end; end; if LRFC2965Needed then begin Headers.AddValue('Cookie2', '$Version="1"'); {Do not Localize} end; end; finally LResultList.Free; end; end; finally CookieCollection.UnlockCookieList(caRead); end; end; procedure TIdCookieManager.DoAddServerCookie(ACookie: TIdCookieRFC2109; ACookieText: String; AURL: TIdURI); begin ACookie.ServerCookie := ACookieText; ACookie.ResolveDefaults(AURL); if not ACookie.IsRejected(AURL) then begin if DoOnNewCookie(ACookie) then begin FCookieCollection.AddCookie(ACookie); Exit; end; ACookie.Collection := nil; end; ACookie.Free; end; { procedure SplitCookies(const ACookie: String; ACookies: TStrings); var LTemp: String; I, LStart: Integer; begin LTemp := Trim(ACookie); I := 1; LStart := 1; while I <= Length(LTemp) do begin I := FindFirstOf('=;,', LTemp, -1, I); {do not localize if I = 0 then begin Break; end; if LTemp[I] = '=' then begin {Do not Localize I := FindFirstOf('";,', LTemp, -1, I+1); {do not localize if I = 0 then begin Break; end; if LTemp[I] = '"' then begin {Do not Localize I := FindFirstOf('"', LTemp, -1, I+1); {do not localize if I <> 0 then begin I := FindFirstOf(';,', LTemp, -1, I+1); {do not localize end; if I = 0 then begin Break; end; end; end; if LTemp[I] = ';' then begin Inc(I); Continue; end; ACookies.Add(Copy(LTemp, LStart, LStart-I)); Inc(I); LStart := I; end; if LStart <= Length(LTemp) then begin ACookies.Add(Copy(LTemp, LStart, MaxInt)); end; end; } procedure TIdCookieManager.AddServerCookie(const ACookie: String; AURL: TIdURI); var LCookie: TIdCookieRFC2109; begin LCookie := FCookieCollection.Add; DoAddServerCookie(LCookie, ACookie, AURL); end; type TIdCookieRFC2965Access = class(TIdCookieRFC2965) end; procedure TIdCookieManager.AddServerCookie2(const ACookie: String; AURL: TIdURI); var LCookie: TIdCookieRFC2965; begin LCookie := FCookieCollection.Add2; TIdCookieRFC2965Access(LCookie).FRecvPort := IndyStrToInt(AURL.Port, IdPORT_HTTP); DoAddServerCookie(LCookie, ACookie, AURL); end; procedure TIdCookieManager.AddCookies(ASource: TIdCookieManager); begin if (ASource <> nil) and (ASource <> Self) then begin FCookieCollection.AddCookies(ASource.CookieCollection); end; end; procedure TIdCookieManager.AddServerCookies(const ACookies: String; AURL: TIdURI); var LCookies, LCookie: String; begin LCookies := ACookies; while ExtractNextCookie(LCookies, LCookie, True) do begin AddServerCookie(LCookie, AURL); end; end; procedure TIdCookieManager.AddServerCookies(const ACookies: TStrings; AURL: TIdURI); var I: Integer; begin for I := 0 to ACookies.Count-1 do begin AddServerCookies(ACookies[I], AURL); end; end; procedure TIdCookieManager.AddServerCookies2(const ACookies: String; AURL: TIdURI); var LCookies, LCookie: String; begin LCookies := ACookies; while ExtractNextCookie(LCookies, LCookie, True) do begin AddServerCookie2(LCookie, AURL); end; end; procedure TIdCookieManager.AddServerCookies2(const ACookies: TStrings; AURL: TIdURI); var I: Integer; begin for I := 0 to ACookies.Count-1 do begin AddServerCookies2(ACookies[I], AURL); end; end; procedure TIdCookieManager.CopyCookie(ACookie: TIdCookieRFC2109); var LCookie: TIdCookieRFC2109; begin LCookie := TIdCookieRFC2109Class(ACookie.ClassType).Create(FCookieCollection); try LCookie.Assign(ACookie); ACookie.ResolveDefaults(nil); if LCookie.Domain <> '' then begin if DoOnNewCookie(LCookie) then begin FCookieCollection.AddCookie(LCookie); LCookie := nil; end; end; finally if LCookie <> nil then begin LCookie.Collection := nil; LCookie.Free; end; end; end; function TIdCookieManager.DoOnNewCookie(ACookie: TIdCookieRFC2109): Boolean; begin Result := True; if Assigned(FOnNewCookie) then begin OnNewCookie(Self, ACookie, Result); end; end; procedure TIdCookieManager.DoOnCreate; begin if Assigned(FOnCreate) then begin OnCreate(Self, FCookieCollection); end; end; procedure TIdCookieManager.DoOnDestroy; begin if Assigned(FOnDestroy) then begin OnDestroy(Self, FCookieCollection); end; end; procedure TIdCookieManager.CleanupCookieList; var LExpires: TDateTime; i, LLastCount: Integer; LCookieList: TIdCookieList; begin LCookieList := FCookieCollection.LockCookieList(caReadWrite); try for i := LCookieList.Count-1 downto 0 do begin LExpires := LCookieList.Cookies[i].Expires; if (LExpires <> 0.0) and (LExpires < Now) then begin // The Cookie has expired. It has to be removed from the collection LLastCount := LCookieList.Count; // RLebeau LCookieList.Cookies[i].Free; // RLebeau - the cookie may already be removed from the list via // its destructor. If that happens then doing so again below can // cause an "index out of bounds" error, so don't do it if not needed. if LLastCount = LCookieList.Count then begin LCookieList.Delete(i); end; end; end; finally FCookieCollection.UnlockCookieList(caReadWrite); end; end; procedure TIdCookieManager.InitComponent; begin inherited InitComponent; FCookieCollection := TIdCookies.Create(Self); DoOnCreate; end; end.
unit uPessoaDAO; interface uses Generics.Collections, SqlExpr, DB, Dialogs, uModelPessoa, SysUtils, DBAccess, Ora, MemDS, OraCall, Datasnap.DBClient, IPPeerClient, StrUtils, Data.DBXCommon; // type TPessoaDAO = class private FQuery : TOraquery; FPessoa: TPessoa; FListaPessoa : TList<TPessoa>; CONST SQLSELECT = 'SELECT * FROM PESSOA WHERE 1=1 '; SQLDELETE = 'DELETE FROM PESSOA WHERE CODIGO = :CODIGO'; SQLUDPATE = 'UPDATE PESSOA SET ' + 'CODIGO = :CODIGO, TIPOPESSOA = :TIPOPESSOA, DATACADASTRO = :DATACADASTRO, RG_IE = :RG_IE , CPF_CNPJ = :CPF_CNPJ, NOMEFANTASIA = :NOMEFANTASIA,' + 'RAZAOSOCIAL = :RAZAOSOCIAL, CEP = :CEP, ENDERECO = :ENDERECO, NUMERO = :NUMERO, BAIRRO = :BAIRRO, CIDADE = :CIDADE, UF = :UF, TELEFONE = :TELEFONE ,' + 'CELULAR = :CELULAR , TIPOCADASTRO = :TIPOCADASTRO, OBSERVACAO = :OBSERVACAO, INATIVO = :INATIVO WHERE CODIGO = :CODIGO;'; public procedure Salvar; function Consultar(pPessoa : TPessoa; pExibirMsgRegNotFound: boolean = False): TList<TPessoa>; function ConsultarCliente(): TList<TPessoa>; function ConsultarFornecedor(): TList<TPessoa>; function GerarProxCodigo(): Double; function Alterar: Boolean; function Excluir: Boolean; Constructor Create(pPessoa: TPessoa); end; implementation { TPessoaDAO } uses udmDados; function TPessoaDAO.Alterar: Boolean; begin FQuery.Close; FQuery.SQL.Clear; FQuery.SQL.Add(SQLUDPATE); FQuery.ParamByName('CODIGO').AsFloat := FPessoa.Codigo; FQuery.ParamByName('TIPOPESSOA').AsString := FPessoa.TipoPessoa; FQuery.ParamByName('DATACADASTRO').AsDateTime := FPessoa.DataCadastro; FQuery.ParamByName('RG_IE').AsString := FPessoa.RG_IE; FQuery.ParamByName('CPF_CNPJ').AsString := FPessoa.CPF_CNPJ; FQuery.ParamByName('NOMEFANTASIA').AsString := FPessoa.NomeFantasia; FQuery.ParamByName('RAZAOSOCIAL').AsString := FPessoa.RazaoSocial; FQuery.ParamByName('CEP').AsString := FPessoa.CEP; FQuery.ParamByName('ENDERECO').AsString := FPessoa.Endereco; FQuery.ParamByName('NUMERO').AsString := FPessoa.Numero; FQuery.ParamByName('BAIRRO').AsString := FPessoa.Bairro; FQuery.ParamByName('CIDADE').AsString := FPessoa.Cidade; FQuery.ParamByName('UF').AsString := FPessoa.UF; FQuery.ParamByName('TELEFONE').AsString := FPessoa.Telefone; FQuery.ParamByName('CELULAR').AsString := FPessoa.Celular; FQuery.ParamByName('TIPOCADASTRO').AsString := FPessoa.TipoCadastro; FQuery.ParamByName('OBSERVACAO').AsString := FPessoa.Observacao; FQuery.ParamByName('INATIVO').AsString := IfThen(FPessoa.Inativo = scAtivo, 'N', 'S'); FQuery.ExecSQL(); Result := true; end; function TPessoaDAO.ConsultarCliente: TList<TPessoa>; var pPessoa : TPessoa; begin; if FQuery.IsEmpty then begin FQuery.Close; FQuery.SQL.Clear; FQuery.SQL.Add(SQLSELECT); FQuery.SQL.Add(' WHERE TIPOCADASTRO=''C'' '); FQuery.Open; FQuery.First; while not FQuery.Eof do begin begin pPessoa := TPessoa.Create; pPessoa.Codigo := FQuery.FieldByName('CODIGO').AsFloat; pPessoa.TipoPessoa := FQuery.FieldByName('TIPOPESSOA').AsString; pPessoa.DataCadastro := FQuery.FieldByName('DATACADASTRO').AsDateTime; pPessoa.RG_IE := FQuery.FieldByName('RG_IE').AsString; pPessoa.CPF_CNPJ := FQuery.FieldByName('CPF_CNPJ').AsString; pPessoa.NomeFantasia := FQuery.FieldByName('NOMEFANTASIA').AsString; pPessoa.RazaoSocial := FQuery.FieldByName('RAZAOSOCIAL').AsString; pPessoa.CEP := FQuery.FieldByName('CEP').AsString; pPessoa.Endereco := FQuery.FieldByName('ENDERECO').AsString; pPessoa.Numero := FQuery.FieldByName('NUMERO').AsString; pPessoa.Bairro := FQuery.FieldByName('BAIRRO').AsString; pPessoa.Cidade := FQuery.FieldByName('CIDADE').AsString; pPessoa.UF := FQuery.FieldByName('UF').AsString; pPessoa.Telefone := FQuery.FieldByName('TELEFONE').AsString; pPessoa.Celular := FQuery.FieldByName('CELULAR').AsString; pPessoa.TipoCadastro := FQuery.FieldByName('TIPOCADASTRO').AsString; pPessoa.Observacao := FQuery.FieldByName('OBSERVACAO').AsString; pPessoa.Inativo := scInativo; FListaPessoa.Add(pPessoa); FQuery.Next; end; end; end; Result := FListaPessoa; end; function TPessoaDAO.ConsultarFornecedor: TList<TPessoa>; var pPessoa : TPessoa; begin; if FQuery.IsEmpty then begin FQuery.Close; FQuery.SQL.Clear; FQuery.SQL.Add(SQLSELECT); FQuery.SQL.Add(' WHERE TIPOCADASTRO=''F'' '); FQuery.Open; FQuery.First; while not FQuery.Eof do begin begin pPessoa := TPessoa.Create; pPessoa.Codigo := FQuery.FieldByName('CODIGO').AsFloat; pPessoa.TipoPessoa := FQuery.FieldByName('TIPOPESSOA').AsString; pPessoa.DataCadastro := FQuery.FieldByName('DATACADASTRO').AsDateTime; pPessoa.RG_IE := FQuery.FieldByName('RG_IE').AsString; pPessoa.CPF_CNPJ := FQuery.FieldByName('CPF_CNPJ').AsString; pPessoa.NomeFantasia := FQuery.FieldByName('NOMEFANTASIA').AsString; pPessoa.RazaoSocial := FQuery.FieldByName('RAZAOSOCIAL').AsString; pPessoa.CEP := FQuery.FieldByName('CEP').AsString; pPessoa.Endereco := FQuery.FieldByName('ENDERECO').AsString; pPessoa.Numero := FQuery.FieldByName('NUMERO').AsString; pPessoa.Bairro := FQuery.FieldByName('BAIRRO').AsString; pPessoa.Cidade := FQuery.FieldByName('CIDADE').AsString; pPessoa.UF := FQuery.FieldByName('UF').AsString; pPessoa.Telefone := FQuery.FieldByName('TELEFONE').AsString; pPessoa.Celular := FQuery.FieldByName('CELULAR').AsString; pPessoa.TipoCadastro := FQuery.FieldByName('TIPOCADASTRO').AsString; pPessoa.Observacao := FQuery.FieldByName('OBSERVACAO').AsString; pPessoa.Inativo := scAtivo; FListaPessoa.Add(pPessoa); FQuery.Next; end; end; end; Result := FListaPessoa; end; function TPessoaDAO.Consultar(pPessoa : TPessoa; pExibirMsgRegNotFound: boolean = False): TList<TPessoa>; var Pessoa : TPessoa; begin; if FQuery.IsEmpty then begin FQuery.Close; FQuery.SQL.Clear; FQuery.SQL.Add(SQLSELECT); if pPessoa.Codigo >= 0 then FQuery.SQL.Add(' AND CODIGO = ' + QuotedStr(FloatToStr(pPessoa.Codigo))); if ( pPessoa.TipoPessoa <> '' ) and ( pPessoa.TipoPessoa <> 'Todos') then FQuery.SQL.Add(' AND TIPOPESSOA = ' + UpperCase(QuotedStr(pPessoa.TipoPessoa))); if (pPessoa.TipoCadastro <> '') and (pPessoa.TipoCadastro <> 'Todos') then FQuery.SQL.Add(' AND TIPOCADASTRO = ' + UpperCase(QuotedStr(pPessoa.TipoCadastro))); if (pPessoa.CPF_CNPJ <> ' . . - ') and (pPessoa.CPF_CNPJ <> '') then FQuery.SQL.Add(' AND CPF_CNPJ = ' + QuotedStr(pPessoa.CPF_CNPJ)); if pPessoa.RazaoSocial <> '' then FQuery.SQL.Add(' AND RAZAOSOCIAL LIKE ' + QuotedStr('%'+ trim(UpperCase(pPessoa.RazaoSocial)) + '%')); if pPessoa.NomeFantasia <> '' then FQuery.SQL.Add(' AND NOMEFANTASIA LIKE ' + QuotedStr('%'+ trim(UpperCase(pPessoa.NomeFantasia)) + '%')); if pPessoa.Inativo = scAtivo then FQuery.SQL.Add(' AND INATIVO = ''N'' ') else if pPessoa.Inativo = scInativo then FQuery.SQL.Add(' AND INATIVO = ''S'' '); FQuery.SQL.Add(' ORDER BY CODIGO ASC ' ); FQuery.Open; FQuery.First; if (FQuery.Eof) and (pExibirMsgRegNotFound) then ShowMessage('Nenhum registro encontrado para esses filtros.' + #13 + 'Por favor, verifique!') else begin while not FQuery.Eof do begin begin Pessoa := TPessoa.Create; Pessoa.Codigo := FQuery.FieldByName('CODIGO').AsFloat; Pessoa.TipoPessoa := FQuery.FieldByName('TIPOPESSOA').AsString; Pessoa.DataCadastro := FQuery.FieldByName('DATACADASTRO').AsDateTime; Pessoa.RG_IE := FQuery.FieldByName('RG_IE').AsString; Pessoa.CPF_CNPJ := FQuery.FieldByName('CPF_CNPJ').AsString; Pessoa.NomeFantasia := FQuery.FieldByName('NOMEFANTASIA').AsString; Pessoa.RazaoSocial := FQuery.FieldByName('RAZAOSOCIAL').AsString; Pessoa.CEP := FQuery.FieldByName('CEP').AsString; Pessoa.Endereco := FQuery.FieldByName('ENDERECO').AsString; Pessoa.Numero := FQuery.FieldByName('NUMERO').AsString; Pessoa.Bairro := FQuery.FieldByName('BAIRRO').AsString; Pessoa.Cidade := FQuery.FieldByName('CIDADE').AsString; Pessoa.UF := FQuery.FieldByName('UF').AsString; Pessoa.Telefone := FQuery.FieldByName('TELEFONE').AsString; Pessoa.Celular := FQuery.FieldByName('CELULAR').AsString; Pessoa.TipoCadastro := FQuery.FieldByName('TIPOCADASTRO').AsString; Pessoa.Observacao := FQuery.FieldByName('OBSERVACAO').AsString; if FQuery.FieldByName('INATIVO').AsString = 'S' then Pessoa.Inativo := scInativo else Pessoa.Inativo := scAtivo; FListaPessoa.Add(Pessoa); FQuery.Next; end; end; end; end; Result := FListaPessoa; end; constructor TPessoaDAO.Create(pPessoa: TPessoa); begin FQuery := TOraquery.Create(nil); FQuery.Connection := udmDados.dmDados.OraSession ; FListaPessoa := TList<TPessoa>.Create; FPessoa := pPessoa; end; function TPessoaDAO.Excluir: Boolean; begin FQuery.Close; FQuery.SQL.Clear; if FPessoa.Inativo = scInativo then Abort ; FQuery.SQL.Add('UPDATE PESSOA SET INATIVO=''S'' WHERE CODIGO = :CODIGO'); FQuery.ParamByName('CODIGO').AsFloat := FPessoa.Codigo; FQuery.ExecSQL(); Result := true; end; function TPessoaDAO.GerarProxCodigo: Double; begin FQuery.Close; FQuery.SQL.Clear; FQuery.SQL.Add('SELECT SEQ_PESSOA.NEXTVAL CODIGO FROM DUAL'); FQuery.Open; Result := FQuery.FieldByName('CODIGO').AsFloat; end; procedure TPessoaDAO.Salvar; begin FQuery.Close; FQuery.SQL.Clear; FQuery.SQL.Add( ' INSERT INTO PESSOA(CODIGO, TIPOPESSOA, DATACADASTRO, RG_IE , CPF_CNPJ, NOMEFANTASIA, '); FQuery.SQL.Add( ' RAZAOSOCIAL, CEP, ENDERECO, NUMERO, BAIRRO, CIDADE, UF, TELEFONE, CELULAR, OBSERVACAO, TIPOCADASTRO, INATIVO) VALUES '); FQuery.SQL.Add( ' (:CODIGO, :TIPOPESSOA, :DATACADASTRO, :RG_IE , :CPF_CNPJ, :NOMEFANTASIA, :RAZAOSOCIAL, '); FQuery.SQL.Add( ' :CEP, :ENDERECO, :NUMERO, :BAIRRO, :CIDADE, :UF, :TELEFONE, :CELULAR, :OBSERVACAO, :TIPOCADASTRO, :INATIVO) '); FQuery.ParamByName('CODIGO').AsFloat := FPessoa.Codigo; FQuery.ParamByName('TIPOPESSOA').AsString := FPessoa.TipoPessoa; FQuery.ParamByName('DATACADASTRO').AsDate := FPessoa.DataCadastro; FQuery.ParamByName('RG_IE').AsString := FPessoa.RG_IE; FQuery.ParamByName('CPF_CNPJ').AsString := FPessoa.CPF_CNPJ; FQuery.ParamByName('NOMEFANTASIA').AsString := FPessoa.NomeFantasia; FQuery.ParamByName('RAZAOSOCIAL').AsString := FPessoa.RazaoSocial; FQuery.ParamByName('CEP').AsString := FPessoa.CEP; FQuery.ParamByName('ENDERECO').AsString := FPessoa.Endereco; FQuery.ParamByName('BAIRRO').AsString := FPessoa.Bairro; FQuery.ParamByName('CIDADE').AsString := FPessoa.Cidade; FQuery.ParamByName('UF').AsString := FPessoa.UF; FQuery.ParamByName('TELEFONE').AsString := FPessoa.Telefone; FQuery.ParamByName('CELULAR').AsString := FPessoa.Celular; FQuery.ParamByName('TIPOCADASTRO').AsString := FPessoa.TipoCadastro; FQuery.ParamByName('OBSERVACAO').AsString := FPessoa.Observacao; FQuery.ParamByName('INATIVO').AsString := 'N'; FQuery.ExecSQL(); end; end.
unit Bullet; interface uses FMX.Layouts, FMX.Objects, System.Classes, MoveGameObject, System.Threading, FMX.types; type TBullet = class(TMoveGameObject) private OwnerPanzer: TObject; timer: TTimer; procedure MoveBySide(Sender: TObject); procedure StartMove; procedure TryCrash; public constructor Create(AOwner: TComponent; OwnerPanzer: TObject); overload; constructor Create(AOwner: TComponent); overload; override; end; implementation uses Helper, Panzer; constructor TBullet.Create(AOwner: TComponent); begin inherited; Self.ObjectName := 'Bullet'; Self.Visible := True; end; procedure TBullet.MoveBySide(Sender: TObject); begin if Self.IsFreeWay then case Self.Side of TSide.Top: MovementTop(0.05); TSide.Bottom: MovementBot(0.05); TSide.Left: MovementLeft(0.05); TSide.Right: MovementRight(0.05); end else Self.TryCrash; end; procedure TBullet.StartMove; begin timer := TTimer.Create(Self); timer.Interval := 1; timer.OnTimer := Self.MoveBySide; timer.Enabled := True; end; procedure TBullet.TryCrash; begin TThread.Queue(nil, procedure() begin (OwnerPanzer as TPanzer).IsBulletFly := False; Self.timer.Enabled := False; Self.Release; end); end; constructor TBullet.Create(AOwner: TComponent; OwnerPanzer: TObject); var PosX, PosY: Integer; begin Self.Create(AOwner); Self.OwnerPanzer := OwnerPanzer; Self.Side := (OwnerPanzer as TPanzer).Side; if (Side = TSide.Top) or (Side = TSide.Bottom) then Self.Width := 2 * BLOCK_SIZE else Self.Height := 2 * BLOCK_SIZE; PosX := (Round((OwnerPanzer as TPanzer).Position.X) div BLOCK_SIZE) * BLOCK_SIZE; PosY := (Round((OwnerPanzer as TPanzer).Position.Y) div BLOCK_SIZE) * BLOCK_SIZE; Self.Position.X := PosX; Self.Position.Y := PosY; case Side of TSide.Right: begin Self.Position.X := PosX + BLOCK_SIZE; end; TSide.Bottom: begin Self.Position.Y := PosY + BLOCK_SIZE; end; end; Self.StartMove; end; end.
unit UPage; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. } interface //this is the real one uses Windows, Messages, SysUtils, Classes, Graphics, JPeg, Controls, Forms, Dialogs, Stdctrls, ExtCtrls, UClasses, UGlobals, UFileGlobals, UBase, UPgView, UCell, UInfoCell, UFiles, UPgAnnotation, UMessages; {Page Types defined in the Form Designer} const ptRegularPage = 1; ptTofC_Continued = 2; ptPhotoComps = 3; ptPhotoListings = 4; ptPhotoRentals = 5; ptMapLocation = 6; ptMapListings = 7; ptMapRental = 8; ptPhotoSubject = 9; ptPhotoSubExtra = 10; ptMapPlat = 11; ptMapFlood = 12; ptSketch = 13; ptExhibit = 14; ptExtraComps = 15; ptExtraListing = 16; ptExtraRental = 17; ptPhotoUntitled = 18; ptComments = 19; ptExhibitWoHeader = 20; ptExhibitFullPg = 21; ptMapOther = 22; ptPhotosUntitled6Photos = 23; type { TDocPage } TDocPage = class(TAppraisalPage) // this is one page in one form in TContainer protected procedure SetDisabled(const Value: Boolean); override; public FPgPrSpec: PagePrintSpecRec; //defined in globals (printIt, copies, Printer ID) pgDesc : TPageDesc; // ref to page in TDocForm's TPageDescList pgData : TDataCellList; // list of the page data cells (in UCell) pgInfo : TInfoCellList; // List of page info cells (in UInfoCell) pgCntls: TPageCntlList; // list of controls for this page (ie buttons) pgMarkups: TMarkUpList; // list of user annotation objects (in UPgAnnotation) pgDisplay: TPageBase; // obj that docView references for display FContextList: Array of TCntxItem; // list of context IDs on this page FLocalConTxList: Array of TCntxItem; // list of local context ids for form FModified: Boolean; // has pg been modified FPgFlags: LongInt; //page flags, inited from PgDesc, then saved with file FPgTitleName: String; //name of page for title and table of contents FPageNum: Integer; //Pg Number in report FPageTag: LongInt; //user defined storage area; used for context table PgIndex or anything else constructor Create(AParent: TAppraisalForm; thePgDesc: TPageDesc; Expanded: Boolean); virtual; destructor Destroy; override; constructor CreateForImport(AParent: TAppraisalForm; thePgDesc: TPageDesc; Expanded: Boolean; bShowMessage:Boolean); procedure Dispatch(const Msg: TDocumentMessageID; const Scope: TDocumentMessageScope; const Data: Pointer); override; procedure Notify(const Msg: TDocumentMessageID; const Data: Pointer); override; function HasData: Boolean; function HasContext: Boolean; function HasLocalContext: Boolean; procedure CreateDataCells; procedure CreateDataCells2(bShowMessage:Boolean=True); procedure CreateInfoCells(doc: TObject); procedure CreateControls(doc: TObject); procedure Assign(srcDocPage: TDocPage); procedure AssignPageTitle(srcDocPage: TDocPage); procedure AssignPageData(srcPgData: TDataCellList); procedure AssignPageDataInfo(srcPgInfo: TInfoCellList); procedure AssignPageMarkUps(srcPgMarks: TMarkUpList); function GetSelectedCell(x, y: Integer; var cellID: CellUID): TBaseCell; Function GetFirstCellInSequence(var cellIdx: integer): TBaseCell; Function GetLastCellInSequence(var cellIdx: integer): TBaseCell; Function GetCellIndexOf(firstInSeqence: Boolean): Integer; function GetCellByID(ID: Integer): TBaseCell; function GetCellByCellClass(clName: String): TBaseCell; function GetCellByXID(ID: Integer): TBaseCell; function GetCellByContxID(ID: Integer): TBaseCell; function GetLocalContext(locCntxID: Integer): String; Function GetPageNumber: Integer; Function GetTotalPgCount: Integer; procedure GetPageObjBounds(var objBounds: TRect); function GetPagePrintFactors(PrFrame: TRect; var PrOrg: TPoint; var PrScale: Integer): TRect; function SaveFormatChanges: Boolean; Procedure WritePageData(Stream: TStream); procedure ReadPageData(Stream: TStream; Version: Integer); function ReadPageDataForImport(Stream: TStream; Version: Integer; bShowMessage: Boolean=True):Boolean; { procedure ReadFutureDataSections(Stream: TFileStream); } procedure SkipPageData(Stream: TStream; Version: Integer); procedure ConvertPageData(Map: TObject; MapStart: Integer; Stream: TStream; Version: Integer; newCells: TList); function ReadPageDataSection1(Stream: TStream): PageSpecRec; procedure ReadPageDataInfoCells(PgSpec: PageSpecRec; Stream: TStream); Procedure WritePageText(var Stream: TextFile); //ascii text export Procedure ReadPageText(var Stream: TextFile); //ascii text import function SavePageAsImage(quality: double;fPath: String): Boolean; //jpeg file export function FindContextData(ContextID: Integer; var Str: String): Boolean; overload; function FindContextData(ContextID: Integer; out DataCell: TBaseCell): Boolean; overload; procedure BroadcastCellContext(ContextID: Integer; Str: String); overload; procedure BroadcastCellContext(ContextID: Integer; const Source: TBaseCell); overload; procedure BroadcastLocalCellContext(LocalCTxID: Integer; Str: String); overload; procedure BroadcastLocalCellContext(LocalCTxID: Integer; const Source: TBaseCell); overload; procedure BroadcastContext2Page(aPage: TDocPage; Flags: Byte = 0); procedure PopulateContextCells(Container: TComponent); //loads this page with context from the container procedure PopulateFromSimilarForm(AForm: TObject); //loads this page with data from cells with same ID procedure SetGlobalUserCellFormating; procedure SetGlobalLongCellFormating; procedure SetGlobalShortCellFormating; procedure SetGlobalHeaderCellFormating; procedure SetGlobalGridFormating(GridKind: Integer); procedure InstallBookMarkMenuItems; procedure RemoveBookMarkMenuItems; procedure LoadUserLogo; function GetSignatureTypes: TStringList; procedure UpdateSignature(const SigKind: String; SignIt, Setup: Boolean); procedure LoadLicensedUser(forceCOName: Boolean); //load the Co and User name on this page procedure UpdateInfoCell(icKind, icIndex: Integer; Value:Double; ValueStr: String); procedure DebugDisplayCellAttribute(value: Integer); Procedure ClearPageText; Procedure InvalidatePage; Procedure SetModifiedFlag; procedure SetDataModified(value: Boolean); procedure SetFormatModified(value: Boolean); procedure SetPgTitleName(const name: String); procedure SetCountPgFlag(Value: Boolean); procedure SetPgInContentFlag(Value: Boolean); function GetCountPgFlag: Boolean; function GetPgInContentFlag: Boolean; function GetPageOwnerID: LongInt; property DataModified: Boolean write SetDataModified; property FormatModified: Boolean write SetFormatModified; property CountThisPage: Boolean read GetCountPgFlag write SetCountPgFlag; property IsPageInContents: Boolean read GetPgInContentFlag write SetPgInContentFlag; property PgTitleName: string read FPgTitleName write SetPgTitleName; property PgTableContentsOffset: LongInt read FPageTag write FPageTag; function ReadPageMarkUps(Stream: TStream): Boolean; function WritePageMarkUps(Stream: TStream): Boolean; function ReadFutureData2(Stream: TStream): Boolean; function ReadFutureData3(Stream: TStream): Boolean; function ReadFutureData4(Stream: TStream): Boolean; function ReadFutureData5(Stream: TStream): Boolean; function ReadFutureData6(Stream: TStream): Boolean; function ReadFutureData7(Stream: TStream): Boolean; function ReadFutureData8(Stream: TStream): Boolean; function ReadFutureData9(Stream: TStream): Boolean; function ReadFutureData10(Stream: TStream): Boolean; function ReadFutureData11(Stream: TStream): Boolean; function ReadFutureData12(Stream: TStream): Boolean; function ReadFutureData13(Stream: TStream): Boolean; function ReadFutureData14(Stream: TStream): Boolean; function ReadFutureData15(Stream: TStream): Boolean; function ReadFutureData16(Stream: TStream): Boolean; function ReadFutureData17(Stream: TStream): Boolean; function ReadFutureData18(Stream: TStream): Boolean; function ReadFutureData19(Stream: TStream): Boolean; function ReadFutureData20(Stream: TStream): Boolean; function ReadFutureData21(Stream: TStream): Boolean; function ReadFutureData22(Stream: TStream): Boolean; function ReadFutureData23(Stream: TStream): Boolean; function ReadFutureData24(Stream: TStream): Boolean; function ReadFutureData25(Stream: TStream): Boolean; function WriteFutureData2(Stream: TStream): Boolean; function WriteFutureData3(Stream: TStream): Boolean; function WriteFutureData4(Stream: TStream): Boolean; function WriteFutureData5(Stream: TStream): Boolean; function WriteFutureData6(Stream: TStream): Boolean; function WriteFutureData7(Stream: TStream): Boolean; function WriteFutureData8(Stream: TStream): Boolean; function WriteFutureData9(Stream: TStream): Boolean; function WriteFutureData10(Stream: TStream): Boolean; function WriteFutureData11(Stream: TStream): Boolean; function WriteFutureData12(Stream: TStream): Boolean; function WriteFutureData13(Stream: TStream): Boolean; function WriteFutureData14(Stream: TStream): Boolean; function WriteFutureData15(Stream: TStream): Boolean; function WriteFutureData16(Stream: TStream): Boolean; function WriteFutureData17(Stream: TStream): Boolean; function WriteFutureData18(Stream: TStream): Boolean; function WriteFutureData19(Stream: TStream): Boolean; function WriteFutureData20(Stream: TStream): Boolean; function WriteFutureData21(Stream: TStream): Boolean; function WriteFutureData22(Stream: TStream): Boolean; function WriteFutureData23(Stream: TStream): Boolean; function WriteFutureData24(Stream: TStream): Boolean; function WriteFutureData25(Stream: TStream): Boolean; end; { TDocPageList } TDocPageList = class(TList) // just a list of docPages protected function Get(Index: Integer): TDocPage; procedure Put(Index: Integer; Item: TDocPage); public destructor Destroy; override; function First: TDocPage; function IndexOf(Item: TDocPage): Integer; function Last: TDocPage; function Remove(Item: TDocPage): Integer; property Pages[Index: Integer]: TDocPage read Get write Put; default; end; /// summary: A helper class for working with PageUID records. /// remarks: Delphi 2006 allows records to have methods. /// Integrate this class with PageUID when we upgrade Delphi. TPageUID = class class function Create(const Page: TDocPage): PageUID; overload; class function Create(const FormID: LongInt; const FormIdx: Integer; const PageIdx: Integer): PageUID; overload; class function GetPage(const Value: PageUID; const Document: TAppraisalReport): TDocPage; class function IsEqual(const Value1: PageUID; const Value2: PageUID): Boolean; class function IsNull(const Value: PageUID): Boolean; class function IsValid(const Value: PageUID; const Document: TAppraisalReport): Boolean; class function Null: PageUID; end; implementation Uses UContainer, UForm, UDraw, UStatus, UUtil1, UAppraisalIDs, UGridMgr,UEditor, {$IFDEF LOG_CELL_MAPPING} XLSReadWriteII2, {$ENDIF} UFileConvert, UFileUtils, UWinUtils; //Utility Function PageContainer(page: TDocPage): TContainer; begin result := TContainer(TDocForm(page.FParentForm).FParentDoc) end; function PageForm(Page: TDocPage): TDocForm; begin result := TDocForm(page.FParentForm); end; { TDocPage } procedure TDocPage.SetDisabled(const Value: Boolean); begin inherited; InvalidatePage; end; constructor TDocPage.Create(AParent: TAppraisalForm; thePgDesc: TPageDesc; Expanded: Boolean); var R: TRect; doc: TContainer; begin inherited Create; FParentForm := AParent; // reference to the form that owns this page FModified := False; FPgPrSpec.OK2Print := True; //init the print specs FPgPrSpec.Copies := 1; //copies of this page to print FPgPrSpec.PrIndex := 1; //use whatever printer is specified in docPrinter #1 PgDesc := thePgDesc; //ref the page description FPgTitleName := thePgDesc.PgName; //default name R := Rect(0,0,PgDesc.PgWidth, PgDesc.PgHeight); PgDisplay := TPageBase.Create(PageContainer(self).docView, R); PgDisplay.DataPage := Self; PgDisplay.Title := FPgTitleName; PgDisplay.Collapsed := not Expanded; SetLength(FContextList, 0); //set the page's context list to 0, we may not have any contexts ID on this page SetLength(FLocalConTxList, 0); //set pages local context list to 0... doc := PageContainer(self); PgData := TDataCellList.Create; PgInfo := TInfoCellList.Create; PgCntls := TPageCntlList.Create; PgMarkUps := TMarkupList.CreateList(PgDisplay.PgBody, PgDisplay.PgBody.Bounds); CreateDataCells; CreateInfoCells(doc); CreateControls(doc); PgDisplay.PgBody.PgDesc := PgDesc; //let display reference the Page Descriptions PgDisplay.PgBody.PgMarks := PgMarkUps; //let display reference the Page Annotatins PgDisplay.PgBody.RefItemList(PgData); //let display.body ref the data cells (stored in FItems) PgDisplay.PgBody.RefItemList(PgCntls); //add the controls list, makes it easy to click, draw, etc PgDisplay.PgBody.RefItemList(PgInfo); //add the infocells list, makes it easy to click, draw, etc FPgFlags := thePgDesc.PgFlags; //copy the page prefs, so they can be modified FPgFlags := SetBit2Flag(FPgFlags, bPgInPDFList, True); //### special until designer can set this flag FPgFlags := SetBit2Flag(FPgFlags, bPgInFAXList, True); //### special until designer can set this flag FPageNum := 0; //Pg Number in container (dynamic) FPageTag := 0; //user defined field end; constructor TDocPage.CreateForImport(AParent: TAppraisalForm; thePgDesc: TPageDesc; Expanded: Boolean; bShowMessage:Boolean); var R: TRect; doc: TContainer; begin inherited Create; FParentForm := AParent; // reference to the form that owns this page FModified := False; FPgPrSpec.OK2Print := True; //init the print specs FPgPrSpec.Copies := 1; //copies of this page to print FPgPrSpec.PrIndex := 1; //use whatever printer is specified in docPrinter #1 PgDesc := thePgDesc; //ref the page description FPgTitleName := thePgDesc.PgName; //default name R := Rect(0,0,PgDesc.PgWidth, PgDesc.PgHeight); PgDisplay := TPageBase.Create(PageContainer(self).docView, R); PgDisplay.DataPage := Self; PgDisplay.Title := FPgTitleName; PgDisplay.Collapsed := not Expanded; SetLength(FContextList, 0); //set the page's context list to 0, we may not have any contexts ID on this page SetLength(FLocalConTxList, 0); //set pages local context list to 0... doc := PageContainer(self); PgData := TDataCellList.Create; PgInfo := TInfoCellList.Create; PgCntls := TPageCntlList.Create; PgMarkUps := TMarkupList.CreateList(PgDisplay.PgBody, PgDisplay.PgBody.Bounds); CreateDataCells2(bShowMessage); CreateInfoCells(doc); CreateControls(doc); PgDisplay.PgBody.PgDesc := PgDesc; //let display reference the Page Descriptions PgDisplay.PgBody.PgMarks := PgMarkUps; //let display reference the Page Annotatins PgDisplay.PgBody.RefItemList(PgData); //let display.body ref the data cells (stored in FItems) PgDisplay.PgBody.RefItemList(PgCntls); //add the controls list, makes it easy to click, draw, etc PgDisplay.PgBody.RefItemList(PgInfo); //add the infocells list, makes it easy to click, draw, etc FPgFlags := thePgDesc.PgFlags; //copy the page prefs, so they can be modified FPgFlags := SetBit2Flag(FPgFlags, bPgInPDFList, True); //### special until designer can set this flag FPgFlags := SetBit2Flag(FPgFlags, bPgInFAXList, True); //### special until designer can set this flag FPageNum := 0; //Pg Number in container (dynamic) FPageTag := 0; //user defined field end; destructor TDocPage.Destroy; var doc: TContainer; begin doc := PageContainer(self); doc.docView.RemovePage(PgDisplay); //remove the display from docView list PgData.Free; //Free the cells objects and their data PgInfo.Free; //Free the info cells on this page PgCntls.Free; //free the controls on this page PgMarkUps.Free; //free all the annotations PgDisplay.Free; //free the display object inherited Destroy; //we're done, kill ourselves end; /// summary: Dispatches an event message up the document hierarchy until the /// specified scope has been reached, and then queues the message for // delivery to the objects within the scope. procedure TDocPage.Dispatch(const Msg: TDocumentMessageID; const Scope: TDocumentMessageScope; const Data: Pointer); var Notification: PNotificationMessageData; begin if (Scope <> DMS_PAGE) then begin // forward message to parent ParentForm.Dispatch(Msg, Scope, Data) end else begin // add to message queue New(Notification); Notification.Msg := Msg; Notification.Scope := Scope; Notification.Data := Data; Notification.NotifyProc := @TDocPage.Notify; Notification.NotifyInstance := Self; PostMessage(ParentForm.ParentDocument.Handle, WM_DOCUMENT_NOTIFICATION, 0, Integer(Notification)); end; end; /// summary: Notifies the object and child objects of event messages received. procedure TDocPage.Notify(const Msg: TDocumentMessageID; const Data: Pointer); var CellList: TCellList; Index: Integer; begin // notify cells CellList := TCellList.Create; try CellList.Assign(pgData); for Index := 0 to CellList.Count - 1 do CellList.Items[Index].Notify(Msg, Data); finally FreeAndNil(CellList); end; end; function TDocPage.HasData: Boolean; var c: Integer; begin c := 0; result := False; if PgData <> nil then while (not result) and (c < PgData.count) do begin result := PgData[c].HasData; inc(c); end; end; function TDocPage.HasContext: Boolean; begin result := length(FContextList) > 0; end; function TDocPage.HasLocalContext: Boolean; begin result := length(FLocalConTxList) > 0; end; Function TDocPage.GetPageNumber: Integer; begin result := FPageNum; end; Function TDocPage.GetTotalPgCount: Integer; begin result := TContainer(TDocForm(FParentForm).FParentDoc).docForm.TotalReportPages; end; function TDocPage.GetCountPgFlag: Boolean; begin result := IsBitSet(FPgFlags, bPgInPageCount); end; procedure TDocPage.SetCountPgFlag(Value: Boolean); begin // do stuff if we are changing // if value <> IsBitSet(FPgFlags, bPgInPageCount) then // begin end; FPgFlags := SetBit2Flag(FPgFlags, bPgInPageCount, value); if not value then FPageNum := 0; end; function TDocPage.GetPgInContentFlag: Boolean; begin result := IsBitSet(FPgFlags, bPgInContent); end; procedure TDocPage.SetPgInContentFlag(Value: Boolean); begin //## do stuff if we are changing // if value <> IsBitSet(FPgFlags, bPgInContent) then // begin end; FPgFlags := SetBit2Flag(FPgFlags, bPgInContent, value); end; function TDocPage.GetPageOwnerID: LongInt; begin result := TDocForm(FParentForm).frmInfo.fFormUID; end; procedure TDocPage.GetPageObjBounds(var objBounds: TRect); var i, Z: Integer; begin with pgDesc do //what is desc bounds begin {Text} if PgFormText <> nil then begin Z := PgFormText.count-1; for i := 0 to Z do with TPgFormTextItem(PgFormText[i]) do CalcFrameBounds(objBounds, strBox); end; {Objects} if PgFormObjs <> nil then begin Z := PgFormObjs.count-1; for i := 0 to Z do with TPgFormObjItem(PgFormObjs[i]) do CalcFrameBounds(objBounds, OBounds); end; {Picts} if PgFormPics <> nil then begin Z := PgFormPics.count-1; for i := 0 to z do with TPgFormGraphic(PgFormPics[i]) do CalcFrameBounds(objBounds, GBounds); end; end; //cells if PgData <> nil then begin Z := PgData.count-1; for i := 0 to Z do with PgData[i] do CalcFrameBounds(objBounds, FFrame); end; //Info Cells if pgInfo <> nil then begin Z := PgInfo.count-1; for i := 0 to Z do with PgInfo[i] do CalcFrameBounds(objBounds, bounds); end; end; //PrFrame is in printer coordinates function TDocPage.GetPagePrintFactors(PrFrame: TRect; var PrOrg: TPoint; var PrScale: Integer): TRect; var ObjFrame, ObjFrameX: TRect; ObjPt, PrPt: TPoint; Scale, ScaleH, ScaleV: Single; Hoff, Voff: Integer; begin ObjFrame.top := 10000; ObjFrame.bottom := -10000; ObjFrame.left := 10000; ObjFrame.right := -10000; GetPageObjBounds(ObjFrame); ObjFrameX := ScaleRect(ObjFrame, 72, PrScale); //scale to printer dimaensions ObjPt.x := ObjFrameX.right - ObjFrameX.left; //work in printer dimensions to make frame fit ObjPt.y := ObjFrameX.bottom - ObjFrameX.top; PrPt.x := PrFrame.right - PrFrame.left; PrPt.y := PrFrame.bottom - PrFrame.top; scaleV := 1.0; scaleH := 1.0; if ObjPt.x > PrPt.x then scaleH := PrPt.x / ObjPt.x; if ObjPt.y > PrPt.y then scaleV := PrPt.y / ObjPt.y; Scale := scaleV; if scaleH < scaleV then Scale := scaleH; PrScale := round(PrScale * Scale); //new scale ObjFrame := ScaleRect(objFrame, 72, PrScale); //scaled to fit within print area ObjPt.x := ObjFrame.right - ObjFrame.left; ObjPt.y := ObjFrame.bottom - ObjFrame.top; PrOrg := ObjFrame.topLeft; {this is new origin} Hoff := ((PrPt.x - ObjPt.x) div 2); Voff := ((ObjPt.y - PrPt.y) div 2); PrOrg.x := PrOrg.x - Hoff; //offsets so scaled page prints PrOrg.y := PrOrg.y + Voff; result := ObjFrame; end; procedure TDocPage.ClearPageText; var n: Integer; begin if pgData <> nil then for n := 0 to pgData.count -1 do PgData[n].Clear; end; procedure TDocPage.DebugDisplayCellAttribute(value: Integer); var n: Integer; {$IFDEF LOG_CELL_MAPPING} ColumnTitle : string; RowCounter, FoundCol : Integer; function FindTitleCol(const ATitle : string; var AColIndex, ASheetIndex : Integer) : Boolean; // case-sensitive, whole text match var SheetCounter, ColCounter : Integer; begin Result := False; for SheetCounter := 0 to CellMappingSpreadsheet.Sheets.Count - 1 do begin for ColCounter := 4 to CellMappingSpreadsheet.Sheets[SheetCounter].LastCol do begin if CellMappingSpreadsheet.Sheets[SheetCounter].AsString[ColCounter, 0] = ATitle then begin AColIndex := ColCounter; ASheetIndex := SheetCounter; Result := True; Break; end; end; end; end; const MAX_SHEET_COL = 255; {$ENDIF} begin PushMouseCursor(crHourGlass); try {$IFDEF LOG_CELL_MAPPING} if value = dbugShowCellID then begin if CellMappingSpreadsheet = nil then begin CellMappingSpreadsheet := TXLSReadWriteII2.Create(Application); CellMappingSpreadsheet.Filename := CELL_MAPPING_FILE_NAME; end; with CellMappingSpreadsheet do try if SysUtils.FileExists(Filename) then Read; ColumnTitle := PgTitleName + ' [' + IntToStr(TDocForm(FParentForm).FormID) + ']'; if FindTitleCol(ColumnTitle, FoundCol, CellMappingSheetIndex) then begin CellMappingNextCell := Point(FoundCol, 1); // start data on row 2 for RowCounter := 1 to Sheets[0].LastRow do Sheets[CellMappingSheetIndex].AsBlank[FoundCol, RowCounter] := True; // clear previous data end else begin CellMappingSheetIndex := 0; while (Sheets[CellMappingSheetIndex].LastCol >= MAX_SHEET_COL) do begin if CellMappingSheetIndex = Sheets.Count - 1 then Sheets.Add; Inc(CellMappingSheetIndex); end; if Sheets[CellMappingSheetIndex].LastCol > 2 then CellMappingNextCell := Point(Sheets[CellMappingSheetIndex].LastCol + 1, 1) // start data on row 2 else CellMappingNextCell := Point(5, 1) // start on column F, row 2 end; Sheets[CellMappingSheetIndex].AsString[CellMappingNextCell.X, 0] := ColumnTitle; except // crashes seem to corrupt the component CellMappingSpreadsheet.Free; CellMappingSpreadsheet := nil; raise; end; end; {$ENDIF} ClearPageText; //clear previous data first if pgData <> nil then for n := 0 to pgData.count -1 do case value of dbugShowCellNum: PgData[n].SetCellNumber(n+1); dbugShowMathID: PgData[n].DisplayCellMathID; dbugShowCellID: PgData[n].DisplayCellID; dbugShowRspID: PgData[n].DisplayCellRspIDs; dbugShowSample: PgData[n].SetCellSampleEntry; dbugShowContext: PgData[n].DisplayCellGlobalContext; dbugShowLocContxt: PgData[n].DisplayCellLocalContext; dbugSpecial: PgData[n].DebugSpecial; dbugShowXMLID: PgData[n].DisplayCellXID; end; {$IFDEF LOG_CELL_MAPPING} if value = dbugShowCellID then CellMappingSpreadsheet.Write; {$ENDIF} finally PopMouseCursor; end; end; function TDocPage.GetCellByID(ID: Integer): TBaseCell; var c: Integer; begin result := nil; c := 0; if (PgData <> nil) then while (result = nil) and (c < PgData.count) do begin if PgData[c].FCellID = ID then result := PgData[c]; inc(c); end; end; function TDocPage.GetCellByCellClass(clName: String): TBaseCell; var c: Integer; begin result := nil; c := 0; if (PgData <> nil) then while (result = nil) and (c < PgData.count) do begin if PgData[c].ClassNameIs(clName) then result := PgData[c]; inc(c); end; end; function TDocPage.GetCellByXID(ID: Integer): TBaseCell; var c: Integer; begin result := nil; c := 0; if (PgData <> nil) then while (result = nil) and (c < PgData.count) do begin if PgData[c].FCellXID = ID then result := PgData[c]; inc(c); end; end; //find first cell with this context ID on this page function TDocPage.GetCellByContxID(ID: Integer): TBaseCell; var c: Integer; begin result := nil; c := 0; if (PgData <> nil) then while (result = nil) and (c < PgData.count) do begin if PgData[c].FContextID = ID then result := PgData[c]; inc(c); end; end; // the first cell is not necessarily the first cell in sequence function TDocPage.GetCellIndexOf(firstInSeqence: Boolean): Integer; var i: integer; foundIt: Boolean; begin foundIt := False; result := 0; if firstInSeqence then //start at top begin i := 0; while (i < PgDesc.PgNumCells) and not foundIt do begin foundIt := (PgDesc.PgCellSeq^[i].SPrev = -1); if foundIt then result := i; inc(i); end; end else //then last check from bottom begin i := PgDesc.PgNumCells; while (i > 0) and not foundIt do begin dec(i); foundIt := (PgDesc.PgCellSeq^[i].SNext = -1); if foundIt then result := i; end; end; end; function TDocPage.GetFirstCellInSequence(var cellIdx: integer): TBaseCell; var i: integer; foundIt: Boolean; begin i := 0; foundIt := False; while (i < PgDesc.PgNumCells) and not foundIt do begin foundIt := (PgDesc.PgCellSeq^[i].SPrev = -1); //-1 terminates the sequence inc(i); end; if foundIt then begin cellIdx := i-1; result := PgData[cellIdx]; end else result := nil; end; function TDocPage.GetLastCellInSequence(var cellIdx: integer): TBaseCell; var i: integer; foundIt: Boolean; begin i := PgDesc.PgNumCells; foundIt := False; while (i > 0) and not foundIt do begin dec(i); foundIt := (PgDesc.PgCellSeq^[i].SNext = -1); end; if foundIt then begin cellIdx := i; result := PgData[cellIdx]; end else result := nil; end; function TDocPage.GetSelectedCell(x, y: Integer; var cellID: CellUID): TBaseCell; var i: Integer; cell: TBaseCell; begin cell:= nil; if PgData <> nil then begin i := 0; repeat if PtInRect(PgData[i].FFrame, Point(x,y)) then begin cell := PgData[i]; cellID.num := i; end; inc(i); until (i = PgData.Count) or (cell <> nil); end; result := cell; end; //Could be moved to UInfoCells and consolidate infoCell stuff procedure TDocPage.CreateInfoCells(doc: TObject); var i: Integer; theCell: TInfoCell; viewParent: TObject; begin if PgDesc <> nil then if PgDesc.PgInfoItems <> nil then with PgDesc.PgInfoItems do begin viewParent := PgDisplay.PgBody; PgInfo.capacity := count; for i := 0 to count -1 do with TPgFormInfoItem(PgDesc.PgInfoItems[i]) do begin case IType of icProgName: theCell := TProgInfo.Create(viewParent, IRect); icPageNote: theCell := TPageNote.Create(viewParent, IRect); icInfoBox: theCell := TValInfo.Create(viewParent, IRect); icAvgBox: theCell := TAvgInfo.Create(viewParent, IRect); icGrossNet: theCell := TGrsNetInfo.Create(viewParent, IRect); icTextBox: theCell := TTextInfo.Create(viewParent, IRect); icSignature: theCell := TSignatureCell.Create(viewParent, IRect); else theCell := nil; end; if assigned(theCell) then begin theCell.ParentViewPage := TPageArea(viewParent).ParentViewPage; theCell.FType := IType; theCell.FDoc := doc; theCell.FFill := IFill; theCell.FJust := IJust; theCell.FHasPercent := (IHasPercent>0); theCell.FIndex := IIndex; theCell.Text := IText; theCell.Value := IValue; PgInfo.add(theCell); end; end; end; end; //Creates the User Controls: buttons, etc. procedure TDocPage.CreateControls(doc: TObject); var i: Integer; theCntl: TPgStdButton; viewParent: TObject; begin if PgDesc <> nil then if PgDesc.PgFormCntls <> nil then with PgDesc.PgFormCntls do begin viewParent := PgDisplay.PgBody; PgCntls.capacity := count; for i := 0 to count -1 do with TPgFormUserCntl(PgDesc.PgFormCntls[i]) do begin theCntl := TPgStdButton.Create(viewParent, UBounds); theCntl.ParentViewPage := TPageArea(viewParent).ParentViewPage; theCntl.Caption := UCaption; //button caption theCntl.ClickCmd := UClickCmd; //these are pre-assigned commands theCntl.LoadCmd := ULoadCmd; //ditto theCntl.OnClick := TContainer(doc).ProcessCommand; //this is where action happens PgCntls.add(theCntl); end; end; end; //Creates the Cells procedure TDocPage.CreateDataCells; var c, m,n, cellType, cellSubType: Integer; theCell: TBaseCell; viewParent: TObject; theCellDef: TCellDesc; ContxtItem: TCntxItem; begin if PgDesc <> nil then if PgDesc.PgNumCells > 0 then begin viewParent := PgDisplay.PgBody; PgData.Capacity := PgDesc.PgNumCells; // make it this big SetLength(FContextList, PgDesc.PgFormCells.CountContextIDs); //count context IDs SetLength(FLocalConTxList, PgDesc.PgFormCells.CountLocalConTxIDs); //count local Cntx IDs m:= 0; n := 0; for c := 0 to PgDesc.PgNumCells-1 do begin theCellDef := PgDesc.PgFormCells[c]; cellType := HiWord(theCellDef.CTypes); cellSubType := LoWord(theCellDef.CTypes); theCell := ConstructCell(cellType, cellSubType, self, viewParent, theCellDef); PgData.Add(theCell); //add the cell to the list //get list of global contexts if theCellDef.CContextID > 0 then //add context if we have one for this cell begin ContxtItem.CntxtID := theCellDef.CContextID; //context of the cell ContxtItem.CellIndex := c; //the cell's index in list FContextList[n] := ContxtItem; inc(n); end; //Get list of Local contexts if theCellDef.CLocalConTxID > 0 then //add context if we have one for this cell begin ContxtItem.CntxtID := theCellDef.CLocalConTxID; //context of the cell ContxtItem.CellIndex := c; //the cell's index in list FLocalConTxList[m] := ContxtItem; inc(m); end; end; // for c end; // if numcells > 0 end; //Creates the Cells procedure TDocPage.CreateDataCells2(bShowMessage:Boolean=True); var c, m,n, cellType, cellSubType: Integer; theCell: TBaseCell; viewParent: TObject; theCellDef: TCellDesc; ContxtItem: TCntxItem; begin if PgDesc <> nil then if PgDesc.PgNumCells > 0 then begin viewParent := PgDisplay.PgBody; PgData.Capacity := PgDesc.PgNumCells; // make it this big SetLength(FContextList, PgDesc.PgFormCells.CountContextIDs); //count context IDs SetLength(FLocalConTxList, PgDesc.PgFormCells.CountLocalConTxIDs); //count local Cntx IDs m:= 0; n := 0; for c := 0 to PgDesc.PgNumCells-1 do begin theCellDef := PgDesc.PgFormCells[c]; cellType := HiWord(theCellDef.CTypes); cellSubType := LoWord(theCellDef.CTypes); theCell := ConstructCell(cellType, cellSubType, self, viewParent, theCellDef); PgData.Add(theCell); //add the cell to the list //get list of global contexts if theCellDef.CContextID > 0 then //add context if we have one for this cell begin ContxtItem.CntxtID := theCellDef.CContextID; //context of the cell ContxtItem.CellIndex := c; //the cell's index in list FContextList[n] := ContxtItem; inc(n); end; //Get list of Local contexts if theCellDef.CLocalConTxID > 0 then //add context if we have one for this cell begin ContxtItem.CntxtID := theCellDef.CLocalConTxID; //context of the cell ContxtItem.CellIndex := c; //the cell's index in list FLocalConTxList[m] := ContxtItem; inc(m); end; end; // for c end; // if numcells > 0 end; procedure TDocPage.Assign(srcDocPage: TDocPage); begin if assigned(srcDocPage) then begin AssignPageTitle(srcDocPage); //title if assigned(srcDocPage.pgData) then AssignPageData(srcDocPage.pgData); //cell text, metaData, labels if assigned(srcDocPage.pgInfo) then AssignPageDataInfo(srcDocPage.pgInfo); //info cells if assigned(srcDocPage.pgMarkups) then AssignPageMarkUps(srcDocPage.pgMarkups); //free text end; end; procedure TDocPage.AssignPageTitle(srcDocPage: TDocPage); begin PgTitleName := srcDocPage.FPgTitleName; //calls SetPgTitleName & updates TofC & PgList end; procedure TDocPage.AssignPageData(srcPgData:TDataCellList); var c, Z, dupZ: Integer; begin //### be careful- eventually we will copy cells to pages that did not have any cells to start with: Exhibit pages if (PgData <> nil) and (srcPgData <> nil) then //make sure we have some cells begin Z := PgData.count; dupZ := srcPgData.count; if Z = dupZ then //make sure we have same number begin for c := 0 to Z-1 do //iterate on the cells begin PgData[c].Assign(srcPgData[c]); end; end; end; end; procedure TDocPage.AssignPageDataInfo(srcPgInfo: TInfoCellList); var c, Z, dupZ: Integer; begin if Assigned(pgInfo) and Assigned(srcPgInfo) then //make sure we have some info cells begin Z := pgInfo.count; dupZ := srcPgInfo.count; if Z = dupZ then //###make sure we have same number, for now... begin for c := 0 to Z-1 do //iterate on the cells begin pgInfo[c].Assign(srcPgInfo[c]); end; end; end; end; procedure TDocPage.AssignPageMarkUps(srcPgMarks: TMarkUpList); begin if assigned(srcPgMarks) then pgMarkups.Assign(srcPgMarks); //these marks are FreeForm text, etc end; procedure TDocPage.ReadPageDataInfoCells(PgSpec: PageSpecRec; Stream: TStream); var nCell: Integer; begin if PgSpec.fNumInfoCells > 0 then //file has some begin if pgInfo <> nil then //form has some if pgInfo.count <> PgSpec.fNumInfoCells then //form and file different for nCell := 0 to PgSpec.fNumInfoCells-1 do //then skip them all SkipInfoCell(stream) else for nCell := 0 to PgSpec.fNumInfoCells-1 do pgInfo[nCell].ReadCellData(Stream) else //form has no Info cell for nCell := 0 to PgSpec.fNumInfoCells-1 do //file does SkipInfoCell(stream) //so skip them all end; end; function TDocPage.ReadPageDataSection1(Stream: TStream): PageSpecRec; var amt: Integer; PgSpec: PageSpecRec; begin try amt := SizeOf(PageSpecRec); Stream.Read(PgSpec, amt); //read the page spec FPgTitleName := PgSpec.fPgTitle; //set the name stored in file FPgFlags := PgSpec.fPgPrefs; //set page pref flags //read the page annotations, free text ReadPageMarkUps(Stream); //added March-2005 ReadFutureData2(Stream); ReadFutureData3(Stream); ReadFutureData4(Stream); ReadFutureData5(Stream); ReadFutureData6(Stream); ReadFutureData7(Stream); ReadFutureData8(Stream); ReadFutureData9(Stream); ReadFutureData10(Stream); ReadFutureData11(Stream); ReadFutureData12(Stream); ReadFutureData13(Stream); ReadFutureData14(Stream); ReadFutureData15(Stream); ReadFutureData16(Stream); ReadFutureData17(Stream); ReadFutureData18(Stream); ReadFutureData19(Stream); ReadFutureData20(Stream); ReadFutureData21(Stream); ReadFutureData22(Stream); ReadFutureData23(Stream); ReadFutureData24(Stream); ReadFutureData25(Stream); amt := SizeOf(PagePrintSpecRec); Stream.Read(FPgPrSpec, amt); //read the print spec PgDisplay.ReadBookMarks(stream); //read any page bookmarks result := PgSpec; except on E:Exception do end; end; procedure TDocPage.ConvertPageData(Map: TObject; MapStart: Integer; Stream: TStream; Version: Integer; newCells: TList); const MaxRevisionCmds = 10; var n, Cmd, oldCell, newCell: Integer; StoredData: String; PgSpec: PageSpecRec; doc: TContainer; RevMap: TFormRevMap; bCellTypeChanged: Boolean; //YF 03.25.03 oldCellType,newCellType: Integer; begin PgSpec := ReadPageDataSection1(Stream); //read page spec rec doc := PageContainer(self); //so we can display progress bar doc.SetProgressBarNote('Converting '+PgSpec.fPgTitle); //convert the data cells StoredData := ''; RevMap := TFormRevMap(Map); if pgData <> nil then //we have data cells (new verison) for n := 0 to PgSpec.fNumCells-1 do begin RevMap.GetMapValues(n+MapStart, Cmd, oldCell, newCell); //read revision map line by line oldCellType := -1; //means the same as the new cell bCellTypeChanged := cmd div MaxRevisionCmds > 0; cmd := cmd mod MaxRevisionCmds; if (newCell < 0) and (Cmd = 0) then //in conversion file newcell = 0, here its -1 SkipCellData(Self, PgDisplay.PgBody, Stream, Version) else if n = oldcell then //one for one conversion begin if (NewCell < 0) then newCell := oldCell; //old cell was skipped, but need to save its data if bCellTypeChanged then oldCellType := GetCellTypeFromStream(stream); newCellType := pgData[newCell].FType; if (oldCellType = -1) or (oldCellType = newCellType) then pgData[newCell].ReadCellData(Stream, Version) else if (newCellType = cSingleLn) and (oldCellType = cMultiLn) then (TTextCell(pgData[newCell])).ReadMlnCellData(stream) else if (newCellType = cMultiLn) and (oldCellType = cSingleLn) then (TMLnTextCell(pgData[newCell])).ReadTextCellData(stream) else cmd := -1; // to skip this cell case Cmd of 0: //reg process - do nothing ; 1: //store data if length(StoredData)> 0 then StoredData := StoredData +' '+ pgData[newCell].Text else StoredData := pgData[newCell].Text; 2: //add stored data to this cell begin if (length(StoredData)>0) and (length(pgData[newCell].Text)>0) then // pgData[newCell].LoadContent(StoredData + ' '+ pgData[newCell].Text, False); pgData[newCell].Text := StoredData + ' '+ pgData[newCell].Text; StoredData := ''; end; else {-1 or 3, skip the cell} SkipCellData(Self, PgDisplay.PgBody, Stream, Version); end; if bCellTypeChanged and (newCellType = cMultiLn) then (TMLnTextCell(pgData[newCell])).LoadContent(pgData[newCell].Text,False); end else ShowNotice(PgSpec.fPgTitle + ': Number of cells is not equal to number of conversion map rows.'); end; if pgData.Count > pgSpec.fNumCells then for n := pgSpec.fNumCells + 1 to pgData.Count do if assigned(pgData[n-1]) then newCells.Add(pgData[n-1]); {Read the Info Cells} ReadPageDataInfoCells(PgSpec, Stream); doc.IncrementProgressBar; end; procedure TDocPage.SkipPageData(Stream: TStream; Version: Integer); var PgSpec: PageSpecRec; viewParent: TObject; doc: TContainer; n: Integer; begin PgSpec := ReadPageDataSection1(Stream); //Load Page Spec Rec doc := PageContainer(self); //so we can display progress bar doc.SetProgressBarNote('Skipping '+PgSpec.fPgTitle); viewParent := PgDisplay.PgBody; if PgSpec.fNumCells > 0 then //skip this number of cells for n := 1 to PgSpec.fNumCells do begin SkipCellData(self, viewParent, Stream, Version); //#### create a cell, read the file with it and // add the cell to the PgData list. // It will not be visible, the data will not be lost end; ReadPageDataInfoCells(PgSpec, Stream); //reads or skips doc.IncrementProgressBar; end; procedure TDocPage.ReadPageData(Stream: TStream; Version: Integer); var nCell: Integer; PgSpec: PageSpecRec; Ok2Read: Boolean; doc: TContainer; begin Ok2Read := true; PgSpec := ReadPageDataSection1(Stream); //Load Page Spec Rec doc := PageContainer(self); //so we can display progress bar doc.SetProgressBarNote('Reading '+PgSpec.fPgTitle); {Read the Data Cells} if PgSpec.fNumCells > 0 then //read any data cells that were saved if pgData <> nil then // if we have preconfigured empty cells begin {ok2Read := True; } if pgData.count <> PgSpec.fNumCells then Ok2Read := Ok2Read and OK2Continue('The number of fields on the page in this file DO NOT match the number of cells in the page. Do you want to continue?'); //force check of reading file Ok2Read := Ok2Read and (pgData.count = PgSpec.fNumCells); if OK2Read then for nCell := 0 to pgData.Count-1 do pgData[nCell].ReadCellData(Stream, Version); //each cell knowns how to read its own stuff. end else //we need to reconstruct the pgData List from saved cell info begin // ### rebuild cell stuff here. end; {Read the Info Cells} ReadPageDataInfoCells(PgSpec, Stream); end; function TDocPage.ReadPageDataForImport(Stream: TStream; Version: Integer; bShowMessage: Boolean=True):Boolean; var nCell: Integer; PgSpec: PageSpecRec; Ok2Read: Boolean; doc: TContainer; begin try Ok2Read := True; result := OK2Read; try try PgSpec := ReadPageDataSection1(Stream); except on E:Exception do begin // showmessage('exception ReadPageDataSection1'+e.Message); result := False; Exit; end; end; doc := PageContainer(self); //so we can display progress bar doc.SetProgressBarNote('Reading '+PgSpec.fPgTitle); {Read the Data Cells} if PgSpec.fNumCells > 0 then //read any data cells that were saved if pgData <> nil then // if we have preconfigured empty cells begin if pgData.count <> PgSpec.fNumCells then begin OK2Read := False; //stop reading result := False; Exit; //we need to exit once we hit the error. end; //force check of reading file Ok2Read := Ok2Read and (pgData.count = PgSpec.fNumCells); if OK2Read then for nCell := 0 to pgData.Count-1 do begin try Application.ProcessMessages; if (GetKeyState(VK_Escape) AND 128) = 128 then break; pgData[nCell].ReadCellData(Stream, Version); //each cell knowns how to read its own stuff. except on E:Exception do begin showmessage('exception ReadCellData'+e.Message); result := False; Exit; end; end; end; end else //we need to reconstruct the pgData List from saved cell info begin // ### rebuild cell stuff here. result := False; Exit; end; {Read the Info Cells} if OK2Read then begin try ReadPageDataInfoCells(PgSpec, Stream); except on E:Exception do begin Showmessage('exception ReadPageDataInfoCells '+e.Message); result := False; Exit; end; end; end; finally result := OK2Read; end; except on E:Exception do result := False; end; end; //writes the page data into container FileHdl procedure TDocPage.WritePageData(Stream: TStream); var amt, nCell: Integer; PgSpec: PageSpecRec; doc: TContainer; begin doc := PageContainer(self); with PgSpec do begin doc.SetProgressBarNote('Writing '+FPgTitleName); {Number of Data Cells} fNumCells := 0; if pgData <> nil then fNumCells := pgData.Count; //number of cells on this page fNumBookmarks := pgDisplay.BookMarkCount; fPgTitle := copy(FPgTitleName, 1, cNameMaxChars); //copy at most cNameMaxChars fPgPrefs := FPgFlags; fExtra0 := 0; //not used, available {Number of Info Cells} fNumInfoCells := 0; if PgInfo <> nil then fNumInfoCells := pgInfo.Count; fNextSectionID := 1; fExtra1 := 0; //extra space when we forget stuff fExtra2 := 0; fExtra3 := 0; fExtra4 := 0; end; //now write the page header rec amt := SizeOf(PageSpecRec); Stream.WriteBuffer(PgSpec, amt); //write the page spec WritePageMarkUps(Stream); //write the page annotations WriteFutureData2(Stream); WriteFutureData3(Stream); WriteFutureData4(Stream); WriteFutureData5(Stream); WriteFutureData6(Stream); WriteFutureData7(Stream); WriteFutureData8(Stream); WriteFutureData9(Stream); WriteFutureData10(Stream); WriteFutureData11(Stream); WriteFutureData12(Stream); WriteFutureData13(Stream); WriteFutureData14(Stream); WriteFutureData15(Stream); WriteFutureData16(Stream); WriteFutureData17(Stream); WriteFutureData18(Stream); WriteFutureData19(Stream); WriteFutureData20(Stream); WriteFutureData21(Stream); WriteFutureData22(Stream); WriteFutureData23(Stream); WriteFutureData24(Stream); WriteFutureData25(Stream); {this is a fixed section that trails the } {PageSpecRec and the var length Future Data} {Sections. } amt := SizeOf(PagePrintSpecRec); Stream.WriteBuffer(FPgPrSpec, amt); //write the page's print spec PgDisplay.WriteBookMarks(stream); //write out any bookmarks if pgData <> nil then // if we have cell data for nCell := 0 to pgData.Count-1 do pgData[nCell].WriteCellData(stream); //write it to the file if pgInfo <> nil then for nCell := 0 to pgInfo.Count-1 do pgInfo[nCell].WriteCellData(stream); doc.IncrementProgressBar; end; Procedure TDocPage.WritePageText(var Stream: TextFile); var nCell: Integer; begin if pgData <> nil then // if we have cell data for nCell := 0 to pgData.Count-1 do pgData[nCell].ExportToTextFile(stream); //write it to the file end; procedure TDocPage.ReadPageText(var Stream: TextFile); begin //the text is read in at MAIN and then passed to cell // Need a Main.OK2Process for this to work. //some text can be a CMD for main to process if pgData <> nil then // if we have preconfigured empty cells begin (* ok2Read := True; if pgData.count <> PgSpec.fNumCells then ok2read := OK2Continue('The number of fields in this file DO NOT match the number of fields in the page0. Do you want to continue?'); Ok2Read := pgData.count = PgSpec.fNumCells; //### if OK2Read then for nCell := 0 to pgData.Count-1 do pgData[nCell].ReadCellText(Stream); //each cell knowns how to read its own stuff. *) end; end; procedure TDocPage.InvalidatePage; begin PageContainer(self).docView.Invalidate; //redraw the screen end; //Used by cells when they want to replicate their contents procedure TDocPage.BroadcastCellContext(ContextID: Integer; Str: String); var n, i: Integer; cell: TBaseCell; begin n := Length(FContextList); if n > 0 then for i := 0 to n-1 do if FContextList[i].CntxtID = ContextID then //do we have any common context IDs begin cell := PgData[FContextList[i].CellIndex]; //yes get the cell, if PageContainer(Self).CanProcessGlobal(cell) then // if (cell <> startCell) and //but, don't replicate ourselves // not IsBitSetUAD(cell.FCellPref, bNoTransferInto)then //YF 06.06.02 and Transfer allowed into the cell if not IsBitSetUAD(cell.FCellPref, bNoTransferInto)then begin cell.SetText(Str); cell.Display; cell.ProcessMath; cell.ReplicateLocal(False); //populate local context //for signature date, we need to go through the munging text //to populate invoice date, transmittal date, and effective date //This will fix the issue on signature form when user only click on set signature date as today //and no edit box entry, the normal process works fine with basecell postprocess event but not on signature form with no cell edit box. if contextid=kAppraiserSignDate then cell.MungeText; end; end; end; //Used by cells when they want to replicate their contents procedure TDocPage.BroadcastCellContext(ContextID: Integer; const Source: TBaseCell); var n, i: Integer; cell: TBaseCell; begin n := Length(FContextList); if n > 0 then for i := 0 to n-1 do if FContextList[i].CntxtID = ContextID then //do we have any common context IDs begin cell := PgData[FContextList[i].CellIndex]; //yes get the cell, if PageContainer(Self).CanProcessGlobal(cell) then if not IsBitSetUAD(cell.FCellPref, bNoTransferInto)then begin // 061813 Do not assign geocoded cells so longitude & latitude are preserved {if cell.FCellID = CGeocodedGridCellID then cell.Text := Source.Text else} cell.AssignContent(Source); cell.ReplicateLocal(False); //populate local context end; end; end; procedure TDocPage.BroadcastLocalCellContext(LocalCTxID: Integer; Str: String); //used by cell to replicate itself var n, i: Integer; cell: TBaseCell; begin n := Length(FLocalConTxList); if n > 0 then for i := 0 to n-1 do if FLocalConTxList[i].CntxtID = LocalCTxID then //do we have any common context IDs begin cell := PgData[FLocalConTxList[i].CellIndex]; //yes get the cell, if PageContainer(Self).CanProcessLocal(Cell) then if not IsBitSetUAD(cell.FCellPref, bNoTransferInto)then begin cell.SetText(Str); cell.Display; cell.ProcessMath; cell.ReplicateGlobal; end; end; end; procedure TDocPage.BroadcastLocalCellContext(LocalCTxID: Integer; const Source: TBaseCell); //used by cell to replicate itself var n, i: Integer; cell: TBaseCell; begin n := Length(FLocalConTxList); if n > 0 then for i := 0 to n-1 do if FLocalConTxList[i].CntxtID = LocalCTxID then //do we have any common context IDs begin cell := PgData[FLocalConTxList[i].CellIndex]; //yes get the cell, if PageContainer(Self).CanProcessLocal(Cell) then if not IsBitSetUAD(cell.FCellPref, bNoTransferInto)then begin // 061813 Do not assign geocoded cells so longitude & latitude are preserved {if cell.FCellID = CGeocodedGridCellID then cell.Text := Source.Text else} cell.AssignContent(Source); cell.ReplicateGlobal; end; end; end; //Used to broadcast data from this page (usually dropped) to the rest of the doc //aPage is a page in our doc, docPage is broadcasting to it procedure TDocPage.BroadcastContext2Page(aPage: TDocPage; Flags: Byte = 0); //add new param and set default to 0 if 1 do postprocess var m,n,i,j, k: Integer; ourCell, pgCell: TBaseCell; text : String; doc : TContainer; begin //Flags // 00000001 - Imported text doc := PageContainer(self); n := Length(FContextList); //do we have anything to broadcast to 'aPage'? m := Length(aPage.FContextList); //does aPage have any context cells? if (n > 0) and (m > 0) then // yes begin for i := 0 to n-1 do //test each of our contesxtID against each of aPags's for j := 0 to m-1 do if FContextList[i].CntxtID = aPage.FContextList[j].CntxtID then //a match? begin ourCell := PgData[FContextList[i].CellIndex]; pgCell := aPage.PgData[aPage.FContextList[j].CellIndex]; // 061813 Do not assign geocoded cells so longitude & latitude are preserved {if pgCell.FCellID = CGeocodedGridCellID then pgCell.Text := ourCell.Text else} pgCell.AssignContent(ourCell); //@Charlie if (Flags and 1 = 1) then pgCell.PostProcess; end; end; if (m > 0) then for k := 0 to m-1 do if doc.FindMungedContextData(aPage.FContextList[k].CntxtID, text) then if length(text) > 0 then begin pgCell := aPage.PgData[aPage.FContextList[k].CellIndex]; pgCell.SetText(text); pgCell.Display; pgCell.ProcessMath; end; end; function TDocPage.FindContextData(ContextID: Integer; var Str: String): Boolean; var n, i: Integer; cell: TBaseCell; begin result := false; str := ''; n := Length(FContextList); if n > 0 then for i := 0 to n-1 do begin if FContextList[i].CntxtID = ContextID then begin Cell := PgData[FContextList[i].CellIndex]; Str := cell.GetText; //returns '' in some cases result := true; Break; //break whether can process or not end; end; end; function TDocPage.FindContextData(ContextID: Integer; out DataCell: TBaseCell): Boolean; var n, i: Integer; begin result := false; DataCell := nil; n := Length(FContextList); if n > 0 then for i := 0 to n-1 do begin if FContextList[i].CntxtID = ContextID then begin DataCell := PgData[FContextList[i].CellIndex]; result := true; Break; //break whether can process or not end; end; end; //used to Populate this page's cells with data from doc //ie, a form is added to doc, so load it with common data procedure TDocPage.PopulateContextCells(Container: TComponent); //loads the context cells from other pages var n, i: Integer; cell: TBaseCell; contextStr: string; doc: TContainer; Source: TBaseCell; begin doc := TContainer(Container); n := Length(FContextList); //do we have anything to populate if n > 0 then for i := 0 to n-1 do //run thru context list begin if doc.FindMungedContextData(FContextList[i].CntxtID, contextStr) then //search munged list begin cell := PgData[FContextList[i].CellIndex]; //### maybe need to save value if its a calc cell cell.SetText(contextStr); //don't forget to format the text // if (appPref_AutoTxAlignHeaders <> atjJustNone) then // doc.SetGlobalCellFormating(true); cell.ReplicateLocal(true); cell.Display; cell.ProcessMath; // 072811 JWyatt Final step is to populate any GSE data from its source cell // Source := doc.GetCellByID(cell.FCellID); // if Source <> nil then // cell.GSEData := Source.GSEData; end else if doc.FindContextData(FContextList[i].CntxtID, Source) then //search in report for data begin cell := PgData[FContextList[i].CellIndex]; // 061813 Do not assign geocoded cells so longitude & latitude are preserved {if cell.FCellID = CGeocodedGridCellID then cell.Text := Source.Text else} cell.AssignContent(Source); cell.ReplicateLocal(true); end; end; end; procedure TDocPage.PopulateFromSimilarForm(AForm: TObject); var c: Integer; similarForm: TDocForm; aCell, similarCell: TBaseCell; begin similarForm := TDocForm(AForm); //get data only from this form if PgData <> nil then for c := 0 to PgData.count - 1 do begin aCell := PgData[c]; if aCell.FCellID > 0 then // 091311 JWyatt Cell ID 925 is defined as a TGeocodedGridCell so we need to detect and // not populate just as we do for standard TGridCell types. if (not aCell.ClassNameIs('TGridCell')) and (not aCell.ClassNameIs('TGeocodedGridCell')) then begin similarCell := similarForm.GetCellByID(aCell.FCellID); if assigned(similarCell) then aCell.AssignContent(similarCell); end; end; end; procedure TDocPage.SetGlobalUserCellFormating; var c, cType, cSubType: Integer; aCell: TBaseCell; begin if PgData <> nil then for c := 0 to PgData.count - 1 do begin aCell := PgData[c]; cType := aCell.FType; cSubType := aCell.FSubType; if cType = cSingleLn then case cSubType of cKindLic: if appPref_AutoTxAlignLicCell <> atjJustNone then aCell.TextJust := appPref_AutoTxAlignLicCell; cKindCo: if appPref_AutoTxAlignCoCell <> atjJustNone then aCell.TextJust := appPref_AutoTxAlignCoCell; end; end; end; procedure TDocPage.SetGlobalLongCellFormating; var c, cType, cSubType: Integer; aCell: TBaseCell; begin if PgData <> nil then for c := 0 to PgData.count - 1 do begin aCell := PgData[c]; cType := aCell.FType; cSubType := aCell.FSubType; if (cType = cSingleLn) and ((cSubType = cKindTx) or (cSubType = cKindDate) or (cSubType = cKindCalc))and (aCell.Width > 144) then //greater 2 inches (72 pix/inch) begin aCell.TextJust := appPref_AutoTxAlignLongCell; end; end; end; procedure TDocPage.SetGlobalShortCellFormating; var c, cType, cSubType: Integer; aCell: TBaseCell; begin if PgData <> nil then for c := 0 to PgData.count - 1 do begin aCell := PgData[c]; cType := aCell.FType; cSubType := aCell.FSubType; if (cType = cSingleLn) and ((cSubType = cKindTx) or (cSubType = cKindDate) or (cSubType = cKindCalc))and (aCell.Width < 145) and //less than 2 inches (72 pix/inch) ((aCell.FContextID <> kFileNo) and (aCell.FContextID <> kCaseName) and (aCell.FContextID <> kcaseNo)) //added by jenny on 2.9.06 - these cells should be left justified always and not (aCell.FCellID = 1500) and not (aCell.FCellID = 1501) and not (aCell.FCellID = 1502) then begin aCell.TextJust := appPref_AutoTxAlignShortCell; end; end; end; procedure TDocPage.SetGlobalHeaderCellFormating; var c, cType, cSubType: Integer; aCell: TBaseCell; begin if PgData <> nil then for c := 0 to PgData.count - 1 do if pgDesc.PgType in [ptPhotoSubject, ptPhotoSubExtra, ptPhotoComps, ptPhotoListings, ptPhotoRentals, ptPhotoUntitled, ptMapLocation, ptMapListings, ptMapRental, ptMapPlat, ptMapFlood, ptMapOther, ptSketch, ptExhibit, ptExtraComps, ptExtraListing, ptExtraRental, ptExhibitWoHeader, ptExhibitFullPg, ptPhotosUntitled6Photos]then begin aCell := PgData[c]; cType := aCell.FType; cSubType := aCell.FSubType; if (cType = cSingleLn) and (cSubType = cKindTx) then case aCell.FContextID of kBorrower, kAddressUnit, kFullAddress, //include full address context id kCity, kCounty, kState, kZip, kLenderCompany, kLenderFullAddress: begin aCell.TextJust := appPref_AutoTxAlignHeaders; end; end; end; end; procedure TDocPage.SetGlobalGridFormating(GridKind: Integer); var Grid: TGridMgr; K, Cmp, r, rows: Integer; ACell: TBaseCell; begin Grid := TGridMgr.Create(True); try Grid.BuildPageGrid(Self, GridKind); //now we have grid with all comps K := Grid.count; //how many comps, k includes subject=0 for cmp := 0 to K-1 do //formatting cells in all the comps with Grid.Comp[cmp] do begin rows := RowCount; for r := 0 to rows - 1 do begin //Comp description cells ACell := GetCellByCoord(Point(0,r)); //added by jenny on 2.9.06 - these cells should be left justified always if assigned(ACell) and not (aCell.FCellID = 1500) and not (aCell.FCellID = 1501) and not (aCell.FCellID = 1502) then ACell.TextJust := appPref_AutoTxAlignGridDesc; //Comp Adjustment cells ACell := GetCellByCoord(Point(1,r)); //added by jenny on 2.9.06 - these cells should be left justified always if assigned(ACell) and not (aCell.FCellID = 1500) and not (aCell.FCellID = 1501) and not (aCell.FCellID = 1502) then begin ACell.TextJust := appPref_AutoTxAlignGridAdj; ACell.FCellFormat := SetBit2Flag(ACell.FCellFormat, bDisplayZero, appPref_AutoTxFormatShowZeros); ACell.FCellFormat := SetBit2Flag(ACell.FCellFormat, bAddPlus, appPref_AutoTxFormatAddPlus); //clear previous rounding bits - all of them ACell.FCellFormat := ClrBit(ACell.FCellFormat, bRnd1000); ACell.FCellFormat := ClrBit(ACell.FCellFormat, bRnd500); ACell.FCellFormat := ClrBit(ACell.FCellFormat, bRnd100); ACell.FCellFormat := ClrBit(ACell.FCellFormat, bRnd1); ACell.FCellFormat := ClrBit(ACell.FCellFormat, bRnd1P1); ACell.FCellFormat := ClrBit(ACell.FCellFormat, bRnd1P2); ACell.FCellFormat := ClrBit(ACell.FCellFormat, bRnd1P3); ACell.FCellFormat := ClrBit(ACell.FCellFormat, bRnd1P4); ACell.FCellFormat := ClrBit(ACell.FCellFormat, bRnd1P5); // 120811 JWyatt Do not allow decimal override format for UAD reports. Specifications // require whole numbers only. case appPref_AutoTxFormatRounding of 0: ACell.FCellFormat := SetBit(ACell.FCellFormat, bRnd1000); //round to 1000 1: ACell.FCellFormat := SetBit(ACell.FCellFormat, bRnd500); //round to 500 2: ACell.FCellFormat := SetBit(ACell.FCellFormat, bRnd100); //round to 100 3: ACell.FCellFormat := SetBit(ACell.FCellFormat, bRnd1); //round to 1 4: if (ACell.ParentPage.ParentForm.ParentDocument as TContainer).UADEnabled then ACell.FCellFormat := SetBit(ACell.FCellFormat, bRnd1) else ACell.FCellFormat := SetBit(ACell.FCellFormat, bRnd1P2); //round to 0.01 end; end; end; end; finally Grid.Free; end; end; procedure TDocPage.InstallBookMarkMenuItems; begin PgDisplay.InstallBookMarkMenuItems; end; procedure TDocPage.RemoveBookMarkMenuItems; begin PgDisplay.RemoveBookMarkMenuItems; end; procedure TDocPage.LoadLicensedUser(forceCOName: Boolean); var c: Integer; begin if PgData <> nil then for c := 0 to PgData.count - 1 do if PgData[c] is TCompanyCell then begin If forceCOName then TCompanyCell(PgData[c]).LoadCurrentUserCompanyName; end else if PgData[c] is TLicenseCell then begin TLicenseCell(PgData[c]).LoadCurrentUser; //DoSetText(CurrentUser); end; end; procedure TDocPage.LoadUserLogo; var ACell: TBaseCell; begin if FileExists(appPref_UserLogoPath) then //must have image file try ACell := GetCellByID(924); //924 = logo cell id if Assigned(ACell) and (not ACell.HasData) then //its there and empty with PageContainer(Self) do begin MakeCurCell(ACell); if assigned(docEditor) and (docEditor is TGraphicEditor) then TGraphicEditor(docEditor).LoadImageFile(appPref_UserLogoPath); end; except; //in case something happens while loading image end; end; function TDocPage.GetSignatureTypes: TStringList; var i: Integer; pageSigList: TStringList; begin pageSigList := TStringList.Create; try try pageSigList.Sorted := True; pageSigList.Duplicates := dupIgnore; if PgInfo <> nil then for i := 0 to PgInfo.count-1 do if PgInfo[i].ICType = icSignature then pageSigList.Add(PgInfo[i].Text); except FreeAndNil(pageSigList); end; finally if (pageSigList <> nil) and (pageSigList.Count = 0) then FreeAndNil(pageSigList); //nothing to sendback result := pageSigList; end; end; // THis routine changes the bounds rect for the info cell. It allows the // signature to be very big or very small depening on the user preference. // mainly it is to accomadate the signatures with certification stamps procedure TDocPage.UpdateSignature(const SigKind: String; SignIt, Setup: Boolean); var i: Integer; begin if PgInfo <> nil then for i := 0 to PgInfo.count-1 do if PgInfo[i].ICType = icSignature then if (CompareText(PgInfo[i].Text, SigKind) = 0) then begin if Setup then TSignatureCell(PgInfo[i]).SetSignatureBounds //change to fit signature else TSignatureCell(PgInfo[i]).RestoreBounds; //restore to original position if SignIt then begin TSignatureCell(PgInfo[i]).Display; DataModified := True; end; end; end; //icKind is for set all of this kind on the page //icIndex is for specifying a particular infoCell // procedure TDocPage.UpdateInfoCell(icKind, icIndex: Integer; Value:Double; ValueStr: String); var i: Integer; begin if PgInfo <> nil then for i := 0 to PgInfo.count-1 do if PgInfo[i].ICType = icKind then begin // if length(ValueStr) > 0 then // PgInfo[i].Text := ValueStr // else PgInfo[i].Value := Value; PgInfo[i].Display; end; end; Procedure TDocPage.SetModifiedFlag; begin FModified := True; //set page flag // TDocForm(FParentForm).SetModifiedFlag; //tell the form its changed end; procedure TDocPage.SetDataModified(value: Boolean); begin TDocForm(FParentForm).DataModified := Value; //pass on to form end; procedure TDocPage.SetFormatModified(value: Boolean); begin FModified := Value; //this pages' format was chged TDocForm(FParentForm).FormatModified := Value; //pass on to form end; function TDocPage.SaveFormatChanges: Boolean; var n, Pref: integer; begin result := True; if pgData <> nil then //this is cell list for n := 0 to pgData.count -1 do //FormMgr object w/page description objects with pgDesc do begin Pref := pgData[n].FCellPref; SetCellPrefJust(pgData[n].FTxJust, Pref); //convert from justification to pref bits SetCellPrefStyle(pgData[n].FTxStyle, Pref); //convert from style to pref bits PgFormCells[n].CPref := Pref; //save pref PgFormCells[n].CFormat := pgData[n].FCellFormat; //save format PgFormCells[n].CSize := pgData[n].FTxSize; //save font size end; end; procedure TDocPage.SetPgTitleName(const Name: String); var N: Integer; doc: TContainer; begin FPgTitleName := Name; doc := PageContainer(Self); if IsPageInContents then //should we update table of contents begin //set the contents page N := doc.GetPageIndexInTableContents(Self); if N > -1 then begin doc.docTableOfContents[N*2] := Name; end; end; //Set the GOTOPage list N := doc.GetPageIndexInPageMgrList(self); if N > -1 then doc.PageMgr.Items.Strings[N] := Name; InvalidatePage; //### make this better, this redraws the whole window end; function TDocPage.ReadPageMarkUps(Stream: TStream): Boolean; var dataCount: LongInt; begin dataCount := ReadLongFromStream(Stream); if dataCount > 0 then PgMarkUps.ReadFromStream(Stream); result := True; end; function TDocPage.WritePageMarkUps(Stream: TStream): Boolean; var dataCount: LongInt; begin PgMarkups.RemoveEmptyMarks; //remove empty strings dataCount := pgMarkups.count; WriteLongToStream(dataCount, Stream); if dataCount > 0 then PgMarkUps.WriteToStream(Stream); result := True; end; {***** These read write functions are for **} {***** future data expansion on the page **} function TDocPage.ReadFutureData2(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData2(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData3(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData3(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData4(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData4(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData5(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData5(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData6(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData6(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData7(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData7(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData8(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData8(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData9(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData9(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData10(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData10(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData11(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData11(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData12(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData12(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData13(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData13(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData14(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData14(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData15(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData15(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData16(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData16(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData17(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData17(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData18(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData18(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData19(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData19(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData20(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData20(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData21(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData21(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData22(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData22(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData23(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData23(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData24(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData24(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.ReadFutureData25(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := ReadLongFromStream(Stream); result := datasize > 0; end; function TDocPage.WriteFutureData25(Stream: TStream): Boolean; var dataSize: LongInt; begin dataSize := 0; WriteLongToStream(dataSize, Stream); result := datasize > 0; end; function TDocPage.GetLocalContext(locCntxID: Integer): String; var itm,nItms : Integer; cl :TBaseCell; begin result := ''; nItms := length(FLocalConTxList); if nItms = 0 then exit; for itm := 0 to nItms - 1 do begin if FLocalConTxList[itm].CntxtID = locCntxID then begin cl := pgData[FLocalConTxList[itm].cellIndex]; if assigned(cl) and (cl.TextSize > 0) then begin result := cl.Text; break; end; end; end; end; //the bigger quality than bigger resolution, better image quality, but bigger image size on the disk and especially in the memory function TDocPage.SavePageAsImage(quality: Double; fPath: String): Boolean; //changed code from TPageImage.GenerateImage in UControlPageImage var btm: TBitmap; jpg: TJpegImage; viewport: TRect; begin result := false; btm := TBitmap.Create; jpg := TJpegImage.Create; try try btm.PixelFormat := pf16bit; viewport := Rect(0,0, pgDesc.PgWidth, pgDesc.PgHeight); viewport := ScaleRect(viewport,cNormScale,round(quality * Screen.PixelsPerInch)); viewport := Rect(0,0,viewport.Right + CMarginwidth, viewport.Bottom + cTitleHeight); //add margin btm.Width := viewport.Right - viewport.Left; btm.Height := viewport.Bottom - viewport.Top; pgDisplay.PgBody.DrawInView(btm.Canvas,viewport,Round(quality * Screen.PixelsPerInch)); except on E: Exception do ShowNotice(E.Message,false); end; jpg.CompressionQuality := 50; jpg.Assign(btm); jpg.SaveToFile(fPath); result := true; finally btm.Free; jpg.Free; end; end; { TDocPageList } destructor TDocPageList.Destroy; begin inherited Destroy; end; function TDocPageList.First: TDocPage; begin result := TDocPage(inherited First); end; function TDocPageList.Get(Index: Integer): TDocPage; begin result := TDocPage(inherited Get(index)); end; function TDocPageList.IndexOf(Item: TDocPage): Integer; begin result := inherited IndexOf(Item); end; function TDocPageList.Last: TDocPage; begin result := TDocPage(inherited Last); end; procedure TDocPageList.Put(Index: Integer; Item: TDocPage); begin inherited Put(Index, item); end; function TDocPageList.Remove(Item: TDocPage): Integer; begin result := inherited Remove(Item); end; // --- TPageUID -------------------------------------------------------------- /// summary: Creates a PageUID for the specified page. class function TPageUID.Create(const Page: TDocPage): PageUID; var Document: TContainer; Form: TDocForm; UID: PageUID; begin UID := Null; if Assigned(Page.ParentForm) then begin Form := Page.ParentForm as TDocForm; if Assigned(Form.ParentDocument) then begin Document := Form.ParentDocument as TContainer; UID := Create(Form.frmInfo.fFormUID, Document.docForm.IndexOf(Form), Form.frmPage.IndexOf(Page)); end; end; Result := UID; end; /// summary: Creates a PageUID with the specified values. class function TPageUID.Create(const FormID: LongInt; const FormIdx: Integer; const PageIdx: Integer): PageUID; var UID: PageUID; begin UID.FormID := FormID; UID.FormIdx := FormIdx; UID.PageIdx := PageIdx; Result := UID; end; /// summary: Gets the TDocPage instance for a PageUID in the specified document. class function TPageUID.GetPage(const Value: PageUID; const Document: TAppraisalReport): TDocPage; var Container: TContainer; Form: TDocForm; begin Result := nil; if Assigned(Document) and (Document is TContainer) then begin Container := Document as TContainer; if Assigned(Container.docForm) and (Value.FormIdx < Container.docForm.Count) and (Value.FormIdx >= 0) then begin Form := Container.docForm[Value.FormIdx]; if Assigned(Form.frmPage) and (Value.PageIdx < Form.frmPage.Count) and (Value.PageIdx >= 0) then Result := Form.frmPage[Value.PageIdx]; end; end; end; /// summary: Tests whether two PageUID records are equal. class function TPageUID.IsEqual(const Value1: PageUID; const Value2: PageUID): Boolean; var Equal: Boolean; begin Equal := True; Equal := Equal and (Value1.FormID = Value2.FormID); Equal := Equal and (Value1.FormIdx = Value2.FormIdx); Equal := Equal and (Value1.PageIdx = Value2.PageIdx); Result := Equal; end; /// summary: Tests whether a PageUID is null. class function TPageUID.IsNull(const Value: PageUID): Boolean; begin Result := IsEqual(Value, Null); end; /// summary: Tests whether a PageUID is valid for the specified document. class function TPageUID.IsValid(const Value: PageUID; const Document: TAppraisalReport): Boolean; begin Result := Assigned(GetPage(Value, Document)); end; /// summary: Gets a null PageUID. class function TPageUID.Null: PageUID; begin Result := Create(-1, -1, -1); end; end.
unit u_langue; // (c) Patrick Prémartin / Olf Software 08/2016 interface function GetOSLangID: String; implementation uses FMX.Platform {$IFDEF MACOS} ,iOSAPI.Foundation, MacAPI.ObjectiveC {$ENDIF} ; // récupération du code langue de l'appareil // https://forums.embarcadero.com/thread.jspa?threadID=108333 // ou http://www.synaptica.info/en/2015/12/21/delphi-10seattle-get-current-device-language/ // ou http://codeverge.com/embarcadero.delphi.firemonkey/detect-current-language-on-andr/2001235#sthash.zjLIi2KY.dpuf function GetOSLangID: String; {$IFDEF MACOS} var Languages: NSArray; begin Languages := TNSLocale.OCClass.preferredLanguages; Result := TNSString.Wrap(Languages.objectAtIndex(0)).UTF8String; {$ENDIF} {$IFDEF ANDROID} var LocServ: IFMXLocaleService; begin if TPlatformServices.Current.SupportsPlatformService(IFMXLocaleService, IInterface(LocServ)) then Result := LocServ.GetCurrentLangID; {$ENDIF} {$IFDEF MSWINDOWS} var buffer: MarshaledString; UserLCID: LCID; BufLen: Integer; begin // defaults UserLCID := GetUserDefaultLCID; BufLen := GetLocaleInfo(UserLCID, LOCALE_SISO639LANGNAME, nil, 0); buffer := StrAlloc(BufLen); if GetLocaleInfo(UserLCID, LOCALE_SISO639LANGNAME, buffer, BufLen) <> 0 then Result := buffer else Result := 'en'; StrDispose(buffer); {$ENDIF} end; end.
unit Formulae; interface uses Polynoms, Rationals, naturals, SysUtils, PolynomsStek, fullSys, signTable, ConstructionSignTable; type (* * Знак в неравенсте: >, >=, <, <=, =, <> *) TInequationSign = (isGreater, isGreaterEqual, isLess, isLessEqual, isEqual, isNotEqual); (* * Неравенство с нулем в правой части *) TInequation = record Polynom : TPolynom; InequationSign : TInequationSign; end; PInequation = ^TInequation; (* * "Операция" - обозначает смысл полей в вершине дерева системы утверждений *) TOperation = (oAnd, oOr, oNot, oInequation); (* * Вершина дерева системы утверждений * Если поле Operation равно * oAnd : LeftSS и RightSS - аргументы конъюнкции, * Inequation не имеет смысла * oOr : LeftSS и RightSS - аргументы дизъюнкции, * Inequation не имеет смысла * oNot : LeftSS - аргумент отрицания, * RightSS, Inequation не имеют смысла (должны быть равны nil) * oInequation : Inequation - неравенство, * LeftSS и RightSS не имеют смысла, * LeftSS должен быть равен nil *) PStatementSystem = ^TStatementSystem; TStatementSystem = record Operation : TOperation; LeftSS : PStatementSystem; case Integer of 1: (RightSS : PStatementSystem); 2: (Inequation : PInequation); end; //это уже СЛЕДУЩИЙ тип! (* * Квантор: существует, для любого *) TQuantor = (qExists, qForAll); (* * Формула с квантором (все полиномы - по одной и той же переменной) *) TQuanitifedFormula = record Quantor : TQuantor; StatementSystem : PStatementSystem; end; function tQuantFormulaToBoolean(var TFormula : TQuanitifedFormula; var table : TSignTable) : boolean; // проверяем истиинность TFormula //function tQuantFormulaToStr(const TFormula : TQuanitifedFormula; k : boolean = false) : string; //TFormula в строку, а если boolean = true, то в FullPArray появляются все многочлены из TFormul-ы implementation {var formulaErrorFlag : boolean; } function tInequatTValueSign(InequationSign : TInequationSign; sign : TValueSign) : boolean; begin case sign of vsMinus: case InequationSign of isLess, isLessEqual, isNotEqual: Result := true; isGreater, isGreaterEqual, isEqual: result := false; end; vsPlus: case InequationSign of isGreater, isGreaterEqual, isNotEqual: result := true; isLess, isLessEqual, isEqual: Result := false; end; vsZero: case InequationSign of isGreaterEqual, isLessEqual, isEqual: result := true; isGreater, isLess, isNotEqual: result := false; end; end; end; function TRatToSign(r : TRationalNumber) : TValueSign; begin if not itIsNotRZero(r) then result := vsZero else begin if r.Sign = nsPlus then result := vsPlus else result := vsMinus; end; end; function intToSign(i : integer) : TValueSign; begin case i of -1: result := vsMinus; 1: result := vsPlus; 0: result := vsZero; end; end; function pIneguationToBoolean(var Inequation : PInequation;var tableColumn : PSignTableColumn) : boolean; var i : integer; pos : TPolynomPosition; p : TPolynom; sign : TValueSign; begin p := inequation.Polynom; if length(p) = 1 then begin result := tInequatTValueSign(Inequation^.InequationSign, TRatToSign(p[0]^)); exit; end; i := search(PolynomSystem, p, pos); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! sign := intToSign(easyGet(tableColumn, i)); result := tInequatTValueSign(Inequation^.InequationSign, sign); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! end; function pStatSystToBoolean(PStatSys : PStatementSystem; var tableColumn : PSignTableColumn) : boolean; begin case pStatSys^.Operation of oAnd: result := pStatSystToBoolean(PStatSys^.LeftSS, tableColumn) and pStatSystToBoolean(PStatSys^.RightSS, tableColumn); oOr: result := pStatSystToBoolean(PStatSys^.LeftSS, tableColumn) or pStatSystToBoolean(PStatSys^.RightSS, tableColumn); oNot: result := not (pStatSystToBoolean(PStatSys^.LeftSS, tableColumn)); oInequation: result := pIneguationToBoolean(pStatSys^.Inequation, tableColumn); end; end; function tQuantFormulaToBoolean(var TFormula : TQuanitifedFormula; var table : TSignTable) : boolean; var tablePColumn : PSignTableColumn; tableNil : TSignTableColumn; begin result := false; tablePColumn := table.FirstColumn; if tablePColumn = nil then begin case TFormula.Quantor of qExists: begin if pStatSystToBoolean(TFormula.StatementSystem, tablePColumn) then result := true else result := false; end; qForAll: begin if pStatSystToBoolean(TFormula.StatementSystem, tablePColumn) then result := true else result := false; end; end;//case exit; end; case TFormula.Quantor of qExists: while tablePColumn <> nil do begin if pStatSystToBoolean(TFormula.StatementSystem, tablePColumn) then begin result := true; exit; end; tablePColumn := tablePColumn^.Next; end; qForAll: begin result := true; while tablePColumn <> nil do begin if not(pStatSystToBoolean(TFormula.StatementSystem, tablePColumn)) then begin result := false; exit; end; tablePColumn := tablePColumn^.Next; end; end; end; end; end.
unit tgsendertypes; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fphttpclient, fpjson; type TParseMode = (pmDefault, pmMarkdown, pmHTML); TLogMessageEvent = procedure(Sender: TObject; LogType: TEventType; const Msg: String) of object; TInlineKeyboardButton = class; { TReplyMarkup } TReplyMarkup = class(TJSONObject) private function GetInlineKeyBoard: TJSONArray; procedure SetInlineKeyBoard(AValue: TJSONArray); public property InlineKeyBoard: TJSONArray read GetInlineKeyBoard write SetInlineKeyBoard; end; { TInlineKeyboardButton } TInlineKeyboardButton = class(TJSONObject) private function CheckOptnlNull: Boolean; procedure CheckOptnlAndSet(const ParamName, ParamValue: String); function Getcallback_data: String; function Getswitch_inline_query: String; function Getswitch_inline_query_current_chat: String; function Gettext: String; function Geturl: String; procedure Setcallback_data(AValue: String); procedure Setswitch_inline_query(AValue: String); procedure Setswitch_inline_query_current_chat(AValue: String); procedure Settext(AValue: String); procedure Seturl(AValue: String); public constructor Create(const AText: String); property text: String read Gettext write Settext; property url: String read Geturl write Seturl; property callback_data: String read Getcallback_data write Setcallback_data; property switch_inline_query: String read Getswitch_inline_query write Setswitch_inline_query; property switch_inline_query_current_chat: String read Getswitch_inline_query_current_chat write Setswitch_inline_query_current_chat; end; { TInlineKeyboardButtons } TInlineKeyboardButtons = class(TJSONArray) public constructor Create(const AButtonText, CallbackData: String); overload; constructor Create(const AButtons: array of String); overload; function AddButton(const AButtonText, CallbackData: String): Integer; procedure AddButtons(const AButtonts: array of String); end; { TTelegramSender } TTelegramSender = class private FOnLogMessage: TLogMessageEvent; FResponse: String; FRequestBody: String; FToken: String; FRequestWhenAnswer: Boolean; procedure DebugMessage(const Msg: String); // будет отправлять в журнал все запросы и ответы. Полезно на время разработки procedure ErrorMessage(const Msg: String); procedure InfoMessage(const Msg: String); function HTTPPostFile(const Method, FileField, FileName: String; AFormData: TStrings): Boolean; function HTTPPostJSON(const Method: String): Boolean; function SendFile(const AMethod, AFileField, AFileName: String; MethodParameters: TStrings): Boolean; function SendMethod(const Method: String; MethodParameters: array of const): Boolean; function SendMethod(const Method: String; MethodParameters: TJSONObject): Boolean; overload; procedure SetRequestBody(AValue: String); procedure SetRequestWhenAnswer(AValue: Boolean); public constructor Create(const AToken: String); function editMessageText(const AMessage: String; chat_id: Int64 = 0; message_id: Int64 = 0; ParseMode: TParseMode = pmDefault; DisableWebPagePreview: Boolean=False; inline_message_id: String = ''; ReplyMarkup: TReplyMarkup = nil): Boolean; function sendDocumentByFileName(chat_id: Int64; const AFileName: String; const ACaption: String; ReplyMarkup: TReplyMarkup = nil): Boolean; function sendLocation(chat_id: Int64; Latitude, Longitude: Real; LivePeriod: Integer = 0; ParseMode: TParseMode = pmDefault; DisableWebPagePreview: Boolean=False; ReplyMarkup: TReplyMarkup = nil): Boolean; function sendMessage(chat_id: Int64; const AMessage: String; ParseMode: TParseMode = pmDefault; DisableWebPagePreview: Boolean=False; ReplyMarkup: TReplyMarkup = nil): Boolean; function sendPhoto(chat_id: Int64; const APhoto: String; const ACaption: String = ''): Boolean; function sendVideo(chat_id: Int64; const AVideo: String; const ACaption: String = ''): Boolean; { Пусть пользователь сам решит какого типа логирование он будет использовать } property OnLogMessage: TLogMessageEvent read FOnLogMessage write FOnLogMessage; property RequestBody: String read FRequestBody write SetRequestBody; property Response: String read FResponse; property Token: String read FToken write FToken; { If you're using webhooks, you can perform a request to the API while sending an answer... In this case the method to be invoked in the method parameter of the request.} property RequestWhenAnswer: Boolean read FRequestWhenAnswer write SetRequestWhenAnswer; end; implementation const // API names constants s_editMessageText='editMessageText'; s_sendMessage='sendMessage'; s_sendPhoto='sendPhoto'; s_sendVideo='sendVideo'; s_sendDocument='sendDocument'; s_sendLocation='sendLocation'; s_Method='method'; s_Url = 'url'; s_Text = 'text'; s_ChatId = 'chat_id'; s_MessageId = 'message_id'; s_InlineMessageId = 'inline_message_id'; s_Document = 'document'; s_Caption = 'caption'; s_ParseMode = 'parse_mode'; s_ReplyMarkup = 'reply_markup'; s_Latitude = 'latitude'; s_Longitude = 'longitude'; s_LivePeriod = 'live_period'; s_DsblWbpgPrvw = 'disable_web_page_preview'; s_InlineKeyboard = 'inline_keyboard'; s_SwitchInlineQuery = 'switch_inline_query'; s_CallbackData = 'callback_data'; s_SwitchInlineQueryCurrentChat = 's_switch_inline_query_current_chat'; ParseModes: array[TParseMode] of PChar = ('Markdown', 'Markdown', 'HTML'); API_URL='https://api.telegram.org/bot'; { TInlineKeyboardButtons } constructor TInlineKeyboardButtons.Create(const AButtonText, CallbackData: String); begin inherited Create; AddButton(AButtonText, CallbackData); end; constructor TInlineKeyboardButtons.Create(const AButtons: array of String); begin inherited Create; AddButtons(AButtons); end; function TInlineKeyboardButtons.AddButton(const AButtonText, CallbackData: String): Integer; var btn: TInlineKeyboardButton; begin btn:=TInlineKeyboardButton.Create(AButtonText); btn.callback_data:=CallbackData; Result:=Add(btn); end; procedure TInlineKeyboardButtons.AddButtons(const AButtonts: array of String); var btn: TInlineKeyboardButton; i, c: Integer; begin c:=Length(AButtonts) div 2; for i:=0 to c-1 do begin btn:=TInlineKeyboardButton.Create(AButtonts[i*2]); btn.callback_data:=AButtonts[i*2+1]; Add(btn); end; end; { TReplyMarkup } function TReplyMarkup.GetInlineKeyBoard: TJSONArray; begin Result:=Arrays[s_InlineKeyboard]; end; procedure TReplyMarkup.SetInlineKeyBoard(AValue: TJSONArray); begin Arrays[s_InlineKeyboard]:=AValue; end; { TInlineKeyboardButton } procedure TInlineKeyboardButton.Settext(AValue: String); begin Strings[s_text]:=AValue; end; procedure TInlineKeyboardButton.Setcallback_data(AValue: String); begin CheckOptnlAndSet(s_callbackdata, AValue); end; function TInlineKeyboardButton.Geturl: String; begin Result:=Strings[s_url]; end; function TInlineKeyboardButton.CheckOptnlNull: Boolean; begin Result:=not (Assigned(Find(s_CallbackData)) or Assigned(Find(s_SwitchInlineQuery)) or Assigned(Find(s_SwitchInlineQueryCurrentChat)) or Assigned(Find(s_Url))) end; procedure TInlineKeyboardButton.CheckOptnlAndSet(const ParamName, ParamValue: String); var Op: Boolean; begin Op:=CheckOptnlNull; if op or (not op and Assigned(Find(ParamName))) then // Only one optional parameters must set! Strings[ParamName]:=ParamValue { else DoError('Error')} end; function TInlineKeyboardButton.Getcallback_data: String; begin Result:=Strings[s_callbackdata]; end; function TInlineKeyboardButton.Getswitch_inline_query: String; begin Result:=Strings[s_SwitchInlineQuery]; end; function TInlineKeyboardButton.Getswitch_inline_query_current_chat: String; begin Result:=Strings[s_SwitchInlineQueryCurrentChat]; end; function TInlineKeyboardButton.Gettext: String; begin Result:=Strings[s_text]; end; procedure TInlineKeyboardButton.Setswitch_inline_query(AValue: String); begin CheckOptnlAndSet(s_SwitchInlineQuery, AValue); end; procedure TInlineKeyboardButton.Setswitch_inline_query_current_chat( AValue: String); begin CheckOptnlAndSet(s_SwitchInlineQueryCurrentChat, AValue); end; procedure TInlineKeyboardButton.Seturl(AValue: String); begin CheckOptnlAndSet(s_url, AValue); end; constructor TInlineKeyboardButton.Create(const AText: String); begin inherited Create; Add(s_text, AText); end; { TTelegramSender } procedure TTelegramSender.DebugMessage(const Msg: String); begin if Assigned(FOnLogMessage) then FOnLogMessage(Self, etDebug, Msg); end; procedure TTelegramSender.ErrorMessage(const Msg: String); begin if Assigned(FOnLogMessage) then FOnLogMessage(Self, etError, Msg); end; procedure TTelegramSender.InfoMessage(const Msg: String); begin if Assigned(FOnLogMessage) then FOnLogMessage(Self, etInfo, Msg); end; function TTelegramSender.HTTPPostFile(const Method, FileField, FileName: String; AFormData: TStrings): Boolean; var HTTP: TFPHTTPClient; AStream: TStringStream; begin HTTP:=TFPHTTPClient.Create(nil); AStream:=TStringStream.Create(''); try HTTP.AddHeader('Content-Type','multipart/form-data'); HTTP.FileFormPost(API_URL+FToken+'/'+Method, AFormData, FileField, FileName, AStream); FResponse:=AStream.DataString; Result:=True; except Result:=False; end; AStream.Free; HTTP.Free; end; function TTelegramSender.HTTPPostJSON(const Method: String): Boolean; var HTTP: TFPHTTPClient; begin HTTP:=TFPHTTPClient.Create(nil); try HTTP.RequestBody:=TStringStream.Create(FRequestBody); try HTTP.AddHeader('Content-Type','application/json'); FResponse:=HTTP.Post(API_URL+FToken+'/'+Method); finally HTTP.RequestBody.Free; end; Result:=True; except Result:=False; end; HTTP.Free; end; function TTelegramSender.SendFile(const AMethod, AFileField, AFileName: String; MethodParameters: TStrings): Boolean; begin Result:=False; DebugMessage('Request for method "'+AMethod+'": '+FRequestBody); DebugMessage('Sending file '+AFileName); try Result:=HTTPPostFile(AMethod, AFileField, AFileName, MethodParameters); DebugMessage('Response: '+FResponse); except ErrorMessage('It is not succesful request to API! Request body: '+FRequestBody); end; end; procedure TTelegramSender.SetRequestBody(AValue: String); begin if FRequestBody=AValue then Exit; FRequestBody:=AValue; end; procedure TTelegramSender.SetRequestWhenAnswer(AValue: Boolean); begin if FRequestWhenAnswer=AValue then Exit; FRequestWhenAnswer:=AValue; end; function TTelegramSender.SendMethod(const Method: String; MethodParameters: array of const): Boolean; var sendObj: TJSONObject; begin sendObj:=TJSONObject.Create(MethodParameters); Result:=SendMethod(Method, sendObj); sendObj.Free; end; function TTelegramSender.SendMethod(const Method: String; MethodParameters: TJSONObject): Boolean; begin Result:=False; if not FRequestWhenAnswer then begin RequestBody:=MethodParameters.AsJSON; DebugMessage('Request for method "'+Method+'": '+FRequestBody); try Result:=HTTPPostJson(Method); DebugMessage('Response: '+FResponse); except ErrorMessage('It is not succesful request to API! Request body: '+FRequestBody); end; end else begin MethodParameters.Strings[s_Method]:=Method; RequestBody:=MethodParameters.AsJSON; DebugMessage('Request in HTTP reply: '+FRequestBody); Result:=True; end; end; constructor TTelegramSender.Create(const AToken: String); begin inherited Create; FToken:=AToken; FRequestWhenAnswer:=False; end; function TTelegramSender.editMessageText(const AMessage: String; chat_id: Int64; message_id: Int64; ParseMode: TParseMode; DisableWebPagePreview: Boolean; inline_message_id: String; ReplyMarkup: TReplyMarkup): Boolean; var sendObj: TJSONObject; begin Result:=False; sendObj:=TJSONObject.Create; with sendObj do try if chat_id<>0 then Add(s_ChatId, chat_id); if message_id<>0 then Add(s_MessageId, message_id); if inline_message_id<>EmptyStr then Add(s_InlineMessageId, inline_message_id); Add(s_Text, AMessage); if ParseMode<>pmDefault then Add(s_ParseMode, ParseModes[ParseMode]); Add(s_DsblWbpgPrvw, DisableWebPagePreview); if Assigned(ReplyMarkup) then Add(s_ReplyMarkup, ReplyMarkup.Clone); // Clone of ReplyMarkup object will have released with sendObject Result:=SendMethod(s_editMessageText, sendObj); finally Free; end; end; function TTelegramSender.sendDocumentByFileName(chat_id: Int64; const AFileName: String; const ACaption: String; ReplyMarkup: TReplyMarkup): Boolean; var sendObj: TStringList; begin Result:=False; sendObj:=TStringList.Create; with sendObj do try Add(s_ChatId+'='+IntToStr(chat_id)); if ACaption<>EmptyStr then Add(s_Caption+'='+ACaption); if Assigned(ReplyMarkup) then Add(s_ReplyMarkup+'='+ReplyMarkup.AsJSON); Result:=SendFile(s_sendDocument, s_Document, AFileName, sendObj); finally Free; end; end; function TTelegramSender.sendLocation(chat_id: Int64; Latitude, Longitude: Real; LivePeriod: Integer; ParseMode: TParseMode; DisableWebPagePreview: Boolean; ReplyMarkup: TReplyMarkup): Boolean; var sendObj: TJSONObject; begin Result:=False; sendObj:=TJSONObject.Create; with sendObj do try Add(s_ChatId, chat_id); Add(s_Latitude, Latitude); Add(s_Longitude, Longitude); if LivePeriod<>0 then Add(s_LivePeriod, LivePeriod); if ParseMode<>pmDefault then Add(s_ParseMode, ParseModes[ParseMode]); Add(s_DsblWbpgPrvw, DisableWebPagePreview); if Assigned(ReplyMarkup) then Add(s_ReplyMarkup, ReplyMarkup.Clone); // Clone of ReplyMarkup object will have released with sendObject Result:=SendMethod(s_sendLocation, sendObj); finally Free; end; end; { https://core.telegram.org/bots/api#sendmessage } function TTelegramSender.sendMessage(chat_id: Int64; const AMessage: String; ParseMode: TParseMode = pmDefault; DisableWebPagePreview: Boolean=False; ReplyMarkup: TReplyMarkup = nil): Boolean; var sendObj: TJSONObject; begin Result:=False; sendObj:=TJSONObject.Create; with sendObj do try Add(s_ChatId, chat_id); Add(s_Text, AMessage); if ParseMode<>pmDefault then Add(s_ParseMode, ParseModes[ParseMode]); Add(s_DsblWbpgPrvw, DisableWebPagePreview); if Assigned(ReplyMarkup) then Add(s_ReplyMarkup, ReplyMarkup.Clone); // Clone of ReplyMarkup object will have released with sendObject Result:=SendMethod(s_sendMessage, sendObj); finally Free; end; end; { https://core.telegram.org/bots/api#sendphoto } function TTelegramSender.sendPhoto(chat_id: Int64; const APhoto: String; const ACaption: String): Boolean; begin Result:=SendMethod(s_sendPhoto, ['chat_id', chat_id, 'photo', APhoto, 'caption', ACaption]); end; { https://core.telegram.org/bots/api#sendvideo } function TTelegramSender.sendVideo(chat_id: Int64; const AVideo: String; const ACaption: String): Boolean; begin Result:=SendMethod(s_sendVideo, ['chat_id', chat_id, 'video', AVideo, 'caption', ACaption]); end; end.
unit DataStorage; { Author: Sergey Bodrov (serbod@gmail.com) 2010-2016 } {$ifdef FPC} {$mode objfpc}{$H+} {$endif} interface uses Classes, SysUtils; type TDataStorageType = (stUnknown, stString, stInteger, stNumber, stList, stDictionary); { IDataStorage } IDataStorage = interface { Items count for (List, Dictionary) types } function GetCount(): integer; //procedure SetStorageType(const AValue: TDataStorageType); function GetStorageType(): TDataStorageType; { Set value, if storage type is Dictionary, then AName used } procedure SetValue(AValue: IDataStorage; const AName: string = ''); overload; procedure SetValue(AValue: AnsiString; const AName: string = ''); overload; procedure SetValue(AValue: Integer; const AName: string = ''); overload; procedure SetValue(AValue: Int64; const AName: string = ''); overload; procedure SetValue(AValue: Real; const AName: string = ''); overload; procedure SetValue(AValue: Boolean; const AName: string = ''); overload; { get storage value } function GetValue(): AnsiString; { Get storage item by name } function GetObject(const AName: string): IDataStorage; overload; { Get storage item by index } function GetObject(Index: integer): IDataStorage; overload; { Get name by index } function GetObjectName(Index: integer): string; { Get string by name (from dictionary). If name empty, get value } function GetString(const AName: string = ''): string; function GetInteger(const AName: string = ''): Integer; function GetInt64(const AName: string = ''): Int64; function GetCardinal(const AName: string = ''): Cardinal; function GetReal(const AName: string = ''): Real; function GetBool(const AName: string = ''): Boolean; function HaveName(const AName: string): Boolean; procedure Clear(); { get length of all contained items and subitems, including dictionary names } function GetSize(): Int64; end; { TDataStorage } TDataStorage = class(TInterfacedObject, IDataStorage) private { stUnknown, stString, stInteger, stNumber, stList, stDictionary } FStorageType: TDataStorageType; { Value for (String, Integer, Number) types } FValue: AnsiString; FIntfList: TInterfaceList; { [name:object] items storage } FItems: TStringList; procedure AddValue(AStorageType: TDataStorageType; const AName: string; const AValue: AnsiString); public constructor Create(AStorageType: TDataStorageType); destructor Destroy(); override; { Items count for (List, Dictionary) types } function GetCount(): integer; //procedure SetStorageType(const AValue: TDataStorageType); function GetStorageType(): TDataStorageType; { Set value, if storage type is Dictionary, then AName used for (List) is add value} procedure SetValue(AValue: IDataStorage; const AName: string = ''); overload; procedure SetValue(AValue: AnsiString; const AName: string = ''); overload; procedure SetValue(AValue: Integer; const AName: string = ''); overload; procedure SetValue(AValue: Int64; const AName: string = ''); overload; procedure SetValue(AValue: Real; const AName: string = ''); overload; procedure SetValue(AValue: Boolean; const AName: string = ''); overload; { get storage value } function GetValue(): AnsiString; { set storage value } procedure SetValueStr(const AValue: AnsiString); overload; { Get storage item by name } function GetObject(const AName: string): IDataStorage; overload; { Get storage item by index } function GetObject(Index: integer): IDataStorage; overload; { Get name by index } function GetObjectName(Index: integer): string; { Get string by name (from dictionary). If name empty, get value } function GetString(const AName: string = ''): string; function GetInteger(const AName: string = ''): Integer; function GetInt64(const AName: string = ''): Int64; function GetCardinal(const AName: string = ''): Cardinal; function GetReal(const AName: string = ''): Real; function GetBool(const AName: string = ''): Boolean; function HaveName(const AName: string): Boolean; procedure Clear(); { get size of all contained items and subitems, including dictionary names: numerics - SizeOf() strings - Length() } function GetSize(): Int64; property Count: Integer read GetCount; { stUnknown, stString, stInteger, stNumber, stList, stDictionary } property StorageType: TDataStorageType read GetStorageType; { Value for (String, Integer, Number) types } property Value: AnsiString read GetValue write SetValueStr; end; { TDataSerializer } TDataSerializer = class(TObject) public function GetName(): string; virtual; // Serialize storage to string function StorageToString(AStorage: IDataStorage): AnsiString; virtual; abstract; // De-serialize string into AStorage (not nil) function StorageFromString(const AString: AnsiString): IDataStorage; virtual; abstract; // Save storage to file. Filename must be without extension function StorageToFile(AStorage: IDataStorage; AFileName: string): Boolean; virtual; abstract; // Fill AStorage (not nil) from file. Filename must be without extension function StorageFromFile(AFileName: string): IDataStorage; virtual; abstract; // Save storage to TStream. function StorageToStream(AStorage: IDataStorage; AStream: TStream): Boolean; virtual; abstract; // Fill AStorage (not nil) from TStream. function StorageFromStream(AStream: TStream): IDataStorage; virtual; abstract; end; { TDataSerializerBencode } { Bencode serializer integers: i<value>e i0e i42e i-42e strings: <value_len>:<value> 3:ben 4:code lists: l<items>e (without any spaces) l i42e 3:ben 4:code e dictionaries: d<items>e where items is <string_name><value> d 4:name 3:ben 4:code i42e e } TDataSerializerBencode = class(TDataSerializer) private function ReadBencodeValue(const AString: AnsiString; var APos: Cardinal; ALen: Cardinal): IDataStorage; function ReadBencodeIntegerStr(const AString: AnsiString; var APos: Cardinal; ALen: Cardinal): AnsiString; function ReadBencodeString(const AString: AnsiString; var APos: Cardinal; ALen: Cardinal): AnsiString; function ReadBencodeList(const AString: AnsiString; var APos: Cardinal; ALen: Cardinal): IDataStorage; function ReadBencodeDictionary(const AString: AnsiString; var APos: Cardinal; ALen: Cardinal): IDataStorage; public function GetName(): string; override; function StorageToString(AStorage: IDataStorage): AnsiString; override; function StorageFromString(const AString: AnsiString): IDataStorage; override; function StorageToFile(AStorage: IDataStorage; AFileName: string): Boolean; override; function StorageFromFile(AFileName: string): IDataStorage; override; function StorageToStream(AStorage: IDataStorage; AStream: TStream): Boolean; override; function StorageFromStream(AStream: TStream): IDataStorage; override; end; // shared functions function StrToFile(const FileName, Str: AnsiString): Boolean; function FileToStr(const FileName: string): AnsiString; var DataFormatSettings: TFormatSettings; implementation function StreamToStr(AStream: TStream): AnsiString; var len, n: Integer; begin if Assigned(AStream) and (AStream.Size > 0) then begin len := AStream.Size; SetLength(Result, len); AStream.Seek(0, soFromBeginning); n := AStream.Read(Result[1], AStream.Size); if n < len then SetLength(Result, n); end else Result := ''; end; function StrToStream(const s: AnsiString; AStream: TStream): Boolean; var len, n: Integer; begin len := Length(s); n := 0; if Assigned(AStream) and (len > 0) then begin AStream.Seek(0, soFromBeginning); n := AStream.Write(s[1], len); end; Result := (n = len); end; function StrToFile(const FileName, Str: AnsiString): Boolean; var fs: TFileStream; begin Result := False; try fs := TFileStream.Create(FileName, fmCreate); except fs := nil; end; if not Assigned(fs) then Exit; try StrToStream(Str, fs); Result := True; finally FreeAndNil(fs); end; end; function FileToStr(const FileName: string): AnsiString; var fs: TFileStream; begin Result := ''; if not FileExists(FileName) then Exit; try fs := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except fs := nil; end; if not Assigned(fs) then Exit; try Result := StreamToStr(fs); finally fs.Free(); end; end; { TDataStorage } constructor TDataStorage.Create(AStorageType: TDataStorageType); begin inherited Create(); FStorageType := AStorageType; FValue := ''; FItems := TStringList.Create(); FIntfList := TInterfaceList.Create(); //FItems.OwnsObjects := True; end; destructor TDataStorage.Destroy(); begin Clear(); FreeAndNil(FIntfList); FreeAndNil(FItems); inherited Destroy(); end; function TDataStorage.GetCount(): integer; begin Result := FItems.Count; end; function TDataStorage.GetObject(const AName: string): IDataStorage; var n: integer; begin n := FItems.IndexOf(AName); if n >= 0 then begin Result := IDataStorage(FIntfList[n]); if Result.GetStorageType() in [stList, stDictionary] then Exit; end; Result := nil; end; function TDataStorage.GetObject(Index: integer): IDataStorage; begin Result := nil; if (Index >= 0) and (Index < Count) then begin Result := IDataStorage(FIntfList[Index]); end; end; function TDataStorage.GetObjectName(Index: integer): string; begin Result := ''; if (Index >= 0) and (Index < FItems.Count) then Result := FItems[Index]; end; function TDataStorage.GetString(const AName: string): string; var n: integer; TmpItem: IDataStorage; begin Result := ''; if AName = '' then Result := FValue else begin n := FItems.IndexOf(AName); if n <> -1 then begin TmpItem := IDataStorage(FIntfList[n]); Result := TmpItem.GetValue(); //if TmpItem.StorageType=stString then Result:=TmpItem.Value; end; end; end; function TDataStorage.GetInteger(const AName: string): Integer; begin Result := StrToIntDef(GetString(AName), 0); end; function TDataStorage.GetInt64(const AName: string = ''): Int64; begin Result := StrToInt64Def(GetString(AName), 0); end; function TDataStorage.GetCardinal(const AName: string): Cardinal; begin Result := StrToInt64Def(GetString(AName), 0); end; function TDataStorage.GetReal(const AName: string): Real; begin Result := StrToFloatDef(GetString(AName), 0, DataFormatSettings); end; function TDataStorage.GetBool(const AName: string): Boolean; begin Result := (GetString(AName) = '1'); end; function TDataStorage.HaveName(const AName: string): Boolean; begin Result := (FItems.IndexOf(AName) <> -1); end; procedure TDataStorage.Clear(); {var i: Integer; TmpObj: TObject; } begin {for i := Count-1 downto 0 do begin TmpObj := FItems.Objects[i]; FItems.Objects[i] := nil; TmpObj.Free(); end; } FItems.Clear(); FIntfList.Clear(); FValue := ''; end; function TDataStorage.GetStorageType(): TDataStorageType; begin Result := FStorageType; end; function TDataStorage.GetValue(): AnsiString; begin Result := FValue; end; procedure TDataStorage.AddValue(AStorageType: TDataStorageType; const AName: string; const AValue: AnsiString); var TmpItem: IDataStorage; begin TmpItem := TDataStorage.Create(AStorageType); TmpItem.SetValue(AValue); FItems.Add(AName); FIntfList.Add(TmpItem); end; procedure TDataStorage.SetValue(AValue: AnsiString; const AName: string); begin if (FStorageType = stDictionary) or (FStorageType = stList) then begin AddValue(stString, AName, AValue); end else FValue := AValue; end; procedure TDataStorage.SetValue(AValue: IDataStorage; const AName: string); begin if (FStorageType = stDictionary) or (FStorageType = stList) then begin if Assigned(AValue) then begin FIntfList.Add(AValue); FItems.Add(AName); end; end else begin // not valid for current storage type end; end; procedure TDataStorage.SetValue(AValue: Integer; const AName: string); begin if (FStorageType = stDictionary) or (FStorageType = stList) then begin AddValue(stInteger, AName, IntToStr(AValue)); end else FValue := IntToStr(AValue); end; procedure TDataStorage.SetValue(AValue: Int64; const AName: string); begin if (FStorageType = stDictionary) or (FStorageType = stList) then begin AddValue(stInteger, AName, IntToStr(AValue)); end else FValue := IntToStr(AValue); end; procedure TDataStorage.SetValue(AValue: Boolean; const AName: string); begin if AValue then Self.SetValue('1', AName) else Self.SetValue('0', AName); end; procedure TDataStorage.SetValue(AValue: Real; const AName: string); begin if (FStorageType = stDictionary) or (FStorageType = stList) then begin AddValue(stNumber, AName, FloatToStr(AValue, DataFormatSettings)); end else FValue := FloatToStr(AValue, DataFormatSettings); end; procedure TDataStorage.SetValueStr(const AValue: AnsiString); begin SetValue(AValue); end; function TDataStorage.GetSize(): Int64; var i: Integer; begin case FStorageType of stUnknown: Result := 0; stString, stInteger, stNumber: Result := Length(FValue); stList, stDictionary: begin Result := 0; for i := 0 to Count-1 do begin Result := Length(GetObjectName(i)) + GetObject(i).GetSize(); end; end; else Result := 0; end; end; { TDataSerializer } function TDataSerializer.GetName: string; begin Result := 'NONE'; end; { TDataSerializerBencode } function TDataSerializerBencode.GetName(): string; begin Result := 'BENCODE'; end; function TDataSerializerBencode.StorageToStream(AStorage: IDataStorage; AStream: TStream): Boolean; procedure WriteStr(const AStr: AnsiString); begin AStream.Write(PAnsiChar(AStr)^, Length(AStr)); end; var sName: AnsiString; SubItem: IDataStorage; i: integer; s: AnsiString; begin case AStorage.GetStorageType() of stString: begin s := AStorage.GetValue(); WriteStr(IntToStr(Length(s)) + ':' + s); end; stNumber: begin s := AStorage.GetValue(); WriteStr(IntToStr(Length(s)) + ':' + s); end; stInteger: begin WriteStr('i' + AStorage.GetValue() + 'e'); end; stDictionary: begin WriteStr('d'); for i := 0 to AStorage.GetCount() - 1 do begin sName := AStorage.GetObjectName(i); SubItem := AStorage.GetObject(i); // name WriteStr(IntToStr(Length(sName)) + ':' + sName); // value StorageToStream(SubItem, AStream); end; WriteStr('e'); end; stList: begin WriteStr('l'); for i := 0 to AStorage.GetCount() - 1 do begin SubItem := AStorage.GetObject(i); // value StorageToStream(SubItem, AStream); end; WriteStr('e'); end; end; Result := True; end; function TDataSerializerBencode.StorageFromStream(AStream: TStream): IDataStorage; var s: AnsiString; begin s := StreamToStr(AStream); Result := StorageFromString(s); end; function TDataSerializerBencode.ReadBencodeIntegerStr(const AString: AnsiString; var APos: Cardinal; ALen: Cardinal): AnsiString; begin Result := ''; if AString[APos] = 'i' then Inc(APos) else Exit; while APos <= ALen do begin if AString[APos] = 'e' then begin Inc(APos); Break end; Result := Result + AString[APos]; Inc(APos); end; end; function TDataSerializerBencode.ReadBencodeString(const AString: AnsiString; var APos: Cardinal; ALen: Cardinal): AnsiString; var sValue: AnsiString; ValueLen: Cardinal; begin Result := ''; sValue := ''; while APos <= ALen do begin if AString[APos] = ':' then begin ValueLen := StrToIntDef(sValue, 0); Result := Copy(AString, APos + 1, ValueLen); APos := APos + ValueLen + 1; Exit; end; sValue := sValue + AString[APos]; Inc(APos); end; end; function TDataSerializerBencode.ReadBencodeDictionary(const AString: AnsiString; var APos: Cardinal; ALen: Cardinal): IDataStorage; var sName: AnsiString; SubStorage: IDataStorage; begin Result := nil; if AString[APos] = 'd' then Inc(APos) else Exit; Result := TDataStorage.Create(stDictionary); while APos <= ALen do begin if AString[APos] = 'e' then begin Inc(APos); Exit; end; sName := ReadBencodeString(AString, APos, ALen); SubStorage := ReadBencodeValue(AString, APos, ALen); if Assigned(SubStorage) then Result.SetValue(SubStorage, sName); end; Assert(False, 'End of dict not found'); Result := nil; end; function TDataSerializerBencode.ReadBencodeList(const AString: AnsiString; var APos: Cardinal; ALen: Cardinal): IDataStorage; var SubStorage: IDataStorage; begin Result := nil; if AString[APos] = 'l' then Inc(APos) else Exit; Result := TDataStorage.Create(stList); while APos <= ALen do begin if AString[APos] = 'e' then begin Inc(APos); Exit; end; SubStorage := ReadBencodeValue(AString, APos, ALen); if Assigned(SubStorage) then Result.SetValue(SubStorage); end; Assert(False, 'End of list not found'); Result := nil; end; function TDataSerializerBencode.ReadBencodeValue(const AString: AnsiString; var APos: Cardinal; ALen: Cardinal): IDataStorage; begin Result := nil; if APos <= ALen then begin if AString[APos] = 'i' then begin // read integer value Result := TDataStorage.Create(stInteger); Result.SetValue(ReadBencodeIntegerStr(AString, APos, ALen)); end else if Pos(AString[APos], '0123456789') > 0 then begin // read string value Result := TDataStorage.Create(stString); Result.SetValue(ReadBencodeString(AString, APos, ALen)); end else if AString[APos] = 'd' then begin // read dictionary value Result := ReadBencodeDictionary(AString, APos, ALen); end else if AString[APos] = 'l' then begin // read list value Result := ReadBencodeList(AString, APos, ALen); end else begin // error Assert(1=0, 'Bencode parsing error, index=' + IntToStr(APos) + ' char=' + AString[APos]); Exit; end; end; end; function TDataSerializerBencode.StorageToString(AStorage: IDataStorage): AnsiString; var ms: TMemoryStream; begin ms := TMemoryStream.Create(); try if StorageToStream(AStorage, ms) then Result := StreamToStr(ms) else Result := ''; finally ms.Free(); end; end; function TDataSerializerBencode.StorageFromString(const AString: AnsiString): IDataStorage; var n: Cardinal; begin n := 1; Result := ReadBencodeValue(AString, n, Length(AString)); Assert(Result <> nil, 'Read value failed, len='+IntToStr(Length(AString))); end; function TDataSerializerBencode.StorageToFile(AStorage: IDataStorage; AFileName: string): Boolean; var ms: TMemoryStream; begin Result := False; if Trim(AFileName) = '' then Exit; if Pos('.be', AFileName) < (Length(AFileName) - 2) then AFileName := AFileName + '.be'; //Result := StrToFile(AFileName, Self.StorageToString(AStorage)); ms := TMemoryStream.Create(); try ms.Size := Trunc(AStorage.GetSize() * 1.1); StorageToStream(AStorage, ms); ms.SaveToFile(AFileName); finally ms.Free(); end; end; function TDataSerializerBencode.StorageFromFile(AFileName: string): IDataStorage; begin Result := nil; if Trim(AFileName) = '' then Exit; if Pos('.be', AFileName) < (Length(AFileName) - 2) then AFileName := AFileName + '.be'; Result := Self.StorageFromString(FileToStr(AFileName)); end; initialization DataFormatSettings.DecimalSeparator := '.'; end.
// Written By Ismael Heredia in the year 2016 unit FormProductos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, Vcl.ComCtrls, Vcl.StdCtrls, AccesoDatos, Producto, Proveedor, Funciones; type TProductos = class(TForm) mmOpciones: TMainMenu; O1: TMenuItem; A1: TMenuItem; E1: TMenuItem; E2: TMenuItem; C1: TMenuItem; R1: TMenuItem; G1: TMenuItem; status: TStatusBar; gbAgregarProducto: TGroupBox; lblNombre: TLabel; lblDescripcion: TLabel; txtNombre: TEdit; mmDescripcion: TMemo; lblProveedor: TLabel; cmbProveedor: TComboBox; lblPrecio: TLabel; txtPrecio: TEdit; txtID: TEdit; btnGrabar: TButton; gbProductos: TGroupBox; lvProductos: TListView; ppOpciones: TPopupMenu; A2: TMenuItem; E3: TMenuItem; B1: TMenuItem; C2: TMenuItem; R2: TMenuItem; G2: TMenuItem; procedure btnGrabarClick(Sender: TObject); procedure lvProductosDblClick(Sender: TObject); procedure A2Click(Sender: TObject); procedure E3Click(Sender: TObject); procedure B1Click(Sender: TObject); procedure C2Click(Sender: TObject); procedure R2Click(Sender: TObject); procedure G2Click(Sender: TObject); procedure A1Click(Sender: TObject); procedure E1Click(Sender: TObject); procedure E2Click(Sender: TObject); procedure C1Click(Sender: TObject); procedure R1Click(Sender: TObject); procedure G1Click(Sender: TObject); private { Private declarations } public { Public declarations } nuevo: boolean; procedure cargarListaProductos(); procedure limpiar(); procedure cargarCamposProducto(id_producto_to_load: integer); function validar(): boolean; procedure agregar(); procedure editar(); procedure cancelar(); procedure cargarComboProveedores(); procedure borrar(); procedure grabar(); procedure recargarLista(); end; var Productos: TProductos; implementation {$R *.dfm} procedure TProductos.cargarComboProveedores(); var AccesoDatos: TAccesoDatos; lista: TStringList; i: integer; Proveedor: TProveedor; begin cmbProveedor.Clear; AccesoDatos := TAccesoDatos.Create(); lista := AccesoDatos.CargarListaProveedores; for i := 0 to lista.Count - 1 do begin Proveedor := TProveedor(lista.Objects[i]); cmbProveedor.AddItem(Proveedor.getNombre_empresa, TObject(Proveedor.getId_proveedor)); end; if (lista.Count >= 1) then begin cmbProveedor.ItemIndex := 0; end; AccesoDatos.Free; end; procedure TProductos.cargarListaProductos(); var AccesoDatos: TAccesoDatos; lista: TStringList; i: integer; Producto: TProducto; var id_producto: integer; nombre_producto: string; descripcion: string; precio: integer; id_proveedor: integer; fecha_registro: string; nombre_proveedor: string; begin lvProductos.Items.Clear; AccesoDatos := TAccesoDatos.Create(); lista := AccesoDatos.cargarListaProductos(); for i := 0 to lista.Count - 1 do begin with lvProductos.Items.Add do begin Producto := TProducto(lista.Objects[i]); id_producto := Producto.getId_producto; nombre_producto := Producto.getNombre_producto; descripcion := Producto.getDescripcion; precio := Producto.getPrecio; id_proveedor := Producto.getId_proveedor; fecha_registro := Producto.getFecha_registro; nombre_proveedor := AccesoDatos.cargarNombreProveedor(id_proveedor); Caption := nombre_producto; SubItems.Add(descripcion); SubItems.Add(IntToStr(precio)); SubItems.Add(fecha_registro); SubItems.Add(nombre_proveedor); Data := Pointer(id_producto); Producto.Free; end; end; lista.Free; AccesoDatos.Free; end; procedure TProductos.E1Click(Sender: TObject); begin editar(); end; procedure TProductos.E2Click(Sender: TObject); begin borrar(); end; procedure TProductos.E3Click(Sender: TObject); begin editar(); end; procedure TProductos.limpiar(); begin txtID.Text := ''; txtNombre.Text := ''; mmDescripcion.Text := ''; cmbProveedor.ItemIndex := -1; txtPrecio.Text := ''; end; procedure TProductos.cargarCamposProducto(id_producto_to_load: integer); var AccesoDatos: TAccesoDatos; Producto: TProducto; nombre_empresa: string; index_proveedor: integer; begin AccesoDatos := TAccesoDatos.Create(); Producto := AccesoDatos.CargarProducto(id_producto_to_load); txtID.Text := IntToStr(Producto.getId_producto); txtNombre.Text := Producto.getNombre_producto; mmDescripcion.Text := Producto.getDescripcion; nombre_empresa := AccesoDatos.cargarNombreProveedor(Producto.getId_proveedor); index_proveedor := cmbProveedor.Items.IndexOf(nombre_empresa); cmbProveedor.ItemIndex := index_proveedor; txtPrecio.Text := IntToStr(Producto.getPrecio); Producto.Free; AccesoDatos.Free(); end; function TProductos.validar(): boolean; var respuesta: boolean; begin if (txtNombre.Text = '') then begin ShowMessage('Falta el nombre'); txtNombre.setFocus; respuesta := false; end else if (mmDescripcion.Text = '') then begin ShowMessage('Falta la descripcion'); mmDescripcion.setFocus; respuesta := false; end else if (cmbProveedor.ItemIndex = -1) or (cmbProveedor.Text = '') then begin ShowMessage('Seleccione proveedor'); cmbProveedor.setFocus; respuesta := false; end else if (txtPrecio.Text = '') then begin ShowMessage('Falta el precio'); txtPrecio.setFocus; respuesta := false; end else begin respuesta := true; end; Result := respuesta; end; procedure TProductos.A1Click(Sender: TObject); begin agregar(); end; procedure TProductos.A2Click(Sender: TObject); begin agregar(); end; procedure TProductos.agregar(); var AccesoDatos: TAccesoDatos; begin AccesoDatos := TAccesoDatos.Create; status.Panels[0].Text := '[+] Programa en modo nuevo'; nuevo := true; limpiar(); // txtID.Text := IntToStr(Conexion.cargar_id_nuevo_para_producto); AccesoDatos.Free; ShowMessage('Programa en modo nuevo'); end; procedure TProductos.B1Click(Sender: TObject); begin borrar(); end; procedure TProductos.editar(); begin status.Panels[0].Text := '[+] Programa en modo editar'; nuevo := false; ShowMessage('Programa en modo editar'); end; procedure TProductos.G1Click(Sender: TObject); begin grabar(); end; procedure TProductos.G2Click(Sender: TObject); begin grabar(); end; procedure TProductos.cancelar(); begin status.Panels[0].Text := '[+] Programa cargado'; nuevo := false; limpiar(); ShowMessage('Opcion cancelada'); end; procedure TProductos.borrar(); var response: integer; AccesoDatos: TAccesoDatos; Producto: TProducto; nombre_producto: string; id_producto: integer; sql: string; begin if lvProductos.Selected <> nil then begin id_producto := integer(lvProductos.Items[lvProductos.Selected.index].Data); AccesoDatos := TAccesoDatos.Create(); Producto := AccesoDatos.CargarProducto(id_producto); nombre_producto := Producto.getNombre_producto; response := Application.MessageBox (Pchar('¿ Esta seguro borrar el registro ' + nombre_producto + ' ?'), '¿ Desea borrar este registro ?', MB_ICONQUESTION or MB_YESNO); if response = IDYES then begin sql := 'delete from productos where id_producto=' + IntToStr(id_producto); if (AccesoDatos.EjecutarComando(sql)) then begin ShowMessage('Registro borrado'); status.Panels[0].Text := 'Registro borrado'; end else begin ShowMessage('Ha ocurrido un error'); status.Panels[0].Text := 'Ha ocurrido un error'; end; end; AccesoDatos.Free(); recargarLista(); end; end; procedure TProductos.recargarLista(); begin cargarListaProductos(); cargarComboProveedores(); end; procedure TProductos.grabar(); var AccesoDatos: TAccesoDatos; Producto: TProducto; sql: string; grabar_ready: boolean; begin grabar_ready := false; if (validar()) then begin Producto := TProducto.Create(); if not(txtID.Text = '') then begin Producto.setId_producto(StrToInt(txtID.Text)); end; Producto.setNombre_producto(txtNombre.Text); Producto.setDescripcion(mmDescripcion.Text); Producto.setPrecio(StrToInt(txtPrecio.Text)); Producto.setFecha_registro(fecha_del_dia()); Producto.setId_proveedor (integer(cmbProveedor.Items.Objects[cmbProveedor.ItemIndex])); sql := ''; AccesoDatos := TAccesoDatos.Create(); if (nuevo) then begin sql := 'insert into productos(nombre_producto,descripcion,precio,id_proveedor,fecha_registro) values("' + Producto.getNombre_producto() + '","' + Producto.getDescripcion() + '","' + IntToStr(Producto.getPrecio()) + '","' + IntToStr(Producto.getId_proveedor()) + '","' + Producto.getFecha_registro() + '")'; end else begin sql := 'update productos set nombre_producto="' + Producto.getNombre_producto() + '",descripcion="' + Producto.getDescripcion() + '",precio=' + IntToStr(Producto.getPrecio()) + ',id_proveedor=' + IntToStr(Producto.getId_proveedor()) + ' where id_producto=' + IntToStr(Producto.getId_producto()); end; // ShowMessage(sql); if (nuevo) then begin if (AccesoDatos.comprobar_existencia_producto_crear (Producto.getNombre_producto())) then begin grabar_ready := false; end else begin grabar_ready := true; end; end else begin if (AccesoDatos.comprobar_existencia_producto_editar (Producto.getId_producto(), Producto.getNombre_producto())) then begin grabar_ready := false; end else begin grabar_ready := true; end; end; // ShowMessage(sql); if (grabar_ready) then begin if (AccesoDatos.EjecutarComando(sql)) then begin if (nuevo) then begin ShowMessage('Registro agregado'); status.Panels[0].Text := 'Registro agregado'; end else begin ShowMessage('Registro actualizado'); status.Panels[0].Text := 'Registro actualizado'; end; end else begin ShowMessage('Ha ocurrido un error'); status.Panels[0].Text := 'Ha ocurrido un error'; end; end else begin ShowMessage('El producto ' + Producto.getNombre_producto() + ' ya existe'); end; AccesoDatos.Free(); Producto.Free(); recargarLista(); end; end; procedure TProductos.lvProductosDblClick(Sender: TObject); var id_producto: integer; begin if lvProductos.Selected <> nil then begin id_producto := integer(lvProductos.Items[lvProductos.Selected.index].Data); cargarCamposProducto(id_producto); end; end; procedure TProductos.R1Click(Sender: TObject); begin recargarLista(); end; procedure TProductos.R2Click(Sender: TObject); begin recargarLista(); end; procedure TProductos.btnGrabarClick(Sender: TObject); begin grabar(); end; procedure TProductos.C1Click(Sender: TObject); begin cancelar(); end; procedure TProductos.C2Click(Sender: TObject); begin cancelar(); end; end.
PROGRAM EasySets (input, output); {Constantes} CONST MAX = 10; {Numéro máximo de elementos en una secuencia.} CANTSEC = 3; {Numéro máximo de secuencias.} {***********************************************************************************************************************} {Definición de tipos} TYPE Natural = 0..MAXINT; rangoSecs = 1..CANTSEC; Secuencia = RECORD valores : ARRAY [1..MAX] OF Natural; tope : 0..MAX; END; Coleccion = ^Celda; Celda = RECORD sec : Secuencia; sig : Coleccion; END; TipoResultado = (Fallo, Creado, Agregado); Resultado = RECORD CASE quePaso : TipoResultado OF Fallo: (); Creado: (); Agregado: (posicion: Natural) END; {***********************************************************************************************************************} {Variables} VAR opcion : Char; res: Resultado; secs : ARRAY [rangoSecs] OF Secuencia; idSec1, idSec2, idSec: rangoSecs; col: Coleccion; valor: Natural; pos, pos1, pos2: Natural; {***********************************************************************************************************************} {Procedimientos y funciones} PROCEDURE CrearSecuencia (VAR sec : Secuencia); {Crea una secuencia de números naturales vacía.} BEGIN sec.tope := 0 END; {-----------------------------------------------------------------------------------------------------------------------} PROCEDURE AgregarValor (VAR sec : Secuencia; valor : Natural; VAR res: Resultado); {Inserta ordenadamente (orden creciente) el parámetro "valor" en el parámetro "sec", y devuelve "Agregado" en "res.quePaso" (campo correspondiente del parámetro "res") y la posición en la cual fue insertado en "res.posicion" (campo correspondiente del parámetro "res"). Si el parámetro "sec" está lleno o el parámetro "valor" ya pertenece al mismo, devuelve "Fallo" en "res.quePaso" (campo correspondiente del parámetro "res").} VAR Indice, i : 1..MAX + 1; BEGIN IF sec.tope = MAX THEN res.quePaso := Fallo ELSE IF sec.tope = 0 THEN BEGIN sec.tope := 1; sec.valores [1] := valor; res.quePaso := Agregado; res.posicion := 1 END ELSE BEGIN Indice := 1; WHILE (Indice <= sec.tope) AND (sec.valores [Indice] < valor) DO Indice := Indice + 1; IF (Indice <= sec.tope) AND (sec.valores [Indice] = valor) THEN res.quePaso := Fallo ELSE BEGIN sec.tope := sec.tope + 1; FOR i := sec.tope DOWNTO Indice + 1 DO sec.valores [i] := sec.valores [i - 1]; sec.valores [Indice] := valor; res.quePaso := Agregado; res.posicion := Indice END END END; {-----------------------------------------------------------------------------------------------------------------------} FUNCTION SecuenciasIguales (sec1, sec2 : Secuencia) : Boolean; {Determina si los parámetros "sec1" y "sec2" tienen los mismos valores y posiciones.} VAR Indice : 1..MAX + 1; BEGIN IF sec1.tope = sec2.tope THEN BEGIN Indice := 1; WHILE (Indice <= sec1.tope) AND (sec1.valores [Indice] = sec2.valores [Indice]) DO Indice := Indice + 1; SecuenciasIguales := Indice > sec1.tope END ELSE SecuenciasIguales := FALSE END; {-----------------------------------------------------------------------------------------------------------------------} PROCEDURE SecuenciaFusionada (sec : Secuencia; VAR secF : Secuencia; VAR res: Resultado); {Le asigna al parámetro "secF" el parámetro "sec", y devuelve "Creado" en "res.quePaso" (campo correspondiente del parámetro "res").} BEGIN secF := sec; res.quePaso := Creado END; {-----------------------------------------------------------------------------------------------------------------------} PROCEDURE AgregarValores (sec1, sec2 : Secuencia; VAR sec3 : Secuencia; VAR res : Resultado); {Devuelve en el parámetro "sec3" la "unión" (entre comillas porque técnicamente no se está trabajando con conjuntos) en orden creciente de los parámetros "sec1" y "sec2", y devuelve "Creado" en "res.quePaso" (campo correspondiente del parámetro "res").} {Precondición: (sec1.tope <> 0) AND (sec2.tope <> 0) AND (sec1.tope + sec2.tope <= MAX)} VAR i : 2..MAX + 1; Indice, Posicion: 1..MAX + 1; BEGIN Indice := 1; Posicion := 1; REPEAT WHILE (Indice <= sec1.tope) AND (sec1.valores [Indice] < sec2.valores [Posicion]) DO Indice := Indice + 1; IF (Indice <= sec1.tope) AND (sec1.valores [Indice] = sec2.valores [Posicion]) THEN Posicion := Posicion + 1 ELSE BEGIN sec1.tope := sec1.tope + 1; FOR i := sec1.tope DOWNTO Indice + 1 DO sec1.valores [i] := sec1.valores [i - 1]; sec1.valores [Indice] := sec2.valores [Posicion]; Posicion := Posicion + 1; Indice := Indice + 1 END; UNTIL Posicion > sec2.tope; SecuenciaFusionada (sec1, sec3, res) END; {-----------------------------------------------------------------------------------------------------------------------} PROCEDURE AgregarValoresRigurosamente (sec1, sec2 : Secuencia; VAR sec3 : Secuencia; VAR res : Resultado); {Análogo al procedimiento "AgregarValores", pero en caso de que el parámetro "sec3" no tenga espacio suficiente para almacenar todos los valores, devuelve "Fallo" en "res.quePaso" (campo correspondiente del parámetro "res"), y el parámetro "sec3" queda indeterminado.} {Precondición: (sec1.tope <> 0) AND (sec2.tope <> 0)} VAR i : 2..MAX + 1; Indice, Posicion: 1..MAX + 1; BEGIN Indice := 1; Posicion := 1; REPEAT WHILE (Indice <= sec1.tope) AND (sec1.valores [Indice] < sec2.valores [Posicion]) DO Indice := Indice + 1; IF (Indice <= sec1.tope) AND (sec1.valores [Indice] = sec2.valores [Posicion]) THEN Posicion := Posicion + 1 ELSE IF sec1.tope < MAX THEN BEGIN sec1.tope := sec1.tope + 1; FOR i := sec1.tope DOWNTO Indice + 1 DO sec1.valores [i] := sec1.valores [i - 1]; sec1.valores [Indice] := sec2.valores [Posicion]; Posicion := Posicion + 1; Indice := Indice + 1 END UNTIL (Posicion > sec2.tope) OR (Indice >= MAX) OR (sec1.tope = MAX); IF (sec1.tope = MAX) AND (sec1.valores [Indice] <= sec2.valores [Posicion]) THEN REPEAT WHILE (Indice <= sec1.tope) AND (sec1.valores [Indice] < sec2.valores [Posicion]) DO Indice := Indice + 1; IF (Indice <= sec1.tope) AND (sec1.valores [Indice] = sec2.valores [Posicion]) THEN Posicion := Posicion + 1 UNTIL (Posicion > sec2.tope) OR (Indice > sec1.tope) OR (sec1.valores [Indice] > sec2.valores [Posicion]); IF Posicion <= sec2.tope THEN res.quePaso := Fallo ELSE SecuenciaFusionada (sec1, sec3, res) END; {-----------------------------------------------------------------------------------------------------------------------} PROCEDURE FusionarSecuencias (sec1, sec2 : Secuencia; VAR sec3 : Secuencia; VAR res: Resultado); {Análogo al procedimiento "AgregarValoresRigurosamente", con la excepción de que este procedimiento no tiene precondiciones.} BEGIN IF sec1.tope = 0 THEN SecuenciaFusionada (sec2, sec3, res) ELSE IF sec2.tope = 0 THEN SecuenciaFusionada (sec1, sec3, res) ELSE IF (sec1.tope = MAX) AND (sec2.tope = MAX) THEN IF SecuenciasIguales (sec1, sec2) THEN SecuenciaFusionada (sec1, sec3, res) ELSE res.quePaso := Fallo ELSE IF sec1.tope + sec2.tope <= MAX THEN IF sec1.tope >= sec2.tope THEN AgregarValores (sec1, sec2, sec3, res) ELSE AgregarValores (sec2, sec1, sec3, res) ELSE IF sec1.tope >= sec2.tope THEN AgregarValoresRigurosamente (sec1, sec2, sec3, res) ELSE AgregarValoresRigurosamente (sec2, sec1, sec3, res) END; {-----------------------------------------------------------------------------------------------------------------------} PROCEDURE CrearColeccion (VAR col : Coleccion); {Crea una lista encadenada vacía.} BEGIN New (col); col := NIL END; {-----------------------------------------------------------------------------------------------------------------------} PROCEDURE AgregarSecuencia (VAR col : Coleccion; sec : Secuencia; VAR pos : Natural); {Inserta el parámetro "sec" al final del parámetro "col", y devuelve en el parámetro "pos" la posición en el cual fue insertado.} VAR Posicion : 1..MAXINT; Final, Temp : Coleccion; BEGIN New (Final); Final^.sec := sec; Final^.sig := NIL; IF col = NIL THEN BEGIN Posicion := 1; col := Final END ELSE BEGIN Posicion := 2; Temp := col; WHILE Temp^.sig <> NIL DO BEGIN Temp := Temp^.sig; Posicion := Posicion + 1 END; Temp^.sig := Final END; pos := Posicion END; {-----------------------------------------------------------------------------------------------------------------------} FUNCTION todasIguales (col : Coleccion) : Boolean; {Determina si todas las secuencias del parámetro "col" son iguales. Si el parámetro "col" está vacío o tiene una sola secuencia, también devuelve true.} VAR sec : Secuencia; BEGIN IF (col = NIL) OR (col^.sig = NIL) THEN todasIguales := TRUE ELSE BEGIN REPEAT sec := col^.sec; col := col^.sig; UNTIL (col^.sig = NIL) OR NOT SecuenciasIguales (sec, col^.sec); todasIguales := SecuenciasIguales (sec, col^.sec) END END; {-----------------------------------------------------------------------------------------------------------------------} PROCEDURE SecuenciaFusionadaEnColeccion (sec : Secuencia; VAR secF : Secuencia; VAR res: Resultado); {Análogo al procedimiento "SecuenciaFusionada", con la excepción de que devuelve "Agregado" en vez de "Creado" en "res.quePaso" (campo correspondiente del parámetro "res").} BEGIN secF := sec; res.quePaso := Agregado END; {-----------------------------------------------------------------------------------------------------------------------} PROCEDURE AgregarValoresEnColeccion (sec1, sec2 : Secuencia; VAR sec3 : Secuencia; VAR res : Resultado); {Análogo al procedimiento "AgregarValores", con la excepción de que utiliza el procedimiento "SecuenciaFusionadaEnColeccion" en lugar de "SecuenciaFusionada".} VAR i : 2..MAX + 1; Indice, Posicion: 1..MAX + 1; BEGIN Indice := 1; Posicion := 1; REPEAT WHILE (Indice <= sec1.tope) AND (sec1.valores [Indice] < sec2.valores [Posicion]) DO Indice := Indice + 1; IF (Indice <= sec1.tope) AND (sec1.valores [Indice] = sec2.valores [Posicion]) THEN Posicion := Posicion + 1 ELSE BEGIN sec1.tope := sec1.tope + 1; FOR i := sec1.tope DOWNTO Indice + 1 DO sec1.valores [i] := sec1.valores [i - 1]; sec1.valores [Indice] := sec2.valores [Posicion]; Posicion := Posicion + 1; Indice := Indice + 1 END; UNTIL Posicion > sec2.tope; SecuenciaFusionadaEnColeccion (sec1, sec3, res) END; {-----------------------------------------------------------------------------------------------------------------------} PROCEDURE AgregarValoresRigurosamenteEnColeccion (sec1, sec2 : Secuencia; VAR sec3 : Secuencia; VAR res : Resultado); {Análogo al procedimiento "AgregarValoresRigurosamente", con la excepción de que utiliza el procedimiento "SecuenciaFusionadaEnColeccion" en lugar de "SecuenciaFusionada".} VAR i : 2..MAX + 1; Indice, Posicion: 1..MAX + 1; BEGIN Indice := 1; Posicion := 1; REPEAT WHILE (Indice <= sec1.tope) AND (sec1.valores [Indice] < sec2.valores [Posicion]) DO Indice := Indice + 1; IF (Indice <= sec1.tope) AND (sec1.valores [Indice] = sec2.valores [Posicion]) THEN Posicion := Posicion + 1 ELSE IF sec1.tope < MAX THEN BEGIN sec1.tope := sec1.tope + 1; FOR i := sec1.tope DOWNTO Indice + 1 DO sec1.valores [i] := sec1.valores [i - 1]; sec1.valores [Indice] := sec2.valores [Posicion]; Posicion := Posicion + 1; Indice := Indice + 1; END UNTIL (Posicion > sec2.tope) OR (Indice > sec1.tope) OR (sec1.tope = MAX); IF (sec1.tope = MAX) AND (sec1.valores [Indice] <= sec2.valores [Posicion]) THEN REPEAT WHILE (Indice <= sec1.tope) AND (sec1.valores [Indice] < sec2.valores [Posicion]) DO Indice := Indice + 1; IF (Indice <= sec1.tope) AND (sec1.valores [Indice] = sec2.valores [Posicion]) THEN Posicion := Posicion + 1 UNTIL (Posicion > sec2.tope) OR (Indice > sec1.tope) OR (sec1.valores [Indice] > sec2.valores [Posicion]); IF Posicion <= sec2.tope THEN res.quePaso := Fallo ELSE SecuenciaFusionadaEnColeccion (sec1, sec3, res) END; {-----------------------------------------------------------------------------------------------------------------------} PROCEDURE FusionarSecuenciasEnColeccion (sec1, sec2 : Secuencia; VAR sec3 : Secuencia; VAR res: Resultado); {Análogo al procedimiento "FusionarSecuencias", con la excepción de que utiliza el procedimiento "SecuenciaFusionadaEnColeccion" en lugar de "SecuenciaFusionada", el procedimiento "AgregarValoresEnColeccion" en lugar de "AgregarValores", y el procedimiento "AgregarValoresRigurosamenteEnColeccion" en lugar de "AgregarValoresRigurosamente".} BEGIN IF sec1.tope = 0 THEN SecuenciaFusionadaEnColeccion (sec2, sec3, res) ELSE IF sec2.tope = 0 THEN SecuenciaFusionadaEnColeccion (sec1, sec3, res) ELSE IF (sec1.tope = MAX) AND (sec2.tope = MAX) THEN IF SecuenciasIguales (sec1, sec2) THEN SecuenciaFusionadaEnColeccion (sec1, sec3, res) ELSE res.quePaso := Fallo ELSE IF sec1.tope + sec2.tope <= MAX THEN IF sec1.tope >= sec2.tope THEN AgregarValoresEnColeccion (sec1, sec2, sec3, res) ELSE AgregarValoresEnColeccion (sec2, sec1, sec3, res) ELSE IF sec1.tope >= sec2.tope THEN AgregarValoresRigurosamenteEnColeccion (sec1, sec2, sec3, res) ELSE AgregarValoresRigurosamenteEnColeccion (sec2, sec1, sec3, res) END; {-----------------------------------------------------------------------------------------------------------------------} PROCEDURE PosicionesDiferentes (VAR col : Coleccion; pos1, pos2 : Natural; VAR res : Resultado); {Dadas las posiciones de dos secuencias del parámetro "col" (parámetros "pos1" y "pos2"), crea una nueva secuencia conteniendo la "unión" (entre comillas porque técnicamente no se está trabajando con conjuntos) de ambas en orden creciente, y la inserta al final del parámetro "col", y devuelve "Agregado" en "res.quePaso" (campo correspondiente del parámetro "res") y la posición en la cual fue insertado en "res.posicion" (campo correspondiente del parámetro "res"). En caso de que los parámetros "pos1" o "pos2" sean posiciones inválidas, o que la nueva secuencia no tenga espacio suficiente para almacenar todos los valores, devuelve "Fallo" en "res.quePaso" (campo correspondiente del parámetro "res").} {Precondición: (col <> NIL) AND (pos1 <> 0) AND (pos2 <> 0) AND (pos1 <> pos2)} VAR Posicion : Natural; sec1, sec2 : Secuencia; Temp, Final : Coleccion; BEGIN Posicion := 1; Temp := col; WHILE (Temp^.sig <> NIL) AND (Posicion < pos1) DO BEGIN Posicion := Posicion + 1; Temp := Temp^.sig; END; IF Posicion = pos1 THEN BEGIN sec1 := Temp^.sec; WHILE (Temp^.sig <> NIL) AND (Posicion < pos2) DO BEGIN Posicion := Posicion + 1; Temp := Temp^.sig; END; IF Posicion = pos2 THEN BEGIN sec2 := Temp^.sec; FusionarSecuenciasEnColeccion (sec1, sec2, sec1, res); IF res.quePaso = Agregado THEN BEGIN WHILE Temp^.sig <> NIL DO BEGIN Posicion := Posicion + 1; Temp := Temp^.sig END; New (Final); Final^.sec := sec1; Final^.sig := NIL; Temp^.sig := Final; res.posicion := Posicion + 1 END END ELSE res.quePaso := Fallo END ELSE res.quePaso := Fallo END; {-----------------------------------------------------------------------------------------------------------------------} PROCEDURE PosicionesIguales (VAR col : Coleccion; pos : Natural; VAR res : Resultado); {Análogo al procedimiento "PosicionesDiferentes", pero con una precondición diferente.} {Precondición: (col <> NIL) AND (pos1 <> 0) AND (pos2 <> 0) AND (pos1 = pos2)} VAR Temp, Final : Coleccion; Posicion : Natural; sec : Secuencia; BEGIN Posicion := 1; Temp := col; WHILE (Temp^.sig <> NIL) AND (Posicion < pos) DO BEGIN Posicion := Posicion + 1; Temp := Temp^.sig END; IF Posicion = pos THEN BEGIN sec := Temp^.sec; WHILE (Temp^.sig <> NIL) DO BEGIN Posicion := Posicion + 1; Temp := Temp^.sig END; New (Final); Final^.sec := sec; Final^.sig := NIL; Temp^.sig := Final; res.quePaso := Agregado; res.posicion := Posicion + 1 END ELSE res.quePaso := Fallo END; {-----------------------------------------------------------------------------------------------------------------------} PROCEDURE FusionarEnColeccion (VAR col : Coleccion; pos1, pos2 : Natural; VAR res : Resultado); {Análogo al procedimiento "PosicionesDiferentes", con la excepción de que este procedimiento no tiene precondiciones.} BEGIN IF (col = NIL) OR (pos1 = 0) OR (pos2 = 0) THEN res.quePaso := Fallo ELSE IF pos1 = pos2 THEN PosicionesIguales (col, pos1, res) ELSE IF pos1 < pos2 THEN PosicionesDiferentes (col, pos1, pos2, res) ELSE PosicionesDiferentes (col, pos2, pos1, res) END; {-----------------------------------------------------------------------------------------------------------------------} PROCEDURE imprimirResultado (res: Resultado); BEGIN CASE res.quepaso OF Fallo: writeln('Fallo'); Creado: writeln('Creado: '); Agregado: writeln('Agregado en posición ', res.posicion:1) END END; {-----------------------------------------------------------------------------------------------------------------------} PROCEDURE imprimirSecuencia (sec: Secuencia); VAR i: 0..MAX; BEGIN Write ('tope: ', sec.tope:1, '; Valores: '); FOR i := 1 TO sec.tope DO Write (sec.valores[i]:1, ' '); Writeln (); END; {***********************************************************************************************************************} {Programa principal} BEGIN Writeln ('s ---> Crear secuencia con el siguiente ID.'); Writeln ('v ---> Agregar en la siguiente secuencia el siguiente valor.'); Writeln ('i ---> ¿Son iguales las siguientes dos secuencias?'); Writeln ('f ---> Fusionar las siguientes dos secuencias en la siguiente secuencia.'); Writeln ('c ---> Crear colección.'); Writeln ('a ---> Agregar en la siguiente colección la siguiente secuencia.'); Writeln ('t ---> ¿Son iguales las secuncias dentro de la siguiente colección?'); Writeln ('e ---> Fusionar en la siguiente colección las dos siguientes secuencias.'); Writeln ('q ---> Salir.'); Writeln (); REPEAT Read (opcion); CASE opcion OF 's' : BEGIN {CrearSecuencia} Read (idSec); CrearSecuencia (secs [idSec]); Writeln ('Se creó la secuencia') END; 'v' : BEGIN {AgregarValor} Read (idSec, valor); AgregarValor (secs [idSec], valor, res); imprimirResultado (res) END; 'i' : BEGIN {SecuenciasIguales} Read (idSec1, idSec2); IF SecuenciasIguales (secs [idSec1], secs [idSec2]) THEN Writeln ('Son iguales') ELSE Writeln ('No son iguales') END; 'f' : BEGIN {FusionarSecuencias} Read (idSec1, idSec2, idSec); FusionarSecuencias (secs [idSec1], secs [idSec2], secs [idSec], res); imprimirResultado (res); IF (res.quepaso = Creado) THEN imprimirSecuencia (secs [idSec]) END; 'c' : BEGIN {CrearColeccion} CrearColeccion (col); Writeln ('Se creó la colección') END; 'a' : BEGIN {AgregarSecuencia} Read (idSec); AgregarSecuencia (col, secs [idSec], pos); Writeln ('Se agregó la secuencia ', idSec:1, ' en la posición ', pos:1); END; 't' : BEGIN {TodasIguales} IF TodasIguales (col) THEN Writeln ('Todas son iguales') ELSE Writeln ('NO todas son iguales') END; 'e' : BEGIN {FusionarEnColeccion} Read (pos1, pos2); FusionarEnColeccion (col, pos1, pos2, res); imprimirResultado (res) END END UNTIL opcion = 'q' END.
unit frmEditMenu_unit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, EditReportForm_Unit, DB, kbmMemTable, Grids, AdvObj, BaseGrid, AdvGrid, DBAdvGrid, AdvSmoothButton, ExtCtrls, AdvPanel; type TEditMenu = class(TEditReport) procedure FormShow(Sender: TObject); procedure btnEditClick(Sender: TObject); procedure DBGrLeftDblClick(Sender: TObject); private procedure EditMenu; public { Public declarations } end; var EditMenu: TEditMenu; implementation uses frmMenuLine_unit; {$R *.dfm} procedure TEditMenu.btnEditClick(Sender: TObject); begin EditMenu; end; procedure TEditMenu.DBGrLeftDblClick(Sender: TObject); begin EditMenu; end; procedure TEditMenu.EditMenu; var FForm: TMenuLine; begin Assert(Assigned(FFrontBase), 'FrontBase not assigned'); FForm := TMenuLine.Create(Self); try FForm.FrontBase := FFrontBase; FForm.Caption := FForm.Caption + ' - ' + MemTable.FieldByName('NAME').AsString; FForm.MenuKey := MemTable.FieldByName('ID').AsInteger; FForm.ShowModal; finally FForm.Free; end; end; procedure TEditMenu.FormShow(Sender: TObject); var FMenuCount: Integer; begin Assert(Assigned(FFrontBase), 'FrontBase not assigned'); FFrontBase.GetMenuList(MemTable, FMenuCount); MemTable.First; end; end.
unit PostgresDatabaseMessagingService; interface uses QueryExecutor, AbstractDatabaseMessagingService, MessagingServiceUnit, SysUtils, Classes; type TPostgresDatabaseMessagingService = class (TAbstractDatabaseMessagingService) protected function MapMessageContentDataFrom(const MessageContent: TStrings): Variant; override; function MapMessageAttachmentsDataFrom(MessageAttachments: IMessageAttachments): Variant; override; protected function PrepareMessageDataInsertingQueryPattern( SchemaData: TDatabaseMessagingServiceSchemaData ): String; override; protected procedure ChangeMessageDataInsertingQueryData( const SourceQuery: String; QueryParams: TQueryParams; var ChangedQuery: String ); procedure ExecuteMessageDataInsertingQuery( const QueryText: String; QueryParams: TQueryParams ); override; procedure ExecuteMessageDataInsertingQueryAsync( const QueryText: String; QueryParams: TQueryParams; Message: IMessage; RelatedState: TObject; OnMessageSentEventHandler: TOnMessageSentEventHandler; OnMessageSendingFailedEventHandler: TOnMessageSendingFailedEventHandler ); override; end; implementation uses AuxiliaryStringFunctions, StrUtils, Variants; { TPostgresDatabaseMessagingService } procedure TPostgresDatabaseMessagingService. ChangeMessageDataInsertingQueryData( const SourceQuery: String; QueryParams: TQueryParams; var ChangedQuery: String ); begin ChangedQuery := ReplaceStr( SourceQuery, ':' + QueryParams[SchemaData.MessageAttachmentsQueryParamName].ParamName, VarToStr(QueryParams[SchemaData.MessageAttachmentsQueryParamName].ParamValue) ); ChangedQuery := ReplaceStr( ChangedQuery, ':' + QueryParams[SchemaData.MessageContentQueryParamName].ParamName, VarToStr(QueryParams[SchemaData.MessageContentQueryParamName].ParamValue) ); QueryParams.RemoveByName(SchemaData.MessageContentQueryParamName); QueryParams.RemoveByName(SchemaData.MessageAttachmentsQueryParamName); QueryParams.RemoveByName(SchemaData.MessageSenderQueryParamName); end; procedure TPostgresDatabaseMessagingService.ExecuteMessageDataInsertingQuery( const QueryText: String; QueryParams: TQueryParams ); var UpdatedQueryText: String; begin ChangeMessageDataInsertingQueryData( QueryText, QueryParams, UpdatedQueryText ); inherited ExecuteMessageDataInsertingQuery( UpdatedQueryText, QueryParams ); end; procedure TPostgresDatabaseMessagingService. ExecuteMessageDataInsertingQueryAsync( const QueryText: String; QueryParams: TQueryParams; Message: IMessage; RelatedState: TObject; OnMessageSentEventHandler: TOnMessageSentEventHandler; OnMessageSendingFailedEventHandler: TOnMessageSendingFailedEventHandler ); var UpdatedQueryText: String; begin ChangeMessageDataInsertingQueryData( QueryText, QueryParams, UpdatedQueryText ); inherited ExecuteMessageDataInsertingQueryAsync( UpdatedQueryText, QueryParams, Message, RelatedState, OnMessageSentEventHandler, OnMessageSendingFailedEventHandler ); end; function TPostgresDatabaseMessagingService.MapMessageAttachmentsDataFrom( MessageAttachments: IMessageAttachments ): Variant; var MessageAttachment: IMessageAttachment; AttachmentPostgresStringArray: String; PostgresFilePathString: String; begin if MessageAttachments.Count = 0 then begin Result := 'NULL::::text[]'; Exit; end; for MessageAttachment in MessageAttachments do begin PostgresFilePathString := 'E' + QuotedStr('"' + EscapeFilePathSpecChars(MessageAttachment.FilePath + '"')); if AttachmentPostgresStringArray = '' then AttachmentPostgresStringArray := PostgresFilePathString else AttachmentPostgresStringArray := AttachmentPostgresStringArray + ',' + PostgresFilePathString; end; AttachmentPostgresStringArray := 'ARRAY[' + AttachmentPostgresStringArray + ']'; Result := AttachmentPostgresStringArray; end; function TPostgresDatabaseMessagingService.MapMessageContentDataFrom( const MessageContent: TStrings): Variant; var I: Integer; MessageLine: String; begin for I := 0 to MessageContent.Count - 1 do begin MessageLine := QuotedStr(MessageContent[I]); if Result = '' then Result := MessageLine else Result := Result + ' || E' + QuotedStr('<br>') + ' || ' + MessageLine; end; end; function TPostgresDatabaseMessagingService. PrepareMessageDataInsertingQueryPattern( SchemaData: TDatabaseMessagingServiceSchemaData ): String; begin Result := Format( 'SELECT sys.sendemail_queue_add(:%s,:%s,:%s,now()::::timestamp without time zone,:%s)', [ SchemaData.MessageReceiversQueryParamName, SchemaData.MessageNameQueryParamName, SchemaData.MessageContentQueryParamName, SchemaData.MessageAttachmentsQueryParamName ] ); end; end.
{******************************************************************************* * * * TksSlideMenu - Slide Menu Component * * * * https://github.com/gmurt/KernowSoftwareFMX * * * * Copyright 2015 Graham Murt * * * * email: graham@kernow-software.co.uk * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * *******************************************************************************} unit ksSlideMenu; interface {$I ksComponents.inc} //{$DEFINE ADD_SAMPLE_MENU_ITEMS} uses System.UITypes, FMX.Controls, FMX.Layouts, FMX.Objects, System.Classes, FMX.Types, Generics.Collections, FMX.Graphics, System.UIConsts, FMX.Effects, FMX.StdCtrls, System.Types, FMX.Forms, ksTableView, ksTypes {$IFDEF XE8_OR_NEWER} ,FMX.ImgList {$ENDIF} ; const C_DEFAULT_MENU_WIDTH = 250; C_DEFAULT_MENU_TOOLBAR_HEIGHT = 44; C_DEFAULT_MENU_HEADER_HEIGHT = 30; C_DEFAULT_MENU_HEADER_FONT_SIZE = 16; C_DEFAULT_MENU_HEADER_TEXT_COLOR = claWhite; C_DEFAULT_MENU_HEADER_COLOR = $FF323232; C_DEFAULT_MENU_ITEM_HEIGHT = 50; C_DEFAULT_MENU_FONT_SIZE = 14; C_DEFAULT_MENU_TOOLBAR_FONT_SIZE = 14; C_DEFAULT_MENU_SLIDE_SPEED = 0.2; C_DEFAULT_MENU_SELECTED_COLOR = claWhite; C_DEFAULT_MENU_SELECTED_FONT_COLOR = claWhite; C_DEFAULT_MENU_FONT_COLOR = claBlack; C_DEFAULT_MENU_BACKGROUND_COLOR = claWhite; C_DEFAULT_MENU_TOOLBAR_COLOR = claWhite; type TSelectMenuItemEvent = procedure(Sender: TObject; AId: string) of object; TksMenuPosition = (mpLeft, mpRight); TKsMenuStyle = (msOverlap, msReveal); TKsMenuTheme = (mtCustom, mtDarkGray, mtDarkBlue, mtDarkOrange, mtDarkGreen, mtLightGray, mtLightBlue, mtLightOrange, mtLightGreen); TksSlideMenu = class; TksSlideMenuItem = class strict private FText: string; FId: string; FFont: TFont; FImage: TBitmap; FHeight: integer; FIndex: integer; FIsHeader: Boolean; public constructor Create(AIndex: integer); virtual; destructor Destroy; override; property Height: integer read FHeight write FHeight; property Index: integer read FIndex; property Font: TFont read FFont write FFont; property Image: TBitmap read FImage write FImage; property ID: string read FId write FId; property Text: string read FText write FText; property IsHeader: Boolean read FIsHeader write FIsHeader; end; TksSlideMenuItems = class(TObjectList<TksSlideMenuItem>) private function AddMenuItem(AId, AText: string; AImage: TBitmap): TksSlideMenuItem; function AddHeaderItem(AText: string): TksSlideMenuItem; end; TksSlideMenuAppearence = class(TPersistent) private [weak]FSlideMenu: TksSlideMenu; FHeaderColor: TAlphaColor; FHeaderFontColor: TAlphaColor; FItemColor: TAlphaColor; FFontColor: TAlphaColor; FSelectedColor: TAlphaColor; FSelectedFontColor: TAlphaColor; FTheme: TKsMenuTheme; FToolBarColor: TAlphaColor; FAccessoryColor: TAlphaColor; procedure SetHeaderColor(const Value: TAlphaColor); procedure SetHeaderFontColor(const Value: TAlphaColor); procedure SetItemColor(const Value: TAlphaColor); procedure SetFontColor(const Value: TAlphaColor); procedure SetSelectedColor(const Value: TAlphaColor); procedure SetSelectedFontColor(const Value: TAlphaColor); procedure SetTheme(const Value: TKsMenuTheme); procedure SetToolBarColor(const Value: TAlphaColor); procedure SetAccessoryColor(const Value: TAlphaColor); public constructor Create(ASlideMenu: TksSlideMenu); virtual; published property AccessoryColor: TAlphaColor read FAccessoryColor write SetAccessoryColor default claWhite; property HeaderColor: TAlphaColor read FHeaderColor write SetHeaderColor default C_DEFAULT_MENU_HEADER_COLOR; property HeaderFontColor: TAlphaColor read FHeaderFontColor write SetHeaderFontColor default C_DEFAULT_MENU_HEADER_TEXT_COLOR; property ItemColor: TAlphaColor read FItemColor write SetItemColor default $FF222222; property FontColor: TAlphaColor read FFontColor write SetFontColor default claWhite; property SelectedItemColor: TAlphaColor read FSelectedColor write SetSelectedColor default claRed; property SelectedFontColor: TAlphaColor read FSelectedFontColor write SetSelectedFontColor default claWhite; property ToolBarColor: TAlphaColor read FToolBarColor write SetToolBarColor default $FF323232; property Theme: TKsMenuTheme read FTheme write SetTheme default mtDarkGray; end; TksSlideMenuToolbar = class(TPersistent) private [weak]FSlideMenu: TksSlideMenu; FHeader: TImage; FBitmap: TBitmap; FText: string; FFont: TFont; FVisible: Boolean; FHeight: integer; procedure SetFont(const Value: TFont); procedure SetBitmap(const Value: TBitmap); function GetBitmap: TBitmap; function GetFont: TFont; function GetText: string; procedure SetText(const Value: string); public constructor Create(AOwner: TComponent; ASlideMenu: TksSlideMenu); virtual; destructor Destroy; override; procedure UpdateToolbar; property Height: integer read FHeight default C_DEFAULT_MENU_TOOLBAR_HEIGHT; published property Bitmap: TBitmap read GetBitmap write SetBitmap; property Visible: Boolean read FVisible write FVisible default True; property Text: string read GetText write SetText; property Font: TFont read GetFont write SetFont; end; TksSlideMenuContainer = class(TLayout) private [weak]FSlideMenu: TksSlideMenu; FToolBar: TksSlideMenuToolbar; FListView: TksTableView; procedure CreateListView; function CalculateListViewHeight: single; procedure ItemClick(Sender: TObject; x, y: single; AItem: TksTableViewItem; AId: string; ARowObj: TksTableViewItemObject); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property ListView: TksTableView read FListView; end; [ComponentPlatformsAttribute(pidWin32 or pidWin64 or {$IFDEF XE8_OR_NEWER} pidiOSDevice32 or pidiOSDevice64 {$ELSE} pidiOSDevice {$ENDIF} or pidiOSSimulator or pidAndroid)] TksSlideMenu = class(TksComponent) strict private FAppearence: TksSlideMenuAppearence; FMenu: TksSlideMenuContainer; FItems: TksSlideMenuItems; {$IFNDEF ANDROID} FShadowLeft: TImage; FShadowRight: TImage; {$ENDIF} FBackground: TRectangle; FFormImage: TImage; FMenuImage: TImage; FFont: TFont; FHeaderFont: TFont; FShowing: Boolean; FTopPadding: integer; FMenuPosition: TksMenuPosition; FMenuStyle: TKsMenuStyle; FSlideSpeed: Single; FOnSelectMenuItemEvent: TSelectMenuItemEvent; FAfterSelectMenuItemEvent: TSelectMenuItemEvent; FOnAfterSlideOut: TNotifyEvent; FOnBeforeSlideOut: TNotifyEvent; {$IFDEF XE8_OR_NEWER} FImages: TCustomImageList; {$ENDIF} FHeaderHeight: integer; FItemHeight: integer; FToggleButton: TCustomButton; FAnimating: Boolean; FHeaderTextAlign: TTextAlign; FItemTextAlign: TTextAlign; FSelectFirstItem: Boolean; procedure SetTopPadding(const Value: integer); procedure DoBackgroundClick(Sender: TObject); //procedure FadeBackground; //procedure UnfadeBackground; procedure GenerateFormImage(AXpos: single); procedure RemoveFormImage; {$IFNDEF ANDROID} procedure GenerateShadows; {$ENDIF} procedure HidePickers; procedure SetToggleButton(const Value: TCustomButton); procedure DoToggleButtonClick(Sender: TObject); private FMenuIndex: integer; procedure MenuItemSelected(Sender: TObject; x, y: single; AItem: TksTableViewItem; AId: string; ARowObj: TksTableViewItemObject); //procedure SetItemIndex(const Value: integer); procedure SwitchMenuToImage; procedure SwitchImageToMenu; function GetToolbar: TksSlideMenuToolbar; function GetToolbarHeight: integer; procedure SetToolbar(const Value: TksSlideMenuToolbar); procedure SetMenuIndex(const Value: integer); function GetMenuItemCount: integer; function GetColorOrDefault(AColor, ADefaultIfNull: TAlphaColor): TAlphaColor; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Clear; procedure AddHeader(AText: string); function AddMenuItem(AId, AText: string; const AImageIndex: integer = -1): TksSlideMenuItem; overload; function AddMenuItem(AId, AText: string; AImage: TBitmap): TksSlideMenuItem; overload; procedure ToggleMenu; procedure UpdateMenu; procedure RefreshMenu; property Showing: Boolean read FShowing; property MenuIndex: integer read FMenuIndex write SetMenuIndex; property MenuItemCount: integer read GetMenuItemCount; published property Appearence: TksSlideMenuAppearence read FAppearence write FAppearence; property Font: TFont read FFont write FFont; property HeaderFont: TFont read FHeaderFont write FHeaderFont; {$IFDEF XE8_OR_NEWER} property Images: TCustomImageList read FImages write FImages; {$ENDIF} property ItemHeight: integer read FItemHeight write FItemHeight default C_DEFAULT_MENU_ITEM_HEIGHT; property HeaderHeight: integer read FHeaderHeight write FHeaderHeight default C_DEFAULT_MENU_HEADER_HEIGHT; property TopPadding: integer read FTopPadding write SetTopPadding default 0; property MenuPosition: TksMenuPosition read FMenuPosition write FMenuPosition default mpLeft; property MenuStyle: TKsMenuStyle read FMenuStyle write FMenuStyle default msReveal; property SlideSpeed: Single read FSlideSpeed write FSlideSpeed; property OnSelectMenuItemEvent: TSelectMenuItemEvent read FOnSelectMenuItemEvent write FOnSelectMenuItemEvent; property AfterSelectItemEvent: TSelectMenuItemEvent read FAfterSelectMenuItemEvent write FAfterSelectMenuItemEvent; property Toolbar: TksSlideMenuToolbar read GetToolbar write SetToolbar; property ToggleButton: TCustomButton read FToggleButton write SetToggleButton; property OnAfterSlideOut: TNotifyEvent read FOnAfterSlideOut write FOnAfterSlideOut; property OnBeforeSlideOut: TNotifyEvent read FOnBeforeSlideOut write FOnBeforeSlideOut; property HeaderTextAlign: TTextAlign read FHeaderTextAlign write FHeaderTextAlign default TTextAlign.Leading; property ItemTextAlign: TTextAlign read FItemTextAlign write FItemTextAlign default TTextAlign.Leading; property SelectFirstItem: Boolean read FSelectFirstItem write FSelectFirstItem default True; end; {$R *.dcr} procedure Register; procedure ReplaceOpaqueColor(ABmp: TBitmap; Color : TAlphaColor); var SlideMenuAnimating: Boolean; implementation uses FMX.Platform, SysUtils, FMX.Ani, FMX.Pickers, Math, FMX.ListView.Types, FMX.Utils, ksCommon; procedure Register; begin RegisterComponents('Kernow Software FMX', [TksSlideMenu]); end; procedure ReplaceOpaqueColor(ABmp: TBitmap; Color : TAlphaColor); var x,y: Integer; AMap: TBitmapData; PixelColor: TAlphaColor; PixelWhiteColor: TAlphaColor; C: PAlphaColorRec; begin if ABmp.Map(TMapAccess.ReadWrite, AMap) then try AlphaColorToPixel(Color , @PixelColor, AMap.PixelFormat); AlphaColorToPixel(claWhite, @PixelWhiteColor, AMap.PixelFormat); for y := 0 to ABmp.Height - 1 do begin for x := 0 to ABmp.Width - 1 do begin C := @PAlphaColorArray(AMap.Data)[y * (AMap.Pitch div 4) + x]; if (C^.Color<>claWhite) and (C^.A>0) then C^.Color := PremultiplyAlpha(MakeColor(PixelColor, C^.A / $FF)); end; end; finally ABmp.Unmap(AMap); end; end; { TSlideMenu } procedure TksSlideMenu.AddHeader(AText: string); var AResult: TksSlideMenuItem; begin AResult := FItems.AddHeaderItem(AText); AResult.Font.Assign(FFont); end; function TksSlideMenu.AddMenuItem(AId, AText: string; AImage: TBitmap): TksSlideMenuItem; begin Result := FItems.AddMenuItem(AId, AText, AImage); Result.Font.Assign(FFont); //UpdateMenu; end; function TksSlideMenu.AddMenuItem(AId, AText: string; const AImageIndex: integer = -1): TksSlideMenuItem; var AImage: TBitmap; ASize: TSizeF; begin AImage := nil; ASize.Width := 64; ASize.Height := 64; {$IFDEF XE8_OR_NEWER} if Images <> nil then AImage := Images.Bitmap(ASize, AImageIndex); {$ENDIF} Result := AddMenuItem(AId, AText, AImage); end; procedure TksSlideMenu.Clear; begin FItems.Clear; UpdateMenu; end; constructor TksSlideMenu.Create(AOwner: TComponent); begin inherited Create(AOwner); FFont := TFont.Create; FHeaderFont := TFont.Create; FItems := TksSlideMenuItems.Create; FAppearence := TksSlideMenuAppearence.Create(Self); FMenu := TksSlideMenuContainer.Create(Self); FFormImage := TImage.Create(Self); FBackground := TRectangle.Create(Self); FHeaderTextAlign := TTextAlign.Leading; FItemTextAlign := TTextAlign.Leading; FShowing := False; FTopPadding := 0; FFont.Size := C_DEFAULT_MENU_FONT_SIZE; FHeaderFont.Size := C_DEFAULT_MENU_HEADER_FONT_SIZE; FFormImage.OnClick := DoBackgroundClick; FMenuPosition := mpLeft; FMenuStyle := msReveal; FSlideSpeed := C_DEFAULT_MENU_SLIDE_SPEED; FHeaderHeight := C_DEFAULT_MENU_HEADER_HEIGHT; FItemHeight := C_DEFAULT_MENU_ITEM_HEIGHT; //FItemIndex := -1; {$IFNDEF ANDROID} FShadowLeft := TImage.Create(Self); FShadowRight := TImage.Create(Self); GenerateShadows; FSelectFirstItem := True; {$ENDIF} FAnimating := False; FMenuIndex := -1; end; destructor TksSlideMenu.Destroy; begin FreeAndNil(FFont); FreeAndNil(FHeaderFont); FreeAndNil(FAppearence); FreeAndNil(FItems); inherited; end; procedure TksSlideMenu.DoBackgroundClick(Sender: TObject); begin ToggleMenu; end; procedure TksSlideMenu.DoToggleButtonClick(Sender: TObject); begin ToggleMenu; end; procedure TksSlideMenu.GenerateFormImage(AXpos: single); var AScale: single; ABmp: TBitmap; ABmp2: TBitmap; AForm: TForm; AOwner : TComponent; AWidth : single; AHeight: single; ATopLeft : TPointF; //AFormTopLeft : TPointF; begin AOwner := Owner; if (AOwner is TForm) then begin AWidth := (AOwner as TForm).Width; AHeight := (AOwner as TForm).Height; ATopLeft := PointF(0,0); end else if (AOwner is TFrame) then begin AWidth := (AOwner as TFrame).Width; AHeight := (AOwner as TFrame).Height; ATopLeft := PointF(0,0); while not (AOwner is TForm) do begin ATopLeft := ATopLeft + (AOwner as TFrame).LocalToAbsolute(PointF(0,0)); AOwner := AOwner.Owner; end; if not (AOwner is TForm) then exit; end else exit; AForm := (AOwner as TForm); FFormImage.Visible := false; FMenu.Visible := False; ABmp := TBitmap.Create; try AScale := GetScreenScale; ABmp.BitmapScale := AScale; ABmp.Width := Round((ATopLeft.x + AWidth ) * AScale); ABmp.Height := Round((ATopLeft.y + AHeight) * AScale); ABmp.Canvas.BeginScene; AForm.PaintTo(ABmp.Canvas); ABmp.Canvas.EndScene; ABmp.Canvas.BeginScene; ABmp.Canvas.Stroke.Color := claBlack; ABmp.Canvas.StrokeThickness := 1; ABmp.Canvas.DrawLine(PointF(0, 0), PointF(0, ABmp.Height), 1); {ABmp.Canvas.Fill.Color := claFuchsia; ABmp.Canvas.FillEllipse(RectF(0, 0, 100, 100), 1);} ABmp.Canvas.EndScene; if (ATopLeft.x>0) or (ATopLeft.y>0) then begin ABmp2 := TBitmap.Create; ABmp2.BitmapScale := AScale; ABmp2.Width := Round(AWidth * AScale); ABmp2.Height := Round(AHeight * AScale); ABmp2.Canvas.BeginScene; ABmp2.Canvas.DrawBitmap(ABmp, RectF(Round(ATopLeft.x * AScale),Round(ATopLeft.y * AScale),ABmp.Width,ABmp.Height), RectF(0,0,AWidth,AHeight), 1,true); ABmp2.Canvas.EndScene; ABmp.Free(); ABmp := ABmp2; end; FFormImage.Width := Round(AWidth); FFormImage.Height := Round(AHeight); FFormImage.Bitmap.Assign(ABmp); finally FreeAndNil(ABmp); end; FFormImage.Position.Y := 0; FFormImage.Position.X := AXpos; {$IFNDEF ANDROID} FShadowLeft.Position.Y := 0; FShadowLeft.Position.X := 0-FShadowLeft.Width; FFormImage.AddObject(FShadowLeft); FShadowRight.Position.Y := 0; FShadowRight.Position.X := FFormImage.Width; FFormImage.AddObject(FShadowRight); {$ENDIF} TfmxObject(Owner).AddObject(FFormImage); FFormImage.Visible := True; FMenu.Visible := True; Application.ProcessMessages; end; procedure TksSlideMenu.RefreshMenu; var AWidth: single; begin if (FAnimating) or (not FShowing) then Exit; if (Owner is TForm) then AWidth := (Owner as TForm).Width else if (Owner is TFrame) then AWidth := (Owner as TFrame).Width else AWidth := 0; HidePickers; GenerateFormImage(FFormImage.Position.x); if (Owner is TForm) then FMenu.Height := (Owner as TForm).ClientHeight else if (Owner is TFrame) then FMenu.Height := (Owner as TFrame).Height else FMenu.Height := 0; case FMenuPosition of mpLeft: FMenu.Position.x := 0; mpRight:FMenu.Position.x := AWidth - C_DEFAULT_MENU_WIDTH; end; if FMenu.FListView.Items.Count = 0 then UpdateMenu; end; procedure TksSlideMenu.RemoveFormImage; begin (Owner as TfmxObject).RemoveObject(FFormImage); end; {$IFNDEF ANDROID} procedure TksSlideMenu.GenerateShadows; var AScale: single; ABmp: TBitmap; AHeight : Single; begin if (Owner is TForm) then AHeight := (Owner as TForm).Height else if (Owner is TFrame) then AHeight := (Owner as TFrame).Height else exit; ABmp := TBitmap.Create; try AScale := GetScreenScale; ABmp.Width := Round(16 * AScale); ABmp.Height := Round(AHeight * AScale); ABmp.Canvas.BeginScene; ABmp.Canvas.Fill.Kind := TBrushKind.Gradient; ABmp.Canvas.Fill.Gradient.Color := claNull; ABmp.Canvas.Fill.Gradient.Color1 := $AA000000; ABmp.Canvas.Fill.Gradient.StartPosition.X := 0; ABmp.Canvas.Fill.Gradient.StartPosition.Y := 1; ABmp.Canvas.Fill.Gradient.StopPosition.X := 1; ABmp.Canvas.FillRect(RectF(0, 0, ABmp.Width, ABmp.Height), 0, 0, [], 1); ABmp.Canvas.EndScene; FShadowLeft.Width := 16; FShadowLeft.Height := Round(AHeight); FShadowLeft.Bitmap.Assign(ABmp); finally FreeAndNil(ABmp); end; ABmp := TBitmap.Create; try AScale := GetScreenScale; ABmp.Width := Round(16 * AScale); ABmp.Height := Round(AHeight * AScale); ABmp.Canvas.BeginScene; ABmp.Canvas.Fill.Kind := TBrushKind.Gradient; ABmp.Canvas.Fill.Gradient.Color := $AA000000; ABmp.Canvas.Fill.Gradient.Color1 := claNull; ABmp.Canvas.Fill.Gradient.StartPosition.X := 0; ABmp.Canvas.Fill.Gradient.StartPosition.Y := 1; ABmp.Canvas.Fill.Gradient.StopPosition.X := 1; ABmp.Canvas.FillRect(RectF(0, 0, ABmp.Width, ABmp.Height), 0, 0, [], 1); ABmp.Canvas.EndScene; FShadowRight.Width := 16; FShadowRight.Height := Round(AHeight); FShadowRight.Bitmap.Assign(ABmp); finally FreeAndNil(ABmp); end; end; {$ENDIF} function TksSlideMenu.GetMenuItemCount: integer; var ICount: integer; lv: TksTableView; begin Result := 0; lv := FMenu.FListView; for ICount := 0 to lv.Items.Count-1 do begin if lv.Items[ICount].Purpose = TksTableViewItemPurpose.None then Result := Result + 1; end; end; function TksSlideMenu.GetToolbar: TksSlideMenuToolbar; begin Result := FMenu.FToolBar; end; function TksSlideMenu.GetToolbarHeight: integer; begin Result := 0; if Toolbar.Visible then Result := C_DEFAULT_MENU_TOOLBAR_HEIGHT; end; procedure TksSlideMenu.HidePickers; var PickerService: IFMXPickerService; begin inherited; if TPlatformServices.Current.SupportsPlatformService(IFMXPickerService, PickerService) then PickerService.CloseAllPickers; end; procedure TksSlideMenu.MenuItemSelected(Sender: TObject; x, y: single; AItem: TksTableViewItem; AId: string; ARowObj: TksTableViewItemObject); begin if Assigned(FOnSelectMenuItemEvent) then FOnSelectMenuItemEvent(Self, AId); GenerateFormImage(FFormImage.Position.X); ToggleMenu; if Assigned(FAfterSelectMenuItemEvent) then FAfterSelectMenuItemEvent(Self, AId); end; procedure TksSlideMenu.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (AComponent = FToggleButton) and (Operation = TOperation.opRemove) then FToggleButton := nil; end; function TksSlideMenu.GetColorOrDefault(AColor, ADefaultIfNull: TAlphaColor): TAlphaColor; begin Result := AColor; if Result = claNull then Result := ADefaultIfNull; end; procedure TksSlideMenu.UpdateMenu; var ICount: integer; AItem: TksSlideMenuItem; ARow: TksTableViewItem; lv: TksTableView; ASelectedColor: TAlphaColor; AFontColor, AHeaderFontColor: TAlphaColor; begin if FMenu.ListView = nil then Exit; Application.ProcessMessages; lv := FMenu.FListView; lv.Position.X := 0; lv.Repaint; //lv.Position.Y := GetToolbarHeight;; lv.Width := C_DEFAULT_MENU_WIDTH; //FMenu FMenu.Width := C_DEFAULT_MENU_WIDTH; AFontColor := GetColorOrDefault(FAppearence.FontColor, C_DEFAULT_MENU_FONT_COLOR); AHeaderFontColor := GetColorOrDefault(FAppearence.HeaderFontColor, C_DEFAULT_MENU_HEADER_TEXT_COLOR); ASelectedColor := GetColorOrDefault(FAppearence.SelectedItemColor, C_DEFAULT_MENU_SELECTED_COLOR); lv.Appearence.Background.Color := GetColorOrDefault(FAppearence.ItemColor, C_DEFAULT_MENU_BACKGROUND_COLOR); lv.Appearence.ItemBackground.Color := GetColorOrDefault(FAppearence.ItemColor, C_DEFAULT_MENU_BACKGROUND_COLOR); lv.Appearence.HeaderColor := GetColorOrDefault(FAppearence.HeaderColor, C_DEFAULT_MENU_HEADER_COLOR); lv.Appearence.SeparatorColor := GetColorOrDefault(FAppearence.HeaderColor, C_DEFAULT_MENU_HEADER_COLOR); lv.Appearence.SelectedColor := ASelectedColor; lv.HeaderOptions.Height := FHeaderHeight; lv.ItemHeight := FItemHeight; lv.ItemImageSize := 24; lv.BeginUpdate; try lv.Items.Clear; {$IFDEF ADD_SAMPLE_MENU_ITEMS} if FItems.Count = 0 then begin // add some sample items... AddHeader('SAMPLE HEADER 0'); AddMenuItem('', 'Menu Item 1'); AddMenuItem('', 'Menu Item 2'); AddHeader('SAMPLE HEADER 1'); AddMenuItem('', 'Menu Item 3'); AddMenuItem('', 'Menu Item 4'); AddMenuItem('', 'Menu Item 5'); AddHeader('SAMPLE HEADER 2'); AddMenuItem('', 'Menu Item 6'); AddMenuItem('', 'Menu Item 7'); AddMenuItem('', 'Menu Item 8'); AddMenuItem('', 'Menu Item 9'); AddMenuItem('', 'Menu Item 10'); end; {$ENDIF} for ICount := 0 to FItems.Count-1 do begin AItem := FItems[ICount]; if AItem.IsHeader then begin ARow := lv.Items.AddHeader(AItem.Text); ARow.Title.Font.Assign(FHeaderFont); ARow.Title.TextColor := AHeaderFontColor; ARow.Title.TextAlignment:= FHeaderTextAlign; end else begin ARow := lv.Items.AddItem(AItem.Text, '', '', atMore); ARow.Image.Bitmap := AItem.Image; ARow.ID := AItem.ID; ARow.Accessory.OwnsBitmap := True; ARow.Accessory.Color := FAppearence.AccessoryColor; ARow.Title.Font.Assign(FFont); ARow.Title.TextColor := AFontColor; ARow.Title.TextAlignment:= FItemTextAlign; end; end; finally lv.EndUpdate; end; lv.RecalcAbsoluteNow; MenuIndex := FMenuIndex; if (lv.ItemIndex = -1) and (FSelectFirstItem) then begin for ICount := 0 to lv.Items.Count-1 do begin if lv.Items[ICount].Purpose = TksTableViewItemPurpose.None then begin lv.ItemIndex := ICount; Break; end; end; end; end; procedure TksSlideMenu.SetMenuIndex(const Value: integer); var ICount: integer; AIndex: integer; lv: TksTableView; begin AIndex := -1; lv := FMenu.FListView; for ICount := 0 to lv.Items.Count-1 do begin if lv.Items[ICount].Purpose = TksTableViewItemPurpose.None then begin Inc(AIndex); if AIndex = Value then begin lv.ItemIndex := ICount; Exit; end; end; end; FMenuIndex := Value; end; procedure TksSlideMenu.SetToggleButton(const Value: TCustomButton); begin FToggleButton := Value; FToggleButton.OnClick := DoToggleButtonClick; end; procedure TksSlideMenu.SetToolbar(const Value: TksSlideMenuToolbar); begin FMenu.FToolBar := Value; end; procedure TksSlideMenu.SetTopPadding(const Value: integer); begin FTopPadding := Value; end; procedure TksSlideMenu.SwitchMenuToImage; var ABmp: TBitmap; ABottom: single; AWidth: single; AClientHeight: single; begin if (Owner is TForm) then begin AWidth := (Owner as TForm).Width; AClientHeight := (Owner as TForm).ClientHeight; end else if (Owner is TFrame) then begin AWidth := (Owner as TFrame).Width; AClientHeight := (Owner as TFrame).Height end else exit; ABmp := TBitmap.Create(Round(C_DEFAULT_MENU_WIDTH * GetScreenScale), Round(AClientHeight * GetScreenScale)); try FMenuImage := TImage.Create(Owner); FMenuImage.Width := C_DEFAULT_MENU_WIDTH; FMenuImage.Height := AClientHeight; case FMenuPosition of mpLeft: FMenuImage.Position.X := 0; mpRight: FMenuImage.Position.X := AWidth - C_DEFAULT_MENU_WIDTH; end; ABmp.Canvas.BeginScene; ABmp.BitmapScale := GetScreenScale; FMenu.PaintTo(ABmp.Canvas, RectF(0, 0, ABmp.Width, ABmp.Height)); ABmp.Canvas.EndScene; ABmp.Canvas.BeginScene; ABottom := (GetToolbarHeight + FMenu.CalculateListViewHeight)*GetScreenScale; ABmp.Canvas.Fill.Color := FAppearence.ItemColor; ABmp.Canvas.FillRect(RectF(0, ABottom, C_DEFAULT_MENU_WIDTH*GetScreenScale, ABmp.Height), 0, 0, AllCorners, 1, ABmp.Canvas.Fill); ABmp.Canvas.EndScene; FMenuImage.Bitmap := ABmp; finally FreeAndNil(ABmp); end; end; procedure TksSlideMenu.SwitchImageToMenu; var AObject: TfmxObject; begin AObject := (Owner as TfmxObject); AObject.InsertObject(AObject.ChildrenCount-1, FMenu); AObject.RemoveObject(FMenuImage); FMenu.HitTest := True; end; procedure TksSlideMenu.ToggleMenu; var AStartXPos: single; ANewXPos: single; AObject: TfmxObject; AWidth: single; begin if FAnimating then Exit; if FShowing = False then begin if Assigned(FOnBeforeSlideOut) then FOnBeforeSlideOut(Self); end; FAnimating := True; try if (FShowing = False) then begin FMenu.FToolBar.UpdateToolbar; //FMenu.UpdateSelectedItem; end; FMenu.HitTest := False; AObject := (Owner as TfmxObject); if (Owner is TForm) then AWidth := (Owner as TForm).Width else if (Owner is TFrame) then AWidth := (Owner as TFrame).Width else AWidth := 0; HidePickers; if FShowing = False then begin AStartXPos := 0; ANewXPos := 0; case FMenuPosition of mpLeft: ANewXPos := C_DEFAULT_MENU_WIDTH; mpRight: ANewXPos := 0-C_DEFAULT_MENU_WIDTH; end; end else begin AStartXPos := FFormImage.Position.X; ANewXPos := 0; end; GenerateFormImage(AStartXPos); if (Owner is TForm) then FMenu.Height := (Owner as TForm).ClientHeight else if (Owner is TFrame) then FMenu.Height := (Owner as TFrame).Height else FMenu.Height := 0; // add the menu just behind the screen image... case FMenuPosition of mpLeft : FMenu.Position.X := 0; mpRight: FMenu.Position.X := AWidth - C_DEFAULT_MENU_WIDTH; end; AObject.InsertObject(0, FMenu); if FMenu.FListView.Items.Count = 0 then UpdateMenu; SwitchMenuToImage; AObject.RemoveObject(FMenu); AObject.InsertObject(AObject.ChildrenCount-1, FMenuImage); FFormImage.HitTest := False; // SlideMenuAnimating := True; TAnimator.AnimateFloatWait(FFormImage, 'Position.X', ANewXPos, FSlideSpeed); SlideMenuAnimating := False; FFormImage.HitTest := True; FShowing := not FShowing; if FShowing = False then begin AObject.RemoveObject(FMenu); RemoveFormImage; end else SwitchImageToMenu; AObject.RemoveObject(FMenuImage); Application.ProcessMessages; finally FAnimating := False; end; if FShowing = False then begin if Assigned(FOnAfterSlideOut) then FOnAfterSlideOut(Self); end; end; {procedure TksSlideMenu.FadeBackground; begin FBackground.Fill.Color := claBlack; FBackground.Align := TAlignLayout.Contents; FBackground.OnClick := DoBackgroundClick; FBackground.Opacity := 0; TForm(Owner).AddObject(FBackground); FBackground.BringToFront; TAnimator.AnimateFloat(FBackground, 'Opacity', 0.2, FSlideSpeed); end; procedure TksSlideMenu.UnfadeBackground; begin TAnimator.AnimateFloat(FBackground, 'Opacity', 0, FSlideSpeed); TForm(Owner).RemoveObject(FBackground); end; } { TksSlideMenuItem } constructor TksSlideMenuItem.Create(AIndex: integer); begin inherited Create; FImage := TBitmap.Create; FFont := TFont.Create; FIndex := AIndex; FIsHeader := False; end; destructor TksSlideMenuItem.Destroy; begin FreeAndNil(FImage); FreeAndNil(FFont); inherited; end; { TksSlideMenuItems } function TksSlideMenuItems.AddHeaderItem(AText: string): TksSlideMenuItem; begin Result := AddMenuItem('', AText, nil); Result.IsHeader := True; end; function TksSlideMenuItems.AddMenuItem(AId, AText: string; AImage: TBitmap): TksSlideMenuItem; begin Result := TksSlideMenuItem.Create(Count); if AImage <> nil then Result.Image.Assign(AImage); Result.Id := AId; Result.Text := AText; Add(Result); end; { TksSlideMenuAppearence } constructor TksSlideMenuAppearence.Create(ASlideMenu: TksSlideMenu); begin FSlideMenu := ASlideMenu; FHeaderColor := $FF323232; FItemColor := $FF222222; FToolBarColor := $FF323232; FFontColor := claWhite; FSelectedFontColor := claWhite; FSelectedColor := claRed; FAccessoryColor := claWhite; FTheme := mtDarkGray; end; procedure TksSlideMenuAppearence.SetAccessoryColor(const Value: TAlphaColor); begin FAccessoryColor := Value; end; procedure TksSlideMenuAppearence.SetFontColor(const Value: TAlphaColor); begin FFontColor := Value; FTheme := mtCustom; end; procedure TksSlideMenuAppearence.SetHeaderColor(const Value: TAlphaColor); begin FHeaderColor := Value; FTheme := mtCustom; end; procedure TksSlideMenuAppearence.SetHeaderFontColor(const Value: TAlphaColor); begin FHeaderFontColor := Value; FTheme := mtCustom; end; procedure TksSlideMenuAppearence.SetItemColor(const Value: TAlphaColor); begin FItemColor := Value; FTheme := mtCustom; end; procedure TksSlideMenuAppearence.SetSelectedColor(const Value: TAlphaColor); begin FSelectedColor := Value; FTheme := mtCustom; end; procedure TksSlideMenuAppearence.SetSelectedFontColor(const Value: TAlphaColor); begin FSelectedFontColor := Value; FTheme := mtCustom; end; procedure TksSlideMenuAppearence.SetTheme(const Value: TKsMenuTheme); begin if Value = mtDarkGray then begin FHeaderColor := $FF424242; FToolBarColor := $FF323232; FItemColor := $FF222222; FFontColor := claWhite; FHeaderFontColor := $FFDADADA; FSelectedFontColor := claWhite; FSelectedColor := claRed; end; if Value = mtDarkBlue then begin FHeaderColor := $FF2A7A9D; FToolBarColor := $FF323232; FItemColor := $FF424242; FFontColor := claWhite; FHeaderFontColor := $FFC7FFFB; FSelectedFontColor := claBlack; FSelectedColor := $FF00F6FF; end; if Value = mtDarkOrange then begin FHeaderColor := $FFFF9900; FToolBarColor := $FF323232; FItemColor := $FF222222; FFontColor := claWhite; FHeaderFontColor := claBlack; FSelectedFontColor := claBlack; FSelectedColor := $FFFFCC00; end; if Value = mtDarkGreen then begin FHeaderColor := $FF76D015; FToolBarColor := $FF323232; FItemColor := $FF424242; FFontColor := claWhite; FHeaderFontColor := claBlack; FSelectedFontColor := claBlack; FSelectedColor := $FFDCFF00; end; if Value = mtLightGray then begin FHeaderColor := $FF424242; FToolBarColor := $FF323232; FItemColor := $FF828282; FFontColor := claWhite; FHeaderFontColor := $FFDADADA; FSelectedFontColor := claWhite; FSelectedColor := claRed; end; if Value = mtLightBlue then begin FHeaderColor := $FF424242; FToolBarColor := $FF323232; FItemColor := $FF2A7A9D; FFontColor := claWhite; FHeaderFontColor := $FFDADADA; FSelectedFontColor := claBlack; FSelectedColor := $FFC7FFFB; end; if Value = mtLightOrange then begin FHeaderColor := $FF424242; FToolBarColor := $FF323232; FItemColor := $FFFF9900; FFontColor := claBlack; FHeaderFontColor := $FFDADADA; FSelectedFontColor := claBlack; FSelectedColor := $FFFFCC00; end; if Value = mtLightGreen then begin FHeaderColor := $FF424242; FToolBarColor := $FF323232; FItemColor := $FF76D015; FFontColor := claBlack; FHeaderFontColor := $FFDADADA; FSelectedFontColor := claBlack; FSelectedColor := $FFDCFF00; end; FTheme := Value; end; procedure TksSlideMenuAppearence.SetToolBarColor(const Value: TAlphaColor); begin FToolBarColor := Value; FTheme := mtCustom; end; { TksSlideMenuContainer } function TksSlideMenuContainer.CalculateListViewHeight: single; var ICount: integer; begin Result := 0; for ICount := 0 to FListView.Items.Count-1 do begin Result := Result + FListView.Items[ICount].Height; end; end; constructor TksSlideMenuContainer.Create(AOwner: TComponent); begin inherited Create(AOwner); FSlideMenu := (AOwner as TksSlideMenu); FToolBar := TksSlideMenuToolbar.Create(Self, FSlideMenu); CreateListView; ClipChildren := True; HitTest := True; end; procedure TksSlideMenuContainer.CreateListView; begin if FListView <> nil then Exit; FListView := TksTableView.Create(Self); FListView.SelectionOptions.KeepSelection := True; FListView.DeleteButton.Enabled := False; FListView.PullToRefresh.Enabled := False; //FListView.ShowSelection := False; FListView.OnItemClick := ItemClick; FListView.Align := TAlignLayout.Client; FListView.FullWidthSeparator := True; FListView.DeleteButton.Enabled := False; AddObject(FListView); end; destructor TksSlideMenuContainer.Destroy; begin {$IFDEF NEXTGEN} FListView.DisposeOf; FToolBar.DisposeOf; {$ELSE} FListView.Free; FToolBar.Free; {$ENDIF} inherited; end; procedure TksSlideMenuContainer.ItemClick(Sender: TObject; x, y: single; AItem: TksTableViewItem; AId: string; ARowObj: TksTableViewItemObject); begin if HitTest = False then Exit; HitTest := False; //UpdateSelectedItem; Sleep(200); FSlideMenu.MenuItemSelected(Self, x, y, AItem, AId, ARowObj); end; { TksSlideMenuToolbar } constructor TksSlideMenuToolbar.Create(AOwner: TComponent; ASlideMenu: TksSlideMenu); begin inherited Create; FSlideMenu := ASlideMenu; FBitmap := TBitmap.Create; FFont := TFont.Create; FFont.Size := C_DEFAULT_MENU_TOOLBAR_FONT_SIZE; FHeader := TImage.Create(AOwner); FHeader.Position.X := 0; FHeader.Position.Y := 0; FHeader.Width := C_DEFAULT_MENU_WIDTH; FHeader.Height := C_DEFAULT_MENU_TOOLBAR_HEIGHT; FHeader.Align := TAlignLayout.Top; FHeader.HitTest := False; FVisible := True; (AOwner as TFmxObject).AddObject(FHeader); end; destructor TksSlideMenuToolbar.Destroy; begin FreeAndNil(FBitmap); FreeAndNil(FFont); FreeAndNil(FHeader); inherited; end; function TksSlideMenuToolbar.GetBitmap: TBitmap; begin Result := FBitmap; end; function TksSlideMenuToolbar.GetFont: TFont; begin Result := FFont; end; function TksSlideMenuToolbar.GetText: string; begin Result := FText; end; procedure TksSlideMenuToolbar.SetBitmap(const Value: TBitmap); begin FBitmap.Assign(Value); end; procedure TksSlideMenuToolbar.SetFont(const Value: TFont); begin FFont.Assign(Value); end; procedure TksSlideMenuToolbar.SetText(const Value: string); begin FText := Value; end; procedure TksSlideMenuToolbar.UpdateToolbar; var ABmp: TBitmap; AXPos: integer; begin if not Visible then begin FHeader.Height := 0; Exit; end; ABmp := TBitmap.Create(Round(C_DEFAULT_MENU_WIDTH*GetScreenScale), Round(C_DEFAULT_MENU_TOOLBAR_HEIGHT*GetScreenScale)); try ABmp.BitmapScale := GetScreenScale; AXPos := 10; ABmp.Clear(FSlideMenu.Appearence.ToolBarColor); ABmp.Canvas.BeginScene; if FBitmap.IsEmpty = False then begin ABmp.Canvas.DrawBitmap(FBitmap, RectF(0, 0, FBitmap.Width, FBitmap.Height), RectF(10, 10, 40, 40), 1); AXPos := 50; end; ABmp.Canvas.Fill.Color := FSlideMenu.Appearence.FFontColor; ABmp.Canvas.Font.Assign(FFont); ABmp.Canvas.FillText(RectF(AXPos, 0, C_DEFAULT_MENU_WIDTH, C_DEFAULT_MENU_TOOLBAR_HEIGHT), FText, False, 1, [], TTextAlign.Leading); ABmp.Canvas.EndScene; ABmp.Canvas.BeginScene; ABmp.Canvas.Fill.Color := FSlideMenu.Appearence.ItemColor; //ABmp.Canvas.StrokeThickness := 1; ABmp.Canvas.FillRect(RectF(0, C_DEFAULT_MENU_TOOLBAR_HEIGHT-1, C_DEFAULT_MENU_WIDTH, C_DEFAULT_MENU_TOOLBAR_HEIGHT), 0, 0, AllCorners, 1, ABmp.Canvas.Fill); //ABmp.Canvas.DrawLine(PointF(0, ABmp.Height-GetScreenScale), PointF(ABmp.Width, ABmp.Height-GetScreenScale), 1, ABmp.Canvas.Stroke); ABmp.Canvas.EndScene; FHeader.Bitmap := ABmp; finally FreeAndNil(ABmp); end; end; initialization SlideMenuAnimating := False; end.
(* ENUNCIADO Dizemos que uma matriz quadrada inteira é um quadrado mágico se a soma dos elementos de cada linha, a soma dos elementos de cada coluna e a soma dos elementos das diagonais principal e secundária são todos iguais. Exemplo: 8 0 7 4 5 6 3 10 2 é um quadrado mágico pois 8+0+7 = 4+5+6 = 3+10+2 = 8+4+3 = 0+5+10 = 7+6+2 = 8+5+2 = 3+5+7 = 15. Crie um programa em Free Pascal que leia um valor n representando o tamanho da matriz e leia uma matrix A(n x n) que representa o quadrado e informe se a matriz é um quadrado mágico. Exemplo de entrada: 3 8 0 7 4 5 6 3 10 2 Saída esperada para o exemplo acima: sim *) program 2quadradomagico; const max = 100; type Tquadrado = record mat : array [1 .. max,1 .. max] of longint; n:longint; lin,col,dia:boolean; end; function diagonal2(var matriz:Tquadrado):longint; var i,j:longint; begin diagonal2:=0; for i:=1 to matriz.n do begin j:=matriz.n-i+1; diagonal2:=diagonal2+matriz.mat[i,j]; end; end; procedure diagonais(var matriz:Tquadrado); var i,dia1,dia2:longint; begin matriz.dia:=true; dia1:=0; for i:=1 to matriz.n do dia1:=dia1+matriz.mat[i,i]; dia2:=diagonal2(matriz); if dia1 <> dia2 then matriz.dia:=false; end; procedure coluna(var matriz:Tquadrado); var i,j:longint; soma: array [1 .. max] of longint; begin matriz.col:=true; for i:=1 to matriz.n do soma[i]:=0; for j:=1 to matriz.n do for i:=1 to matriz.n do soma[j]:=soma[j]+matriz.mat[i,j]; i:=0; while (matriz.col=true) and (i<matriz.n-1) do begin i:=i+1; if soma[i] <> soma[i+1] then matriz.col:=false; end; end; procedure linha(var matriz:Tquadrado); var i,j:longint; soma:array [1 .. max] of longint; begin matriz.lin:=true; for i:=1 to max do soma[i]:=0; for i:=1 to matriz.n do for j:=1 to matriz.n do soma[i]:=soma[i]+matriz.mat[i,j]; i:=0; while (matriz.lin = true)and(i<matriz.n-1) do begin i:=i+1; if soma[i] <> soma[i+1] then matriz.lin:=false; end; end; procedure ler(var matriz:Tquadrado); var i,j:longint; begin for i:=1 to matriz.n do for j:=1 to matriz.n do read(matriz.mat[i,j]); end; var matriz:Tquadrado; begin read(matriz.n); ler(matriz); linha(matriz); coluna(matriz); diagonais(matriz); (*writeln(matriz.dia); writeln(matriz.lin); writeln(matriz.col);*) if ((matriz.lin=true)and(matriz.col=true)and(matriz.dia=true)) then writeln('sim') else writeln('nao'); end.
unit CFDClave; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, nbLabels; type TDFDClave = class(TForm) lblUsuario: TnbLabel; lblClave: TnbLabel; eUsuario: TEdit; eClave: TEdit; btnAceptar: TButton; btnCancelar: TButton; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnCancelarClick(Sender: TObject); procedure btnAceptarClick(Sender: TObject); private { Private declarations } public { Public declarations } sUsuario, sClave: string; bAceptar: boolean; end; function Ejecutar( var AUsuario, AClave: string ): boolean; implementation {$R *.dfm} var DFDClave: TDFDClave; function Ejecutar( var AUsuario, AClave: string ): boolean; begin DFDClave:= TDFDClave.Create( nil ); DFDClave.ShowModal; result:= DFDClave.bAceptar; if result then begin AUsuario:= DFDClave.sUsuario; AClave:= DFDClave.sClave; end; FreeAndNil( DFDClave ); end; procedure TDFDClave.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case key of vk_Return, vk_down: begin Key := 0; PostMessage(Handle, WM_NEXTDLGCTL, 0, 0); end; vk_up: begin Key := 0; PostMessage(Handle, WM_NEXTDLGCTL, 1, 0); end; vk_f1: begin Key := 0; btnAceptar.Click; end; vk_escape: begin Key := 0; btnCancelar.Click; end; end; end; procedure TDFDClave.btnCancelarClick(Sender: TObject); begin bAceptar:= False; Close; end; procedure TDFDClave.btnAceptarClick(Sender: TObject); begin bAceptar:= True; sUsuario:= eUsuario.Text; sClave:= eClave.Text; Close; end; end.
unit Company; {$mode objfpc}{$H+} interface uses Classes, SysUtils, BaseModel, CompanyHeadquarters, CompanyLinks; type IBaseCompany = interface(IBaseModel) ['{AB9CEA45-E3B6-4C08-A2BB-15F5C7CA232E}'] function GetId: string; function GetName: string; function GetFounder: string; function GetEmployees: LongWord; function GetVehicles: LongWord; function GetCEO: string; function GetCTO: string; function GetCOO: string; function GetValuation: Currency; function GetSummary: string; function GetHeadquarters: ICompanyHeadquarters; function GetLinks: ICompanyLinks; function GetFoundedYear: LongWord; function GetLaunchSites: LongWord; function GetTestSites: LongWord; function GetCtoPropulsion: string; procedure SetId(AValue: string); procedure SetName(AValue: string); procedure SetFounder(AValue: string); procedure SetEmployees(AValue: LongWord); procedure SetVehicles(AValue: LongWord); procedure SetCEO(AValue: string); procedure SetCTO(AValue: string); procedure SetCOO(AValue: string); procedure SetValuation(AValue: Currency); procedure SetSummary(AValue: string); procedure SetHeadquarters(AValue: ICompanyHeadquarters); procedure SetLinks(AValue: ICompanyLinks); procedure SetFoundedYear(AValue: LongWord); procedure SetLaunchSites(AValue: LongWord); procedure SetTestSites(AValue: LongWord); procedure SetCtoPropulsion(AValue: string); end; ICompany = interface(IBaseCompany) ['{81A8951C-05DE-4FC7-8277-5D8B38549FA2}'] property CEO: string read GetCEO write SetCEO; property COO: string read GetCOO write SetCOO; property CTO: string read GetCTO write SetCTO; property CtoPropulsion: string read GetCtoPropulsion write SetCtoPropulsion; property Employees: LongWord read GetEmployees write SetEmployees; property FoundedYear: LongWord read GetFoundedYear write SetFoundedYear; property Founder: string read GetFounder write SetFounder; property Headquarters: ICompanyHeadquarters read GetHeadquarters write SetHeadquarters; property Id: string read GetId write SetId; property LaunchSites: LongWord read GetLaunchSites write SetLaunchSites; property Links: ICompanyLinks read GetLinks write SetLinks; property Name: string read GetName write SetName; property Summary: string read GetSummary write SetSummary; property TestSites: LongWord read GetTestSites write SetTestSites; property Valuation: Currency read GetValuation write SetValuation; property Vehicles: LongWord read GetVehicles write SetVehicles; end; function NewCompany: ICompany; implementation uses JSON_Helper, Variants; type { TCompany } TCompany = class(TBaseModel, ICompany) private FId: string; FName: string; FFounder: string; FEmployees: LongWord; FVehicles: LongWord; FCEO: string; FCTO: string; FCOO: string; FValuation: Currency; FSummary: string; FHeadquarters: ICompanyHeadquarters; FLinks: ICompanyLinks; FFoundedYear: LongWord; FLaunchSites: LongWord; FTestSites: LongWord; FCtoPropulsion: string; private function GetId: string; function GetName: string; function GetFounder: string; function GetEmployees: LongWord; function GetVehicles: LongWord; function GetCEO: string; function GetCTO: string; function GetCOO: string; function GetValuation: Currency; function GetSummary: string; function GetHeadquarters: ICompanyHeadquarters; function GetLinks: ICompanyLinks; function GetFoundedYear: LongWord; function GetLaunchSites: LongWord; function GetTestSites: LongWord; function GetCtoPropulsion: string; private procedure SetId(AValue: string); procedure SetId(AValue: Variant); procedure SetName(AValue: string); procedure SetName(AValue: Variant); procedure SetFounder(AValue: string); procedure SetFounder(AValue: Variant); procedure SetEmployees(AValue: LongWord); procedure SetEmployees(AValue: Variant); procedure SetVehicles(AValue: LongWord); procedure SetVehicles(AValue: Variant); procedure SetCEO(AValue: string); procedure SetCEO(AValue: Variant); procedure SetCTO(AValue: string); procedure SetCTO(AValue: Variant); procedure SetCOO(AValue: string); procedure SetCOO(AValue: Variant); procedure SetValuation(AValue: Currency); procedure SetValuation(AValue: Variant); procedure SetSummary(AValue: string); procedure SetSummary(AValue: Variant); procedure SetHeadquarters(AValue: ICompanyHeadquarters); procedure SetLinks(AValue: ICompanyLinks); procedure SetFoundedYear(AValue: LongWord); procedure SetFoundedYear(AValue: Variant); procedure SetLaunchSites(AValue: LongWord); procedure SetLaunchSites(AValue: Variant); procedure SetTestSites(AValue: LongWord); procedure SetTestSites(AValue: Variant); procedure SetCtoPropulsion(AValue: string); procedure SetCtoPropulsion(AValue: Variant); public function ToString: string; override; public procedure BuildSubObjects(const JSONData: IJSONData); override; published property ceo: Variant write SetCEO; property coo: Variant write SetCOO; property cto: Variant write SetCTO; property cto_propulsion: Variant write SetCtoPropulsion; property employees: Variant write SetEmployees; property founded: Variant write SetFoundedYear; property founder: Variant write SetFounder; property id: Variant write SetId; property launch_sites: Variant write SetLaunchSites; property name: Variant write SetName; property summary: Variant write SetSummary; property test_sites: Variant write SetTestSites; property valuation: Variant write SetValuation; property vehicles: Variant write SetVehicles; end; function NewCompany: ICompany; begin Result := TCompany.Create; end; { TCompany } function TCompany.GetId: string; begin Result := FId; end; function TCompany.GetName: string; begin Result := FName; end; function TCompany.GetFounder: string; begin Result := FFounder; end; function TCompany.GetEmployees: LongWord; begin Result := FEmployees; end; function TCompany.GetVehicles: LongWord; begin Result := FVehicles; end; function TCompany.GetCEO: string; begin Result := FCEO; end; function TCompany.GetCTO: string; begin Result := FCTO; end; function TCompany.GetCOO: string; begin Result := FCOO; end; function TCompany.GetValuation: Currency; begin Result := FValuation; end; function TCompany.GetSummary: string; begin Result := FSummary; end; function TCompany.GetHeadquarters: ICompanyHeadquarters; begin Result := FHeadquarters; end; function TCompany.GetLinks: ICompanyLinks; begin Result := FLinks; end; function TCompany.GetFoundedYear: LongWord; begin Result := FFoundedYear; end; function TCompany.GetLaunchSites: LongWord; begin Result := FLaunchSites; end; function TCompany.GetTestSites: LongWord; begin Result := FTestSites; end; function TCompany.GetCtoPropulsion: string; begin Result := FCtoPropulsion; end; procedure TCompany.SetId(AValue: string); begin FId := AValue; end; procedure TCompany.SetId(AValue: Variant); begin if VarIsNull(AValue) then AValue := ''; FId := AValue; end; procedure TCompany.SetName(AValue: string); begin FName := AValue; end; procedure TCompany.SetName(AValue: Variant); begin if VarIsNull(AValue) then AValue := ''; FName := AValue; end; procedure TCompany.SetFounder(AValue: string); begin FFounder := AValue; end; procedure TCompany.SetFounder(AValue: Variant); begin if VarIsNull(AValue) then AValue := ''; FFounder := AValue; end; procedure TCompany.SetEmployees(AValue: LongWord); begin FEmployees := AValue; end; procedure TCompany.SetEmployees(AValue: Variant); begin if VarIsNull(AValue) then AValue := 0; FEmployees := AValue; end; procedure TCompany.SetVehicles(AValue: LongWord); begin FVehicles := AValue; end; procedure TCompany.SetVehicles(AValue: Variant); begin if VarIsNull(AValue) then AValue := 0; FVehicles := AValue; end; procedure TCompany.SetCEO(AValue: string); begin FCEO := AValue; end; procedure TCompany.SetCEO(AValue: Variant); begin if VarIsNull(AValue) then AValue := ''; FCEO := AValue; end; procedure TCompany.SetCTO(AValue: string); begin FCTO := AValue; end; procedure TCompany.SetCTO(AValue: Variant); begin if VarIsNull(AValue) then AValue := ''; FCTO := AValue; end; procedure TCompany.SetCOO(AValue: string); begin FCOO := AValue; end; procedure TCompany.SetCOO(AValue: Variant); begin if VarIsNull(AValue) then AValue := ''; FCOO := AValue; end; procedure TCompany.SetValuation(AValue: Currency); begin FValuation := AValue; end; procedure TCompany.SetValuation(AValue: Variant); begin if VarIsNull(AValue) then AValue := 0; FValuation := AValue; end; procedure TCompany.SetSummary(AValue: string); begin FSummary := AValue; end; procedure TCompany.SetSummary(AValue: Variant); begin if VarIsNull(AValue) then AValue := ''; FSummary := AValue; end; procedure TCompany.SetHeadquarters(AValue: ICompanyHeadquarters); begin FHeadquarters := AValue; end; procedure TCompany.SetLinks(AValue: ICompanyLinks); begin FLinks := AValue; end; procedure TCompany.SetFoundedYear(AValue: LongWord); begin FFoundedYear := AValue; end; procedure TCompany.SetFoundedYear(AValue: Variant); begin if VarIsNull(AValue) then AValue := 0; FFoundedYear := AValue; end; procedure TCompany.SetLaunchSites(AValue: LongWord); begin FLaunchSites := AValue; end; procedure TCompany.SetLaunchSites(AValue: Variant); begin if VarIsNull(AValue) then AValue := 0; FLaunchSites := AValue; end; procedure TCompany.SetTestSites(AValue: LongWord); begin FTestSites := AValue; end; procedure TCompany.SetTestSites(AValue: Variant); begin if VarIsNull(AValue) then AValue := 0; FTestSites := AValue; end; procedure TCompany.SetCtoPropulsion(AValue: string); begin FCtoPropulsion := AValue; end; procedure TCompany.SetCtoPropulsion(AValue: Variant); begin if VarIsNull(AValue) then AValue := ''; FCtoPropulsion := AValue; end; function TCompany.ToString: string; begin Result := Format('' + 'CEO: %s' + LineEnding + 'COO: %s' + LineEnding + 'CTO: %s' + LineEnding + 'CTO Propulsion: %s' + LineEnding + 'Employees: %u' + LineEnding + 'Founded Year: %u' + LineEnding + 'Founder: %s' + LineEnding + 'Headquarters: %s' + LineEnding + 'Id: %s' + LineEnding + 'Launch Sites: %u' + LineEnding + 'Links:' + LineEnding + ' %s' + 'Name: %s' + LineEnding + 'Summary: %s' + LineEnding + 'Test Sites: %u' + LineEnding + 'Valuation: %m' + LineEnding + 'Vehicles: %u' , [ GetCEO, GetCOO, GetCTO, GetCtoPropulsion, GetEmployees, GetFoundedYear, GetFounder, GetHeadquarters.ToString, GetId, GetLaunchSites, StringReplace( GetLinks.ToString, LineEnding, LineEnding + ' ', [rfReplaceAll]), GetName, GetSummary, GetTestSites, GetValuation, GetVehicles ]); end; procedure TCompany.BuildSubObjects(const JSONData: IJSONData); var Headquarters: ICompanyHeadquarters; Links: ICompanyLinks; SubJSONData: IJSONData; begin inherited BuildSubObjects(JSONData); SubJSONData := JSONData.GetPath('headquarters'); Headquarters := NewCompanyHeadquarters; JSONToModel(SubJSONData.GetJSONData, Headquarters); Self.FHeadquarters := Headquarters; SubJSONData := JSONData.GetPath('links'); Links := NewCompanyLinks; JSONToModel(SubJSONData.GetJSONData, Links); Self.FLinks := Links; end; end.
unit uCadastroUsuario; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons; type TReg = record id:integer; nome:string[255]; sobrenome:string[255]; email:string[128]; senha:string[128]; ativo: boolean; end; TfCadastroUsuario = class(TForm) editTextSobrenome: TEdit; editTextEmail: TEdit; editTextSenha: TEdit; editTextNome: TEdit; lblNome: TLabel; lblSobrenome: TLabel; lblEmail: TLabel; lblSenha: TLabel; lblConfirmarSenha: TLabel; editTextConfirmarSenha: TEdit; btnCadastrar: TSpeedButton; editTextId: TEdit; procedure FormActivate(Sender: TObject); procedure btnCadastrarClick(Sender: TObject); private mensagensErro: TStringList; procedure AbrirArquivo(caminho: string); procedure MostrarMensagensErro(); procedure EscreverArquivo(); procedure LimparTela(); procedure MostrarDialogMensagemSucesso(); procedure LimparMensagensErro(); procedure MostrarDialogMensagensErro(); procedure ConfigurarID(var reg: tReg); procedure ValidarNome(nome:string); procedure ValidarSobrenome(sobrenome:string); procedure ValidarEmail(email:string); procedure ValidarSenha(senha:string); procedure ValidarConfirmacaoSenha(confirmacaoSenha, senha:string); procedure InicializarDados(var nome, sobrenome, email, senha, confirmacaoSenha: string); procedure InicializarRegistro(var reg:tReg); function getRegistroUsuario() : TReg; function UsuarioIsValid() : boolean; function getCodigo: integer; function getMensagemErro() : PWideChar; function getText(edit: TEdit) : string; const caminhoArquivoUsuarios = 'C:\Users\TECBMNLS\Documents\Embarcadero\Studio\Projects\CadastroReceitasRepository\CadastroReceitas\dados\usuarios'; lengthMaximoNomeUsuario = 255; lengthMaximoSobrenomeUsuario = 255; lengthMaximoEmailUsuario = 128; lengthMaximoSenhaUsuario = 128; mensagemInseridoSucesso = 'Registro salvo com sucesso.'; tituloDialogSucesso = 'Sucesso'; quebrarLinha = #10; tituloDialogAviso = 'Aviso'; mensagemNomeObrigatorio = 'O nome é obrigatório.'; mensagemNomeMuitoLongo = 'O nome é muito longo.'; mensagemSobrenomeObrigatorio = 'O sobrenome é obrigatório.'; mensagemSobrenomeMuitoLongo = 'O sobrenome é muito longo.'; mensagemEmailObrigatorio = 'O email é obrigatório.'; mensagemEmailMuitoLongo = 'O email é muito longo.'; mensagemSenhaObrigatoria = 'A senha é obrigatória.'; mensagemSenhaMuitoLonga = 'A senha é muito longa.'; mensagemConfirmacaoSenhaObrigatoria = 'A confirmação da senha é obrigatória.'; mensagemConfirmacaoSenhaMuitoLonga = 'A confirmação da senha é muito longa.'; mensagemSenhaEConfirmacaoDiferentes = 'A senha e a confirmação não são iguais.'; public { Public declarations } end; var fCadastroUsuario: TfCadastroUsuario; implementation {$R *.dfm} uses uListarUsuarios; procedure TfCadastroUsuario.AbrirArquivo(caminho: string); var arq: file of TReg; begin AssignFile(arq, caminho); if (not FileExists(caminho)) then Rewrite(arq) else Reset(arq); CloseFile(arq); end; function TfCadastroUsuario.getCodigo: integer; var arq:File of tReg; begin AssignFile(arq, caminhoArquivoUsuarios); reset(arq); result:= FileSize(arq) + 1; CloseFile(arq); end; function TfCadastroUsuario.getMensagemErro: PWideChar; var I: Integer; mensagem: string; pWideCharMensagem: PWideChar; begin mensagem:= ''; for I := 0 to mensagensErro.Count - 1 do begin mensagem:= mensagem + mensagensErro.Strings[I] + quebrarLinha; end; pWideCharMensagem := PWideChar(mensagem); result:= pWideCharMensagem; end; procedure TfCadastroUsuario.btnCadastrarClick(Sender: TObject); begin if (UsuarioIsValid()) then begin self.EscreverArquivo(); self.LimparTela(); self.MostrarDialogMensagemSucesso(); end else self.MostrarMensagensErro(); end; procedure TfCadastroUsuario.EscreverArquivo(); var reg: TReg; arq: file of TReg; begin reg := getRegistroUsuario(); AssignFile(arq, caminhoArquivoUsuarios); Reset(arq); Seek(arq, reg.id - 1); Write(arq,reg); CloseFile(arq); end; procedure TfCadastroUsuario.FormActivate(Sender: TObject); begin self.AbrirArquivo(caminhoArquivoUsuarios); self.LimparMensagensErro(); end; procedure TfCadastroUsuario.LimparMensagensErro; begin self.mensagensErro := TStringList.Create; self.mensagensErro.Clear; end; procedure TfCadastroUsuario.LimparTela; begin editTextNome.Text := ''; editTextSobrenome.Text := ''; editTextEmail.Text := ''; editTextSenha.Text := ''; editTextConfirmarSenha.Text := ''; editTextId.Text := ''; end; procedure TfCadastroUsuario.MostrarDialogMensagensErro; begin Application.MessageBox(self.getMensagemErro(), tituloDialogAviso, MB_OK+MB_ICONERROR); end; procedure TfCadastroUsuario.MostrarDialogMensagemSucesso; begin Application.MessageBox(mensagemInseridoSucesso, tituloDialogSucesso, MB_OK+MB_ICONINFORMATION); end; procedure TfCadastroUsuario.MostrarMensagensErro; begin if (mensagensErro.Count > 0) then begin self.MostrarDialogMensagensErro(); end; end; function TfCadastroUsuario.getRegistroUsuario : TReg; var reg: TReg; begin self.InicializarRegistro(reg); result := reg; end; function TfCadastroUsuario.getText(edit: TEdit): string; begin result:= Trim(edit.Text); end; procedure TfCadastroUsuario.InicializarDados(var nome, sobrenome, email, senha, confirmacaoSenha: string); begin nome:= getText(editTextNome); sobrenome:= getText(editTextSobrenome); email:= getText(editTextEmail); senha:= getText(editTextSenha); confirmacaoSenha:= getText(editTextConfirmarSenha); end; procedure TfCadastroUsuario.InicializarRegistro(var reg:tReg); begin self.ConfigurarID(reg); reg.nome := getText(editTextNome); reg.sobrenome := getText(editTextSobrenome); reg.email := getText(editTextEmail); reg.senha := getText(editTextSenha); reg.ativo := true; end; procedure TfCadastroUsuario.ConfigurarID(var reg: tReg); begin if editTextId.Text = '' then reg.id := getCodigo() else reg.id := strtoint(editTextId.Text); end; function TfCadastroUsuario.UsuarioIsValid: boolean; var nome, sobrenome, email, senha, confirmacaoSenha: string; begin self.LimparMensagensErro(); self.InicializarDados(nome, sobrenome, email, senha, confirmacaoSenha); self.ValidarNome(nome); self.ValidarSobrenome(sobrenome); self.ValidarEmail(email); self.ValidarSenha(senha); self.ValidarConfirmacaoSenha(confirmacaoSenha, senha); result:= mensagensErro.Count = 0; end; procedure TfCadastroUsuario.ValidarConfirmacaoSenha(confirmacaoSenha, senha: string); begin if (confirmacaoSenha.IsEmpty()) then begin mensagensErro.Add(mensagemConfirmacaoSenhaObrigatoria); end else if (confirmacaoSenha.Length > lengthMaximoSenhaUsuario) then begin mensagensErro.Add(mensagemConfirmacaoSenhaMuitoLonga); end else if (not senha.Equals(confirmacaoSenha)) then begin mensagensErro.Add(mensagemSenhaEConfirmacaoDiferentes); end; end; procedure TfCadastroUsuario.ValidarEmail(email: string); begin if (email.IsEmpty()) then begin mensagensErro.Add(mensagemEmailObrigatorio); end else if (email.Length > lengthMaximoEmailUsuario) then begin mensagensErro.Add(mensagemEmailMuitoLongo); end; end; procedure TfCadastroUsuario.ValidarNome(nome: string); begin if (nome.IsEmpty()) then begin mensagensErro.Add(mensagemNomeObrigatorio); end else if (nome.Length > lengthMaximoNomeUsuario) then begin mensagensErro.Add(mensagemNomeMuitoLongo); end; end; procedure TfCadastroUsuario.ValidarSenha(senha: string); begin if (senha.IsEmpty()) then begin mensagensErro.Add(mensagemSenhaObrigatoria); end else if (senha.Length > lengthMaximoSenhaUsuario) then begin mensagensErro.Add(mensagemSenhaMuitoLonga); end; end; procedure TfCadastroUsuario.ValidarSobrenome(sobrenome: string); begin if (sobrenome.IsEmpty()) then begin mensagensErro.Add(mensagemSobrenomeObrigatorio); end else if (sobrenome.Length > lengthMaximoSobrenomeUsuario) then begin mensagensErro.Add(mensagemSobrenomeMuitoLongo); end; end; end.
unit AqDrop.DB.FB; interface uses AqDrop.DB.Adapter, AqDrop.DB.SQL.Intf; type TAqDBFBSQLSolver = class(TAqDBSQLSolver) strict protected function SolveGUIDConstant(pConstant: IAqDBSQLGUIDConstant): string; override; function SolveLimit(pSelect: IAqDBSQLSelect): string; override; function SolveOffset(pSelect: IAqDBSQLSelect): string; override; function SolveBooleanConstant(pConstant: IAqDBSQLBooleanConstant): string; override; function SolveLikeLeftValue(pLeftValue: IAqDBSQLValue): string; override; function SolveLikeRightValue(pRightValue: IAqDBSQLValue): string; override; public function SolveSelect(pSelect: IAqDBSQLSelect): string; override; function SolveGeneratorName(const pTableName, pFieldName: string): string; override; function GetAutoIncrementQuery(const pGeneratorName: string): string; override; end; implementation uses System.SysUtils, AqDrop.Core.Helpers; { TAqDBFBSQLSolver } function TAqDBFBSQLSolver.GetAutoIncrementQuery(const pGeneratorName: string): string; begin Result := Format('select GEN_ID(%s, 1) from RDB$DATABASE', [pGeneratorName]); end; function TAqDBFBSQLSolver.SolveBooleanConstant(pConstant: IAqDBSQLBooleanConstant): string; begin if pConstant.Value then begin Result := '1'; end else begin Result := '0'; end; Result := Result.Quote; end; function TAqDBFBSQLSolver.SolveGeneratorName(const pTableName, pFieldName: string): string; begin Result := Format('GEN_%s_ID', [pTableName]); end; function TAqDBFBSQLSolver.SolveGUIDConstant(pConstant: IAqDBSQLGUIDConstant): string; begin Result := StringOf(pConstant.Value.ToByteArray()).Quote; end; function TAqDBFBSQLSolver.SolveLikeLeftValue(pLeftValue: IAqDBSQLValue): string; begin Result := Format('upper(%s)', [inherited]); end; function TAqDBFBSQLSolver.SolveLikeRightValue(pRightValue: IAqDBSQLValue): string; begin Result := Format('upper(%s)', [inherited]); end; function TAqDBFBSQLSolver.SolveLimit(pSelect: IAqDBSQLSelect): string; begin if pSelect.IsLimitDefined then begin Result := 'first ' + pSelect.Limit.ToString + ' '; end else begin Result := ''; end; end; function TAqDBFBSQLSolver.SolveOffset(pSelect: IAqDBSQLSelect): string; begin if pSelect.IsOffsetDefined then begin Result := 'skip ' + pSelect.Offset.ToString + ' '; end else begin Result := ''; end; end; function TAqDBFBSQLSolver.SolveSelect(pSelect: IAqDBSQLSelect): string; begin Result := 'select ' + SolveLimit(pSelect) + SolveOffset(pSelect) + SolveSelectBody(pSelect); end; end.
unit AppCommands; interface uses SysUtils, Classes, tiObject, mvc_base, AppModel, AppController, MainFrm, ComCtrls; type // ----------------------------------------------------------------- // Class Objects // ----------------------------------------------------------------- {: App command which listens for standard TNotifyEvent. } TCmdNotifyEvent = class(TMVCCommand) private FSender: TObject; procedure SetSender(const Value: TObject); protected procedure HandleNotifyEvent(Sender: TObject); virtual; public property Sender: TObject read FSender write SetSender; end; {: Base application command that reintroduces the controller. } TAppCommand = class(TCmdNotifyEvent) public function Controller: TAppController; reintroduce; end; {: Command to load a project. } TCmdLoadProject = class(TAppCommand) protected procedure DoExecute; override; procedure DoAddListeners; override; procedure DoRemoveListeners; override; end; {: Save project command object. } TCmdSaveProject = class(TAppCommand) protected procedure DoExecute; override; procedure DoAddListeners; override; procedure DoRemoveListeners; override; end; {: Save project as... command object. } TCmdSaveProjectAs = class(TAppCommand) protected procedure DoExecute; override; procedure DoAddListeners; override; procedure DoRemoveListeners; override; end; {: close project command object. } TCmdCloseProject = class(TAppCommand) protected procedure DoExecute; override; procedure DoAddListeners; override; procedure DoRemoveListeners; override; end; {: Create a new project. } TCmdCreateProject = class(TAppCommand) protected procedure DoExecute; override; procedure DoAddListeners; override; procedure DoRemoveListeners; override; end; {: Exits the application} TCmdDoExistApp = class(TAppCommand) protected procedure DoExecute; override; procedure DoAddListeners; override; procedure DoRemoveListeners; override; end; {: Command object that executes a group of command objects when a a project is loaded. } TCmdGrpOnProjectLoaded = class(TAppCommand) protected procedure DoExecute; override; procedure DoAddListeners; override; procedure DoRemoveListeners; override; end; {: Update the MRL list with the new project filename. } TCmdDoUpdateMRUList = class(TAppCommand) protected procedure DoExecute; override; public constructor Create(AController: TMVCController); override; end; {: Updates the main forms menu to show most recent projects/quick loading. } TCmdDoUpdateMRUMenus = class(TAppCommand) protected procedure DoExecute; override; procedure DoAddListeners; override; public constructor Create(AController: TMVCController); override; end; {: Updates the main form when a project is loaded. } TCmdUpdateMainFormProjLoaded = class(TAppCommand) protected procedure DoExecute; override; public constructor Create(AController: TMVCController); override; end; {: Grouped command that calls a other commands assigned to a group name. } TCmdGrpOnProjectClosed = class(TAppCommand) protected procedure DoExecute; override; procedure DoAddListeners; override; procedure DoRemoveListeners; override; end; {: Grouped command that updates the general labels and such of the main form. } TCmdUpdateMainFormProjClose = class(TAppCommand) protected procedure DoExecute; override; public constructor Create(AController: TMVCController); override; end; {: Listens for edit project settings gesture. } TCmdHandleDoEditProjectSettings = class(TAppCommand) protected procedure DoExecute; override; procedure DoAddListeners; override; procedure DoRemoveListeners; override; end; {: Listens for OnBeforeTerminate of App model and cleans up internal controllers before shutdown. } TCmdHandleOnBeforeAppTerminate = class(TAppCommand) protected procedure DoExecute; override; procedure DoAddListeners; override; procedure DoRemoveListeners; override; end; {: Listens for unit selection in the units listview and updates the classes and enums for that unit. } TCmdHandleUnitSelected = class(TAppCommand) private FItem: TListItem; procedure SetItem(const Value: TListItem); protected property Item: TListItem read FItem write SetItem; procedure DoExecute; override; procedure DoAddListeners; override; procedure DoRemoveListeners; override; procedure HandleNotifyEvent(Sender: TObject; Item: TListItem; Selected: Boolean); reintroduce; end; {: Listen for unit list pop up menu New Unit gesture. } TCmdHandleDoAddUnit = class(TAppCommand) protected procedure DoExecute; override; procedure DoAddListeners; override; procedure DoRemoveListeners; override; end; {: Listen for delete unit gesture and execute. } TCmdHandleDoDeleteUnit = class(TAppCommand) protected procedure DoExecute; override; procedure DoAddListeners; override; procedure DoRemoveListeners; override; end; // ----------------------------------------------------------------- // Class defintions related // ----------------------------------------------------------------- {: Listens for gesture to edit a selected unit class. } TCmdHandleDoEditClassDef = class(TAppCommand) protected procedure DoExecute; override; procedure DoAddListeners; override; procedure DoRemoveListeners; override; end; {: Creates new Class definition } TCmdHandleDoCreateClassDef = class(TAppCommand) protected procedure DoExecute; override; procedure DoAddListeners; override; procedure DoRemoveListeners; override; end; {: Deletes new Class definition } TCmdHandleDoDeleteClassDef = class(TAppCommand) protected procedure DoExecute; override; procedure DoAddListeners; override; procedure DoRemoveListeners; override; end; // ----------------------------------------------------------------- // Enumerations // ----------------------------------------------------------------- {: Create a new Enumeration for the unit.} TCmdHandleDoCreateEnum = class(TAppCommand) protected procedure DoExecute; override; procedure DoAddListeners; override; procedure DoRemoveListeners; override; end; {: Edit an Enumeration for the unit.} TCmdHandleDoEditEnum = class(TAppCommand) protected procedure DoExecute; override; procedure DoAddListeners; override; procedure DoRemoveListeners; override; end; {: Delete an Enumeration for the unit.} TCmdHandleDoDeleteEnum = class(TAppCommand) protected procedure DoExecute; override; procedure DoAddListeners; override; procedure DoRemoveListeners; override; end; // ----------------------------------------------------------------- // Project genderation // ----------------------------------------------------------------- {: Generate project file(s).} TCmdHandleDoGenerateProject = class(TAppCommand) protected procedure DoExecute; override; procedure DoAddListeners; override; procedure DoRemoveListeners; override; end; // ----------------------------------------------------------------- // Other/Misc // ----------------------------------------------------------------- {: Load project from a MRU menu item.} TCmdHandleDoProjectMRU = class(TAppCommand) protected procedure DoExecute; override; procedure DoAddListeners; override; procedure DoRemoveListeners; override; end; procedure RegisterCommands(AController: TMVCController); implementation uses Dialogs, Controls, Menus, tiUtils, EventsConsts, DialogViewFrm, mapper, ProjectOptionsController, ProjectOptionsViewFrm, ClassEditViewFrm, ClassEditController, EnumEditViewFrm, EnumEditController, vcl_controllers, AppConsts // ,tiOPFStreamer // ,tiopf_super_streamer ; procedure RegisterCommands(AController: TMVCController); begin AController.AddCommand(TCmdDoExistApp.Create(AController)); AController.AddCommand(TCmdCreateProject.Create(AController)); AController.AddCommand(TCmdLoadProject.Create(AController)); AController.AddCommand(TCmdSaveProject.Create(AController)); AController.AddCommand(TCmdSaveProjectAs.Create(AController)); AController.AddCommand(TCmdCloseProject.Create(AController)); AController.AddCommand(TCmdGrpOnProjectLoaded.Create(AController)); AController.AddCommand(TCmdUpdateMainFormProjLoaded.Create(AController)); AController.AddCommand(TCmdUpdateMainFormProjClose.Create(AController)); AController.AddCommand(TCmdGrpOnProjectClosed.Create(AController)); AController.AddCommand(TCmdHandleUnitSelected.Create(AController)); AController.AddCommand(TCmdHandleDoAddUnit.Create(AController)); AController.AddCommand(TCmdHandleDoEditProjectSettings.Create(AController)); AController.AddCommand(TCmdhandleDoDeleteUnit.Create(AController)); AController.AddCommand(TCmdHandleOnBeforeAppTerminate.Create(AController)); AController.AddCommand(TCmdHandleDoEditClassDef.Create(AController)); AController.AddCommand(TCmdHandleDoCreateClassDef.Create(AController)); AController.AddCommand(TCmdHandleDoDeleteClassDef.Create(AController)); AController.AddCommand(TCmdCreateProject.Create(AController)); AController.AddCommand(TCmdHandleDoCreateEnum.Create(AController)); AController.AddCommand(TCmdHandleDoEditEnum.Create(AController)); AController.AddCommand(TCmdHandleDoDeleteEnum.Create(AController)); AController.AddCommand(TCmdHandleDoGenerateProject.Create(AController)); AController.AddCommand(TCmdDoUpdateMRUMenus.Create(AController)); AController.AddCommand(TCmdDoUpdateMRUList.Create(AController)); AController.AddCommand(TCmdHandleDoProjectMRU.Create(AController)); end; { TAppCommand } function TAppCommand.Controller: TAppController; begin result := inherited Controller as TAppController; end; { TCmdLoadProject } procedure TCmdNotifyEvent.HandleNotifyEvent(Sender: TObject); begin if Enabled then begin self.Sender := Sender; Execute; end; end; { TCmdLoadProject } procedure TCmdLoadProject.DoAddListeners; var lCtrl: TAppController; lView: TMainForm; begin lCtrl := Controller; if lCtrl <> nil then begin lView := lCtrl.View; if lView <> nil then begin lView.mnuOpen.OnClick := HandleNotifyEvent; end; end; end; procedure TCmdLoadProject.DoExecute; var lDialog: TOpenDialog; begin lDialog := TOpenDialog.Create(nil); try lDialog.Filter := 'XML files (.xml)|*.xml'; lDialog.DefaultExt := 'xml'; if Controller.Model.LastDirectoryUsed <> '' then lDialog.InitialDir := Controller.Model.LastDirectoryUsed else lDialog.InitialDir := ExtractFilePath(ParamStr(0)); if lDialog.Execute then begin if not FileExists(lDialog.FileName) then raise Exception.Create(ClassName + '.DoExecute: File is does not exist'); Controller.Model.LoadProject(lDialog.FileName); end; finally lDialog.Free; end; end; procedure TCmdLoadProject.DoRemoveListeners; begin Controller.View.mnuOpen.OnClick := nil; end; { TCmdSaveProject } procedure TCmdSaveProject.DoAddListeners; begin Controller.View.mnuSave.OnClick := self.HandleNotifyEvent; end; procedure TCmdSaveProject.DoExecute; begin if Controller.Model.State = mpsClosed then raise Exception.Create(ClassName + '.DoExecute: No project open'); Controller.Model.SaveProject; end; procedure TCmdSaveProject.DoRemoveListeners; begin Controller.View.mnuSave.OnClick := nil; end; { TCmdSaveProjectAs } procedure TCmdSaveProjectAs.DoAddListeners; begin Controller.View.mnuSaveAs.OnClick := self.HandleNotifyEvent; end; procedure TCmdSaveProjectAs.DoExecute; var lDialog: TSaveDialog; begin lDialog := TSaveDialog.Create(nil); try lDialog.Filter := 'XML Files|*.xml'; if Controller.Model.LastDirectoryUsed <> '' then lDialog.InitialDir := Controller.Model.LastDirectoryUsed else lDialog.InitialDir := ExtractFilePath(ParamStr(0)); if lDialog.Execute then begin Controller.Model.SaveProjectAs(lDialog.FileName); end; finally lDialog.Free; end; end; procedure TCmdSaveProjectAs.DoRemoveListeners; begin Controller.View.mnuSaveAs.OnClick := nil; end; { TCmdCloseProject } procedure TCmdCloseProject.DoAddListeners; begin Controller.View.mnuClose.OnClick := self.HandleNotifyEvent; end; procedure TCmdCloseProject.DoExecute; begin Controller.Model.CloseProject; end; procedure TCmdCloseProject.DoRemoveListeners; begin Controller.View.mnuClose.OnClick := nil; end; { TCmdGrpOnProjectLoaded } procedure TCmdGrpOnProjectLoaded.DoAddListeners; begin Controller.Model.OnProjectLoaded := Self.HandleNotifyEvent; end; procedure TCmdGrpOnProjectLoaded.DoExecute; begin Controller.Commands.ExecuteGroup(ON_PROJ_LOADED); end; procedure TCmdGrpOnProjectLoaded.DoRemoveListeners; begin Controller.Model.OnProjectLoaded := nil; end; procedure TCmdNotifyEvent.SetSender(const Value: TObject); begin FSender := Value; end; { TCmdUpdateMainFormInfo } constructor TCmdUpdateMainFormProjClose.Create(AController: TMVCController); begin inherited; Group := PROJ_CLOSED; end; procedure TCmdUpdateMainFormProjClose.DoExecute; var lProjLoaded: Boolean; begin lProjLoaded := Controller.Model.State <> mpsClosed; with Controller.View do begin // Menus --> mnuSave.Enabled := lProjLoaded; mnuSaveAs.Enabled := lProjLoaded; mnuClose.Enabled := lProjLoaded; mnuAddUnit.Enabled := lProjLoaded; mnuUnitChangeName.Enabled := lProjLoaded; mnuDeleteUnit.Enabled := lProjLoaded; mnuNewClass.Enabled := lProjLoaded; mnuEditClass.Enabled := lProjLoaded; mnuDeleteClass.Enabled := lProjLoaded; mnuSettings.Enabled := lProjLoaded; mnuGenerate.Enabled := lProjLoaded; mnuOpen.Enabled := True; mnuNewProject.Enabled := True; mnuNewEnum.Enabled := lProjLoaded; mnuEditEnum.Enabled := lProjLoaded; mnuDeleteEnum.Enabled := lProjLoaded; // General --> CurrentUnitLabel.Caption := ''; tsClasses.Caption := 'Classes'; tsEnums.Caption := 'Enumerations'; // status bar statMain.SimpleText := ''; end; Controller.View.Caption := 'Mapping Designer'; end; { TCmdHandleUnitSelected } procedure TCmdHandleUnitSelected.DoAddListeners; begin Controller.View.lvUnits.OnSelectItem := self.HandleNotifyEvent; end; procedure TCmdHandleUnitSelected.DoExecute; begin if Controller.View.lvUnits.Selected = nil then exit; Controller.Model.CurrentUnit := Controller.Model.Project.Units.Items[Controller.View.lvUnits.Selected.Index]; Controller.Model.UpdateUnitClasses; Controller.Model.UpdateUnitEnums; Controller.View.CurrentUnitLabel.Caption := 'Current Unit: ' + Controller.Model.CurrentUnit.Name; Controller.View.tsClasses.Caption := 'Classes (' + IntToStr(Controller.Model.CurrentClasses.Count) + ')'; Controller.View.tsEnums.Caption := 'Enumerations (' + IntToStr(Controller.Model.CurrentEnums.Count) + ')'; end; procedure TCmdHandleUnitSelected.DoRemoveListeners; begin Controller.View.lvUnits.OnSelectItem := nil; end; procedure TCmdHandleUnitSelected.HandleNotifyEvent(Sender: TObject; Item: TListItem; Selected: Boolean); begin FItem := Item; inherited HandleNotifyEvent(Sender); end; procedure TCmdHandleUnitSelected.SetItem(const Value: TListItem); begin FItem := Value; end; { TCmdHandleDoAddUnit } procedure TCmdHandleDoAddUnit.DoAddListeners; begin Controller.View.mnuAddUnit.OnClick := self.HandleNotifyEvent; end; procedure TCmdHandleDoAddUnit.DoExecute; var lVal: string; lNewUnit: TMapUnitDef; begin lVal := 'New Unit Name'; if TDialogView.GetString(lVal, 'Enter new unit name') then begin // Get rid of spaces if any if Pos(' ', lVal) > 0 then lVal := StringReplace(lVal, ' ', '_', [rfReplaceAll]); // Is there one already present? lNewUnit := TMapUnitDef(Controller.Model.Project.Units.FindByName(lVal)); if lNewUnit <> nil then raise Exception.Create(ClassName + '.DoExecute: Attempt to add duplicate unit "' + lNewUnit.Name + '".'); lNewUnit := TMapUnitDef.CreateNew; lNewUnit.Name := lVal; Controller.Model.Project.Units.Add(lNewUnit); Controller.Model.Project.Units.NotifyObservers; end; end; procedure TCmdHandleDoAddUnit.DoRemoveListeners; begin Controller.View.mnuAddUnit.OnClick := nil; end; { TCmdGrpOnProjectClosed } procedure TCmdGrpOnProjectClosed.DoAddListeners; begin Controller.Model.OnProjectUnloaded := self.HandleNotifyEvent; end; procedure TCmdGrpOnProjectClosed.DoExecute; begin Controller.Commands.ExecuteGroup(PROJ_CLOSED); end; procedure TCmdGrpOnProjectClosed.DoRemoveListeners; begin Controller.Model.OnProjectUnloaded := nil; end; { TCmdUpdateMainFormProjLoaded } constructor TCmdUpdateMainFormProjLoaded.Create(AController: TMVCController); begin inherited; Group := ON_PROJ_LOADED; end; procedure TCmdUpdateMainFormProjLoaded.DoExecute; var lProjLoaded: Boolean; begin lProjLoaded := Controller.Model.State <> mpsClosed; with Controller.View do begin mnuSave.Enabled := lProjLoaded; mnuSaveAs.Enabled := lProjLoaded; mnuClose.Enabled := lProjLoaded; mnuAddUnit.Enabled := lProjLoaded; mnuUnitChangeName.Enabled := lProjLoaded; mnuDeleteUnit.Enabled := lProjLoaded; mnuNewClass.Enabled := lProjLoaded; mnuEditClass.Enabled := lProjLoaded; mnuDeleteClass.Enabled := lProjLoaded; mnuSettings.Enabled := lProjLoaded; mnuGenerate.Enabled := lProjLoaded; mnuOpen.Enabled := lProjLoaded; mnuNewProject.Enabled := lProjLoaded; mnuNewEnum.Enabled := lProjLoaded; mnuEditEnum.Enabled := lProjLoaded; mnuDeleteEnum.Enabled := lProjLoaded; CurrentUnitLabel.Caption := ''; statMain.SimpleText := self.Controller.Model.Project.FileName; end; Controller.View.Caption := 'Mapping Designer [' + Controller.Model.Project.GeneralOptions.ProjectName + ']'; end; { TCmdHandleDoEditProjectSettings } procedure TCmdHandleDoEditProjectSettings.DoAddListeners; begin Controller.View.mnuSettings.OnClick := Self.HandleNotifyEvent; end; procedure TCmdHandleDoEditProjectSettings.DoExecute; var lCtrl: TProjectOptionsController; lView: TProjectOptionsView; begin lView := TProjectOptionsView.Create(nil); lCtrl := TProjectOptionsController.Create(Controller.Model.Project, lView); try lCtrl.Init; lCtrl.Active := True; lCtrl.Active := False; finally lCtrl.Free; end; end; procedure TCmdHandleDoEditProjectSettings.DoRemoveListeners; begin Controller.View.mnuSettings.OnClick := nil; end; { TCmdhandleDoDeleteUnit } procedure TCmdhandleDoDeleteUnit.DoAddListeners; begin Controller.View.mnuDeleteUnit.OnClick := self.HandleNotifyEvent; end; procedure TCmdhandleDoDeleteUnit.DoExecute; var lListCtrl: TListViewController; lUnit: TMapUnitDef; begin lListCtrl := TListViewController(Controller.Controllers.FindByName('units_ctl')); if lListCtrl.SelectedItem = nil then exit; lUnit := TMapUnitDef(lListCtrl.SelectedItem); if MessageDlg('Delete Unit: ' + lUnit.Name + '?', mtConfirmation, [mbYes, mbNo], 0) = mrNo then exit; Controller.Model.Project.Units.Extract(lUnit); Controller.Model.Project.Units.NotifyObservers; lUnit.Free; end; procedure TCmdhandleDoDeleteUnit.DoRemoveListeners; begin Controller.View.mnuDeleteUnit.OnClick := nil; end; { TCmdHandleOnBeforeAppTerminate } procedure TCmdHandleOnBeforeAppTerminate.DoAddListeners; begin Controller.Model.OnBeforeAppTerminate := self.HandleNotifyEvent; end; procedure TCmdHandleOnBeforeAppTerminate.DoExecute; begin Controller.Controllers.ChangeAllActive(False); Controller.Controllers.Clear; end; procedure TCmdHandleOnBeforeAppTerminate.DoRemoveListeners; begin Controller.Model.OnBeforeAppTerminate := nil; end; { TCmdHandleDoEditClassDef } procedure TCmdHandleDoEditClassDef.DoAddListeners; begin Controller.View.mnuEditClass.OnClick := self.HandleNotifyEvent; Controller.View.lvClasses.OnDblClick := self.HandleNotifyEvent; end; procedure TCmdHandleDoEditClassDef.DoExecute; var lListCtrl: TListViewController; lClassDef, lClassDefTmp: TMapClassDef; lEditCtrl: TClassEditController; lView: TClassEditView; begin if Controller.Model.CurrentUnit = nil then exit; lListCtrl := TListViewController(Controller.Controllers.FindByName('classes_ctl')); if lListCtrl.SelectedItem = nil then exit; lClassDef := TMapClassDef(lListCtrl.SelectedItem); lClassDefTmp := TMapClassDef.Create; lClassDefTmp.Assign(lClassDef); lView := TClassEditView.Create(nil); lEditCtrl := TClassEditController.Create(lClassDefTmp, lView); try lEditCtrl.ParentController := Controller; lEditCtrl.Init; lEditCtrl.Active := True; if lEditCtrl.Ok then begin lClassDef.Assign(lClassDefTmp); lClassDef.NotifyObservers; end; lEditCtrl.Active := False; finally lEditCtrl.Free; FreeAndNil(lClassDefTmp); end; end; procedure TCmdHandleDoEditClassDef.DoRemoveListeners; begin Controller.View.mnuEditClass.OnClick := nil; Controller.View.lvClasses.OnDblClick := nil; end; { TCmdHandleDoCreateClassDef } procedure TCmdHandleDoCreateClassDef.DoAddListeners; begin Controller.View.mnuNewClass.OnClick := self.HandleNotifyEvent; end; procedure TCmdHandleDoCreateClassDef.DoExecute; var lCtrl: TClassEditController; lView: TClassEditView; lClassDef: TMapClassDef; lSelected: Boolean; begin if Controller.Model.CurrentUnit = nil then exit; lClassDef := TMapClassDef.Create; try lView := TClassEditView.Create(nil); lCtrl := TClassEditController.Create(lClassDef, lView); try lClassDef.BaseClassParent := 'TtiObject'; lClassDef.BaseClassName := 'TMyNewClass'; lClassDef.ClassMapping.TableName := 'db_table_name_here'; lClassDef.ClassMapping.PKName := 'OID'; lClassDef.ClassMapping.PKField := 'OID'; lCtrl.ParentController := Controller; lCtrl.Init; lCtrl.Active := True; if lCtrl.Ok then begin Controller.Model.CurrentUnit.UnitClasses.Add(lClassDef); Controller.Model.UpdateUnitClasses; Controller.Model.CurrentClasses.NotifyObservers; lSelected := Controller.View.lvUnits.Selected <> nil; Controller.View.lvUnits.OnSelectItem(Controller.View.lvUnits, Controller.View.lvUnits.Selected, lSelected); end else FreeAndNil(lClassDef); lCtrl.Active := False; finally lCtrl.Free; end; except lClassDef.Free; end; end; procedure TCmdHandleDoCreateClassDef.DoRemoveListeners; begin Controller.View.mnuNewClass.OnClick := nil; end; { TCmdHandleDoDeleteClassDef } procedure TCmdHandleDoDeleteClassDef.DoAddListeners; begin Controller.View.mnuDeleteClass.OnClick := self.HandleNotifyEvent; end; procedure TCmdHandleDoDeleteClassDef.DoExecute; var lClassDef: TMapClassDef; lListCtrl: TListViewController; lMsg: string; begin if Controller.Model.CurrentUnit = nil then exit; lListCtrl := TListViewController(Controller.Controllers.FindByName('classes_ctl')); if lListCtrl.SelectedItem = nil then exit; lClassDef := TMapClassDef(lListCtrl.SelectedItem); lMsg := Format(CONFIRM_PROP_DELETE, [lClassDef.BaseClassName]); if MessageDlg(lMsg, mtConfirmation, [mbYes, mbNo], Controller.View.Handle) = mrNo then exit; Controller.Model.CurrentClasses.Extract(lClassDef); Controller.Model.CurrentUnit.UnitClasses.Extract(lClassDef); lClassDef.Free; Controller.Model.CurrentClasses.NotifyObservers; end; procedure TCmdHandleDoDeleteClassDef.DoRemoveListeners; begin Controller.View.mnuDeleteClass.OnClick := nil; end; { TCmdCreateProject } procedure TCmdCreateProject.DoAddListeners; begin Controller.View.mnuNewProject.OnClick := self.HandleNotifyEvent; end; procedure TCmdCreateProject.DoExecute; var lDialog: TSaveDialog; begin lDialog := TSaveDialog.Create(nil); try lDialog.Filter := 'XML files (.xml)|*.xml'; lDialog.DefaultExt := 'xml'; lDialog.Options := lDialog.Options + [ofOverwritePrompt]; lDialog.InitialDir := ExtractFilePath(ParamStr(0)); if lDialog.Execute then begin Controller.Model.CreateNewProject(lDialog.FileName); end; finally lDialog.Free; end; end; procedure TCmdCreateProject.DoRemoveListeners; begin Controller.View.mnuNewProject.OnClick := nil; end; { TCmdHandleDoCreateEnum } procedure TCmdHandleDoCreateEnum.DoAddListeners; begin Controller.View.mnuNewEnum.OnClick := self.HandleNotifyEvent; end; procedure TCmdHandleDoCreateEnum.DoExecute; var lView: TEnumEditView; lCtrl: TEnumEditController; lEnum: TMapEnum; begin lView := TEnumEditView.Create(nil); lEnum := TMapEnum.Create; lCtrl := TEnumEditController.Create(lEnum, lView); try lEnum.TypeName := 'My_New_Enum'; lCtrl.ParentController := Controller; lCtrl.Init; lCtrl.Active := True; if lCtrl.Ok then begin Controller.Model.CurrentUnit.UnitEnums.Add(lEnum); Controller.Model.CurrentPropertyTypes.Add(lEnum); Controller.Model.UpdateUnitEnums; Controller.Model.CurrentEnums.NotifyObservers; Controller.View.lvUnits.OnSelectItem(Controller.View.lvUnits, Controller.View.lvUnits.Selected, Controller.View.lvUnits.Selected <> nil); end else begin FreeAndNil(lEnum); end; lCtrl.Active := false; finally lCtrl.Free; end; end; procedure TCmdHandleDoCreateEnum.DoRemoveListeners; begin Controller.View.mnuNewEnum.OnClick := nil; end; { TCmdHandleDoEditEnum } procedure TCmdHandleDoEditEnum.DoAddListeners; begin Controller.View.mnuEditEnum.OnClick := self.HandleNotifyEvent; Controller.View.lvEnums.OnDblClick := self.HandleNotifyEvent; end; procedure TCmdHandleDoEditEnum.DoExecute; var lListCtrl: TListViewController; lEnum, lEnumTmp: TMapEnum; lEditCtrl: TEnumEditController; lView: TEnumEditView; begin if Controller.Model.CurrentUnit = nil then exit; lListCtrl := TListViewController(Controller.Controllers.FindByName('enums_ctl')); if lListCtrl.SelectedItem = nil then exit; lEnum := TMapEnum(lListCtrl.SelectedItem); lEnumTmp := TMapEnum(lEnum.Clone); lView := TEnumEditView.Create(nil); lEditCtrl := TEnumEditController.Create(lEnumTmp, lView); try lEditCtrl.Init; lEditCtrl.Active := True; if lEditCtrl.Ok then begin lEnum.Assign(lEnumTmp); lEnum.NotifyObservers; end; lEditCtrl.Active := False; finally lEditCtrl.Free; FreeAndNil(lEnumTmp); end; end; procedure TCmdHandleDoEditEnum.DoRemoveListeners; begin Controller.View.mnuEditEnum.OnClick := nil; Controller.View.lvEnums.OnDblClick := nil; end; { TCmdHandleDoDeleteEnum } procedure TCmdHandleDoDeleteEnum.DoAddListeners; begin Controller.View.mnuDeleteEnum.OnClick := Self.HandleNotifyEvent; end; procedure TCmdHandleDoDeleteEnum.DoExecute; var lEnum: TMapEnum; lListCtrl: TListViewController; lMsg: string; begin if Controller.Model.CurrentUnit = nil then exit; lListCtrl := TListViewController(Controller.Controllers.FindByName('enums_ctl')); if lListCtrl.SelectedItem = nil then exit; lEnum := TMapEnum(lListCtrl.SelectedItem); lMsg := Format(CONFIRM_PROP_DELETE, [lEnum.TypeName]); if MessageDlg(lMsg, mtConfirmation, [mbYes, mbNo], Controller.View.Handle) = mrNo then exit; Controller.Model.CurrentEnums.Extract(lEnum); Controller.Model.CurrentPropertyTypes.Extract(lEnum); Controller.Model.CurrentUnit.UnitEnums.Extract(lEnum); lEnum.Free; Controller.Model.CurrentEnums.NotifyObservers; Controller.View.lvUnits.OnSelectItem(Controller.View.lvUnits, Controller.View.lvUnits.Selected, Controller.View.lvUnits.Selected <> nil); end; procedure TCmdHandleDoDeleteEnum.DoRemoveListeners; begin Controller.View.mnuDeleteEnum.OnClick := nil; end; { TCmdHandleDoGenerateProject } procedure TCmdHandleDoGenerateProject.DoAddListeners; begin Controller.View.mnuGenerate.OnClick := self.HandleNotifyEvent; end; procedure TCmdHandleDoGenerateProject.DoExecute; begin Controller.Model.WriteProject; end; procedure TCmdHandleDoGenerateProject.DoRemoveListeners; begin Controller.View.mnuGenerate.OnClick := nil; end; { TCmdDoExistApp } procedure TCmdDoExistApp.DoAddListeners; begin Controller.View.mnuExit.OnClick := self.HandleNotifyEvent; end; procedure TCmdDoExistApp.DoExecute; begin Controller.View.Close; end; procedure TCmdDoExistApp.DoRemoveListeners; begin Controller.View.mnuExit.OnClick := nil; end; { TCmdDoUpdateMRU } constructor TCmdDoUpdateMRUMenus.Create(AController: TMVCController); begin inherited; //Group := ON_PROJ_LOADED; end; procedure TCmdDoUpdateMRUMenus.DoAddListeners; begin Controller.Model.OnAppLoaded := Self.HandleNotifyEvent; end; procedure TCmdDoUpdateMRUMenus.DoExecute; var lSL: TStringList; lItem: TMenuItem; lSubItem: TMenuItem; lCtr: Integer; lDir: string; lFile: string; begin lItem := Controller.View.mnuMRU; lDir := tiGetUserLocalAppDataDir('mapper'); if not DirectoryExists(lDir) then CreateDir(lDir); lFile := lDir + PathDelim + 'mru.txt'; for lCtr := lItem.Count - 1 downto 0 do begin lItem.Delete(lCtr); end; lSL := TStringList.Create; try // create if not exist already if not FileExists(lFile) then lSL.SaveToFile(lFile) else lSL.LoadFromFile(lFile); lItem := Controller.View.mnuMRU; for lCtr := 0 to lSL.Count - 1 do begin lSubItem := TMenuItem.Create(lItem); lSubItem.Caption := lSL[lCtr]; lSubItem.OnClick := Controller.HandleMRLClick; lItem.Add(lSubItem); end; finally lSL.Free; end; end; { TCmdDoUpdateMRUList } constructor TCmdDoUpdateMRUList.Create(AController: TMVCController); begin inherited; Group := ON_PROJ_LOADED; end; procedure TCmdDoUpdateMRUList.DoExecute; var lSL: TStringList; lCtr: Integer; lDir: string; lFile: string; lPOS: Integer; begin lDir := tiGetUserLocalAppDataDir('mapper'); if not DirectoryExists(lDir) then CreateDir(lDir); lFile := lDir + PathDelim + 'mru.txt'; lSL := TStringList.Create; try // create if not exist already if not FileExists(lFile) then lSL.SaveToFile(lFile) else lSL.LoadFromFile(lFile); lPOS := lSL.IndexOf(Controller.Model.Project.FileName); if lPOS >= 0 then begin if lPOS <> 0 then begin lSL.Delete(lPOS); lSL.Insert(0, Controller.Model.Project.FileName); end; end else begin lSL.Insert(0, Controller.Model.Project.FileName); end; if lSL.Count > 10 then begin while lSL.Count > 10 do lSL.Delete(lSL.Count - 1); end; lSL.SaveToFile(lFile); Controller.Model.OnAppLoaded(Controller.Model); finally lSL.Free; end; end; { TCmdHandleDoProjectMRU } procedure TCmdHandleDoProjectMRU.DoAddListeners; begin Controller.OnMRLClicked := self.HandleNotifyEvent; end; procedure TCmdHandleDoProjectMRU.DoExecute; begin Controller.Model.LoadProject(Controller.SelectedMRU); end; procedure TCmdHandleDoProjectMRU.DoRemoveListeners; begin Controller.OnMRLClicked := nil; end; end.
unit TSTOCustomPatchesIntf; interface Uses Classes, HsInterfaceEx; Type ITSTOPatchData = Interface(IInterfaceEx) ['{4B61686E-29A0-2112-8A2C-401F6BBB0CCC}'] Function GetInterfaceState() : TInterfaceState; Function GetPatchType() : Integer; Procedure SetPatchType(Const APatchType : Integer); Function GetPatchPath() : WideString; Procedure SetPatchPath(Const APatchPath : WideString); Function GetCode() : WideString; Procedure SetCode(Const ACode : WideString); Procedure Assign(ASource : IInterface); Property InterfaceState : TInterfaceState Read GetInterfaceState; Property PatchType : Integer Read GetPatchType Write SetPatchType; Property PatchPath : WideString Read GetPatchPath Write SetPatchPath; Property Code : WideString Read GetCode Write SetCode; End; ITSTOPatchDatas = Interface(IInterfaceListEx) ['{4B61686E-29A0-2112-B632-9DA31BA6BE39}'] Function Get(Index : Integer) : ITSTOPatchData; Procedure Put(Index : Integer; Const Item : ITSTOPatchData); Function Add() : ITSTOPatchData; OverLoad; Function Add(Const AItem : ITSTOPatchData) : Integer; OverLoad; Property Items[Index : Integer] : ITSTOPatchData Read Get Write Put; Default; End; ITSTOCustomPatch = Interface(IInterfaceEx) ['{4B61686E-29A0-2112-BB3E-3D4F9116C15A}'] Function GetInterfaceState() : TInterfaceState; Function GetPatchName() : WideString; Procedure SetPatchName(Const APatchName : WideString); Function GetPatchActive() : Boolean; Procedure SetPatchActive(Const APatchActive : Boolean); Function GetPatchDesc() : WideString; Procedure SetPatchDesc(Const APatchDesc : WideString); Function GetFileName() : WideString; Procedure SetFileName(Const AFileName : WideString); Function GetPatchData() : ITSTOPatchDatas; Procedure Assign(ASource : IInterface); Property InterfaceState : TInterfaceState Read GetInterfaceState; Property PatchName : WideString Read GetPatchName Write SetPatchName; Property PatchActive : Boolean Read GetPatchActive Write SetPatchActive; Property PatchDesc : WideString Read GetPatchDesc Write SetPatchDesc; Property FileName : WideString Read GetFileName Write SetFileName; Property PatchData : ITSTOPatchDatas Read GetPatchData; End; ITSTOCustomPatchList = Interface(IInterfaceListEx) ['{4B61686E-29A0-2112-82BA-B6A965408045}'] Function Get(Index : Integer) : ITSTOCustomPatch; Procedure Put(Index : Integer; Const Item : ITSTOCustomPatch); Function Add() : ITSTOCustomPatch; OverLoad; Function Add(Const AItem : ITSTOCustomPatch) : Integer; OverLoad; Property Items[Index : Integer] : ITSTOCustomPatch Read Get Write Put; Default; End; ITSTOCustomPatches = Interface(IInterfaceEx) ['{4B61686E-29A0-2112-B69C-ED06DD06DF1B}'] Function GetInterfaceState() : TInterfaceState; Function GetActivePatchCount() : Integer; Function GetPatches() : ITSTOCustomPatchList; Procedure Assign(ASource : IInterface); Property InterfaceState : TInterfaceState Read GetInterfaceState; Property ActivePatchCount : Integer Read GetActivePatchCount; Property Patches : ITSTOCustomPatchList Read GetPatches; End; (******************************************************************************) ITSTOPatchDataIO = Interface(ITSTOPatchData) ['{4B61686E-29A0-2112-BEDF-E83EBF2AEC51}'] Function GetOnChange() : TNotifyEvent; Procedure SetOnChange(AOnChange : TNotifyEvent); Property OnChange : TNotifyEvent Read GetOnChange Write SetOnChange; End; ITSTOPatchDatasIO = Interface(ITSTOPatchDatas) ['{4B61686E-29A0-2112-BB65-879B0C21F3FC}'] Function Get(Index : Integer) : ITSTOPatchDataIO; Procedure Put(Index : Integer; Const Item : ITSTOPatchDataIO); Function GetOnChange() : TNotifyEvent; Procedure SetOnChange(AOnChange : TNotifyEvent); Function Add() : ITSTOPatchDataIO; OverLoad; Function Add(Const AItem : ITSTOPatchDataIO) : Integer; OverLoad; Function Remove(Const AItem : ITSTOPatchDataIO) : Integer; Property Items[Index : Integer] : ITSTOPatchDataIO Read Get Write Put; Default; Property OnChange : TNotifyEvent Read GetOnChange Write SetOnChange; End; ITSTOCustomPatchIO = Interface(ITSTOCustomPatch) ['{4B61686E-29A0-2112-95A5-DFC99ED38E13}'] Function GetPatchData() : ITSTOPatchDatasIO; Function GetOnChange() : TNotifyEvent; Procedure SetOnChange(AOnChange : TNotifyEvent); Property PatchData : ITSTOPatchDatasIO Read GetPatchData; Property OnChange : TNotifyEvent Read GetOnChange Write SetOnChange; End; ITSTOCustomPatchListIO = Interface(ITSTOCustomPatchList) ['{4B61686E-29A0-2112-ABB1-EF0013E01FA7}'] Function Get(Index : Integer) : ITSTOCustomPatchIO; Procedure Put(Index : Integer; Const Item : ITSTOCustomPatchIO); Function GetModified() : Boolean; Function GetOnChange() : TNotifyEvent; Procedure SetOnChange(AOnChange : TNotifyEvent); Function Add() : ITSTOCustomPatchIO; OverLoad; Function Add(Const AItem : ITSTOCustomPatchIO) : Integer; OverLoad; Function Remove(Const AItem : ITSTOCustomPatchIO) : Integer; Property Items[Index : Integer] : ITSTOCustomPatchIO Read Get Write Put; Default; Property Modified : Boolean Read GetModified; Property OnChange : TNotifyEvent Read GetOnChange Write SetOnChange; End; (******************************************************************************) ITSTOCustomPatchesIO = Interface(ITSTOCustomPatches) ['{4B61686E-29A0-2112-9AB6-78B41DBCF99D}'] Function GetAsXml() : String; Procedure SetAsXml(Const AXml : String); Function GetPatches() : ITSTOCustomPatchListIO; Function GetModified() : Boolean; Function GetOnChange() : TNotifyEvent; Procedure SetOnChange(AOnChange : TNotifyEvent); Procedure ForceChanged(); Procedure ClearChanges(); Property AsXml : String Read GetAsXml Write SetAsXml; Property Patches : ITSTOCustomPatchListIO Read GetPatches; Property Modified : Boolean Read GetModified; Property OnChange : TNotifyEvent Read GetOnChange Write SetOnChange; End; implementation end.
{ $HDR$} {**********************************************************************} { Unit archived using Team Coherence } { Team Coherence is Copyright 2002 by Quality Software Components } { } { For further information / comments, visit our WEB site at } { http://www.TeamCoherence.com } {**********************************************************************} {} { $Log: 23936: EncoderPlayground.pas { { Rev 1.1 04/10/2003 15:22:50 CCostelloe { Emails generated now have the same date } { { Rev 1.0 26/09/2003 00:04:08 CCostelloe { Initial } unit EncoderPlayground; interface {$I IdCompilerDefines.inc} uses EncoderBox, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, Menus, ActnList, ImgList, ToolWin, ExtCtrls, StdCtrls, BXBubble, IdMessage, Spin; type TformEncoderPlayground = class(TForm) lboxMessages: TListBox; Splitter1: TSplitter; alstMain: TActionList; MainMenu1: TMainMenu; PopupMenu1: TPopupMenu; ToolBar1: TToolBar; ImageList1: TImageList; actnFile_Exit: TAction; actnTest_Test: TAction; File1: TMenuItem; actnFileTest1: TMenuItem; Exit1: TMenuItem; ToolButton1: TToolButton; Panel2: TPanel; Panel1: TPanel; Label1: TLabel; lablFilename: TLabel; actnTest_Emit: TAction; Exit2: TMenuItem; Emit1: TMenuItem; Emit2: TMenuItem; actnTest_Verify: TAction; estandVerify1: TMenuItem; estandVerify2: TMenuItem; eset1: TMenuItem; Label4: TLabel; lablErrors: TLabel; N1: TMenuItem; actnTest_VerifyAll: TAction; VerifyAll1: TMenuItem; bublEncoderPlayground: TBXBubble; Label5: TLabel; pctlMessage: TPageControl; TabSheet1: TTabSheet; memoRaw: TMemo; Panel3: TPanel; Label2: TLabel; Memo1: TMemo; Label3: TLabel; ComboBox1: TComboBox; Label6: TLabel; Label7: TLabel; ComboBox2: TComboBox; Label8: TLabel; Label9: TLabel; ListBox1: TListBox; Label10: TLabel; Edit1: TEdit; Button2: TButton; Button3: TButton; RadioGroup1: TRadioGroup; OpenDialog1: TOpenDialog; Label11: TLabel; ComboBox3: TComboBox; Button4: TButton; Label12: TLabel; ComboBox4: TComboBox; Bevel1: TBevel; Bevel2: TBevel; Button5: TButton; Button1: TButton; TabSheet2: TTabSheet; memoCorrect: TMemo; Label13: TLabel; Edit2: TEdit; Bevel3: TBevel; Button6: TButton; Button7: TButton; Button8: TButton; Label14: TLabel; ComboBox5: TComboBox; SpinEdit1: TSpinEdit; Label15: TLabel; Label16: TLabel; Edit3: TEdit; procedure actnFile_ExitExecute(Sender: TObject); procedure actnTest_TestExecute(Sender: TObject); procedure alstMainUpdate(Action: TBasicAction; var Handled: Boolean); procedure lboxMessagesDblClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure actnTest_VerifyAllExecute(Sender: TObject); procedure bublEncoderPlaygroundPlayground(Sender: TBXBubble); procedure Button4Click(Sender: TObject); procedure Edit1Change(Sender: TObject); procedure Button2Click(Sender: TObject); procedure ListBox1Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure Button6Click(Sender: TObject); procedure Button7Click(Sender: TObject); procedure Button8Click(Sender: TObject); private protected FDataPath: string; FEncoderBox: TEncoderBox; public TheMsg: TIdMessage; procedure ResetFieldsToDefaults; procedure SetupEmail; end; var formEncoderPlayground: TformEncoderPlayground; implementation {$R *.dfm} uses IdGlobal, IdText, IdAttachmentFile, IdCoreGlobal, EmailSender; const EncoderBody = 'This is the text for the sample body.' + EOL + 'This is a deliberately long line, and the reason it is a long line is that it should test whether the encoder breaks and reassembles it properly since it is longer than any line length I can think of.' + EOL; procedure TformEncoderPlayground.actnFile_ExitExecute(Sender: TObject); begin Close; end; procedure TformEncoderPlayground.actnTest_TestExecute(Sender: TObject); var LFilename: string; begin LFilename := ''; Screen.Cursor := crHourglass; try try if Assigned(FEncoderBox) then begin FreeAndNil(FEncoderBox); end; lablErrors.Caption := ''; LFilename := Copy(lboxMessages.Items[lboxMessages.ItemIndex], 3, MaxInt); FEncoderBox := TEncoderBox.Create(Self); with FEncoderBox do begin TestMessage(FDataPath + LFilename, Sender = actnTest_Verify, Sender = actnTest_Emit); lablFilename.Caption := LFilename; lablErrors.Caption := '<None>'; //Load generated message into raw message... GeneratedStream.Seek(0, soFromBeginning); memoRaw.Lines.LoadFromStream(GeneratedStream); //Load what the correct result is into memoCorrect... memoCorrect.Lines.LoadFromFile(TestMessageName); end; lboxMessages.Items[lboxMessages.ItemIndex] := '+' + Copy(lboxMessages.Items[lboxMessages.ItemIndex], 2, MaxInt); except on E: Exception do begin lablFilename.Caption := LFilename; lablErrors.Caption := E.Message; lboxMessages.Items[lboxMessages.ItemIndex] := '-' + Copy(lboxMessages.Items[lboxMessages.ItemIndex], 2, MaxInt); memoCorrect.Clear; if FEncoderBox.TestMessageName <> '' then memoCorrect.Lines.LoadFromFile(FEncoderBox.TestMessageName); memoRaw.Clear; if Assigned(FEncoderBox.GeneratedStream) then memoRaw.Lines.LoadFromStream(FEncoderBox.GeneratedStream); end; end; finally Screen.Cursor := crDefault; end; end; procedure TformEncoderPlayground.alstMainUpdate(Action: TBasicAction; var Handled: Boolean); begin actnTest_Test.Enabled := lboxMessages.ItemIndex > -1; Handled := True; end; procedure TformEncoderPlayground.lboxMessagesDblClick(Sender: TObject); begin // Here instead of linked at design because of .Enabled actnTest_Verify.Execute; end; procedure TformEncoderPlayground.FormCreate(Sender: TObject); var i: integer; LRec: TSearchRec; begin pctlMessage.ActivePage := TabSheet1; {CC: Don't append \ if already in AppDataDir...} FDataPath := bublEncoderPlayground.AppDataDir; if FDataPath[Length(FDataPath)] <> '\' then FDataPath := FDataPath + '\'; FDataPath := FDataPath + 'Encoder\'; //Find and display all the test messages... i := FindFirst(FDataPath + '*.ini', faAnyFile, LRec); try while i = 0 do begin lboxMessages.Items.Add(' ' + LRec.Name); i := FindNext(LRec); end; finally FindClose(LRec); end; //Set up the comboboxes with the options in TIdMessage... OpenDialog1.InitialDir := 'C:\'; ComboBox1.Items.Add('Default'); ComboBox1.Items.Add('base64'); ComboBox1.Items.Add('quoted-printable'); ComboBox2.Items.Add('Default'); ComboBox2.Items.Add('True'); ComboBox2.Items.Add('False'); ComboBox3.Items.Add('Default'); ComboBox3.Items.Add('7bit'); ComboBox3.Items.Add('base64'); ComboBox3.Items.Add('quoted-printable'); ComboBox4.Items.Add('Default'); ComboBox4.Items.Add('meMIME'); ComboBox4.Items.Add('meUU'); ComboBox4.Items.Add('meXX'); ComboBox5.Items.Add('Default'); ComboBox5.Items.Add('text/plain'); ComboBox5.Items.Add('text/html'); ComboBox5.Items.Add('multipart/alternative'); ComboBox5.Items.Add('multipart/mixed'); ResetFieldsToDefaults; end; procedure TformEncoderPlayground.actnTest_VerifyAllExecute(Sender: TObject); var i: Integer; begin for i := 0 to lboxMessages.Items.Count - 1 do begin lboxMessages.ItemIndex := i; actnTest_Verify.Execute; end; end; procedure TformEncoderPlayground.bublEncoderPlaygroundPlayground(Sender: TBXBubble); begin ShowModal; end; procedure TformEncoderPlayground.Button4Click(Sender: TObject); var sTemp: string; begin if RadioGroup1.ItemIndex = 0 then begin sTemp := 'TIdAttachment,'; end else begin sTemp := 'TIdText,'; end; sTemp := sTemp+ComboBox3.Items[ComboBox3.ItemIndex]+','+Edit1.Text; sTemp := sTemp+IntToStr(SpinEdit1.Value); //ParentPart sTemp := sTemp+ComboBox5.Items[ComboBox5.ItemIndex]; //ContentType ListBox1.Items.Add(sTemp); end; procedure TformEncoderPlayground.Edit1Change(Sender: TObject); begin if Edit1.Text = '' then begin Button4.Enabled := False; end else begin Button4.Enabled := True; end; end; procedure TformEncoderPlayground.Button2Click(Sender: TObject); begin if OpenDialog1.Execute = True then Edit1.Text := OpenDialog1.FileName; end; procedure TformEncoderPlayground.ListBox1Click(Sender: TObject); begin if ListBox1.ItemIndex = -1 then begin Button3.Enabled := False; end else begin Button3.Enabled := True; end; end; procedure TformEncoderPlayground.Button3Click(Sender: TObject); begin ListBox1.Items.Delete(ListBox1.ItemIndex); Button3.Enabled := False; end; procedure TformEncoderPlayground.Button1Click(Sender: TObject); var TempStream: TMemoryStream; begin memoRaw.Clear; memoCorrect.Clear; SetupEmail; //Finally save it to a stream... TempStream := TMemoryStream.Create; TheMsg.SaveToStream(TempStream); TempStream.Seek(0, soFromBeginning); memoRaw.Lines.LoadFromStream(TempStream); Button5.Enabled := True; end; procedure TformEncoderPlayground.SetupEmail; var i: integer; sTemp, sType, sEncoding, sFile, sContentType: string; nPos, nParentPart: integer; TheTextPart: TIdText; {$IFDEF INDY100} TheAttachment: TIdAttachmentFile; {$ELSE} TheAttachment: TIdAttachment; {$ENDIF} begin //Make the message from the control values... if Assigned(TheMsg) then FreeAndNil(TheMsg); TheMsg := TIdMessage.Create(nil); //Make sure the date will always be the same, else get different //outputs for the Date header... TheMsg.UseNowForDate := False; TheMsg.Date := EncodeDate(2011, 11, 11); if Memo1.Text <> '' then TheMsg.Body.Text := Memo1.Text; if ComboBox1.Items[ComboBox1.ItemIndex] <> 'Default' then TheMsg.ContentTransferEncoding := ComboBox1.Items[ComboBox1.ItemIndex]; if ComboBox2.Items[ComboBox2.ItemIndex] = 'True' then begin TheMsg.ConvertPreamble := True; end else if ComboBox2.Items[ComboBox2.ItemIndex] = 'False' then begin TheMsg.ConvertPreamble := False; end; for i := 0 to ListBox1.Items.Count-1 do begin sTemp := ListBox1.Items.Strings[i]; nPos := Pos(',', sTemp); sType := Copy(sTemp, 1, nPos-1); sTemp := Copy(sTemp, nPos+1, MAXINT); nPos := Pos(',', sTemp); sEncoding := Copy(sTemp, 1, nPos-1); sTemp := Copy(sTemp, nPos+1, MAXINT); sContentType := ''; nParentPart := -999; nPos := Pos(',', sTemp); if nPos > 0 then begin //ParentPart+ContentType are optional sFile := Copy(sTemp, 1, nPos-1); sTemp := Copy(sTemp, nPos+1, MAXINT); nPos := Pos(',', sTemp); sContentType := Copy(sTemp, nPos+1, MAXINT); sTemp := Copy(sTemp, 1, nPos-1); nParentPart := StrToInt(sTemp); end else begin sFile := sTemp; end; if sType = 'TIdText' then begin TheTextPart := TIdText.Create(TheMsg.MessageParts); TheTextPart.Body.LoadFromFile(sFile); if sEncoding <> 'Default' then TheTextPart.ContentTransfer := sEncoding; if ((sContentType <> '') and (sContentType <> 'Default')) then TheTextPart.ContentType := sContentType; {$IFDEF INDY100} if nParentPart <> -999 then TheTextPart.ParentPart := nParentPart; {$ENDIF} end else begin {$IFDEF INDY100} TheAttachment := TIdAttachmentFile.Create(TheMsg.MessageParts, sFile); {$ELSE} TheAttachment := TIdAttachment.Create(TheMsg.MessageParts, sFile); {$ENDIF} if sEncoding <> 'Default' then TheAttachment.ContentTransfer := sEncoding; if ((sContentType <> '') and (sContentType <> 'Default')) then TheAttachment.ContentType := sContentType; {$IFDEF INDY100} if nParentPart <> -999 then TheAttachment.ParentPart := nParentPart; {$ENDIF} end; end; if TheMsg.Encoding <> meDefault then ShowMessage('Warning: Message encoding was not initially meDefault???'); if ComboBox4.Items[ComboBox4.ItemIndex] = 'meMIME' then begin TheMsg.Encoding := meMIME; end else if ComboBox4.Items[ComboBox4.ItemIndex] = 'meUU' then begin TheMsg.Encoding := meUU; end else if ComboBox4.Items[ComboBox4.ItemIndex] = 'meXX' then begin TheMsg.Encoding := meXX; end; if Edit3.Text <> '' then begin TheMsg.ContentType := Edit3.Text; end; end; procedure TformEncoderPlayground.Button5Click(Sender: TObject); var ExtractPath: string; TestName: string; TestIni: TStringList; i: Integer; AttachmentName, PortedAttachmentName: string; nPos: Integer; sContentType, sType, sEncoding, sParentPath, sTemp: string; begin if MessageDlg('Warning: Dont add tests in this manner unless you are sure they are valid tests. Add this test?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin //Make sure we don't have a test of this name already... TestName := Edit2.Text; if TestName = '' then begin ShowMessage('You must enter a test name in the edit box provided'); Exit; end; if Pos('.', TestName) > 0 then begin ShowMessage('Test name may not include a period'); Exit; end; if FileExists(FDataPath+TestName+'.ini') then begin ShowMessage('This test name exists already, try another.'); Exit; end; //Create the test directory... ExtractPath := FDataPath + ChangeFileExt(TestName, '') + '\'; ForceDirectories(ExtractPath); //Copy the generated message to it as a .msg... memoRaw.Lines.SaveToFile(ExtractPath+TestName+'.msg'); //Write out the INI... TestIni := TStringList.Create; if Memo1.Text <> '' then begin for i := 0 to Memo1.Lines.Count-1 do begin TestIni.Add('Body'+IntToStr(i)+'='+Memo1.Lines[i]); end; end; if ComboBox1.Items[ComboBox1.ItemIndex] <> 'Default' then TestIni.Add('ContentTransferEncoding='+ComboBox1.Items[ComboBox1.ItemIndex]); if ComboBox2.Items[ComboBox2.ItemIndex] <> 'Default' then TestIni.Add('ConvertPreamble='+ComboBox2.Items[ComboBox2.ItemIndex]); if ComboBox4.Items[ComboBox4.ItemIndex] <> 'Default' then TestIni.Add('Encoding='+ComboBox4.Items[ComboBox4.ItemIndex]); if Edit3.Text <> '' then TestIni.Add('ContentType='+Edit3.Text); //Copy any attachments into test dir, note the same attachment may be in more than one part... for i := 0 to ListBox1.Items.Count-1 do begin AttachmentName := ListBox1.Items.Strings[i]; nPos := Pos(',', AttachmentName); sType := Copy(AttachmentName, 1, nPos-1); AttachmentName := Copy(AttachmentName, nPos+1, MAXINT); nPos := Pos(',', AttachmentName); sEncoding := Copy(AttachmentName, 1, nPos-1); AttachmentName := Copy(AttachmentName, nPos+1, MAXINT); nPos := Pos(',', AttachmentName); AttachmentName := Copy(AttachmentName, 1, nPos-1); sTemp := Copy(AttachmentName, nPos+1, MAXINT); nPos := Pos(',', sTemp); sContentType := Copy(sTemp, nPos+1, MAXINT); sParentPath := Copy(sTemp, 1, nPos-1); PortedAttachmentName := ExtractPath+ExtractFileName(AttachmentName); CopyFile(PAnsiChar(AttachmentName), PAnsiChar(PortedAttachmentName), False); //Update our INI with the ported path... TestIni.Add('Part'+IntToStr(i)+'='+sType+','+sEncoding+','+PortedAttachmentName+','+sParentPath+','+sContentType); end; TestIni.SaveToFile(FDataPath+TestName+'.ini'); ShowMessage('Test message '+TestName+' successfully set up, you may need to restart to see it listed.'); end; end; procedure TformEncoderPlayground.Button6Click(Sender: TObject); begin Memo1.Text := EncoderBody; end; procedure TformEncoderPlayground.ResetFieldsToDefaults; begin Memo1.Text := ''; Edit1.Text := ''; Edit2.Text := ''; Edit3.Text := ''; ComboBox1.ItemIndex := 0; ComboBox2.ItemIndex := 0; ComboBox3.ItemIndex := 0; ComboBox4.ItemIndex := 0; ComboBox5.ItemIndex := 0; Button3.Enabled := False; Button4.Enabled := False; Button5.Enabled := False; ListBox1.Items.Clear; end; procedure TformEncoderPlayground.Button7Click(Sender: TObject); begin ResetFieldsToDefaults; end; procedure TformEncoderPlayground.Button8Click(Sender: TObject); begin //This sends an email so you can see if that client can decode it... SendEmail.ShowModal; end; end.
unit AliasServ; interface uses SysUtils,Classes,DB,ComWriUtils; const AliasHeader : char = '#'; PathSeperator : char = '\'; type TAliasServer = class(TStringMap) private protected public procedure LoadFromStrings(AStrings : TStrings); procedure LoadFromFile(const FileName : string); dynamic; procedure LoadFromDataSet(DataSet : TDataSet; NameField,ValueField : TField); dynamic; published end; TFileProcMethod = procedure (const filename : string) of object; TPathServer = class(TComponent) private FSearchPaths : TStringList; FAliasServer: TAliasServer; FNextPathServer: TPathServer; FMatchedPath: string; FMatchedAlias: string; procedure SetSearchPaths(const Value: TStrings); procedure SetNextPathServer(const Value: TPathServer); function GetSearchPaths: TStrings; protected public constructor Create(AOwner : TComponent); override; destructor destroy; override; property AliasServer : TAliasServer read FAliasServer; procedure SafeFileProc(FP : TFileProcMethod; const Filename:string); { return value is whether file exists RealFilename VALUE: 1. FileName have An alias, MatchedAlias=AliasName 1) Alias Value is not empty : RealFilename = AliasValue + RestFileName 2) Alias Value is empty : RealFilename = RestFileName below , MatchedAlias='' 2. FileName have full path, RealFilename = FileName 3. FileName have no path, Search file in SearchPaths 1) if found, RealFileName = pathname + filename 2) if not found, RealFileName = filename } function GetRealFileName(const FileName:string; var RealFilename : string):boolean; // if not found , return empty string function GetAliasValue(const AliasName : string):string; // Add AliasValues to a TStrings procedure GetAliasValues(const AliasName : string; Values : TStrings); { Search File in SearchPaths and NextPathServers' SearchPaths RelativeFileName do not have a absolute path, it is to say, RelativeFileName do not start with Driver letter or PathSeperator. if found return file path, otherwise return RelativeFileName. } function SearchFile(const RelativeFileName:string):string; { Search File in given paths. return whether find. if found, FullName is the full name of the file, path is the path added before RelativeFileName, otherwise not change FullName and path } function SearchFileInPaths(const RelativeFileName:string;Paths : TStrings; var FullName,Path : string):boolean; property MatchedAlias : string read FMatchedAlias; property MatchedPath : string read FMatchedPath; published property SearchPaths : TStrings read GetSearchPaths write SetSearchPaths; // when self not find a file, use NextPathServer property NextPathServer : TPathServer read FNextPathServer write SetNextPathServer; end; implementation { TAliasServer } procedure TAliasServer.LoadFromDataSet(DataSet: TDataSet; NameField, ValueField: TField); begin assert(Assigned(DataSet) and Assigned(NameField) and Assigned(ValueField)); clear; DataSet.First; while not DataSet.eof do begin Add(NameField.AsString,ValueField.AsString); dataSet.next; end; end; procedure TAliasServer.LoadFromFile(const FileName: string); var Strings : TStringList; begin Strings := TStringList.Create; try Strings.LoadFromFile(Filename); LoadFromStrings(Strings); finally Strings.free; end; end; procedure TAliasServer.LoadFromStrings(AStrings: TStrings); var i : integer; p : integer; AString : string; begin clear; for i:=0 to AStrings.count-1 do begin AString := AStrings[i]; p := pos('=',AString); if p>1 then begin Add(copy(AString,1,p-1),copy(AString,p+1,length(AString)-p)); end; end; end; { TPathServer } constructor TPathServer.Create(AOwner: TComponent); begin inherited Create(AOwner); FAliasServer := TAliasServer.Create; FSearchPaths := TStringList.Create; RegisterRefProp(self,'NextPathServer'); end; destructor TPathServer.destroy; begin FSearchPaths.free; FAliasServer.free; inherited destroy; end; function TPathServer.GetRealFileName(const FileName: string; var RealFilename: string): boolean; var AliasName,FullName,Path : string; index : integer; RelativeFileName : string; AliasValues : TStringList; begin if FileName<>'' then begin if FileName[1]=AliasHeader then begin // this contains a alias index := pos(PathSeperator,FileName); if (index<=2) or (index=length(Filename)) then result:=false else begin // not copy Alias Header and PathSeperator AliasName := copy(FileName,2,index-2); FMatchedAlias := AliasName; // not copy PathSeperator and next RelativeFileName := copy(FileName,index+1,length(FileName)-index ); // get Alias values in AliasValues AliasValues := TStringList.Create; try GetAliasValues(AliasName,AliasValues); // search file in AliasValues result:=SearchFileInPaths(RelativeFileName,AliasValues,FullName,Path); if result then begin RealFileName := FullName; FMatchedPath := Path; end else begin RealFileName := RelativeFileName; FMatchedPath := ''; end; finally AliasValues.free; end; end; end else begin // filename have no alias FMatchedAlias := ''; if (ExtractFileDrive(FileName)<>'') or (FileName[1]=PathSeperator) then begin // file have full path FMatchedPath := ''; RealFileName := FileName; result := FileExists(RealFileName); end else begin RelativeFileName := FileName; // file name is relative RealFileName := SearchFile(RelativeFileName); result := FileExists(RealFileName); end; end; end // file name is empty else result:=false; end; procedure TPathServer.SafeFileProc(FP: TFileProcMethod; const Filename:string); var realFileName : string; begin if Assigned(FP) and GetRealFileName(FileName,realFileName) then try FP(realFileName); except // log exception end; end; function TPathServer.GetAliasValue(const AliasName: string): string; begin if not AliasServer.GetValueByName(AliasName,result) then begin if Assigned(NextPathServer) then result := NextPathServer.GetAliasValue(AliasName) else result:=''; end; end; function TPathServer.SearchFile(const RelativeFileName: string): string; var Fullname,FilePath : string; begin if SearchFileInPaths(RelativeFileName,SearchPaths,Fullname,FilePath) then begin // found file in self search paths FMatchedPath := FilePath; result := FullName; end else // not found file in self search paths if Assigned(NextPathServer) then begin // then call NextPathServer result := NextPathServer.SearchFile(RelativeFileName); FMatchedPath := NextPathServer.MatchedPath; end else begin // if no NextPathServer, file not found result := RelativeFileName; FMatchedPath := ''; end; end; procedure TPathServer.SetNextPathServer(const Value: TPathServer); begin if FNextPathServer <> Value then begin FNextPathServer := Value; ReferTo(value); end; end; procedure TPathServer.SetSearchPaths(const Value: TStrings); begin FSearchPaths.Assign(Value); end; function TPathServer.GetSearchPaths: TStrings; begin result := FSearchPaths; end; procedure TPathServer.GetAliasValues(const AliasName: string; Values: TStrings); begin AliasServer.GetValuesByName(AliasName,values); if Assigned(FNextPathServer) then FNextPathServer.GetAliasValues(AliasName,values); end; function TPathServer.SearchFileInPaths(const RelativeFileName: string; Paths: TStrings; var FullName, Path: string): boolean; var i : integer; FilePath : string; begin for i:=0 to Paths.count-1 do begin FilePath := Paths[i]+PathSeperator+RelativeFileName; if FileExists(FilePath) then begin result:=true; Path := Paths[i]; FullName := FilePath; exit; end; end; result := false; end; end.
unit ditte_frm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, ZDataset, aziende_frm; type { TDitte } TDitte = class(TForm) btapriaziende: TButton; btelimina: TButton; btnuovo: TButton; btsalva: TButton; cbaziende: TComboBox; cbaziendeID:TStringList; cbditte: TComboBox; cbditteID:TStringList; edDescrizione: TMemo; Label1: TLabel; lblAziende: TLabel; lblDescrizione: TLabel; lblNote: TLabel; zq_ditte: TZQuery; procedure btapriaziendeClick(Sender: TObject); procedure bteliminaClick(Sender: TObject); procedure btnuovoClick(Sender: TObject); procedure btsalvaClick(Sender: TObject); procedure cbaziendeChange(Sender: TObject); procedure cbditteChange(Sender: TObject); procedure cbditteExit(Sender: TObject); procedure cbditteKeyPress(Sender: TObject; var Key: char); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); procedure LoadComboDitte(); procedure LoadComboAziende(); procedure ClearCampi(); private { private declarations } public { public declarations } end; var Ditte: TDitte; implementation { TDitte } procedure TDitte.FormCreate(Sender: TObject); begin cbditteID:=TStringList.Create; cbaziendeID:=TStringList.Create; //seleziono tutte le ditte e le visualizzo nella combobox LoadComboDitte(); //seleziono tutte le aziende e popolo le combobox LoadComboAziende(); //applico i permessi in base ai ruoli end; procedure TDitte.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin CloseAction := cafree; end; procedure TDitte.btnuovoClick(Sender: TObject); begin //pulisce tutti i campi per consentire un nuovo inserimento ClearCampi(); cbaziende.SetFocus; end; procedure TDitte.btsalvaClick(Sender: TObject); begin if cbaziende.ItemIndex=-1 then begin ShowMessage('Devi selezionare un''azienda valida.'); cbaziende.SetFocus; exit(); end; if cbditte.Text<>'' then begin //////////////////////////////////////////////////////////////////// /// Modifica ditta //////////////////////////////////////////////////////////////////// with zq_ditte do begin Close; sql.Clear; sql.Add('UPDATE DITTE SET ' + 'IDAZIENDA=:IDAZIENDA,' + 'DESCRIZIONE=:DESCRIZIONE ' + 'WHERE IDDITTA=:ID'); ParamByName('IDAZIENDA').AsInteger := strtoint(cbaziendeID[cbaziende.ItemIndex]); ParamByName('DESCRIZIONE').AsString := edDescrizione.Text; ParamByName('ID').AsInteger := strtoint(cbditteID[cbditte.ItemIndex]); ExecSQL; //riaggiorna la lista delle ditte nelle combo LoadComboDitte(); //comunica l'esito positivo della modifica ShowMessage(cbaziende.Text + ' è stata modificata correttamente.'); end; end else begin //////////////////////////////////////////////////////////////////// /// INSERIMENTO DITTA //////////////////////////////////////////////////////////////////// //inserisci la nuova ditta nel DB with zq_ditte do begin Close; sql.Clear; sql.Add('INSERT INTO DITTE (' + 'IDAZIENDA,' + 'DESCRIZIONE' + ') VALUES (:IDAZIENDA,:DESCRIZIONE)'); ParamByName('IDAZIENDA').AsInteger := strtoint(cbaziendeID[cbaziende.ItemIndex]); ParamByName('DESCRIZIONE').AsString := edDescrizione.Text; ExecSQL; //riaggiorna la lista delle ditte LoadComboDitte(); //comunica l'esito positivo dell'inserimento ShowMessage(cbaziende.Text + ' è ora abilitata per utilizzare il software.'); end; end; btnuovoClick(self); end; procedure TDitte.bteliminaClick(Sender: TObject); var buttonSelected: integer; begin //controllo che sia stata selezionata una ditta sennò avverto //che è necessario selezionarne una if cbDitte.ItemIndex <> -1 then begin //chiede conferma e poi cancella il record buttonSelected := MessageDlg( 'Si sta per togliere i privilegi di utilizzo del software a ' + cbditte.Text + '. Continuare?', mtInformation, mbOKCancel, 0); if buttonSelected = mrOk then begin with zq_ditte do begin Close; sql.Clear; sql.Add('DELETE FROM DITTE WHERE IDDITTA=:ID'); ParamByName('ID').AsInteger := strtoint(cbditteID[cbditte.ItemIndex]); ExecSQL; end; //rilegge tutte le ditte e le carica nelle combo LoadComboDitte(); //pulisce tutti i campi ClearCampi(); end; end else ShowMessage('Per eliminare una ditta è necessario prima selezionarne una dalla lista.'); end; procedure TDitte.btapriaziendeClick(Sender: TObject); begin //Apro la form aziende Aziende := TAziende.Create(self); Aziende.showmodal; //ricarico la lista delle aziende visto che probabilmente sarà cambiata LoadComboAziende(); end; procedure TDitte.cbditteChange(Sender: TObject); begin if cbDitte.ItemIndex<>-1 then begin //mostro nei campi l'azienda selezionata with zq_ditte do begin Close; sql.Clear; sql.Add('SELECT * FROM DITTE WHERE IDDITTA=:ID'); ParamByName('ID').AsInteger := strtoint(cbditteID[cbditte.ItemIndex]); ExecSQL; Open; edDescrizione.Text := FieldByName('DESCRIZIONE').AsString; cbAziende.ItemIndex:= cbAziendeID.IndexOf(inttostr(FieldByName('IDAZIENDA').AsInteger)); end; end; end; procedure TDitte.cbditteExit(Sender: TObject); begin (sender as TComboBox).ItemIndex := (sender as TComboBox).Items.IndexOfObject(TObject((sender as TComboBox).Items.Objects[(sender as TComboBox).ItemIndex])); (sender as TComboBox).OnChange(self); end; procedure TDitte.cbditteKeyPress(Sender: TObject; var Key: char); begin if key=#13 then SelectNext(sender as twincontrol,true,true); end; procedure TDitte.cbaziendeChange(Sender: TObject); begin btsalva.Enabled:=True; end; //la procedura svuota tutti i campi delle textbox e elimina la selezione nelle combo procedure TDitte.ClearCampi(); begin cbditte.ClearSelection; cbAziende.ClearSelection; edDescrizione.Clear; btsalva.Enabled:=False; end; procedure TDitte.LoadComboDitte(); begin cbditte.Clear; cbditteID.Clear; with zq_ditte do begin Close; sql.Clear; sql.Add('SELECT ANAGAZIENDE.NOME,DITTE.IDDITTA FROM ANAGAZIENDE ' + 'INNER JOIN DITTE ON ANAGAZIENDE.IDAZIENDA=DITTE.IDAZIENDA'); ExecSQL; Open; while not EOF do begin //cbditte.Items.AddObject(FieldByName('NOME').AsString,TObject(FieldByName('IDDITTA').AsInteger)); cbditte.Items.Add (FieldByName('NOME').AsString); cbditteID.Add(inttostr(FieldByName('IDDITTA').AsInteger)); Next; end; end; btsalva.Enabled:=false; end; procedure TDitte.LoadComboAziende(); begin cbAziende.Clear; cbaziendeID.Clear; with zq_ditte do begin Close; sql.Clear; sql.Add('SELECT IDAZIENDA, NOME FROM ANAGAZIENDE'); ExecSQL; Open; while not EOF do begin //cbAziende.Items.AddObject(FieldByName('NOME').AsString,TObject(FieldByName('IDAZIENDA').AsInteger)); cbAziende.Items.Add (FieldByName('NOME').AsString); cbaziendeID.Add(inttostr(FieldByName('IDAZIENDA').AsInteger)); Next; end; end; end; initialization {$I ditte_frm.lrs} end.
unit Models.User; interface uses GBSwagger.Model.Attributes; type TUser = class private Fid: Int64; Fname: string; FlastName: string; FlastUpdate: TDateTime; public [SwagProp('Código', True)] property id: Int64 read Fid write Fid; [SwagProp('Nome', True)] property name: String read Fname write Fname; [SwagString(100)] [SwagProp('Sobrenome', False)] property lastName: string read FlastName write FlastName; [SwagIgnore] property lastUpdate: TDateTime read FlastUpdate write FlastUpdate; end; implementation end.
{***********************************************************} { Exemplo de lanšamento de nota fiscal orientado a objetos, } { com banco de dados Oracle } { Reinaldo Silveira - reinaldopsilveira@gmail.com } { Franca/SP - set/2019 } {***********************************************************} unit U_NotaFiscal; interface uses System.Classes, U_BaseControl, U_Fornecedor, U_Produto, U_NatOperacao, System.SysUtils, Data.DBXCommon; type TNFItem = class(TCollectionItem) private FNAT_OPERACAO: TNatOperacao; FPRODUTO: TProduto; FVR_IPI: Double; FALIQ_ICMS: Double; FVR_DESCONTO: Double; FVR_UNITARIO: Double; FVR_ICMS: Double; FNF_ID: Integer; FITEM: Integer; FQUANTIDADE: Double; FVR_TOTAL_ITEM: Double; FALIQ_IPI: Double; FPERC_DESCONTO: Double; procedure SetALIQ_ICMS(const Value: Double); procedure SetALIQ_IPI(const Value: Double); procedure SetITEM(const Value: Integer); procedure SetNAT_OPERACAO(const Value: TNatOperacao); procedure SetNF_ID(const Value: Integer); procedure SetPERC_DESCONTO(const Value: Double); procedure SetPRODUTO(const Value: TProduto); procedure SetQUANTIDADE(const Value: Double); procedure SetVR_DESCONTO(const Value: Double); procedure SetVR_ICMS(const Value: Double); procedure SetVR_IPI(const Value: Double); procedure SetVR_TOTAL_ITEM(const Value: Double); procedure SetVR_UNITARIO(const Value: Double); { private declarations } protected { protected declarations } public { public declarations } property NF_ID: Integer read FNF_ID write SetNF_ID; property ITEM: Integer read FITEM write SetITEM; property PRODUTO: TProduto read FPRODUTO write SetPRODUTO; property QUANTIDADE: Double read FQUANTIDADE write SetQUANTIDADE; property VR_UNITARIO: Double read FVR_UNITARIO write SetVR_UNITARIO; property NAT_OPERACAO: TNatOperacao read FNAT_OPERACAO write SetNAT_OPERACAO; property ALIQ_IPI: Double read FALIQ_IPI write SetALIQ_IPI; property VR_IPI: Double read FVR_IPI write SetVR_IPI; property PERC_DESCONTO: Double read FPERC_DESCONTO write SetPERC_DESCONTO; property VR_DESCONTO: Double read FVR_DESCONTO write SetVR_DESCONTO; property ALIQ_ICMS: Double read FALIQ_ICMS write SetALIQ_ICMS; property VR_ICMS: Double read FVR_ICMS write SetVR_ICMS; property VR_TOTAL_ITEM: Double read FVR_TOTAL_ITEM write SetVR_TOTAL_ITEM; end; TItens = class(TOwnedCollection) private function GetItem(index: Integer): TNFItem; procedure SetItem(index: Integer; const Value: TNFItem); public function Add: TNFItem; procedure Delete(Index: Integer); property Items[index: Integer]: TNFItem read GetItem write SetItem; end; TNotaFiscal = class(TBaseControl) private FVR_IPI: Double; FDT_ENTRADA: TDate; FSERIE: String; FVR_ICMS: Double; FVR_ITENS: Double; FNUMERO: Integer; FNF_ID: Integer; FDT_EMISSAO: TDate; FVR_TOTAL: Double; FFORNECEDOR: TFornecedor; FVR_BASE_ICMS: Double; FItensNF: TItens; procedure SetDT_EMISSAO(const Value: TDate); procedure SetDT_ENTRADA(const Value: TDate); procedure SetFORNECEDOR(const Value: TFornecedor); procedure SetNF_ID(const Value: Integer); procedure SetNUMERO(const Value: Integer); procedure SetSERIE(const Value: String); procedure SetVR_BASE_ICMS(const Value: Double); procedure SetVR_ICMS(const Value: Double); procedure SetVR_IPI(const Value: Double); procedure SetVR_ITENS(const Value: Double); procedure SetVR_TOTAL(const Value: Double); procedure SetItensNF(const Value: TItens); { private declarations } protected { protected declarations } public { public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; property NF_ID: Integer read FNF_ID write SetNF_ID; property FORNECEDOR: TFornecedor read FFORNECEDOR write SetFORNECEDOR; property NUMERO: Integer read FNUMERO write SetNUMERO; property SERIE: String read FSERIE write SetSERIE; property DT_EMISSAO: TDate read FDT_EMISSAO write SetDT_EMISSAO; property DT_ENTRADA: TDate read FDT_ENTRADA write SetDT_ENTRADA; property VR_ITENS: Double read FVR_ITENS write SetVR_ITENS; property VR_IPI: Double read FVR_IPI write SetVR_IPI; property VR_BASE_ICMS: Double read FVR_BASE_ICMS write SetVR_BASE_ICMS; property VR_TOTAL: Double read FVR_TOTAL write SetVR_TOTAL; property VR_ICMS: Double read FVR_ICMS write SetVR_ICMS; property ItensNF: TItens read FItensNF write SetItensNF; function Incluir: Boolean; end; implementation { TNotaFiscal } uses U_Conexao; constructor TNotaFiscal.Create(AOwner: TComponent); begin inherited Create(AOwner); FItensNF := TItens.Create(Self, TNFItem); end; destructor TNotaFiscal.Destroy; begin FItensNF.Free; inherited; end; function TNotaFiscal.Incluir: Boolean; var tran: TDBXTransaction; i: Integer; begin NF_ID := GetID('SEQ_TB_NOTAFISCAL'); try tran := TConexao.GetInstance.Conexao.BeginTransaction; Query.Close; Query.SQL.Clear; Query.SQL.Add('insert into TB_NOTAFISCAL( '); Query.SQL.Add(' NF_ID, '); Query.SQL.Add(' FORNECEDOR_ID, '); Query.SQL.Add(' NUMERO, '); Query.SQL.Add(' SERIE, '); Query.SQL.Add(' DT_EMISSAO, '); Query.SQL.Add(' DT_ENTRADA, '); Query.SQL.Add(' VR_ITENS, '); Query.SQL.Add(' VR_IPI, '); Query.SQL.Add(' VR_BASE_ICMS, '); Query.SQL.Add(' VR_ICMS, '); Query.SQL.Add(' VR_TOTAL) '); Query.SQL.Add('values( '); Query.SQL.Add(Format('%d, ', [FNF_ID])); Query.SQL.Add(Format('%d, ', [FFORNECEDOR.FORNECEDOR_ID])); Query.SQL.Add(Format('%d, ', [FNUMERO])); Query.SQL.Add(Format('%s, ', [QuotedStr(FSERIE)])); Query.SQL.Add(Format('%s, ', [QuotedStr(FormatDateTime('dd/mm/yyyy', FDT_EMISSAO))])); Query.SQL.Add(Format('%s, ', [QuotedStr(FormatDateTime('dd/mm/yyyy', FDT_ENTRADA))])); Query.SQL.Add(Format('%s, ', [FloatToSQL(FVR_ITENS)])); Query.SQL.Add(Format('%s, ', [FloatToSQL(FVR_IPI)])); Query.SQL.Add(Format('%s, ', [FloatToSQL(FVR_BASE_ICMS)])); Query.SQL.Add(Format('%s, ', [FloatToSQL(FVR_ICMS)])); Query.SQL.Add(Format('%s) ', [FloatToSQL(FVR_TOTAL)])); Query.ExecSQL; for i := 0 to ItensNF.Count -1 do begin Query.Close; Query.SQL.Clear; Query.SQL.Add('insert into TB_NOTAFISCAL_ITEM( '); Query.SQL.Add(' NF_ID, '); Query.SQL.Add(' ITEM, '); Query.SQL.Add(' PRODUTO_ID, '); Query.SQL.Add(' QUANTIDADE, '); Query.SQL.Add(' VR_UNITARIO, '); Query.SQL.Add(' CODCFO, '); Query.SQL.Add(' ALIQ_IPI, '); Query.SQL.Add(' VR_IPI, '); Query.SQL.Add(' PERC_DESCONTO, '); Query.SQL.Add(' VR_DESCONTO, '); Query.SQL.Add(' ALIQ_ICMS, '); Query.SQL.Add(' VR_ICMS, '); Query.SQL.Add(' VR_TOTAL_ITEM) '); Query.SQL.Add('values( '); Query.SQL.Add(Format('%d, ', [FNF_ID])); Query.SQL.Add(Format('%d, ', [i + 1])); Query.SQL.Add(Format('%d, ', [FItensNF.Items[i].PRODUTO.PRODUTO_ID])); Query.SQL.Add(Format('%s, ', [FloatToSQL(FItensNF.Items[i].QUANTIDADE)])); Query.SQL.Add(Format('%s, ', [FloatToSQL(FItensNF.Items[i].VR_UNITARIO)])); Query.SQL.Add(Format('%s, ', [QuotedStr(FItensNF.Items[i].NAT_OPERACAO.CODCFO)])); Query.SQL.Add(Format('%s, ', [FloatToSQL(FItensNF.Items[i].ALIQ_IPI)])); Query.SQL.Add(Format('%s, ', [FloatToSQL(FItensNF.Items[i].VR_IPI)])); Query.SQL.Add(Format('%s, ', [FloatToSQL(FItensNF.Items[i].PERC_DESCONTO)])); Query.SQL.Add(Format('%s, ', [FloatToSQL(FItensNF.Items[i].VR_DESCONTO)])); Query.SQL.Add(Format('%s, ', [FloatToSQL(FItensNF.Items[i].ALIQ_ICMS)])); Query.SQL.Add(Format('%s, ', [FloatToSQL(FItensNF.Items[i].VR_ICMS)])); Query.SQL.Add(Format('%s) ', [FloatToSQL(FItensNF.Items[i].VR_TOTAL_ITEM)])); Query.ExecSQL; end; TConexao.GetInstance.Conexao.CommitFreeAndNil(tran); Result := True; except on E: Exception do begin TConexao.GetInstance.Conexao.RollbackFreeAndNil(tran); raise Exception.CreateFmt('Erro ao incluir a Nota Fiscal: %s', [E.Message]); end; end; end; procedure TNotaFiscal.SetDT_EMISSAO(const Value: TDate); begin FDT_EMISSAO := Value; end; procedure TNotaFiscal.SetDT_ENTRADA(const Value: TDate); begin FDT_ENTRADA := Value; end; procedure TNotaFiscal.SetFORNECEDOR(const Value: TFornecedor); begin FFORNECEDOR := Value; end; procedure TNotaFiscal.SetItensNF(const Value: TItens); begin FItensNF := Value; end; procedure TNotaFiscal.SetNF_ID(const Value: Integer); begin FNF_ID := Value; end; procedure TNotaFiscal.SetNUMERO(const Value: Integer); begin FNUMERO := Value; end; procedure TNotaFiscal.SetSERIE(const Value: String); begin FSERIE := Value; end; procedure TNotaFiscal.SetVR_BASE_ICMS(const Value: Double); begin FVR_BASE_ICMS := Value; end; procedure TNotaFiscal.SetVR_ICMS(const Value: Double); begin FVR_ICMS := Value; end; procedure TNotaFiscal.SetVR_IPI(const Value: Double); begin FVR_IPI := Value; end; procedure TNotaFiscal.SetVR_ITENS(const Value: Double); begin FVR_ITENS := Value; end; procedure TNotaFiscal.SetVR_TOTAL(const Value: Double); begin FVR_TOTAL := Value; end; { TItens } function TItens.Add: TNFItem; begin Result := TNFItem(inherited Add); end; procedure TItens.Delete(Index: Integer); begin inherited Delete(Index); end; function TItens.GetItem(index: Integer): TNFItem; begin Result := TNFItem(inherited Items[Index]); end; procedure TItens.SetItem(index: Integer; const Value: TNFItem); begin Items[Index].Assign(Value); end; { TNFItem } procedure TNFItem.SetALIQ_ICMS(const Value: Double); begin FALIQ_ICMS := Value; end; procedure TNFItem.SetALIQ_IPI(const Value: Double); begin FALIQ_IPI := Value; end; procedure TNFItem.SetITEM(const Value: Integer); begin FITEM := Value; end; procedure TNFItem.SetNAT_OPERACAO(const Value: TNatOperacao); begin FNAT_OPERACAO := Value; end; procedure TNFItem.SetNF_ID(const Value: Integer); begin FNF_ID := Value; end; procedure TNFItem.SetPERC_DESCONTO(const Value: Double); begin FPERC_DESCONTO := Value; end; procedure TNFItem.SetPRODUTO(const Value: TProduto); begin FPRODUTO := Value; end; procedure TNFItem.SetQUANTIDADE(const Value: Double); begin FQUANTIDADE := Value; end; procedure TNFItem.SetVR_DESCONTO(const Value: Double); begin FVR_DESCONTO := Value; end; procedure TNFItem.SetVR_ICMS(const Value: Double); begin FVR_ICMS := Value; end; procedure TNFItem.SetVR_IPI(const Value: Double); begin FVR_IPI := Value; end; procedure TNFItem.SetVR_TOTAL_ITEM(const Value: Double); begin FVR_TOTAL_ITEM := Value; end; procedure TNFItem.SetVR_UNITARIO(const Value: Double); begin FVR_UNITARIO := Value; end; end.
unit uGetDetails; interface {$I definitions.inc} uses Classes, SysUtils, TypInfo, Variants, XMLDoc, EbayConnect, CommonTypes, TradingServiceXMLClasses, IdThread, IdComponent, IdSync, DB, nxdb, Forms; type Operations = (OpWriteLogMes,OpIncApiUsage,OpOnSave,OpSaveLog,OpOnWork); TFTSync = class(TidSync) public Operation : Operations; Value: String; iVal : Integer; WorkMode: TWorkMode; procedure DoSynchronize; override; procedure IncApiUsage; procedure OnSave(Saved,Total : Integer); procedure OnHttpWork(AWorkMode: TWorkMode; const AWorkCount: Integer); end; TGetDetailsThread = class(TidThread) private // Private declarations FForm : TForm; FOperationResult : AckCodeType; FErrorRecord : eBayAPIError; FEbayTradingConnect : TEbayTradingConnect; FGeteBayDetails : TGeteBayDetails; OpResult : string; FRxDelta : Integer; FTxDelta : Integer; procedure SaveDetails; procedure SaveCountryDetails; procedure SaveCurrencyDetails; procedure SaveDispatchTimeMaxDetails; procedure SavePaymentOptionDetails; procedure SaveRegionDetails; procedure SaveShippingLocationDetails; procedure SaveShippingServiceDetails; procedure SaveReturnPolicyDetails; protected // Protected declarations //procedure SaveDetails(Category:TCatRec); procedure GetAllDetails; procedure WriteEbayApiExceptionLog(E : Exception); procedure GetDetailsAPIError(Sender: TObject; ErrorRecord: eBayAPIError); procedure GetDetailsEndRequest(Sender: TObject); procedure GetDetailsStartRequest(Sender: TObject); procedure EbayTradingConnectWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); public // Public declarations FDevID : ShortString; FAppID : ShortString; FCertID : ShortString; FToken : WideString; FSiteID : SiteCodeType; FGlobalSiteID : Global_ID; FHost : ShortString; // 'api.ebay.com'; FServiceURL : ShortString; // 'https://api.ebay.com/ws/api.dll'; FSSLCertFile : ShortString; // 'test_b_crt.pem'; FSSLKeyFile : ShortString; // 'test_b_key.pem'; FSSLRootCertFile: ShortString; // 'test_b_ca.pem'; FSSLPassword : ShortString; // 'aaaa'; FCategoryVersion : Integer; FBasePath : string; FConnectString : string; FDataBase : string; FServer : string; FUser : string; FPassword : string; // Objects visible outside threads FQuery1 : TnxQuery; FQuery2 : TnxQuery; FSyncObj : TFTSync; // methods constructor Create(Form: TForm); destructor Destroy; override; procedure Run; override; end; implementation uses XMLIntf, uMain, functions, hotlog, ActiveX; { TGetCategoriesThread } constructor TGetDetailsThread.Create(Form: TForm); begin inherited Create(true); FForm := Form; FreeOnTerminate := True; FSyncObj := TFTSync.Create; end; destructor TGetDetailsThread.Destroy; begin inherited; end; procedure TGetDetailsThread.Run; var hr: HRESULT; begin inherited; try hr := CoInitializeEx(nil, COINIT_APARTMENTTHREADED); FEbayTradingConnect := TEbayTradingConnect.Create(nil); with FEbayTradingConnect do begin Host := FHost; ServiceURL := FServiceURL; SSLCertFile := FSSLCertFile; SSLKeyFile := FSSLKeyFile; SSLRootCertFile := FSSLRootCertFile; SSLPassword := FSSLPassword; SiteID := FSiteID; AppID := FAppID; DevID := FDevID; CertID := FCertID; Token := FToken; OnWork := EbayTradingConnectWork; end; FGeteBayDetails := TGeteBayDetails.Create(nil); FGeteBayDetails.Connector := FEbayTradingConnect; FGeteBayDetails.OnAPIError := GetDetailsAPIError; FGeteBayDetails.OnEndRequest := GetDetailsEndRequest; FGeteBayDetails.OnStartRequest := GetDetailsStartRequest; FGeteBayDetails.OnAPIError := GetDetailsAPIError; FQuery1 := TnxQuery.Create(nil); FQuery1.Database := fmMain.nxdtbs1; FQuery1.Session := fmMain.nxsn1; FQuery1.Prepared := False; GetAllDetails; finally FEbayTradingConnect.Free; FGeteBayDetails.Free; FQuery1.Free; CoUninitialize; end; Stop; end; procedure TGetDetailsThread.GetAllDetails; begin try FRxDelta := 0; FTxDelta := 0; FOperationResult := FGeteBayDetails.DoRequestEx; if (FOperationResult in [Success, Warning, PartialFailure]) then begin SaveDetails; end; if (FOperationResult in [Failure, PartialFailure]) then begin //GetDetailsAPIError(FGeteBayDetails.Errors); Exception.Create('Request Failure'); end; except on E : Exception do WriteEbayApiExceptionLog(E); end; end; procedure TGetDetailsThread.GetDetailsAPIError(Sender: TObject; ErrorRecord: eBayAPIError); begin with ErrorRecord do begin hlog.add('{hms}: - ApiCall: GetEbayDetails. API Error'); hlog.add(Format('Short Message %s , Error Code %s , Severity Code %s ,Error Classification %s',[ShortMessage, ErrorCode, SeverityCode, ErrorClassification])); hlog.add(Format('Message %s ',[LongMessage])); end; FEbayTradingConnect.RequestXMLText.SaveToFile(hLog.hlWriter.hlFileDef.path+'\Request.xml'); hlog.Add('Request XML saved'); FEbayTradingConnect.RequestXMLText.SaveToFile(hLog.hlWriter.hlFileDef.path+'\Response.xml'); hlog.Add('Response XML saved'); end; procedure TGetDetailsThread.GetDetailsEndRequest(Sender: TObject); begin //FGeteBayDetails.SaveResponseXMLDoc(fmMain.BasePath+'\GeteBayDetails.xml'); hlog.Add(Format('{hms}: ApiCall: GetEbayDetails. Result %s',[GetEnumName(TypeInfo(AckCodeType),ord(FGetEbayDetails.Ack))])); FSyncObj.IncApiUsage; end; procedure TGetDetailsThread.GetDetailsStartRequest(Sender: TObject); begin hlog.Add('{hms}: ApiCall: GetEbayDetails. Start request'); end; procedure TGetDetailsThread.SaveCountryDetails; var i:Integer; sid : string; begin sid := GetEnumName(TypeInfo(SiteCodeType),Ord(FGeteBayDetails.Connector.SiteID)); hlog.Add(Format('{hms}: Start saving Country Details for site %s',[sid])); with FQuery1 do try SQL.Clear; SQL.Add('delete from CountryDetails where SiteID = :SiteID'); Prepared := True; ParamByName('SiteID').DataType := ftString; ParamByName('SiteID').Value := GetEnumName(TypeInfo(SiteCodeType),Ord(FGeteBayDetails.Connector.SiteID)); ExecSQL; SQL.Clear; SQL.Add('insert into CountryDetails (Code,Name,SiteID,DetailVersion) values (:Code,:Name,:SiteID,:DetailVersion)'); Prepared := True; ParamByName('Code').DataType := ftString; ParamByName('Name').DataType := ftString; ParamByName('SiteID').DataType := ftString; ParamByName('DetailVersion').DataType := ftInteger; for I := 0 to FGeteBayDetails.CountryDetails.Count - 1 do begin ParamByName('Code').Value := FGeteBayDetails.CountryDetails[i].Country; ParamByName('Name').Value := FGeteBayDetails.CountryDetails[i].Description; ParamByName('SiteID').Value := sid; ParamByName('DetailVersion').Value := FGeteBayDetails.CountryDetails[i].DetailVersion; ExecSQL; end; hlog.Add(Format('{hms}: End saving Country Details for site %s. Saved %d',[sid,FGeteBayDetails.CountryDetails.Count])); except on E : Exception do hlog.AddException(E); end; end; procedure TGetDetailsThread.SaveCurrencyDetails; var i:Integer; sid : string; begin sid := GetEnumName(TypeInfo(SiteCodeType),Ord(FGeteBayDetails.Connector.SiteID)); hlog.Add(Format('{hms}: Start saving Currency Details for site %s',[sid])); with FQuery1 do try SQL.Clear; SQL.Add('delete from CurrencyDetails where SiteID = :SiteID'); Prepared := True; ParamByName('SiteID').DataType := ftString; ParamByName('SiteID').Value := sid; ExecSQL; SQL.Clear; SQL.Add('insert into CurrencyDetails (Code,Name,SiteID,DetailVersion) values (:Code,:Name,:SiteID,:DetailVersion)'); Prepared := True; ParamByName('Code').DataType := ftString; ParamByName('Name').DataType := ftString; ParamByName('SiteID').DataType := ftString; ParamByName('DetailVersion').DataType := ftInteger; for I := 0 to FGeteBayDetails.CurrencyDetails.Count - 1 do begin ParamByName('Code').Value := FGeteBayDetails.CurrencyDetails[i].Currency; ParamByName('Name').Value := FGeteBayDetails.CurrencyDetails[i].Description; ParamByName('SiteID').Value := sid; ParamByName('DetailVersion').Value := FGeteBayDetails.CurrencyDetails[i].DetailVersion; ExecSQL; end; hlog.Add(Format('{hms}: End saving Currency Details for site %s. Saved %d',[sid,FGeteBayDetails.CurrencyDetails.Count])); except on E : Exception do hlog.AddException(E); end; end; procedure TGetDetailsThread.SaveDispatchTimeMaxDetails; var i:Integer; sid : string; begin sid := GetEnumName(TypeInfo(SiteCodeType),Ord(FGeteBayDetails.Connector.SiteID)); hlog.Add(Format('{hms}: Start saving Dispatch Time Max Details for site %s',[sid])); with FQuery1 do try SQL.Clear; SQL.Add('delete from DispatchTimeMaxDetails where SiteID = :SiteID'); Prepared := True; ParamByName('SiteID').DataType := ftString; ParamByName('SiteID').Value := sid; ExecSQL; SQL.Clear; SQL.Add('insert into DispatchTimeMaxDetails (Code,Name,SiteID,DetailVersion) values (:Code,:Name,:SiteID,:DetailVersion)'); Prepared := True; ParamByName('Code').DataType := ftInteger; ParamByName('Name').DataType := ftString; ParamByName('SiteID').DataType := ftString; ParamByName('DetailVersion').DataType := ftInteger; for I := 0 to FGeteBayDetails.DispatchTimeMaxDetails.Count - 1 do begin ParamByName('Code').Value := FGeteBayDetails.DispatchTimeMaxDetails[i].DispatchTimeMax; ParamByName('Name').Value := FGeteBayDetails.DispatchTimeMaxDetails[i].Description; ParamByName('SiteID').Value := sid; ParamByName('DetailVersion').Value := FGeteBayDetails.DispatchTimeMaxDetails[i].DetailVersion; ExecSQL; end; hlog.Add(Format('{hms}: End saving Dispatch Time Max Details for site %s. Saved %d',[sid,FGeteBayDetails.DispatchTimeMaxDetails.Count])); except on E : Exception do hlog.AddException(E); end; end; procedure TGetDetailsThread.SavePaymentOptionDetails; var i:Integer; sid : string; begin sid := GetEnumName(TypeInfo(SiteCodeType),Ord(FGeteBayDetails.Connector.SiteID)); hlog.Add(Format('{hms}: Start saving Payment Option Details for site %s',[sid])); with FQuery1 do try SQL.Clear; SQL.Add('delete from PaymentOptionDetails where SiteID = :SiteID'); Prepared := True; ParamByName('SiteID').DataType := ftString; ParamByName('SiteID').Value := sid; ExecSQL; SQL.Clear; SQL.Add('insert into PaymentOptionDetails (Code,Name,SiteID,DetailVersion) values (:Code,:Name,:SiteID,:DetailVersion)'); Prepared := True; ParamByName('Code').DataType := ftString; ParamByName('Name').DataType := ftString; ParamByName('SiteID').DataType := ftString; ParamByName('DetailVersion').DataType := ftInteger; for I := 0 to FGeteBayDetails.PaymentOptionDetails.Count - 1 do begin ParamByName('Code').Value := FGeteBayDetails.PaymentOptionDetails[i].PaymentOption; ParamByName('Name').Value := FGeteBayDetails.PaymentOptionDetails[i].Description; ParamByName('SiteID').Value := sid; ParamByName('DetailVersion').Value := FGeteBayDetails.PaymentOptionDetails[i].DetailVersion; ExecSQL; end; hlog.Add(Format('{hms}: End saving Payment Option Details for site %s. Saved %d',[sid,FGeteBayDetails.PaymentOptionDetails.Count])); except on E : Exception do hlog.AddException(E); end; end; procedure TGetDetailsThread.SaveRegionDetails; var i:Integer; sid : string; begin sid := GetEnumName(TypeInfo(SiteCodeType),Ord(FGeteBayDetails.Connector.SiteID)); hlog.Add(Format('{hms}: Start saving Region Details for site %s',[sid])); with FQuery1 do try SQL.Clear; SQL.Add('delete from RegionDetails where SiteID = :SiteID'); Prepared := True; ParamByName('SiteID').DataType := ftString; ParamByName('SiteID').Value := sid; ExecSQL; SQL.Clear; SQL.Add('insert into RegionDetails (Code,Name,SiteID,DetailVersion) values (:Code,:Name,:SiteID,:DetailVersion)'); Prepared := True; ParamByName('Code').DataType := ftInteger; ParamByName('Name').DataType := ftString; ParamByName('SiteID').DataType := ftString; ParamByName('DetailVersion').DataType := ftInteger; for I := 0 to FGeteBayDetails.RegionDetails.Count - 1 do begin ParamByName('Code').Value := FGeteBayDetails.RegionDetails[i].RegionID; ParamByName('Name').Value := FGeteBayDetails.RegionDetails[i].Description; ParamByName('SiteID').Value := sid; ParamByName('DetailVersion').Value := FGeteBayDetails.RegionDetails[i].DetailVersion; ExecSQL; end; hlog.Add(Format('{hms}: End saving Region Details for site %s. Saved %d',[sid,FGeteBayDetails.RegionDetails.Count])); except on E : Exception do hlog.AddException(E); end; end; procedure TGetDetailsThread.SaveReturnPolicyDetails; var i:Integer; sid : string; begin sid := GetEnumName(TypeInfo(SiteCodeType),Ord(FGeteBayDetails.Connector.SiteID)); hlog.Add(Format('{hms}: Start saving Return policy details for site %s',[sid])); with FQuery1 do try SQL.Clear; SQL.Add('delete from ReturnPolicyDetails where SiteID = :SiteID'); Prepared := True; ParamByName('SiteID').DataType := ftString; ParamByName('SiteID').Value := sid; ExecSQL; SQL.Clear; SQL.Add('insert into ReturnPolicyDetails (Type,Name,Value,SiteID,Version) values (:Type,:Name,:Value,:SiteID,:DetailVersion)'); Prepared := True; ParamByName('Type').DataType := ftString; ParamByName('Name').DataType := ftString; ParamByName('Value').DataType := ftString; ParamByName('SiteID').DataType := ftString; ParamByName('DetailVersion').DataType := ftInteger; ParamByName('DetailVersion').Value := StrToInt(FGeteBayDetails.ReturnPolicyDetails.DetailVersion); for I := 0 to FGeteBayDetails.ReturnPolicyDetails.Refund.Count - 1 do begin ParamByName('Type').Value := 'Refund'; ParamByName('Name').Value := FGeteBayDetails.ReturnPolicyDetails.Refund[i].Description; ParamByName('Value').Value := FGeteBayDetails.ReturnPolicyDetails.Refund[i].RefundOption; ParamByName('SiteID').Value := sid; ExecSQL; end; hlog.Add(Format('{hms}: End saving Refund of Return policy details for site %s. Saved %d',[sid,FGeteBayDetails.ReturnPolicyDetails.Refund.Count])); for I := 0 to FGeteBayDetails.ReturnPolicyDetails.ReturnsWithin.Count - 1 do begin ParamByName('Type').Value := 'ReturnsWithin'; ParamByName('Name').Value := FGeteBayDetails.ReturnPolicyDetails.ReturnsWithin[i].Description; ParamByName('Value').Value := FGeteBayDetails.ReturnPolicyDetails.ReturnsWithin[i].ReturnsWithinOption; ParamByName('SiteID').Value := sid; ExecSQL; end; hlog.Add(Format('{hms}: End saving ReturnsWithin of Return policy details for site %s. Saved %d',[sid,FGeteBayDetails.ReturnPolicyDetails.ReturnsWithin.Count])); for I := 0 to FGeteBayDetails.ReturnPolicyDetails.ReturnsAccepted.Count - 1 do begin ParamByName('Type').Value := 'ReturnsAccepted'; ParamByName('Name').Value := FGeteBayDetails.ReturnPolicyDetails.ReturnsAccepted[i].Description; ParamByName('Value').Value := FGeteBayDetails.ReturnPolicyDetails.ReturnsAccepted[i].ReturnsAcceptedOption; ParamByName('SiteID').Value := sid; ExecSQL; end; hlog.Add(Format('{hms}: End saving ReturnsAccepted of Return policy details for site %s. Saved %d',[sid,FGeteBayDetails.ReturnPolicyDetails.ReturnsAccepted.Count])); for I := 0 to FGeteBayDetails.ReturnPolicyDetails.ShippingCostPaidBy.Count - 1 do begin ParamByName('Type').Value := 'ShippingCostPaidBy'; ParamByName('Name').Value := FGeteBayDetails.ReturnPolicyDetails.ShippingCostPaidBy[i].Description; ParamByName('Value').Value := FGeteBayDetails.ReturnPolicyDetails.ShippingCostPaidBy[i].ShippingCostPaidByOption; ParamByName('SiteID').Value := sid; ExecSQL; end; hlog.Add(Format('{hms}: End saving ShippingCostPaidBy of Return policy details for site %s. Saved %d',[sid,FGeteBayDetails.ReturnPolicyDetails.ShippingCostPaidBy.Count])); except on E : Exception do hlog.AddException(E); end; end; procedure TGetDetailsThread.SaveShippingLocationDetails; var i:Integer; sid : string; begin sid := GetEnumName(TypeInfo(SiteCodeType),Ord(FGeteBayDetails.Connector.SiteID)); hlog.Add(Format('{hms}: Start saving Shipping Location Details for site %s',[sid])); with FQuery1 do try SQL.Clear; SQL.Add('delete from ShippingLocationDetails where SiteID = :SiteID'); Prepared := True; ParamByName('SiteID').DataType := ftString; ParamByName('SiteID').Value := sid; ExecSQL; SQL.Clear; SQL.Add('insert into ShippingLocationDetails (Code,Name,SiteID,DetailVersion) values (:Code,:Name,:SiteID,:DetailVersion)'); Prepared := True; ParamByName('Code').DataType := ftString; ParamByName('Name').DataType := ftString; ParamByName('SiteID').DataType := ftString; ParamByName('DetailVersion').DataType := ftInteger; for I := 0 to FGeteBayDetails.ShippingLocationDetails.Count - 1 do begin ParamByName('Code').Value := FGeteBayDetails.ShippingLocationDetails[i].ShippingLocation; ParamByName('Name').Value := FGeteBayDetails.ShippingLocationDetails[i].Description; ParamByName('SiteID').Value := sid; ParamByName('DetailVersion').Value := FGeteBayDetails.ShippingLocationDetails[i].DetailVersion; ExecSQL; end; hlog.Add(Format('{hms}: End saving Shipping Location Details for site %s. Saved %d',[sid,FGeteBayDetails.ShippingLocationDetails.Count])); except on E : Exception do hlog.AddException(E); end; end; procedure TGetDetailsThread.SaveShippingServiceDetails; var i,j:Integer; sid : string; begin sid := GetEnumName(TypeInfo(SiteCodeType),Ord(FGeteBayDetails.Connector.SiteID)); hlog.Add(Format('{hms}: Start saving Shipping Services Details for site %s',[sid])); with FQuery1 do try SQL.Clear; SQL.Add('delete from ShippingServiceDetails where SiteID = :SiteID'); Prepared := True; ParamByName('SiteID').DataType := ftString; ParamByName('SiteID').Value := sid; ExecSQL; SQL.Clear; SQL.Add(' insert into ShippingServiceDetails (ShippingServiceID , ShippingService , Description , ShippingTimeMax ,'); SQL.Add(' InternationalService, ShippingTimeMin, ServiceTypeFlat , ServiceTypeCalculated , DetailVersion , SiteID)'); SQL.Add(' values (:ShippingServiceID , :ShippingService , :Description , :ShippingTimeMax ,'); SQL.Add(' :InternationalService , :ShippingTimeMin , :ServiceTypeFlat , :ServiceTypeCalculated , :DetailVersion , :SiteID )'); Prepared := True; ParamByName('ShippingServiceID').DataType := ftInteger; ParamByName('ShippingService').DataType := ftString; ParamByName('Description').DataType := ftString; ParamByName('ShippingTimeMax').DataType := ftInteger; ParamByName('ShippingTimeMin').DataType := ftInteger; ParamByName('InternationalService').DataType := ftBoolean; ParamByName('ServiceTypeFlat').DataType := ftBoolean; ParamByName('ServiceTypeCalculated').DataType := ftBoolean; ParamByName('DetailVersion').DataType := ftInteger; ParamByName('SiteID').Value := sid; for I := 0 to FGeteBayDetails.ShippingServiceDetails.Count - 1 do begin ParamByName('ShippingServiceID').Value := FGeteBayDetails.ShippingServiceDetails[i].ShippingServiceID; ParamByName('ShippingService').Value := FGeteBayDetails.ShippingServiceDetails[i].ShippingService; ParamByName('Description').Value := FGeteBayDetails.ShippingServiceDetails[i].Description; if FGeteBayDetails.ShippingServiceDetails[i].ChildNodes.FindNode('ShippingTimeMax')<>nil then ParamByName('ShippingTimeMax').Value := FGeteBayDetails.ShippingServiceDetails[i].ShippingTimeMax else ParamByName('ShippingTimeMax').Value := null; if FGeteBayDetails.ShippingServiceDetails[i].ChildNodes.FindNode('ShippingTimeMin')<>nil then ParamByName('ShippingTimeMin').Value := FGeteBayDetails.ShippingServiceDetails[i].ShippingTimeMin else ParamByName('ShippingTimeMin').Value := null; if FGeteBayDetails.ShippingServiceDetails[i].ChildNodes.FindNode('InternationalService')<>nil then ParamByName('InternationalService').Value := FGeteBayDetails.ShippingServiceDetails[i].InternationalService else ParamByName('InternationalService').Value := False; ParamByName('ServiceTypeFlat').Value := False; ParamByName('ServiceTypeCalculated').Value := False; for J := 0 to FGeteBayDetails.ShippingServiceDetails[i].ServiceType.Count - 1 do begin if FGeteBayDetails.ShippingServiceDetails[i].ServiceType.Items[j]='Flat' then begin ParamByName('ServiceTypeFlat').Value := True; end; if FGeteBayDetails.ShippingServiceDetails[i].ServiceType.Items[j]='Calculated' then begin ParamByName('ServiceTypeCalculated').Value := True; end; end; ParamByName('DetailVersion').Value := FGeteBayDetails.ShippingServiceDetails[i].DetailVersion; ParamByName('SiteID').Value := sid; ExecSQL; end; hlog.Add(Format('{hms}: End saving Shipping Services Details for site %s. Saved %d',[sid,FGeteBayDetails.ShippingServiceDetails.Count])); except on E : Exception do hlog.AddException(E); end; end; procedure TGetDetailsThread.SaveDetails; var Operation : string; begin try Operation := 'SaveCountryDetails'; SaveCountryDetails; Operation := 'SaveCurrencyDetails'; SaveCurrencyDetails; Operation := 'SaveDispatchTimeMaxDetails'; SaveDispatchTimeMaxDetails; Operation := 'SavePaymentOptionDetails'; SavePaymentOptionDetails; Operation := 'SaveRegionDetails'; SaveRegionDetails; Operation := 'SaveShippingLocationDetails'; SaveShippingLocationDetails; Operation := 'SaveShippingServiceDetails'; SaveShippingServiceDetails; Operation := 'SaveReturnPolicyDetails'; SaveReturnPolicyDetails; except on E : Exception do begin hlog.AddException(E); hlog.Add(Format('{hms}: Operation %s',[Operation])); end; end; end; procedure TGetDetailsThread.WriteEbayApiExceptionLog(E : Exception); begin hlog.AddException(E); FEbayTradingConnect.RequestXMLText.SaveToFile(hLog.hlWriter.hlFileDef.path+'\Request.xml'); hlog.Add('Request XML saved'); FEbayTradingConnect.RequestXMLText.SaveToFile(hLog.hlWriter.hlFileDef.path+'\Response.xml'); hlog.Add('Response XML saved'); end; procedure TGetDetailsThread.EbayTradingConnectWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); begin case AWorkMode of wmRead : begin FSyncObj.OnHttpWork(AWorkMode,AWorkCount-FRxDelta); FRxDelta := AWorkCount; end; wmWrite : begin FSyncObj.OnHttpWork(AWorkMode,AWorkCount-FTxDelta); FTxDelta := AWorkCount; end; end; end; { TFTSync } procedure TFTSync.DoSynchronize; begin inherited; case Operation of OpIncApiUsage : fmMain.IncApiUsage; OpOnSave : fmMain.dxRibbonStatusBar1.Panels[4].Text := Value; OpOnWork : begin case WorkMode of wmRead : begin fmMain.RxCounter := fmMain.RxCounter + iVal; fmMain.RxCounterDelta := fmMain.RxCounterDelta + iVal; end; wmWrite : begin fmMain.TxCounter := fmMain.TxCounter + iVal; fmMain.TxCounterDelta := fmMain.TxCounterDelta + iVal; end end; end; end; end; procedure TFTSync.IncApiUsage; begin Operation := OpIncApiUsage; Synchronize; end; procedure TFTSync.OnHttpWork(AWorkMode: TWorkMode; const AWorkCount: Integer); begin WorkMode := AWorkMode; iVal := AWorkCount; Operation := OpOnWork; Synchronize; end; procedure TFTSync.OnSave(Saved, Total: Integer); begin Operation := OpOnSave; Value := Format('Saved %d of %d items',[Saved,Total]); Synchronize; end; end.
unit Aspect4D.Impl; interface uses System.SysUtils, System.Rtti, System.Generics.Collections, Aspect4D; type TAspectInterceptor = class private fAspects: TDictionary<string, IAspect>; protected { protected declarations } public constructor Create; destructor Destroy; override; procedure Add(const name: string; aspect: IAspect); function Contains(const name: string): Boolean; procedure DoBefore(instance: TObject; method: TRttiMethod; const args: TArray<TValue>; out invoke: Boolean; out result: TValue); procedure DoAfter(instance: TObject; method: TRttiMethod; const args: TArray<TValue>; var result: TValue); procedure DoException(instance: TObject; method: TRttiMethod; const args: TArray<TValue>; out raiseException: Boolean; theException: Exception; out result: TValue); end; TAspectWeaver = class(TInterfacedObject, IAspectWeaver) private fVMIs: TObjectDictionary<string, TVirtualMethodInterceptor>; fInterceptor: TAspectInterceptor; procedure RegisterObjectClass(objectClass: TClass); protected procedure Proxify(instance: TObject); procedure Unproxify(instance: TObject); public constructor Create(interceptor: TAspectInterceptor); destructor Destroy; override; end; TAspectContext = class(TInterfacedObject, IAspectContext) private fInterceptor: TAspectInterceptor; fWeaver: IAspectWeaver; protected procedure &Register(aspect: IAspect); function Weaver: IAspectWeaver; public constructor Create; destructor Destroy; override; end; implementation { TAspectInterceptor } procedure TAspectInterceptor.Add(const name: string; aspect: IAspect); begin fAspects.AddOrSetValue(name, aspect); end; function TAspectInterceptor.Contains(const name: string): Boolean; begin Result := fAspects.ContainsKey(name); end; constructor TAspectInterceptor.Create; begin inherited Create; fAspects := TDictionary<string, IAspect>.Create; end; destructor TAspectInterceptor.Destroy; begin fAspects.Free; inherited Destroy; end; procedure TAspectInterceptor.DoAfter(instance: TObject; method: TRttiMethod; const args: TArray<TValue>; var result: TValue); var aspectPair: TPair<string, IAspect>; begin for aspectPair in fAspects do aspectPair.Value.DoAfter(instance, method, args, result); end; procedure TAspectInterceptor.DoBefore(instance: TObject; method: TRttiMethod; const args: TArray<TValue>; out invoke: Boolean; out result: TValue); var aspectPair: TPair<string, IAspect>; begin for aspectPair in fAspects do aspectPair.Value.DoBefore(instance, method, args, invoke, result); end; procedure TAspectInterceptor.DoException(instance: TObject; method: TRttiMethod; const args: TArray<TValue>; out raiseException: Boolean; theException: Exception; out result: TValue); var aspectPair: TPair<string, IAspect>; begin for aspectPair in fAspects do aspectPair.Value.DoException(instance, method, args, raiseException, theException, result); end; { TAspectWeaver } constructor TAspectWeaver.Create(interceptor: TAspectInterceptor); begin inherited Create; fVMIs := TObjectDictionary<string, TVirtualMethodInterceptor>.Create([doOwnsValues]); fInterceptor := interceptor; end; destructor TAspectWeaver.Destroy; begin fVMIs.Free; inherited; end; procedure TAspectWeaver.Proxify(instance: TObject); begin RegisterObjectClass(instance.ClassType); fVMIs.Items[instance.QualifiedClassName].Proxify(instance); end; procedure TAspectWeaver.RegisterObjectClass(objectClass: TClass); var newVMI: TVirtualMethodInterceptor; begin if not fVMIs.ContainsKey(objectClass.QualifiedClassName) then begin newVMI := TVirtualMethodInterceptor.Create(objectClass); newVMI.OnBefore := fInterceptor.DoBefore; newVMI.OnAfter := fInterceptor.DoAfter; newVMI.OnException := fInterceptor.DoException; fVMIs.Add(objectClass.QualifiedClassName, newVMI); end; end; procedure TAspectWeaver.Unproxify(instance: TObject); begin if fVMIs.ContainsKey(instance.QualifiedClassName) then fVMIs.Items[instance.QualifiedClassName].Unproxify(instance); end; { TAspectContext } constructor TAspectContext.Create; begin inherited Create; fInterceptor := TAspectInterceptor.Create; fWeaver := TAspectWeaver.Create(fInterceptor); end; destructor TAspectContext.Destroy; begin fInterceptor.Free; inherited Destroy; end; procedure TAspectContext.Register(aspect: IAspect); begin if not fInterceptor.Contains(aspect.Name) then fInterceptor.Add(aspect.Name, aspect); end; function TAspectContext.Weaver: IAspectWeaver; begin Result := fWeaver; end; end.
unit UBasicPlugins; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, UPlugin, ActnList; type TRDSBasicPlugIns = class(TRDSPlugIn) acAdjustCtrls: TAction; acLinkCtrls: TAction; acLinkColumns: TAction; acCopyChildren: TAction; acAddToSelection: TAction; acDeleteFromSelection: TAction; acClearSelection: TAction; acSelectChildren: TAction; procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean); procedure acAdjustCtrlsExecute(Sender: TObject); procedure acLinkCtrlsExecute(Sender: TObject); procedure acLinkColumnsExecute(Sender: TObject); procedure acCopyChildrenExecute(Sender: TObject); procedure acAddToSelectionExecute(Sender: TObject); procedure acDeleteFromSelectionExecute(Sender: TObject); procedure acClearSelectionExecute(Sender: TObject); procedure acSelectChildrenExecute(Sender: TObject); private { Private declarations } public { Public declarations } end; var RDSBasicPlugIns: TRDSBasicPlugIns; implementation uses UReportInspector, RPCtrls, UAdjustCtrls, ULinkCtrls, ULinkColumns, UCopyChildren, UTools; {$R *.DFM} procedure TRDSBasicPlugIns.ActionListUpdate(Action: TBasicAction; var Handled: Boolean); begin inherited; Assert(ReportInspector<>nil); Handled := True; acAdjustCtrls.Enabled := (ReportInspector.Selected is TRDSimpleBand); acLinkCtrls.Enabled := acAdjustCtrls.Enabled; acCopyChildren.Enabled := (ReportInspector.Selected is TWinControl); end; procedure TRDSBasicPlugIns.acAdjustCtrlsExecute(Sender: TObject); begin inherited; Assert(ReportInspector<>nil); Assert(ReportInspector.Selected is TRDSimpleBand); Assert(dlgAdjustCtrls<>nil); if dlgAdjustCtrls.Execute(TRDSimpleBand(ReportInspector.Selected)) then begin ReportInspector.Modified; end; end; procedure TRDSBasicPlugIns.acLinkCtrlsExecute(Sender: TObject); begin inherited; Assert(ReportInspector<>nil); Assert(ReportInspector.Selected is TRDSimpleBand); Assert(dlgLinkCtrls<>nil); if dlgLinkCtrls.Execute(TRDSimpleBand(ReportInspector.Selected)) then begin ReportInspector.Modified; end; end; procedure TRDSBasicPlugIns.acLinkColumnsExecute(Sender: TObject); begin Assert(ReportInspector<>nil); Assert(ReportInspector.Report<>nil); if LinkColumns(ReportInspector.Report) then ReportInspector.Modified; end; procedure TRDSBasicPlugIns.acCopyChildrenExecute(Sender: TObject); begin Assert(ReportInspector<>nil); Assert(ReportInspector.Report<>nil); if ReportInspector.Selected is TWinControl then CopyChildren(TWinControl(ReportInspector.Selected)); end; procedure TRDSBasicPlugIns.acAddToSelectionExecute(Sender: TObject); begin inherited; if DesignSelection<>nil then DesignSelection.AddSelected; end; procedure TRDSBasicPlugIns.acDeleteFromSelectionExecute(Sender: TObject); begin inherited; if DesignSelection<>nil then DesignSelection.RemoveSelected; end; procedure TRDSBasicPlugIns.acClearSelectionExecute(Sender: TObject); begin inherited; if DesignSelection<>nil then DesignSelection.ClearSelection; end; procedure TRDSBasicPlugIns.acSelectChildrenExecute(Sender: TObject); var I : Integer; Band : TWinControl; begin inherited; if (DesignSelection<>nil) and (ReportInspector.Selected is TRDSimpleBand) then begin Band := TWinControl(ReportInspector.Selected); for I:=0 to Band.ControlCount-1 do begin DesignSelection.AddSelectedComponent(Band.Controls[I]); end; end; end; end.
program media_billboards; uses Utils; type IntArr2D = array[,] of integer; var M, N, K: integer; banners: IntArr2D; i, j: integer; start_time: real; (*Процедура для считывания данных с клавиатуры*) procedure read_input( var M, N, K: integer; var banners: IntArr2D); var i: integer; begin readln(M, N, K); setLength(banners, K, 5); for i := 0 to K-1 do begin readln( banners[i, 0], banners[i, 1], banners[i, 2], banners[i, 3], banners[i, 4] ) end end; (*Возвращает наибольшую возможную выручку. Заказы на баннеры * перебираются в том порядке, в котором они перечислены в массиве * `banners`. * * Параметры: * M: количество рядов плиток на билборде (фасаде) * N: количетсво столбцов плиток на билборде * K: количество заказов на баннеры * banners: двумерный массив целых чисел с формой `[K, 5]`. * Каждый ряд массива содержит параметры заказа на баннер: * 5 чисел R, C, H, W, P (пояснения в условии задачи). * * Возвращает: * вещественное число * *) function calculate_revenue( M, N, K: integer; banners: IntArr2D): real; var i, row, col: integer; tile_price, revenue: real; (*Массив с лучшими ценами плиток*) billboard: array[,] of real; begin (*Ваш код*) for i:=0 to K-1 do begin tile_price:=banners[i, 4]/banners[i, 2]/banners[i, 3]; for row=:banners[i, 0] to banners[i, 0]+banners[i, 2] do for col=:banners[i, 1] to banners[i, 1]+banners[i, 3] do if tile_price > billboard[row, col] then billboard[row, col]:=tile_price end; for row=:0 to M do for col:=0 to N do end; (*Сортировка пузырьком для рядов массива*) procedure bubble_sort_2d(var IntArr2D: arr); begin read_input(M, N, K, banners); start_time := Milliseconds; writeln(calculate_revenue(M, N, K, banners)); writeln(Milliseconds - start_time); end.
unit UWinPrint; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2005 by Bradford Technologies, Inc. } interface uses Windows, Messages, SysUtils, Classes, Dialogs, Uglobals, UContainer; type TWinPrint = class(TObject) FDoc: TContainer; FPgSpec: Array of PagePrintSpecRec; //duplicate of doc.pages PagePrintSpecRec FPrintDialog: TPrintDialog; public Constructor Create(doc: TContainer); Destructor Destroy; override; function Execute: Boolean; procedure ConfigurePagesToPrint; end; implementation uses UUtil2, UStatus; { TWinPrint } constructor TWinPrint.Create(doc: TContainer); begin inherited Create; FDoc := doc; if NotNil(FDoc) then try //Set up the print dialog FPrintDialog := TPrintDialog.Create(doc); FPrintDialog.MinPage := 1; FPrintDialog.MaxPage := FDoc.docForm.TotalPages; FPrintDialog.Options := [poPageNums,poWarning]; // FPrintDialog.Copies := 1; //causes crash if printer not installed FPrintDialog.FromPage := 1; FPrintDialog.ToPage := FDoc.docForm.TotalPages; FPrintDialog.Collate := False; except ShowNotice('There was a problem creating the printer dialog. Please check your printer drivers and printer connection.'); Self.Free; //lets say bye end; end; destructor TWinPrint.Destroy; begin Finalize(FPgSpec); FPrintDialog.Free; inherited Destroy; end; function TWinPrint.Execute: Boolean; begin result := FPrintDialog.execute; if result then begin ConfigurePagesToPrint; if FPrintDialog.Collate then FDoc.DoWinPrint(FPrintDialog.Copies, FPgSpec) else FDoc.DoWinPrint(1, FPgSpec); end; end; procedure TWinPrint.ConfigurePagesToPrint; var n,z: Integer; MinPg,MaxPg: Integer; begin MinPg := FPrintDialog.FromPage-1; MaxPg := FPrintDialog.ToPage-1; z := FDoc.docForm.TotalPages; //Setup the array of page specs SetLength(FPgSpec, FDoc.docForm.TotalPages); for n := 0 to z-1 do //Set the printers page array of spec record, begin FPgSpec[n].PrIndex := 1; //always use one FPgSpec[n].Copies := FPrintDialog.Copies; //normal print if FPrintDialog.Collate then //if collate, set to 1 FPgSpec[n].Copies := 1; FPgSpec[n].OK2Print := True; //selected only certain pages if FPrintDialog.PrintRange = prPageNums then FPgSpec[n].OK2Print := ((n >= MinPg) and (n <= MaxPg)); end; end; end.
{$mode objfpc} // {$unitpath /foldername} // Uncomment the previous line if you own units // are on a folder near your plugin code. library pluginmodel; (* Plugin will have the name "mcp*.dll" * * E.g.: "mcpStopwatch.dll" * * * * It must export only one function: * * function PluginInit(host : IPluginHost) : IPlugin; stdcall; * * Without this function, the plugin is NOT recognised. *) uses mcIntf; const MYNAME = 'Plugin name'; // The name of your plugin - shown in the main menu. // No bigger than 15 characters, please. type // The class which implements the plugin interface TYourClass = class(TInterfacedObject, IPlugin) private function GetMyName : WideString; public property PluginName : WideString read GetMyName; procedure Execute; end; var thehost : IPluginHost = nil; // Reference to the host (which is Mini Calc) function TYourClass.GetMyName : WideString; (* Do NOT change. *) begin GetMyName := MYNAME; end; procedure TYourClass.Execute; (* Method called by Mini Calc to execute the plugin. *) begin // Your plugin code here. // You may use whatever you want outside this procedure: // consider this method as your main block of a program. end; function PluginInit(host : IPluginHost) : IPlugin; stdcall; (* Do NOT change. *) begin thehost := host; PluginInit := TYourClass.Create as IPlugin; end; (* Mini Calc Plugin Initializer recognizes this and loads the plugin. *) exports PluginInit; begin // This must be empty in order to be valid. end;
{******************************************************************************} { } { Indy (Internet Direct) - Internet Protocols Simplified } { } { https://www.indyproject.org/ } { https://gitter.im/IndySockets/Indy } { } {******************************************************************************} { } { This file is part of the Indy (Internet Direct) project, and is offered } { under the dual-licensing agreement described on the Indy website. } { (https://www.indyproject.org/license/) } { } { Copyright: } { (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { } {******************************************************************************} { } { Originally written by: Fabian S. Biehn } { fbiehn@aagon.com (German & English) } { } { Contributers: } { Here could be your name } { } {******************************************************************************} // This File is auto generated! // Any change to this file should be made in the // corresponding unit in the folder "intermediate"! // Generation date: 23.07.2021 14:35:33 unit IdOpenSSLHeaders_ssl; interface // Headers for OpenSSL 1.1.1 // ssl.h {$i IdCompilerDefines.inc} uses IdCTypes, IdGlobal, IdOpenSSLConsts, IdOpenSSLHeaders_ossl_typ, IdOpenSSLHeaders_async, IdOpenSSLHeaders_bio, IdOpenSSLHeaders_crypto, IdOpenSSLHeaders_pem, IdOpenSSLHeaders_tls1, IdOpenSSLHeaders_ssl3, IdOpenSSLHeaders_x509; {$MINENUMSIZE 4} const (* OpenSSL version number for ASN.1 encoding of the session information *) (*- * Version 0 - initial version * Version 1 - added the optional peer certificate *) SSL_SESSION_ASN1_VERSION = $0001; SSL_MAX_SSL_SESSION_ID_LENGTH = 32; SSL_MAX_SID_CTX_LENGTH = 32; SSL_MIN_RSA_MODULUS_LENGTH_IN_BYTES = 512/8; SSL_MAX_KEY_ARG_LENGTH = 8; SSL_MAX_MASTER_KEY_LENGTH = 48; (* The maximum number of encrypt/decrypt pipelines we can support *) SSL_MAX_PIPELINES = 32; (* text strings for the ciphers *) (* These are used to specify which ciphers to use and not to use *) SSL_TXT_LOW = AnsiString('LOW'); SSL_TXT_MEDIUM = AnsiString('MEDIUM'); SSL_TXT_HIGH = AnsiString('HIGH'); SSL_TXT_FIPS = AnsiString('FIPS'); SSL_TXT_aNULL = AnsiString('aNULL'); SSL_TXT_eNULL = AnsiString('eNULL'); SSL_TXT_NULL = AnsiString('NULL'); SSL_TXT_kRSA = AnsiString('kRSA'); SSL_TXT_kDHr = AnsiString('kDHr'); SSL_TXT_kDHd = AnsiString('kDHd'); SSL_TXT_kDH = AnsiString('kDH'); SSL_TXT_kEDH = AnsiString('kEDH'); SSL_TXT_kDHE = AnsiString('kDHE'); SSL_TXT_kECDHr = AnsiString('kECDHr'); //const SSL_TXT_kECDHe = AnsiString('kECDHe'); SSL_TXT_kECDH = AnsiString('kECDH'); SSL_TXT_kEECDH = AnsiString('kEECDH'); SSL_TXT_kECDHE = AnsiString('kECDHE'); SSL_TXT_kPSK = AnsiString('kPSK'); SSL_TXT_kRSAPSK = AnsiString('kRSAPSK'); SSL_TXT_kECDHEPSK = AnsiString('kECDHEPSK'); SSL_TXT_kDHEPSK = AnsiString('kDHEPSK'); SSL_TXT_kGOST = AnsiString('kGOST'); SSL_TXT_kSRP = AnsiString('kSRP'); SSL_TXT_aRSA = AnsiString('aRSA'); SSL_TXT_aDSS = AnsiString('aDSS'); SSL_TXT_aDH = AnsiString('aDH'); SSL_TXT_aECDH = AnsiString('aECDH'); SSL_TXT_aECDSA = AnsiString('aECDSA'); SSL_TXT_aPSK = AnsiString('aPSK'); SSL_TXT_aGOST94 = AnsiString('aGOST94'); SSL_TXT_aGOST01 = AnsiString('aGOST01'); SSL_TXT_aGOST12 = AnsiString('aGOST12'); SSL_TXT_aGOST = AnsiString('aGOST'); SSL_TXT_aSRP = AnsiString('aSRP'); SSL_TXT_DSS = AnsiString('DSS'); SSL_TXT_DH = AnsiString('DH'); SSL_TXT_DHE = AnsiString('DHE'); SSL_TXT_EDH = AnsiString('EDH'); //SSL_TXT_ADH = AnsiString('ADH'); SSL_TXT_RSA = AnsiString('RSA'); SSL_TXT_ECDH = AnsiString('ECDH'); SSL_TXT_EECDH = AnsiString('EECDH'); SSL_TXT_ECDHE = AnsiString('ECDHE'); //SSL_TXT_AECDH = AnsiString('AECDH'); SSL_TXT_ECDSA = AnsiString('ECDSA'); SSL_TXT_PSK = AnsiString('PSK'); SSL_TXT_SRP = AnsiString('SRP'); SSL_TXT_DES = AnsiString('DES'); SSL_TXT_3DES = AnsiString('3DES'); SSL_TXT_RC4 = AnsiString('RC4'); SSL_TXT_RC2 = AnsiString('RC2'); SSL_TXT_IDEA = AnsiString('IDEA'); SSL_TXT_SEED = AnsiString('SEED'); SSL_TXT_AES128 = AnsiString('AES128'); SSL_TXT_AES256 = AnsiString('AES256'); SSL_TXT_AES = AnsiString('AES'); SSL_TXT_AES_GCM = AnsiString('AESGCM'); SSL_TXT_AES_CCM = AnsiString('AESCCM'); SSL_TXT_AES_CCM_8 = AnsiString('AESCCM8'); SSL_TXT_CAMELLIA128 = AnsiString('CAMELLIA128'); SSL_TXT_CAMELLIA256 = AnsiString('CAMELLIA256'); SSL_TXT_CAMELLIA = AnsiString('CAMELLIA'); SSL_TXT_CHACHA20 = AnsiString('CHACHA20'); SSL_TXT_GOST = AnsiString('GOST89'); SSL_TXT_ARIA = AnsiString('ARIA'); SSL_TXT_ARIA_GCM = AnsiString('ARIAGCM'); SSL_TXT_ARIA128 = AnsiString('ARIA128'); SSL_TXT_ARIA256 = AnsiString('ARIA256'); SSL_TXT_MD5 = AnsiString('MD5'); SSL_TXT_SHA1 = AnsiString('SHA1'); SSL_TXT_SHA = AnsiString('SHA'); SSL_TXT_GOST94 = AnsiString('GOST94'); SSL_TXT_GOST89MAC = AnsiString('GOST89MAC'); SSL_TXT_GOST12 = AnsiString('GOST12'); SSL_TXT_GOST89MAC12 = AnsiString('GOST89MAC12'); SSL_TXT_SHA256 = AnsiString('SHA256'); SSL_TXT_SHA384 = AnsiString('SHA384'); SSL_TXT_SSLV3 = AnsiString('SSLv3'); SSL_TXT_TLSV1 = AnsiString('TLSv1'); SSL_TXT_TLSV1_1 = AnsiString('TLSv1.1'); SSL_TXT_TLSV1_2 = AnsiString('TLSv1.2'); SSL_TXT_ALL = AnsiString('ALL'); (*- * COMPLEMENTOF* definitions. These identifiers are used to (de-select) * ciphers normally not being used. * Example: "RC4" will activate all ciphers using RC4 including ciphers * without authentication, which would normally disabled by DEFAULT (due * the "!ADH" being part of default). Therefore "RC4:!COMPLEMENTOFDEFAULT" * will make sure that it is also disabled in the specific selection. * COMPLEMENTOF* identifiers are portable between version, as adjustments * to the default cipher setup will also be included here. * * COMPLEMENTOFDEFAULT does not experience the same special treatment that * DEFAULT gets, as only selection is being done and no sorting as needed * for DEFAULT. *) SSL_TXT_CMPALL = AnsiString('COMPLEMENTOFALL'); SSL_TXT_CMPDEF = AnsiString('COMPLEMENTOFDEFAULT'); (* * The following cipher list is used by default. It also is substituted when * an application-defined cipher list string starts with 'DEFAULT'. * This applies to ciphersuites for TLSv1.2 and below. *) SSL_DEFAULT_CIPHER_LIST = AnsiString('ALL:!COMPLEMENTOFDEFAULT:!eNULL'); (* This is the default set of TLSv1.3 ciphersuites *) TLS_DEFAULT_CIPHERSUITES = AnsiString('TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256'); (* * As of OpenSSL 1.0.0, ssl_create_cipher_list() in ssl/ssl_ciph.c always * starts with a reasonable order, and all we have to do for DEFAULT is * throwing out anonymous and unencrypted ciphersuites! (The latter are not * actually enabled by ALL, but "ALL:RSA" would enable some of them.) *) (* Used in SSL_set_shutdown()/SSL_get_shutdown(); *) SSL_SENT_SHUTDOWN = 1; SSL_RECEIVED_SHUTDOWN = 2; SSL_FILETYPE_ASN1 = X509_FILETYPE_ASN1; SSL_FILETYPE_PEM = X509_FILETYPE_PEM; (* Extension context codes *) (* This extension is only allowed in TLS *) SSL_EXT_TLS_ONLY = $0001; (* This extension is only allowed in DTLS *) SSL_EXT_DTLS_ONLY = $0002; (* Some extensions may be allowed in DTLS but we don't implement them for it *) SSL_EXT_TLS_IMPLEMENTATION_ONLY = $0004; (* Most extensions are not defined for SSLv3 but EXT_TYPE_renegotiate is *) SSL_EXT_SSL3_ALLOWED = $0008; (* Extension is only defined for TLS1.2 and below *) SSL_EXT_TLS1_2_AND_BELOW_ONLY = $0010; (* Extension is only defined for TLS1.3 and above *) SSL_EXT_TLS1_3_ONLY = $0020; (* Ignore this extension during parsing if we are resuming *) SSL_EXT_IGNORE_ON_RESUMPTION = $0040; SSL_EXT_CLIENT_HELLO = $0080; (* Really means TLS1.2 or below *) SSL_EXT_TLS1_2_SERVER_HELLO = $0100; SSL_EXT_TLS1_3_SERVER_HELLO = $0200; SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS = $0400; SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST = $0800; SSL_EXT_TLS1_3_CERTIFICATE = $1000; SSL_EXT_TLS1_3_NEW_SESSION_TICKET = $2000; SSL_EXT_TLS1_3_CERTIFICATE_REQUEST = $4000; (* * Some values are reserved until OpenSSL 1.2.0 because they were previously * included in SSL_OP_ALL in a 1.1.x release. * * Reserved value (until OpenSSL 1.2.0) $00000001U * Reserved value (until OpenSSL 1.2.0) $00000002U *) (* Allow initial connection to servers that don't support RI *) SSL_OP_LEGACY_SERVER_CONNECT = TIdC_UINT($00000004); (* Reserved value (until OpenSSL 1.2.0) $00000008U *) SSL_OP_TLSEXT_PADDING = TIdC_UINT($00000010); (* Reserved value (until OpenSSL 1.2.0) $00000020U *) SSL_OP_SAFARI_ECDHE_ECDSA_BUG = TIdC_UINT($00000040); (* * Reserved value (until OpenSSL 1.2.0) $00000080U * Reserved value (until OpenSSL 1.2.0) $00000100U * Reserved value (until OpenSSL 1.2.0) $00000200U *) (* In TLSv1.3 allow a non-(ec)dhe based kex_mode *) SSL_OP_ALLOW_NO_DHE_KEX = TIdC_UINT($00000400); (* * Disable SSL 3.0/TLS 1.0 CBC vulnerability workaround that was added in * OpenSSL 0.9.6d. Usually (depending on the application protocol) the * workaround is not needed. Unfortunately some broken SSL/TLS * implementations cannot handle it at all, which is why we include it in * SSL_OP_ALL. Added in 0.9.6e *) SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS = TIdC_UINT($00000800); (* DTLS options *) SSL_OP_NO_QUERY_MTU = TIdC_UINT($00001000); (* Turn on Cookie Exchange (on relevant for servers) *) SSL_OP_COOKIE_EXCHANGE = TIdC_UINT($00002000); (* Don't use RFC4507 ticket extension *) SSL_OP_NO_TICKET = TIdC_UINT($00004000); (* Use Cisco's "speshul" version of DTLS_BAD_VER * (only with deprecated DTLSv1_client_method()) *) SSL_OP_CISCO_ANYCONNECT = TIdC_UINT($00008000); (* As server, disallow session resumption on renegotiation *) SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION = TIdC_UINT($00010000); (* Don't use compression even if supported *) SSL_OP_NO_COMPRESSION = TIdC_UINT($00020000); (* Permit unsafe legacy renegotiation *) SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION = TIdC_UINT($00040000); (* Disable encrypt-then-mac *) SSL_OP_NO_ENCRYPT_THEN_MAC = TIdC_UINT($00080000); (* * Enable TLSv1.3 Compatibility mode. This is on by default. A future version * of OpenSSL may have this disabled by default. *) SSL_OP_ENABLE_MIDDLEBOX_COMPAT = TIdC_UINT($00100000); (* Prioritize Chacha20Poly1305 when client does. * Modifies SSL_OP_CIPHER_SERVER_PREFERENCE *) SSL_OP_PRIORITIZE_CHACHA = TIdC_UINT($00200000); (* * Set on servers to choose the cipher according to the server's preferences *) SSL_OP_CIPHER_SERVER_PREFERENCE = TIdC_UINT($00400000); (* * If set, a server will allow a client to issue a SSLv3.0 version number as * latest version supported in the premaster secret, even when TLSv1.0 * (version 3.1) was announced in the client hello. Normally this is * forbidden to prevent version rollback attacks. *) SSL_OP_TLS_ROLLBACK_BUG = TIdC_UINT($00800000); (* * Switches off automatic TLSv1.3 anti-replay protection for early data. This * is a server-side option only (no effect on the client). *) SSL_OP_NO_ANTI_REPLAY = TIdC_UINT($01000000); SSL_OP_NO_SSLv3 = TIdC_UINT($02000000); SSL_OP_NO_TLSv1 = TIdC_UINT($04000000); SSL_OP_NO_TLSv1_2 = TIdC_UINT($08000000); SSL_OP_NO_TLSv1_1 = TIdC_UINT($10000000); SSL_OP_NO_TLSv1_3 = TIdC_UINT($20000000); SSL_OP_NO_DTLSv1 = TIdC_UINT($04000000); SSL_OP_NO_DTLSv1_2 = TIdC_UINT($08000000); SSL_OP_NO_SSL_MASK = SSL_OP_NO_SSLv3 or SSL_OP_NO_TLSv1 or SSL_OP_NO_TLSv1_1 or SSL_OP_NO_TLSv1_2 or SSL_OP_NO_TLSv1_3; SSL_OP_NO_DTLS_MASK = SSL_OP_NO_DTLSv1 or SSL_OP_NO_DTLSv1_2; (* Disallow all renegotiation *) SSL_OP_NO_RENEGOTIATION = TIdC_UINT($40000000); (* * Make server add server-hello extension from early version of cryptopro * draft, when GOST ciphersuite is negotiated. Required for interoperability * with CryptoPro CSP 3.x *) SSL_OP_CRYPTOPRO_TLSEXT_BUG = TIdC_UINT($80000000); (* * SSL_OP_ALL: various bug workarounds that should be rather harmless. * This used to be $000FFFFFL before 0.9.7. * This used to be $80000BFFU before 1.1.1. *) SSL_OP_ALL = SSL_OP_CRYPTOPRO_TLSEXT_BUG or SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS or SSL_OP_LEGACY_SERVER_CONNECT or SSL_OP_TLSEXT_PADDING or SSL_OP_SAFARI_ECDHE_ECDSA_BUG; (* OBSOLETE OPTIONS: retained for compatibility *) (* Removed from OpenSSL 1.1.0. Was $00000001L *) (* Related to removed SSLv2. *) SSL_OP_MICROSOFT_SESS_ID_BUG = $0; (* Removed from OpenSSL 1.1.0. Was $00000002L *) (* Related to removed SSLv2. *) SSL_OP_NETSCAPE_CHALLENGE_BUG = $0; (* Removed from OpenSSL 0.9.8q and 1.0.0c. Was $00000008L *) (* Dead forever, see CVE-2010-4180 *) SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = $0; (* Removed from OpenSSL 1.0.1h and 1.0.2. Was $00000010L *) (* Refers to ancient SSLREF and SSLv2. *) SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG = $0; (* Removed from OpenSSL 1.1.0. Was $00000020 *) SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER = $0; (* Removed from OpenSSL 0.9.7h and 0.9.8b. Was $00000040L *) SSL_OP_MSIE_SSLV2_RSA_PADDING = $0; (* Removed from OpenSSL 1.1.0. Was $00000080 *) (* Ancient SSLeay version. *) SSL_OP_SSLEAY_080_CLIENT_DH_BUG = $0; (* Removed from OpenSSL 1.1.0. Was $00000100L *) SSL_OP_TLS_D5_BUG = $0; (* Removed from OpenSSL 1.1.0. Was $00000200L *) SSL_OP_TLS_BLOCK_PADDING_BUG = $0; (* Removed from OpenSSL 1.1.0. Was $00080000L *) SSL_OP_SINGLE_ECDH_USE = $0; (* Removed from OpenSSL 1.1.0. Was $00100000L *) SSL_OP_SINGLE_DH_USE = $0; (* Removed from OpenSSL 1.0.1k and 1.0.2. Was $00200000L *) SSL_OP_EPHEMERAL_RSA = $0; (* Removed from OpenSSL 1.1.0. Was $01000000L *) SSL_OP_NO_SSLv2 = $0; (* Removed from OpenSSL 1.0.1. Was $08000000L *) SSL_OP_PKCS1_CHECK_1 = $0; (* Removed from OpenSSL 1.0.1. Was $10000000L *) SSL_OP_PKCS1_CHECK_2 = $0; (* Removed from OpenSSL 1.1.0. Was $20000000L *) SSL_OP_NETSCAPE_CA_DN_BUG = $0; (* Removed from OpenSSL 1.1.0. Was $40000000L *) SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = $0; (* * Allow SSL_write(..., n) to return r with 0 < r < n (i.e. report success * when just a single record has been written): *) SSL_MODE_ENABLE_PARTIAL_WRITE = TIdC_UINT($00000001); (* * Make it possible to retry SSL_write() with changed buffer location (buffer * contents must stay the same!); this is not the default to avoid the * misconception that non-blocking SSL_write() behaves like non-blocking * write(): *) SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER = TIdC_UINT($00000002); (* * Never bother the application with retries if the transport is blocking: *) SSL_MODE_AUTO_RETRY = TIdC_UINT($00000004); (* Don't attempt to automatically build certificate chain *) SSL_MODE_NO_AUTO_CHAIN = TIdC_UINT($00000008); (* * Save RAM by releasing read and write buffers when they're empty. (SSL3 and * TLS only.) Released buffers are freed. *) SSL_MODE_RELEASE_BUFFERS = TIdC_UINT($00000010); (* * Send the current time in the Random fields of the ClientHello and * ServerHello records for compatibility with hypothetical implementations * that require it. *) SSL_MODE_SEND_CLIENTHELLO_TIME = TIdC_UINT($00000020); SSL_MODE_SEND_SERVERHELLO_TIME = TIdC_UINT($00000040); (* * Send TLS_FALLBACK_SCSV in the ClientHello. To be set only by applications * that reconnect with a downgraded protocol version; see * draft-ietf-tls-downgrade-scsv-00 for details. DO NOT ENABLE THIS if your * application attempts a normal handshake. Only use this in explicit * fallback retries, following the guidance in * draft-ietf-tls-downgrade-scsv-00. *) SSL_MODE_SEND_FALLBACK_SCSV = TIdC_UINT($00000080); (* * Support Asynchronous operation *) SSL_MODE_ASYNC = TIdC_UINT($00000100); (* * When using DTLS/SCTP, include the terminating zero in the label * used for computing the endpoint-pair shared secret. Required for * interoperability with implementations having this bug like these * older version of OpenSSL: * - OpenSSL 1.0.0 series * - OpenSSL 1.0.1 series * - OpenSSL 1.0.2 series * - OpenSSL 1.1.0 series * - OpenSSL 1.1.1 and 1.1.1a *) SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG = TIdC_UINT($00000400); (* Cert related flags *) (* * Many implementations ignore some aspects of the TLS standards such as * enforcing certificate chain algorithms. When this is set we enforce them. *) SSL_CERT_FLAG_TLS_STRICT = TIdC_UINT($00000001); (* Suite B modes, takes same values as certificate verify flags *) SSL_CERT_FLAG_SUITEB_128_LOS_ONLY = $10000; (* Suite B 192 bit only mode *) SSL_CERT_FLAG_SUITEB_192_LOS = $20000; (* Suite B 128 bit mode allowing 192 bit algorithms *) SSL_CERT_FLAG_SUITEB_128_LOS = $30000; (* Perform all sorts of protocol violations for testing purposes *) SSL_CERT_FLAG_BROKEN_PROTOCOL = $10000000; (* Flags for building certificate chains *) (* Treat any existing certificates as untrusted CAs *) SSL_BUILD_CHAIN_FLAG_UNTRUSTED = $1; (* Don't include root CA in chain *) SSL_BUILD_CHAIN_FLAG_NO_ROOT = $2; (* Just check certificates already there *) SSL_BUILD_CHAIN_FLAG_CHECK = $4; (* Ignore verification errors *) SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR = $8; (* Clear verification errors from queue *) SSL_BUILD_CHAIN_FLAG_CLEAR_ERROR = $10; (* Flags returned by SSL_check_chain *) (* Certificate can be used with this session *) CERT_PKEY_VALID = $1; (* Certificate can also be used for signing *) CERT_PKEY_SIGN = $2; (* EE certificate signing algorithm OK *) CERT_PKEY_EE_SIGNATURE = $10; (* CA signature algorithms OK *) CERT_PKEY_CA_SIGNATURE = $20; (* EE certificate parameters OK *) CERT_PKEY_EE_PARAM = $40; (* CA certificate parameters OK *) CERT_PKEY_CA_PARAM = $80; (* Signing explicitly allowed as opposed to SHA1 fallback *) CERT_PKEY_EXPLICIT_SIGN = $100; (* Client CA issuer names match (always set for server cert) *) CERT_PKEY_ISSUER_NAME = $200; (* Cert type matches client types (always set for server cert) *) CERT_PKEY_CERT_TYPE = $400; (* Cert chain suitable to Suite B *) CERT_PKEY_SUITEB = $800; SSL_CONF_FLAG_CMDLINE = $1; SSL_CONF_FLAG_FILE = $2; SSL_CONF_FLAG_CLIENT = $4; SSL_CONF_FLAG_SERVER = $8; SSL_CONF_FLAG_SHOW_ERRORS = $10; SSL_CONF_FLAG_CERTIFICATE = $20; SSL_CONF_FLAG_REQUIRE_PRIVATE = $40; (* Configuration value types *) SSL_CONF_TYPE_UNKNOWN = $0; SSL_CONF_TYPE_STRING = $1; SSL_CONF_TYPE_FILE = $2; SSL_CONF_TYPE_DIR = $3; SSL_CONF_TYPE_NONE = $4; (* Maximum length of the application-controlled segment of a a TLSv1.3 cookie *) SSL_COOKIE_LENGTH = 4096; (* 100k max cert list *) SSL_MAX_CERT_LIST_DEFAULT = 1024 * 100; SSL_SESSION_CACHE_MAX_SIZE_DEFAULT = 1024 * 20; SSL_SESS_CACHE_OFF = $0000; SSL_SESS_CACHE_CLIENT = $0001; SSL_SESS_CACHE_SERVER = $0002; SSL_SESS_CACHE_BOTH = (SSL_SESS_CACHE_CLIENT or SSL_SESS_CACHE_SERVER); SSL_SESS_CACHE_NO_AUTO_CLEAR = $0080; (* enough comments already ... see SSL_CTX_set_session_cache_mode(3) *) SSL_SESS_CACHE_NO_INTERNAL_LOOKUP = $0100; SSL_SESS_CACHE_NO_INTERNAL_STORE = $0200; SSL_SESS_CACHE_NO_INTERNAL = (SSL_SESS_CACHE_NO_INTERNAL_LOOKUP or SSL_SESS_CACHE_NO_INTERNAL_STORE); OPENSSL_NPN_UNSUPPORTED = 0; OPENSSL_NPN_NEGOTIATED = 1; OPENSSL_NPN_NO_OVERLAP = 2; (* * the maximum length of the buffer given to callbacks containing the * resulting identity/psk *) PSK_MAX_IDENTITY_LEN = 128; PSK_MAX_PSK_LEN = 256; SSL_NOTHING = 1; SSL_WRITING = 2; SSL_READING = 3; SSL_X509_LOOKUP = 4; SSL_ASYNC_PAUSED = 5; SSL_ASYNC_NO_JOBS = 6; SSL_CLIENT_HELLO_CB = 7; SSL_MAC_FLAG_READ_MAC_STREAM = 1; SSL_MAC_FLAG_WRITE_MAC_STREAM = 2; (* TLSv1.3 KeyUpdate message types *) (* -1 used so that this is an invalid value for the on-the-wire protocol *) SSL_KEY_UPDATE_NONE = -1; (* Values as defined for the on-the-wire protocol *) SSL_KEY_UPDATE_NOT_REQUESTED = 0; SSL_KEY_UPDATE_REQUESTED = 1; (* * Most of the following state values are no longer used and are defined to be * the closest equivalent value in_ the current state machine code. Not all * defines have an equivalent and are set to a dummy value (-1). SSL_ST_CONNECT * and SSL_ST_ACCEPT are still in_ use in_ the definition of SSL_CB_ACCEPT_LOOP, * SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP and SSL_CB_CONNECT_EXIT. *) SSL_ST_CONNECT = $1000; SSL_ST_ACCEPT = $2000; SSL_ST_MASK = $0FFF; SSL_CB_LOOP = $01; SSL_CB_EXIT = $02; SSL_CB_READ = $04; SSL_CB_WRITE = $08; SSL_CB_ALERT = $4000; SSL_CB_READ_ALERT = SSL_CB_ALERT or SSL_CB_READ; SSL_CB_WRITE_ALERT = SSL_CB_ALERT or SSL_CB_WRITE; SSL_CB_ACCEPT_LOOP = SSL_ST_ACCEPT or SSL_CB_LOOP; SSL_CB_ACCEPT_EXIT = SSL_ST_ACCEPT or SSL_CB_EXIT; SSL_CB_CONNECT_LOOP = SSL_ST_CONNECT or SSL_CB_LOOP; SSL_CB_CONNECT_EXIT = SSL_ST_CONNECT or SSL_CB_EXIT; SSL_CB_HANDSHAKE_START = $10; SSL_CB_HANDSHAKE_DONE = $20; (* * The following 3 states are kept in ssl->rlayer.rstate when reads fail, you * should not need these *) SSL_ST_READ_HEADER = $F0; SSL_ST_READ_BODY = $F1; SSL_ST_READ_DONE = $F2; (* * use either SSL_VERIFY_NONE or SSL_VERIFY_PEER, the last 3 options are * 'ored' with SSL_VERIFY_PEER if they are desired *) SSL_VERIFY_NONE = $00; SSL_VERIFY_PEER = $01; SSL_VERIFY_FAIL_IF_NO_PEER_CERT = $02; SSL_VERIFY_CLIENT_ONCE = $04; SSL_VERIFY_POST_HANDSHAKE = $08; SSL_AD_REASON_OFFSET = 1000; (* offset to get SSL_R_... value * from SSL_AD_... *) (* These alert types are for SSLv3 and TLSv1 *) SSL_AD_CLOSE_NOTIFY = SSL3_AD_CLOSE_NOTIFY; (* fatal *) SSL_AD_UNEXPECTED_MESSAGE = SSL3_AD_UNEXPECTED_MESSAGE; (* fatal *) SSL_AD_BAD_RECORD_MAC = SSL3_AD_BAD_RECORD_MAC; SSL_AD_DECRYPTION_FAILED = TLS1_AD_DECRYPTION_FAILED; SSL_AD_RECORD_OVERFLOW = TLS1_AD_RECORD_OVERFLOW; (* fatal *) SSL_AD_DECOMPRESSION_FAILURE = SSL3_AD_DECOMPRESSION_FAILURE; (* fatal *) SSL_AD_HANDSHAKE_FAILURE = SSL3_AD_HANDSHAKE_FAILURE; (* Not for TLS *) SSL_AD_NO_CERTIFICATE = SSL3_AD_NO_CERTIFICATE; SSL_AD_BAD_CERTIFICATE = SSL3_AD_BAD_CERTIFICATE; SSL_AD_UNSUPPORTED_CERTIFICATE = SSL3_AD_UNSUPPORTED_CERTIFICATE; SSL_AD_CERTIFICATE_REVOKED = SSL3_AD_CERTIFICATE_REVOKED; SSL_AD_CERTIFICATE_EXPIRED = SSL3_AD_CERTIFICATE_EXPIRED; SSL_AD_CERTIFICATE_UNKNOWN = SSL3_AD_CERTIFICATE_UNKNOWN; (* fatal *) SSL_AD_ILLEGAL_PARAMETER = SSL3_AD_ILLEGAL_PARAMETER; (* fatal *) SSL_AD_UNKNOWN_CA = TLS1_AD_UNKNOWN_CA; (* fatal *) SSL_AD_ACCESS_DENIED = TLS1_AD_ACCESS_DENIED; (* fatal *) SSL_AD_DECODE_ERROR = TLS1_AD_DECODE_ERROR; SSL_AD_DECRYPT_ERROR = TLS1_AD_DECRYPT_ERROR; (* fatal *) SSL_AD_EXPORT_RESTRICTION = TLS1_AD_EXPORT_RESTRICTION; (* fatal *) SSL_AD_PROTOCOL_VERSION = TLS1_AD_PROTOCOL_VERSION; (* fatal *) SSL_AD_INSUFFICIENT_SECURITY = TLS1_AD_INSUFFICIENT_SECURITY; (* fatal *) SSL_AD_INTERNAL_ERROR = TLS1_AD_INTERNAL_ERROR; SSL_AD_USER_CANCELLED = TLS1_AD_USER_CANCELLED; SSL_AD_NO_RENEGOTIATION = TLS1_AD_NO_RENEGOTIATION; SSL_AD_MISSING_EXTENSION = TLS13_AD_MISSING_EXTENSION; SSL_AD_CERTIFICATE_REQUIRED = TLS13_AD_CERTIFICATE_REQUIRED; SSL_AD_UNSUPPORTED_EXTENSION = TLS1_AD_UNSUPPORTED_EXTENSION; SSL_AD_CERTIFICATE_UNOBTAINABLE = TLS1_AD_CERTIFICATE_UNOBTAINABLE; SSL_AD_UNRECOGNIZED_NAME = TLS1_AD_UNRECOGNIZED_NAME; SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE = TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE; SSL_AD_BAD_CERTIFICATE_HASH_VALUE = TLS1_AD_BAD_CERTIFICATE_HASH_VALUE; (* fatal *) SSL_AD_UNKNOWN_PSK_IDENTITY = TLS1_AD_UNKNOWN_PSK_IDENTITY; (* fatal *) SSL_AD_INAPPROPRIATE_FALLBACK = TLS1_AD_INAPPROPRIATE_FALLBACK; SSL_AD_NO_APPLICATION_PROTOCOL = TLS1_AD_NO_APPLICATION_PROTOCOL; SSL_ERROR_NONE = 0; SSL_ERROR_SSL = 1; SSL_ERROR_WANT_READ = 2; SSL_ERROR_WANT_WRITE = 3; SSL_ERROR_WANT_X509_LOOKUP = 4; SSL_ERROR_SYSCALL = 5; (* look at error stack/return * value/errno *) SSL_ERROR_ZERO_RETURN = 6; SSL_ERROR_WANT_CONNECT = 7; SSL_ERROR_WANT_ACCEPT = 8; SSL_ERROR_WANT_ASYNC = 9; SSL_ERROR_WANT_ASYNC_JOB = 10; SSL_ERROR_WANT_CLIENT_HELLO_CB = 11; SSL_CTRL_SET_TMP_DH = 3; SSL_CTRL_SET_TMP_ECDH = 4; SSL_CTRL_SET_TMP_DH_CB = 6; SSL_CTRL_GET_CLIENT_CERT_REQUEST = 9; SSL_CTRL_GET_NUM_RENEGOTIATIONS = 10; SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS = 11; SSL_CTRL_GET_TOTAL_RENEGOTIATIONS = 12; SSL_CTRL_GET_FLAGS = 13; SSL_CTRL_EXTRA_CHAIN_CERT = 14; SSL_CTRL_SET_MSG_CALLBACK = 15; SSL_CTRL_SET_MSG_CALLBACK_ARG = 16; (* only applies to datagram connections *) SSL_CTRL_SET_MTU = 17; (* Stats *) SSL_CTRL_SESS_NUMBER = 20; SSL_CTRL_SESS_CONNECT = 21; SSL_CTRL_SESS_CONNECT_GOOD = 22; SSL_CTRL_SESS_CONNECT_RENEGOTIATE = 23; SSL_CTRL_SESS_ACCEPT = 24; SSL_CTRL_SESS_ACCEPT_GOOD = 25; SSL_CTRL_SESS_ACCEPT_RENEGOTIATE = 26; SSL_CTRL_SESS_HIT = 27; SSL_CTRL_SESS_CB_HIT = 28; SSL_CTRL_SESS_MISSES = 29; SSL_CTRL_SESS_TIMEOUTS = 30; SSL_CTRL_SESS_CACHE_FULL = 31; SSL_CTRL_MODE = 33; SSL_CTRL_GET_READ_AHEAD = 40; SSL_CTRL_SET_READ_AHEAD = 41; SSL_CTRL_SET_SESS_CACHE_SIZE = 42; SSL_CTRL_GET_SESS_CACHE_SIZE = 43; SSL_CTRL_SET_SESS_CACHE_MODE = 44; SSL_CTRL_GET_SESS_CACHE_MODE = 45; SSL_CTRL_GET_MAX_CERT_LIST = 50; SSL_CTRL_SET_MAX_CERT_LIST = 51; SSL_CTRL_SET_MAX_SEND_FRAGMENT = 52; (* see tls1.h for macros based on these *) SSL_CTRL_SET_TLSEXT_SERVERNAME_CB = 53; SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG = 54; SSL_CTRL_SET_TLSEXT_HOSTNAME = 55; SSL_CTRL_SET_TLSEXT_DEBUG_CB = 56; SSL_CTRL_SET_TLSEXT_DEBUG_ARG = 57; SSL_CTRL_GET_TLSEXT_TICKET_KEYS = 58; SSL_CTRL_SET_TLSEXT_TICKET_KEYS = 59; SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB = 63; SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB_ARG = 64; SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE = 65; SSL_CTRL_GET_TLSEXT_STATUS_REQ_EXTS = 66; SSL_CTRL_SET_TLSEXT_STATUS_REQ_EXTS = 67; SSL_CTRL_GET_TLSEXT_STATUS_REQ_IDS = 68; SSL_CTRL_SET_TLSEXT_STATUS_REQ_IDS = 69; SSL_CTRL_GET_TLSEXT_STATUS_REQ_OCSP_RESP = 70; SSL_CTRL_SET_TLSEXT_STATUS_REQ_OCSP_RESP = 71; SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB = 72; SSL_CTRL_SET_TLS_EXT_SRP_USERNAME_CB = 75; SSL_CTRL_SET_SRP_VERIFY_PARAM_CB = 76; SSL_CTRL_SET_SRP_GIVE_CLIENT_PWD_CB = 77; SSL_CTRL_SET_SRP_ARG = 78; SSL_CTRL_SET_TLS_EXT_SRP_USERNAME = 79; SSL_CTRL_SET_TLS_EXT_SRP_STRENGTH = 80; SSL_CTRL_SET_TLS_EXT_SRP_PASSWORD = 81; SSL_CTRL_DTLS_EXT_SEND_HEARTBEAT = 85; SSL_CTRL_GET_DTLS_EXT_HEARTBEAT_PENDING = 86; SSL_CTRL_SET_DTLS_EXT_HEARTBEAT_NO_REQUESTS = 87; DTLS_CTRL_GET_TIMEOUT = 73; DTLS_CTRL_HANDLE_TIMEOUT = 74; SSL_CTRL_GET_RI_SUPPORT = 76; SSL_CTRL_CLEAR_MODE = 78; SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB = 79; SSL_CTRL_GET_EXTRA_CHAIN_CERTS = 82; SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS = 83; SSL_CTRL_CHAIN = 88; SSL_CTRL_CHAIN_CERT = 89; SSL_CTRL_GET_GROUPS = 90; SSL_CTRL_SET_GROUPS = 91; SSL_CTRL_SET_GROUPS_LIST = 92; SSL_CTRL_GET_SHARED_GROUP = 93; SSL_CTRL_SET_SIGALGS = 97; SSL_CTRL_SET_SIGALGS_LIST = 98; SSL_CTRL_CERT_FLAGS = 99; SSL_CTRL_CLEAR_CERT_FLAGS = 100; SSL_CTRL_SET_CLIENT_SIGALGS = 101; SSL_CTRL_SET_CLIENT_SIGALGS_LIST = 102; SSL_CTRL_GET_CLIENT_CERT_TYPES = 103; SSL_CTRL_SET_CLIENT_CERT_TYPES = 104; SSL_CTRL_BUILD_CERT_CHAIN = 105; SSL_CTRL_SET_VERIFY_CERT_STORE = 106; SSL_CTRL_SET_CHAIN_CERT_STORE = 107; SSL_CTRL_GET_PEER_SIGNATURE_NID = 108; SSL_CTRL_GET_PEER_TMP_KEY = 109; SSL_CTRL_GET_RAW_CIPHERLIST = 110; SSL_CTRL_GET_EC_POINT_FORMATS = 111; SSL_CTRL_GET_CHAIN_CERTS = 115; SSL_CTRL_SELECT_CURRENT_CERT = 116; SSL_CTRL_SET_CURRENT_CERT = 117; SSL_CTRL_SET_DH_AUTO = 118; DTLS_CTRL_SET_LINK_MTU = 120; DTLS_CTRL_GET_LINK_MIN_MTU = 121; SSL_CTRL_GET_EXTMS_SUPPORT = 122; SSL_CTRL_SET_MIN_PROTO_VERSION = 123; SSL_CTRL_SET_MAX_PROTO_VERSION = 124; SSL_CTRL_SET_SPLIT_SEND_FRAGMENT = 125; SSL_CTRL_SET_MAX_PIPELINES = 126; SSL_CTRL_GET_TLSEXT_STATUS_REQ_TYPE = 127; SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB = 128; SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB_ARG = 129; SSL_CTRL_GET_MIN_PROTO_VERSION = 130; SSL_CTRL_GET_MAX_PROTO_VERSION = 131; SSL_CTRL_GET_SIGNATURE_NID = 132; SSL_CTRL_GET_TMP_KEY = 133; SSL_CERT_SET_FIRST = 1; SSL_CERT_SET_NEXT = 2; SSL_CERT_SET_SERVER = 3; (* * The following symbol names are old and obsolete. They are kept * for compatibility reasons only and should not be used anymore. *) SSL_CTRL_GET_CURVES = SSL_CTRL_GET_GROUPS; SSL_CTRL_SET_CURVES = SSL_CTRL_SET_GROUPS; SSL_CTRL_SET_CURVES_LIST = SSL_CTRL_SET_GROUPS_LIST; SSL_CTRL_GET_SHARED_CURVE = SSL_CTRL_GET_SHARED_GROUP; // SSL_get1_curves = SSL_get1_groups; // SSL_CTX_set1_curves = SSL_CTX_set1_groups; // SSL_CTX_set1_curves_list = SSL_CTX_set1_groups_list; // SSL_set1_curves = SSL_set1_groups; // SSL_set1_curves_list = SSL_set1_groups_list; // SSL_get_shared_curve = SSL_get_shared_group; (* serverinfo file format versions *) SSL_SERVERINFOV1 = 1; SSL_SERVERINFOV2 = 2; SSL_CLIENT_HELLO_SUCCESS = 1; SSL_CLIENT_HELLO_ERROR = 0; SSL_CLIENT_HELLO_RETRY = -1; SSL_READ_EARLY_DATA_ERROR = 0; SSL_READ_EARLY_DATA_SUCCESS = 1; SSL_READ_EARLY_DATA_FINISH = 2; SSL_EARLY_DATA_NOT_SENT = 0; SSL_EARLY_DATA_REJECTED = 1; SSL_EARLY_DATA_ACCEPTED = 2; //SSLv23_method = TLS_method; //SSLv23_server_method = TLS_server_method; //SSLv23_client_method = TLS_client_method; (* What the 'other' parameter contains in_ security callback *) (* Mask for type *) SSL_SECOP_OTHER_TYPE = $ffff0000; SSL_SECOP_OTHER_NONE = 0; SSL_SECOP_OTHER_CIPHER = (1 shl 16); SSL_SECOP_OTHER_CURVE = (2 shl 16); SSL_SECOP_OTHER_DH = (3 shl 16); SSL_SECOP_OTHER_PKEY = (4 shl 16); SSL_SECOP_OTHER_SIGALG = (5 shl 16); SSL_SECOP_OTHER_CERT = (6 shl 16); (* Indicated operation refers to peer key or certificate *) SSL_SECOP_PEER = $1000; (* Values for "op" parameter in security callback *) (* Called to filter ciphers *) (* Ciphers client supports *) SSL_SECOP_CIPHER_SUPPORTED = 1 or SSL_SECOP_OTHER_CIPHER; (* Cipher shared by client/server *) SSL_SECOP_CIPHER_SHARED = 2 or SSL_SECOP_OTHER_CIPHER; (* Sanity check of cipher server selects *) SSL_SECOP_CIPHER_CHECK = 3 or SSL_SECOP_OTHER_CIPHER; (* Curves supported by client *) SSL_SECOP_CURVE_SUPPORTED = 4 or SSL_SECOP_OTHER_CURVE; (* Curves shared by client/server *) SSL_SECOP_CURVE_SHARED = 5 or SSL_SECOP_OTHER_CURVE; (* Sanity check of curve server selects *) SSL_SECOP_CURVE_CHECK = 6 or SSL_SECOP_OTHER_CURVE; (* Temporary DH key *) SSL_SECOP_TMP_DH = 7 or SSL_SECOP_OTHER_PKEY; (* SSL/TLS version *) SSL_SECOP_VERSION = 9 or SSL_SECOP_OTHER_NONE; (* Session tickets *) SSL_SECOP_TICKET = 10 or SSL_SECOP_OTHER_NONE; (* Supported signature algorithms sent to peer *) SSL_SECOP_SIGALG_SUPPORTED = 11 or SSL_SECOP_OTHER_SIGALG; (* Shared signature algorithm *) SSL_SECOP_SIGALG_SHARED = 12 or SSL_SECOP_OTHER_SIGALG; (* Sanity check signature algorithm allowed *) SSL_SECOP_SIGALG_CHECK = 13 or SSL_SECOP_OTHER_SIGALG; (* Used to get mask of supported public key signature algorithms *) SSL_SECOP_SIGALG_MASK = 14 or SSL_SECOP_OTHER_SIGALG; (* Use to see if compression is allowed *) SSL_SECOP_COMPRESSION = 15 or SSL_SECOP_OTHER_NONE; (* EE key in certificate *) SSL_SECOP_EE_KEY = 16 or SSL_SECOP_OTHER_CERT; (* CA key in certificate *) SSL_SECOP_CA_KEY = 17 or SSL_SECOP_OTHER_CERT; (* CA digest algorithm in certificate *) SSL_SECOP_CA_MD = 18 or SSL_SECOP_OTHER_CERT; (* Peer EE key in certificate *) SSL_SECOP_PEER_EE_KEY = SSL_SECOP_EE_KEY or SSL_SECOP_PEER; (* Peer CA key in certificate *) SSL_SECOP_PEER_CA_KEY = SSL_SECOP_CA_KEY or SSL_SECOP_PEER; (* Peer CA digest algorithm in certificate *) SSL_SECOP_PEER_CA_MD = SSL_SECOP_CA_MD or SSL_SECOP_PEER; (* OPENSSL_INIT flag 0x010000 reserved for internal use *) OPENSSL_INIT_NO_LOAD_SSL_STRINGS = TIdC_LONG($00100000); OPENSSL_INIT_LOAD_SSL_STRINGS = TIdC_LONG($00200000); OPENSSL_INIT_SSL_DEFAULT = OPENSSL_INIT_LOAD_SSL_STRINGS or OPENSSL_INIT_LOAD_CRYPTO_STRINGS; (* Support for ticket appdata *) (* fatal error, malloc failure *) SSL_TICKET_FATAL_ERR_MALLOC = 0; (* fatal error, either from parsing or decrypting the ticket *) SSL_TICKET_FATAL_ERR_OTHER = 1; (* No ticket present *) SSL_TICKET_NONE = 2; (* Empty ticket present *) SSL_TICKET_EMPTY = 3; (* the ticket couldn't be decrypted *) SSL_TICKET_NO_DECRYPT = 4; (* a ticket was successfully decrypted *) SSL_TICKET_SUCCESS = 5; (* same as above but the ticket needs to be renewed *) SSL_TICKET_SUCCESS_RENEW = 6; (* An error occurred *) SSL_TICKET_RETURN_ABORT = 0; (* Do not use the ticket, do not send a renewed ticket to the client *) SSL_TICKET_RETURN_IGNORE = 1; (* Do not use the ticket, send a renewed ticket to the client *) SSL_TICKET_RETURN_IGNORE_RENEW = 2; (* Use the ticket, do not send a renewed ticket to the client *) SSL_TICKET_RETURN_USE = 3; (* Use the ticket, send a renewed ticket to the client *) SSL_TICKET_RETURN_USE_RENEW = 4; type (* * This is needed to stop compilers complaining about the 'struct ssl_st *' * function parameters used to prototype callbacks in SSL_CTX. *) ssl_crock_st = ^ssl_st; TLS_SESSION_TICKET_EXT = tls_session_ticket_ext_st; ssl_method_st = type Pointer; SSL_METHOD = ssl_method_st; PSSL_METHOD = ^SSL_METHOD; ssl_session_st = type Pointer; SSL_CIPHER = ssl_session_st; PSSL_CIPHER = ^SSL_CIPHER; SSL_SESSION = ssl_session_st; PSSL_SESSION = ^SSL_SESSION; PPSSL_SESSION = ^PSSL_SESSION; tls_sigalgs_st = type Pointer; TLS_SIGALGS = tls_sigalgs_st; ssl_conf_ctx_st = type Pointer; SSL_CONF_CTX = ssl_conf_ctx_st; PSSL_CONF_CTX = ^SSL_CONF_CTX; ssl_comp_st = type Pointer; SSL_COMP = ssl_comp_st; //STACK_OF(SSL_CIPHER); //STACK_OF(SSL_COMP); (* SRTP protection profiles for use with the use_srtp extension (RFC 5764)*) srtp_protection_profile_st = record name: PIdAnsiChar; id: TIdC_ULONG; end; SRTP_PROTECTION_PROFILE = srtp_protection_profile_st; PSRTP_PROTECTION_PROFILE = ^SRTP_PROTECTION_PROFILE; //DEFINE_STACK_OF(SRTP_PROTECTION_PROFILE) (* Typedefs for handling custom extensions *) custom_ext_add_cb = function (s: PSSL; ext_type: TIdC_UINT; const out_: PByte; outlen: PIdC_SIZET; al: PIdC_INT; add_arg: Pointer): TIdC_INT; cdecl; custom_ext_free_cb = procedure (s: PSSL; ext_type: TIdC_UINT; const out_: PByte; add_arg: Pointer); cdecl; custom_ext_parse_cb = function (s: PSSL; ext_type: TIdC_UINT; const in_: PByte; inlen: TIdC_SIZET; al: PIdC_INT; parse_arg: Pointer): TIdC_INT; cdecl; SSL_custom_ext_add_cb_ex = function (s: PSSL; ext_type: TIdC_UINT; context: TIdC_UINT; const out_: PByte; outlen: PIdC_SIZET; x: Px509; chainidx: TIdC_SIZET; al: PIdC_INT; add_arg: Pointer): TIdC_INT; cdecl; SSL_custom_ext_free_cb_ex = procedure (s: PSSL; ext_type: TIdC_UINT; context: TIdC_UINT; const out_: PByte; add_arg: Pointer); cdecl; SSL_custom_ext_parse_cb_ex = function (s: PSSL; ext_type: TIdC_UINT; context: TIdC_UINT; const in_: PByte; inlen: TIdC_SIZET; x: Px509; chainidx: TIdC_SIZET; al: PIdC_INT; parse_arg: Pointer): TIdC_INT; cdecl; (* Typedef for verification callback *) SSL_verify_cb = function (preverify_ok: TIdC_INT; x509_ctx: PX509_STORE_CTX): TIdC_INT; cdecl; tls_session_ticket_ext_cb_fn = function (s: PSSL; const data: PByte; len: TIdC_INT; arg: Pointer): TIdC_INT; cdecl; (* * This callback type is used inside SSL_CTX, SSL, and in_ the functions that * set them. It is used to override the generation of SSL/TLS session IDs in_ * a server. Return value should be zero on an error, non-zero to proceed. * Also, callbacks should themselves check if the id they generate is unique * otherwise the SSL handshake will fail with an error - callbacks can do * this using the 'ssl' value they're passed by; * SSL_has_matching_session_id(ssl, id, *id_len) The length value passed in_ * is set at the maximum size the session ID can be. in_ SSLv3/TLSv1 it is 32 * bytes. The callback can alter this length to be less if desired. It is * also an error for the callback to set the size to zero. *) GEN_SESSION_CB = function (ssl: PSSL; id: PByte; id_len: PIdC_UINT): TIdC_INT; cdecl; SSL_CTX_info_callback = procedure (const ssl: PSSL; type_: TIdC_INT; val: TIdC_INT); cdecl; SSL_CTX_client_cert_cb = function (ssl: PSSL; x509: PPx509; pkey: PPEVP_PKEY): TIdC_INT; cdecl; SSL_CTX_cookie_verify_cb = function (ssl: PSSL; cookie: PByte; cookie_len: PIdC_UINT): TIdC_INT; cdecl; SSL_CTX_set_cookie_verify_cb_app_verify_cookie_cb = function (ssl: PSSL; const cookie: PByte; cookie_len: TIdC_UINT): TIdC_INT; cdecl; SSL_CTX_set_stateless_cookie_generate_cb_gen_stateless_cookie_cb = function (ssl: PSSL; cookie: PByte; cookie_len: PIdC_SIZET): TIdC_INT; cdecl; SSL_CTX_set_stateless_cookie_verify_cb_verify_stateless_cookie_cb = function (ssl: PSSL; const cookie: PByte; cookie_len: TIdC_SIZET): TIdC_INT; cdecl; SSL_CTX_alpn_select_cb_func = function (ssl: PSSL; const out_: PPByte; outlen: PByte; const in_: PByte; inlen: TIdC_UINT; arg: Pointer): TIdC_INT; cdecl; SSL_psk_client_cb_func = function (ssl: PSSL; const hint: PIdAnsiChar; identity: PIdAnsiChar; max_identity_len: TIdC_UINT; psk: PByte; max_psk_len: TIdC_UINT): TIdC_UINT; cdecl; SSL_psk_server_cb_func = function (ssl: PSSL; const identity: PIdAnsiChar; psk: PByte; max_psk_len: TIdC_UINT): TIdC_UINT; cdecl; SSL_psk_find_session_cb_func = function (ssl: PSSL; const identity: PByte; identity_len: TIdC_SIZET; sess: PPSSL_SESSION): TIdC_INT; cdecl; SSL_psk_use_session_cb_func = function (ssl: PSSL; const md: PEVP_MD; const id: PPByte; idlen: PIdC_SIZET; sess: PPSSL_SESSION): TIdC_INT; cdecl; (* * A callback for logging out TLS key material. This callback should log out * |line| followed by a newline. *) SSL_CTX_keylog_cb_func = procedure(const ssl: PSSL; const line: PIdAnsiChar); cdecl; (* * The valid handshake states (one for each type message sent and one for each * type of message received). There are also two "special" states: * TLS = TLS or DTLS state * DTLS = DTLS specific state * CR/SR = Client Read/Server Read * CW/SW = Client Write/Server Write * * The "special" states are: * TLS_ST_BEFORE = No handshake has been initiated yet * TLS_ST_OK = A handshake has been successfully completed *) TLS_ST_OK = ( DTLS_ST_CR_HELLO_VERIFY_REQUEST, TLS_ST_CR_SRVR_HELLO, TLS_ST_CR_CERT, TLS_ST_CR_CERT_STATUS, TLS_ST_CR_KEY_EXCH, TLS_ST_CR_CERT_REQ, TLS_ST_CR_SRVR_DONE, TLS_ST_CR_SESSION_TICKET, TLS_ST_CR_CHANGE, TLS_ST_CR_FINISHED, TLS_ST_CW_CLNT_HELLO, TLS_ST_CW_CERT, TLS_ST_CW_KEY_EXCH, TLS_ST_CW_CERT_VRFY, TLS_ST_CW_CHANGE, TLS_ST_CW_NEXT_PROTO, TLS_ST_CW_FINISHED, TLS_ST_SW_HELLO_REQ, TLS_ST_SR_CLNT_HELLO, DTLS_ST_SW_HELLO_VERIFY_REQUEST, TLS_ST_SW_SRVR_HELLO, TLS_ST_SW_CERT, TLS_ST_SW_KEY_EXCH, TLS_ST_SW_CERT_REQ, TLS_ST_SW_SRVR_DONE, TLS_ST_SR_CERT, TLS_ST_SR_KEY_EXCH, TLS_ST_SR_CERT_VRFY, TLS_ST_SR_NEXT_PROTO, TLS_ST_SR_CHANGE, TLS_ST_SR_FINISHED, TLS_ST_SW_SESSION_TICKET, TLS_ST_SW_CERT_STATUS, TLS_ST_SW_CHANGE, TLS_ST_SW_FINISHED, TLS_ST_SW_ENCRYPTED_EXTENSIONS, TLS_ST_CR_ENCRYPTED_EXTENSIONS, TLS_ST_CR_CERT_VRFY, TLS_ST_SW_CERT_VRFY, TLS_ST_CR_HELLO_REQ, TLS_ST_SW_KEY_UPDATE, TLS_ST_CW_KEY_UPDATE, TLS_ST_SR_KEY_UPDATE, TLS_ST_CR_KEY_UPDATE, TLS_ST_EARLY_DATA, TLS_ST_PENDING_EARLY_DATA_END, TLS_ST_CW_END_OF_EARLY_DATA ); OSSL_HANDSHAKE_STATE = TLS_ST_OK; SSL_CTX_set_cert_verify_callback_cb = function (v1: PX509_STORE_CTX; v2: Pointer): TIdC_INT; cdecl; SSL_CTX_set_cert_cb_cb = function (ssl: PSSL; arg: Pointer): TIdC_INT; cdecl; SSL_CTX_set_srp_client_pwd_callback_cb = function (v1: PSSL; v2: Pointer): PIdAnsiChar; cdecl; SSL_CTX_set_srp_verify_param_callback_cb = function (v1: PSSL; v2: Pointer): TIdC_INT; cdecl; SSL_CTX_set_srp_username_callback_cb = function (v1: PSSL; v2: PIdC_INT; v3: Pointer): TIdC_INT; cdecl; SSL_client_hello_cb_fn = function (s: PSSL; al: PIdC_INT; arg: Pointer): TIdC_INT; cdecl; SSL_callback_ctrl_v3 = procedure; cdecl; SSL_CTX_callback_ctrl_v3 = procedure; cdecl; SSL_info_callback = procedure (const ssl: PSSL; type_: TIdC_INT; val: TIdC_INT); cdecl; (* NB: the |keylength| is only applicable when is_export is true *) SSL_CTX_set_tmp_dh_callback_dh = function (ssl: PSSL; is_export: TIdC_INT; keylength: TIdC_INT): PDH; cdecl; SSL_set_tmp_dh_callback_dh = function (ssl: PSSL; is_export: TIdC_INT; keylength: TIdC_INT): PDH; cdecl; SSL_CTX_set_not_resumable_session_callback_cb = function (ssl: PSSL; is_forward_secure: TIdC_INT): TIdC_INT; cdecl; SSL_set_not_resumable_session_callback_cb = function (ssl: PSSL; is_forward_secure: TIdC_INT): TIdC_INT; cdecl; SSL_CTX_set_record_padding_callback_cb = function (ssl: PSSL; type_: TIdC_INT; len: TIdC_SIZET; arg: Pointer): TIdC_SIZET; cdecl; SSL_set_record_padding_callback_cb = function (ssl: PSSL; type_: TIdC_INT; len: TIdC_SIZET; arg: Pointer): TIdC_SIZET; cdecl; (* * The validation type enumerates the available behaviours of the built-in SSL * CT validation callback selected via SSL_enable_ct() and SSL_CTX_enable_ct(). * The underlying callback is a static function in libssl. *) SSL_CT_VALIDATION = ( SSL_CT_VALIDATION_PERMISSIVE = 0, SSL_CT_VALIDATION_STRICT ); SSL_security_callback = function (const s: PSSL; const ctx: PSSL_CTX; op: TIdC_INT; bits: TIdC_INT; nid: TIdC_INT; other: Pointer; ex: Pointer): TIdC_INT; cdecl; (* Status codes passed to the decrypt session ticket callback. Some of these * are for internal use only and are never passed to the callback. *) SSL_TICKET_STATUS = TIdC_INT; SSL_TICKET_RETURN = TIdC_INT; SSL_CTX_generate_session_ticket_fn = function(s: PSSL; arg: Pointer): TIdC_INT; cdecl; SSL_CTX_decrypt_session_ticket_fn = function (s: PSSL; ss: PSSL_SESSION; const keyname: PByte; keyname_length: TIdC_SIZET; status: SSL_TICKET_STATUS; arg: Pointer): SSL_TICKET_RETURN; cdecl; DTLS_timer_cb = function(s: PSSL; timer_us: TIdC_UINT): TIdC_UINT; cdecl; SSL_allow_early_data_cb_fn = function(s: PSSL; arg: Pointer): TIdC_INT; cdecl; SSL_CTX_sess_new_cb = function (ssl: PSSL; sess: PSSL_SESSION): TIdC_INT; cdecl; SSL_CTX_sess_remove_cb = procedure(ctx: PSSL_CTX; sess: PSSL_SESSION); cdecl; function SSL_CTX_set_mode(ctx: PSSL_CTX; op: TIdC_LONG): TIdC_LONG; function SSL_CTX_clear_mode(ctx: PSSL_CTX; op: TIdC_LONG): TIdC_LONG; function SSL_CTX_sess_set_cache_size(ctx: PSSL_CTX; t: TIdC_LONG): TIdC_LONG; function SSL_CTX_sess_get_cache_size(ctx: PSSL_CTX): TIdC_LONG; function SSL_CTX_set_session_cache_mode(ctx: PSSL_CTX; m: TIdC_LONG): TIdC_LONG; function SSL_CTX_get_session_cache_mode(ctx: PSSL_CTX): TIdC_LONG; function SSL_num_renegotiations(ssl: PSSL): TIdC_LONG; function SSL_clear_num_renegotiations(ssl: PSSL): TIdC_LONG; function SSL_total_renegotiations(ssl: PSSL): TIdC_LONG; function SSL_CTX_set_tmp_dh(ctx: PSSL_CTX; dh: PByte): TIdC_LONG; function SSL_CTX_set_tmp_ecdh(ctx: PSSL_CTX; ecdh: PByte): TIdC_LONG; function SSL_CTX_set_dh_auto(ctx: PSSL_CTX; onoff: TIdC_LONG): TIdC_LONG; function SSL_set_dh_auto(s: PSSL; onoff: TIdC_LONG): TIdC_LONG; function SSL_set_tmp_dh(ssl: PSSL; dh: PByte): TIdC_LONG; function SSL_set_tmp_ecdh(ssl: PSSL; ecdh: PByte): TIdC_LONG; function SSL_CTX_add_extra_chain_cert(ctx: PSSL_CTX; x509: PByte): TIdC_LONG; function SSL_CTX_get_extra_chain_certs(ctx: PSSL_CTX; px509: Pointer): TIdC_LONG; function SSL_CTX_get_extra_chain_certs_only(ctx: PSSL_CTX; px509: Pointer): TIdC_LONG; function SSL_CTX_clear_extra_chain_certs(ctx: PSSL_CTX): TIdC_LONG; function SSL_CTX_set0_chain(ctx: PSSL_CTX; sk: PByte): TIdC_LONG; function SSL_CTX_set1_chain(ctx: PSSL_CTX; sk: PByte): TIdC_LONG; function SSL_CTX_add0_chain_cert(ctx: PSSL_CTX; x509: PByte): TIdC_LONG; function SSL_CTX_add1_chain_cert(ctx: PSSL_CTX; x509: PByte): TIdC_LONG; function SSL_CTX_get0_chain_certs(ctx: PSSL_CTX; px509: Pointer): TIdC_LONG; function SSL_CTX_clear_chain_certs(ctx: PSSL_CTX): TIdC_LONG; function SSL_CTX_build_cert_chain(ctx: PSSL_CTX; flags: TIdC_LONG): TIdC_LONG; function SSL_CTX_select_current_cert(ctx: PSSL_CTX; x509: PByte): TIdC_LONG; function SSL_CTX_set_current_cert(ctx: PSSL_CTX; op: TIdC_LONG): TIdC_LONG; function SSL_CTX_set0_verify_cert_store(ctx: PSSL_CTX; st: Pointer): TIdC_LONG; function SSL_CTX_set1_verify_cert_store(ctx: PSSL_CTX; st: Pointer): TIdC_LONG; function SSL_CTX_set0_chain_cert_store(ctx: PSSL_CTX; st: Pointer): TIdC_LONG; function SSL_CTX_set1_chain_cert_store(ctx: PSSL_CTX; st: Pointer): TIdC_LONG; function SSL_set0_chain(s: PSSL; sk: PByte): TIdC_LONG; function SSL_set1_chain(s: PSSL; sk: PByte): TIdC_LONG; function SSL_add0_chain_cert(s: PSSL; x509: PByte): TIdC_LONG; function SSL_add1_chain_cert(s: PSSL; x509: PByte): TIdC_LONG; function SSL_get0_chain_certs(s: PSSL; px509: Pointer): TIdC_LONG; function SSL_clear_chain_certs(s: PSSL): TIdC_LONG; function SSL_build_cert_chain(s: PSSL; flags: TIdC_LONG): TIdC_LONG; function SSL_select_current_cert(s: PSSL; x509: PByte): TIdC_LONG; function SSL_set_current_cert(s: PSSL; op: TIdC_LONG): TIdC_LONG; function SSL_set0_verify_cert_store(s: PSSL; st: PByte): TIdC_LONG; function SSL_set1_verify_cert_store(s: PSSL; st: PByte): TIdC_LONG; function SSL_set0_chain_cert_store(s: PSSL; st: PByte): TIdC_LONG; function SSL_set1_chain_cert_store(s: PSSL; st: PByte): TIdC_LONG; function SSL_get1_groups(s: PSSL; glist: PIdC_INT): TIdC_LONG; function SSL_CTX_set1_groups(ctx: PSSL_CTX; glist: PByte; glistlen: TIdC_LONG): TIdC_LONG; function SSL_CTX_set1_groups_list(ctx: PSSL_CTX; s: PByte): TIdC_LONG; function SSL_set1_groups(s: PSSL; glist: PByte; glistlen: TIdC_LONG): TIdC_LONG; function SSL_set1_groups_list(s: PSSL; str: PByte): TIdC_LONG; function SSL_get_shared_group(s: PSSL; n: TIdC_LONG): TIdC_LONG; function SSL_CTX_set1_sigalgs(ctx: PSSL_CTX; slist: PIdC_INT; slistlen: TIdC_LONG): TIdC_LONG; function SSL_CTX_set1_sigalgs_list(ctx: PSSL_CTX; s: PByte): TIdC_LONG; function SSL_set1_sigalgs(s: PSSL; slist: PIdC_INT; slistlen: TIdC_LONG): TIdC_LONG; function SSL_set1_sigalgs_list(s: PSSL; str: PByte): TIdC_LONG; function SSL_CTX_set1_client_sigalgs(ctx: PSSL_CTX; slist: PIdC_INT; slistlen: TIdC_LONG): TIdC_LONG; function SSL_CTX_set1_client_sigalgs_list(ctx: PSSL_CTX; s: PByte): TIdC_LONG; function SSL_set1_client_sigalgs(s: PSSL; slist: PIdC_INT; slistlen: TIdC_LONG): TIdC_LONG; function SSL_set1_client_sigalgs_list(s: PSSL; str: PByte): TIdC_LONG; function SSL_get0_certificate_types(s: PSSL; clist: PByte): TIdC_LONG; function SSL_CTX_set1_client_certificate_types(ctx: PSSL_CTX; clist: PByte; clistlen: TIdC_LONG): TIdC_LONG; function SSL_set1_client_certificate_types(s: PSSL; clist: PByte; clistlen: TIdC_LONG): TIdC_LONG; function SSL_get_signature_nid(s: PSSL; pn: Pointer): TIdC_LONG; function SSL_get_peer_signature_nid(s: PSSL; pn: Pointer): TIdC_LONG; function SSL_get_peer_tmp_key(s: PSSL; pk: Pointer): TIdC_LONG; function SSL_get_tmp_key(s: PSSL; pk: Pointer): TIdC_LONG; function SSL_get0_raw_cipherlist(s: PSSL; plst: Pointer): TIdC_LONG; function SSL_get0_ec_point_formats(s: PSSL; plst: Pointer): TIdC_LONG; function SSL_CTX_set_min_proto_version(ctx: PSSL_CTX; version: TIdC_LONG): TIdC_LONG; function SSL_CTX_set_max_proto_version(ctx: PSSL_CTX; version: TIdC_LONG): TIdC_LONG; function SSL_CTX_get_min_proto_version(ctx: PSSL_CTX): TIdC_LONG; function SSL_CTX_get_max_proto_version(ctx: PSSL_CTX): TIdC_LONG; function SSL_set_min_proto_version(s: PSSL; version: TIdC_LONG): TIdC_LONG; function SSL_set_max_proto_version(s: PSSL; version: TIdC_LONG): TIdC_LONG; function SSL_get_min_proto_version(s: PSSL): TIdC_LONG; function SSL_get_max_proto_version(s: PSSL): TIdC_LONG; //typedef TIdC_INT (*tls_session_secret_cb_fn)(s: PSSL, void *secret, TIdC_INT *secret_len, // STACK_OF(SSL_CIPHER) *peer_ciphers, // const SSL_CIPHER **cipher, void *arg); function SSL_CTX_get_options(const ctx: PSSL_CTX): TIdC_ULONG cdecl; external CLibSSL; function SSL_get_options(const s: PSSL): TIdC_ULONG cdecl; external CLibSSL; function SSL_CTX_clear_options(ctx: PSSL_CTX; op: TIdC_ULONG): TIdC_ULONG cdecl; external CLibSSL; function SSL_clear_options(s: PSSL; op: TIdC_ULONG): TIdC_ULONG cdecl; external CLibSSL; function SSL_CTX_set_options(ctx: PSSL_CTX; op: TIdC_ULONG): TIdC_ULONG cdecl; external CLibSSL; function SSL_set_options(s: PSSL; op: TIdC_ULONG): TIdC_ULONG cdecl; external CLibSSL; //# define SSL_CTX_set_mode(ctx,op) \ // SSL_CTX_ctrl((ctx),SSL_CTRL_MODE,(op),NULL) //# define SSL_CTX_clear_mode(ctx,op) \ // SSL_CTX_ctrl((ctx),SSL_CTRL_CLEAR_MODE,(op),NULL) //# define SSL_CTX_get_mode(ctx) \ // SSL_CTX_ctrl((ctx),SSL_CTRL_MODE,0,NULL) //# define SSL_clear_mode(ssl,op) \ // SSL_ctrl((ssl),SSL_CTRL_CLEAR_MODE,(op),NULL) //# define SSL_set_mode(ssl,op) \ // SSL_ctrl((ssl),SSL_CTRL_MODE,(op),NULL) //# define SSL_get_mode(ssl) \ // SSL_ctrl((ssl),SSL_CTRL_MODE,0,NULL) //# define SSL_set_mtu(ssl, mtu) \ // SSL_ctrl((ssl),SSL_CTRL_SET_MTU,(mtu),NULL) //# define DTLS_set_link_mtu(ssl, mtu) \ // SSL_ctrl((ssl),DTLS_CTRL_SET_LINK_MTU,(mtu),NULL) //# define DTLS_get_link_min_mtu(ssl) \ // SSL_ctrl((ssl),DTLS_CTRL_GET_LINK_MIN_MTU,0,NULL) // //# define SSL_get_secure_renegotiation_support(ssl) \ // SSL_ctrl((ssl), SSL_CTRL_GET_RI_SUPPORT, 0, NULL) // //# ifndef OPENSSL_NO_HEARTBEATS //# define SSL_heartbeat(ssl) \ // SSL_ctrl((ssl),SSL_CTRL_DTLS_EXT_SEND_HEARTBEAT,0,NULL) //# endif // //# define SSL_CTX_set_cert_flags(ctx,op) \ // SSL_CTX_ctrl((ctx),SSL_CTRL_CERT_FLAGS,(op),NULL) //# define SSL_set_cert_flags(s,op) \ // SSL_ctrl((s),SSL_CTRL_CERT_FLAGS,(op),NULL) //# define SSL_CTX_clear_cert_flags(ctx,op) \ // SSL_CTX_ctrl((ctx),SSL_CTRL_CLEAR_CERT_FLAGS,(op),NULL) //# define SSL_clear_cert_flags(s,op) \ // SSL_ctrl((s),SSL_CTRL_CLEAR_CERT_FLAGS,(op),NULL) // //void SSL_CTX_set_msg_callback(ctx: PSSL_CTX, // void (*cb) (TIdC_INT write_p, TIdC_INT version, // TIdC_INT content_type, const void *buf, // TIdC_SIZET len, ssl: PSSL, void *arg)); //void SSL_set_msg_callback(ssl: PSSL, // void (*cb) (TIdC_INT write_p, TIdC_INT version, // TIdC_INT content_type, const void *buf, // TIdC_SIZET len, ssl: PSSL, void *arg)); //# define SSL_CTX_set_msg_callback_arg(ctx, arg) SSL_CTX_ctrl((ctx), SSL_CTRL_SET_MSG_CALLBACK_ARG, 0, (arg)) //# define SSL_set_msg_callback_arg(ssl, arg) SSL_ctrl((ssl), SSL_CTRL_SET_MSG_CALLBACK_ARG, 0, (arg)) // //# define SSL_get_extms_support(s) \ // SSL_ctrl((s),SSL_CTRL_GET_EXTMS_SUPPORT,0,NULL) // //# ifndef OPENSSL_NO_SRP ///* see tls_srp.c */ //__owur TIdC_INT SSL_SRP_CTX_init(s: PSSL); //__owur TIdC_INT SSL_CTX_SRP_CTX_init(ctx: PSSL_CTX); //TIdC_INT SSL_SRP_CTX_free(SSL *ctx); //TIdC_INT SSL_CTX_SRP_CTX_free(ctx: PSSL_CTX); //__owur TIdC_INT SSL_srp_server_param_with_username(s: PSSL, TIdC_INT *ad); //__owur TIdC_INT SRP_Calc_A_param(s: PSSL); // # endif // LHASH_OF(SSL_SESSION) *SSL_CTX_sessions(ctx: PSSL_CTX); //# define SSL_CTX_sess_number(ctx) \ // SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_NUMBER,0,NULL) //# define SSL_CTX_sess_connect(ctx) \ // SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CONNECT,0,NULL) //# define SSL_CTX_sess_connect_good(ctx) \ // SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CONNECT_GOOD,0,NULL) //# define SSL_CTX_sess_connect_renegotiate(ctx) \ // SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CONNECT_RENEGOTIATE,0,NULL) //# define SSL_CTX_sess_accept(ctx) \ // SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_ACCEPT,0,NULL) //# define SSL_CTX_sess_accept_renegotiate(ctx) \ // SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_ACCEPT_RENEGOTIATE,0,NULL) //# define SSL_CTX_sess_accept_good(ctx) \ // SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_ACCEPT_GOOD,0,NULL) //# define SSL_CTX_sess_hits(ctx) \ // SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_HIT,0,NULL) //# define SSL_CTX_sess_cb_hits(ctx) \ // SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CB_HIT,0,NULL) //# define SSL_CTX_sess_misses(ctx) \ // SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_MISSES,0,NULL) //# define SSL_CTX_sess_timeouts(ctx) \ // SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_TIMEOUTS,0,NULL) //# define SSL_CTX_sess_cache_full(ctx) \ // SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CACHE_FULL,0,NULL) procedure SSL_CTX_sess_set_new_cb(ctx: PSSL_CTX; new_session_cb: SSL_CTX_sess_new_cb) cdecl; external CLibSSL; function SSL_CTX_sess_get_new_cb(ctx: PSSL_CTX): SSL_CTX_sess_new_cb cdecl; external CLibSSL; procedure SSL_CTX_sess_set_remove_cb(ctx: PSSL_CTX; remove_session_cb: SSL_CTX_sess_remove_cb) cdecl; external CLibSSL; function SSL_CTX_sess_get_remove_cb(ctx: PSSL_CTX): SSL_CTX_sess_remove_cb cdecl; external CLibSSL; //void SSL_CTX_sess_set_get_cb(ctx: PSSL_CTX, // SSL_SESSION *(*get_session_cb) (struct ssl_st // *ssl, // const Byte // *data, TIdC_INT len, // TIdC_INT *copy)); //SSL_SESSION *(*SSL_CTX_sess_get_get_cb(ctx: PSSL_CTX)) (struct ssl_st *ssl, // const d: PByteata, // TIdC_INT len, TIdC_INT *copy); procedure SSL_CTX_set_info_callback(ctx: PSSL_CTX; cb: SSL_CTX_info_callback) cdecl; external CLibSSL; function SSL_CTX_get_info_callback(ctx: PSSL_CTX): SSL_CTX_info_callback cdecl; external CLibSSL; procedure SSL_CTX_set_client_cert_cb(ctx: PSSL_CTX; client_cert_cb: SSL_CTX_client_cert_cb) cdecl; external CLibSSL; function SSL_CTX_get_client_cert_cb(ctx: PSSL_CTX): SSL_CTX_client_cert_cb cdecl; external CLibSSL; function SSL_CTX_set_client_cert_engine(ctx: PSSL_CTX; e: PENGINE): TIdC_INT cdecl; external CLibSSL; procedure SSL_CTX_set_cookie_generate_cb(ctx: PSSL_CTX; app_gen_cookie_cb: SSL_CTX_cookie_verify_cb) cdecl; external CLibSSL; procedure SSL_CTX_set_cookie_verify_cb(ctx: PSSL_CTX; app_verify_cookie_cb: SSL_CTX_set_cookie_verify_cb_app_verify_cookie_cb) cdecl; external CLibSSL; procedure SSL_CTX_set_stateless_cookie_generate_cb(ctx: PSSL_CTX; gen_stateless_cookie_cb: SSL_CTX_set_stateless_cookie_generate_cb_gen_stateless_cookie_cb) cdecl; external CLibSSL; procedure SSL_CTX_set_stateless_cookie_verify_cb(ctx: PSSL_CTX; verify_stateless_cookie_cb: SSL_CTX_set_stateless_cookie_verify_cb_verify_stateless_cookie_cb) cdecl; external CLibSSL; //__owur TIdC_INT SSL_CTX_set_alpn_protos(ctx: PSSL_CTX, const Byte *protos, // TIdC_UINT protos_len); //__owur TIdC_INT SSL_set_alpn_protos(ssl: PSSL, const Byte *protos, // TIdC_UINT protos_len); procedure SSL_CTX_set_alpn_select_cb(ctx: PSSL_CTX; cb: SSL_CTX_alpn_select_cb_func; arg: Pointer) cdecl; external CLibSSL; procedure SSL_get0_alpn_selected(const ssl: PSSL; const data: PPByte; len: PIdC_UINT) cdecl; external CLibSSL; procedure SSL_CTX_set_psk_client_callback(ctx: PSSL_CTX; cb: SSL_psk_client_cb_func) cdecl; external CLibSSL; procedure SSL_set_psk_client_callback(ssl: PSSL; cb: SSL_psk_client_cb_func) cdecl; external CLibSSL; procedure SSL_CTX_set_psk_server_callback(ctx: PSSL_CTX; cb: SSL_psk_server_cb_func) cdecl; external CLibSSL; procedure SSL_set_psk_server_callback(ssl: PSSL; cb: SSL_psk_server_cb_func) cdecl; external CLibSSL; //__owur TIdC_INT SSL_CTX_use_psk_identity_hint(ctx: PSSL_CTX, const PIdAnsiChar *identity_hint); //__owur TIdC_INT SSL_use_psk_identity_hint(s: PSSL, const PIdAnsiChar *identity_hint); //const PIdAnsiChar *SSL_get_psk_identity_hint(const s: PSSL); //const PIdAnsiChar *SSL_get_psk_identity(const s: PSSL); procedure SSL_set_psk_find_session_callback(s: PSSL; cb: SSL_psk_find_session_cb_func) cdecl; external CLibSSL; procedure SSL_CTX_set_psk_find_session_callback(ctx: PSSL_CTX; cb: SSL_psk_find_session_cb_func) cdecl; external CLibSSL; procedure SSL_set_psk_use_session_callback(s: PSSL; cb: SSL_psk_use_session_cb_func) cdecl; external CLibSSL; procedure SSL_CTX_set_psk_use_session_callback(ctx: PSSL_CTX; cb: SSL_psk_use_session_cb_func) cdecl; external CLibSSL; ///* Register callbacks to handle custom TLS Extensions for client or server. */ //__owur TIdC_INT SSL_CTX_has_client_custom_ext(const ctx: PSSL_CTX, // TIdC_UINT ext_type); // //__owur TIdC_INT SSL_CTX_add_client_custom_ext(ctx: PSSL_CTX, // TIdC_UINT ext_type, // custom_ext_add_cb add_cb, // custom_ext_free_cb free_cb, // void *add_arg, // custom_ext_parse_cb parse_cb, // void *parse_arg); // //__owur TIdC_INT SSL_CTX_add_server_custom_ext(ctx: PSSL_CTX, // TIdC_UINT ext_type, // custom_ext_add_cb add_cb, // custom_ext_free_cb free_cb, // void *add_arg, // custom_ext_parse_cb parse_cb, // void *parse_arg); // //__owur TIdC_INT SSL_CTX_add_custom_ext(ctx: PSSL_CTX, TIdC_UINT ext_type, // TIdC_UINT context, // SSL_custom_ext_add_cb_ex add_cb, // SSL_custom_ext_free_cb_ex free_cb, // void *add_arg, // SSL_custom_ext_parse_cb_ex parse_cb, // void *parse_arg); //__owur TIdC_INT SSL_extension_supported(TIdC_UINT ext_type); ///* These will only be used when doing non-blocking IO */ //# define SSL_want_nothing(s) (SSL_want(s) == SSL_NOTHING) //# define SSL_want_read(s) (SSL_want(s) == SSL_READING) //# define SSL_want_write(s) (SSL_want(s) == SSL_WRITING) //# define SSL_want_x509_lookup(s) (SSL_want(s) == SSL_X509_LOOKUP) //# define SSL_want_async(s) (SSL_want(s) == SSL_ASYNC_PAUSED) //# define SSL_want_async_job(s) (SSL_want(s) == SSL_ASYNC_NO_JOBS) //# define SSL_want_client_hello_cb(s) (SSL_want(s) == SSL_CLIENT_HELLO_CB) (* * SSL_CTX_set_keylog_callback configures a callback to log key material. This * is intended for debugging use with tools like Wireshark. The cb function * should log line followed by a newline. *) procedure SSL_CTX_set_keylog_callback(ctx: PSSL_CTX; cb: SSL_CTX_keylog_cb_func) cdecl; external CLibSSL; (* * SSL_CTX_get_keylog_callback returns the callback configured by * SSL_CTX_set_keylog_callback. *) function SSL_CTX_get_keylog_callback(const ctx: PSSL_CTX): SSL_CTX_keylog_cb_func cdecl; external CLibSSL; function SSL_CTX_set_max_early_data(ctx: PSSL_CTX; max_early_data: TIdC_UINT32): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_get_max_early_data(const ctx: PSSL_CTX): TIdC_UINT32 cdecl; external CLibSSL; function SSL_set_max_early_data(s: PSSL; max_early_data: TIdC_UINT32): TIdC_INT cdecl; external CLibSSL; function SSL_get_max_early_data(const s: PSSL): TIdC_UINT32 cdecl; external CLibSSL; function SSL_CTX_set_recv_max_early_data(ctx: PSSL_CTX; recv_max_early_data: TIdC_UINT32): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_get_recv_max_early_data(const ctx: PSSL_CTX): TIdC_UINT32 cdecl; external CLibSSL; function SSL_set_recv_max_early_data(s: PSSL; recv_max_early_data: TIdC_UINT32): TIdC_INT cdecl; external CLibSSL; function SSL_get_recv_max_early_data(const s: PSSL): TIdC_UINT32 cdecl; external CLibSSL; ///* // * These need to be after the above set of includes due to a compiler bug // * in_ VisualStudio 2015 // */ //DEFINE_STACK_OF_CONST(SSL_CIPHER) //DEFINE_STACK_OF(SSL_COMP) ///* compatibility */ //# define SSL_set_app_data(s,arg) (SSL_set_ex_data(s,0,(PIdAnsiChar *)(arg))) //# define SSL_get_app_data(s) (SSL_get_ex_data(s,0)) //# define SSL_SESSION_set_app_data(s,a) (SSL_SESSION_set_ex_data(s,0, \ // (PIdAnsiChar *)(a))) //# define SSL_SESSION_get_app_data(s) (SSL_SESSION_get_ex_data(s,0)) //# define SSL_CTX_get_app_data(ctx) (SSL_CTX_get_ex_data(ctx,0)) //# define SSL_CTX_set_app_data(ctx,arg) (SSL_CTX_set_ex_data(ctx,0, \ // (PIdAnsiChar *)(arg))) ///* Is the SSL_connection established? */ //# define SSL_in_connect_init(a) (SSL_in_init(a) && !SSL_is_server(a)) //# define SSL_in_accept_init(a) (SSL_in_init(a) && SSL_is_server(a)) function SSL_in_init(const s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_in_before(const s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_is_init_finished(const s: PSSL): TIdC_INT cdecl; external CLibSSL; (*- * Obtain latest Finished message * -- that we sent (SSL_get_finished) * -- that we expected from peer (SSL_get_peer_finished). * Returns length (0 == no Finished so far), copies up to 'count' bytes. *) function SSL_get_finished(const s: PSSL; buf: Pointer; count: TIdC_SIZET): TIdC_SIZET cdecl; external CLibSSL; function SSL_get_peer_finished(const s: PSSL; buf: Pointer; count: TIdC_SIZET): TIdC_SIZET cdecl; external CLibSSL; //# if OPENSSL_API_COMPAT < 0x10100000L //# define OpenSSL_add_ssl_algorithms() SSL_library_init() //# define SSLeay_add_ssl_algorithms() SSL_library_init() //# endif ///* More backward compatibility */ //# define SSL_get_cipher(s) \ // SSL_CIPHER_get_name(SSL_get_current_cipher(s)) //# define SSL_get_cipher_bits(s,np) \ // SSL_CIPHER_get_bits(SSL_get_current_cipher(s),np) //# define SSL_get_cipher_version(s) \ // SSL_CIPHER_get_version(SSL_get_current_cipher(s)) //# define SSL_get_cipher_name(s) \ // SSL_CIPHER_get_name(SSL_get_current_cipher(s)) //# define SSL_get_time(a) SSL_SESSION_get_time(a) //# define SSL_set_time(a,b) SSL_SESSION_set_time((a),(b)) //# define SSL_get_timeout(a) SSL_SESSION_get_timeout(a) //# define SSL_set_timeout(a,b) SSL_SESSION_set_timeout((a),(b)) // //# define d2i_SSL_SESSION_bio(bp,s_id) ASN1_d2i_bio_of(SSL_SESSION,SSL_SESSION_new,d2i_SSL_SESSION,bp,s_id) //# define i2d_SSL_SESSION_bio(bp,s_id) ASN1_i2d_bio_of(SSL_SESSION,i2d_SSL_SESSION,bp,s_id) //DECLARE_PEM_rw(SSL_SESSION, SSL_SESSION) //# define DTLSv1_get_timeout(ssl, arg) \ // SSL_ctrl(ssl,DTLS_CTRL_GET_TIMEOUT,0, (void *)(arg)) //# define DTLSv1_handle_timeout(ssl) \ // SSL_ctrl(ssl,DTLS_CTRL_HANDLE_TIMEOUT,0, NULL) // ///* Backwards compatibility, original 1.1.0 names */ //# define SSL_CTRL_GET_SERVER_TMP_KEY \ // SSL_CTRL_GET_PEER_TMP_KEY //# define SSL_get_server_tmp_key(s, pk) \ // SSL_get_peer_tmp_key(s, pk) //# if OPENSSL_API_COMPAT < 0x10100000L //const SSL_CTX_need_tmp_RSA = (ctx) 0; //const SSL_CTX_set_tmp_rsa = (ctx;rsa) 1; //const SSL_need_tmp_RSA = (ssl) 0; //const SSL_set_tmp_rsa = (ssl;rsa) 1; //# define SSL_CTX_set_ecdh_auto(dummy, onoff) ((onoff) != 0) //# define SSL_set_ecdh_auto(dummy, onoff) ((onoff) != 0) ///* // * We 'pretend' to call the callback to avoid warnings about unused static // * functions. // */ //# define SSL_CTX_set_tmp_rsa_callback(ctx, cb) while(0) (cb)(NULL, 0, 0) //# define SSL_set_tmp_rsa_callback(ssl, cb) while(0) (cb)(NULL, 0, 0) //# endif // function BIO_f_ssl: PBIO_METHOD cdecl; external CLibSSL; function BIO_new_ssl(ctx: PSSL_CTX; client: TIdC_INT): PBIO cdecl; external CLibSSL; function BIO_new_ssl_connect(ctx: PSSL_CTX): PBIO cdecl; external CLibSSL; function BIO_new_buffer_ssl_connect(ctx: PSSL_CTX): PBIO cdecl; external CLibSSL; function BIO_ssl_copy_session_id(to_: PBIO; from: PBIO): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_set_cipher_list(v1: PSSL_CTX; const str: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_new(const meth: PSSL_METHOD): PSSL_CTX cdecl; external CLibSSL; function SSL_CTX_set_timeout(ctx: PSSL_CTX; t: TIdC_LONG): TIdC_LONG cdecl; external CLibSSL; function SSL_CTX_get_timeout(const ctx: PSSL_CTX): TIdC_LONG cdecl; external CLibSSL; function SSL_CTX_get_cert_store(const v1: PSSL_CTX): PX509_STORE cdecl; external CLibSSL; function SSL_want(const s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_clear(s: PSSL): TIdC_INT cdecl; external CLibSSL; procedure BIO_ssl_shutdown(ssl_bio: PBIO) cdecl; external CLibSSL; function SSL_CTX_up_ref(ctx: PSSL_CTX): TIdC_INT cdecl; external CLibSSL; procedure SSL_CTX_free(v1: PSSL_CTX) cdecl; external CLibSSL; procedure SSL_CTX_set_cert_store(v1: PSSL_CTX; v2: PX509_STORE) cdecl; external CLibSSL; procedure SSL_CTX_set1_cert_store(v1: PSSL_CTX; v2: PX509_STORE) cdecl; external CLibSSL; procedure SSL_CTX_flush_sessions(ctx: PSSL_CTX; tm: TIdC_LONG) cdecl; external CLibSSL; function SSL_get_current_cipher(const s: PSSL): PSSL_CIPHER cdecl; external CLibSSL; function SSL_get_pending_cipher(const s: PSSL): PSSL_CIPHER cdecl; external CLibSSL; function SSL_CIPHER_get_bits(const c: PSSL_CIPHER; alg_bits: PIdC_INT): TIdC_INT cdecl; external CLibSSL; function SSL_CIPHER_get_version(const c: PSSL_CIPHER): PIdAnsiChar cdecl; external CLibSSL; function SSL_CIPHER_get_name(const c: PSSL_CIPHER): PIdAnsiChar cdecl; external CLibSSL; function SSL_CIPHER_standard_name(const c: PSSL_CIPHER): PIdAnsiChar cdecl; external CLibSSL; function OPENSSL_cipher_name(const rfc_name: PIdAnsiChar): PIdAnsiChar cdecl; external CLibSSL; function SSL_CIPHER_get_id(const c: PSSL_CIPHER): TIdC_UINT32 cdecl; external CLibSSL; function SSL_CIPHER_get_protocol_id(const c: PSSL_CIPHER): TIdC_UINT16 cdecl; external CLibSSL; function SSL_CIPHER_get_kx_nid(const c: PSSL_CIPHER): TIdC_INT cdecl; external CLibSSL; function SSL_CIPHER_get_auth_nid(const c: PSSL_CIPHER): TIdC_INT cdecl; external CLibSSL; function SSL_CIPHER_get_handshake_digest(const c: PSSL_CIPHER): PEVP_MD cdecl; external CLibSSL; function SSL_CIPHER_is_aead(const c: PSSL_CIPHER): TIdC_INT cdecl; external CLibSSL; function SSL_get_fd(const s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_get_rfd(const s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_get_wfd(const s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_get_cipher_list(const s: PSSL; n: TIdC_INT): PIdAnsiChar cdecl; external CLibSSL; function SSL_get_shared_ciphers(const s: PSSL; buf: PIdAnsiChar; size: TIdC_INT): PIdAnsiChar cdecl; external CLibSSL; function SSL_get_read_ahead(const s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_pending(const s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_has_pending(const s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_set_fd(s: PSSL; fd: TIdC_INT): TIdC_INT cdecl; external CLibSSL; function SSL_set_rfd(s: PSSL; fd: TIdC_INT): TIdC_INT cdecl; external CLibSSL; function SSL_set_wfd(s: PSSL; fd: TIdC_INT): TIdC_INT cdecl; external CLibSSL; procedure SSL_set0_rbio(s: PSSL; rbio: PBIO) cdecl; external CLibSSL; procedure SSL_set0_wbio(s: PSSL; wbio: PBIO) cdecl; external CLibSSL; procedure SSL_set_bio(s: PSSL; rbio: PBIO; wbio: PBIO) cdecl; external CLibSSL; function SSL_get_rbio(const s: PSSL): PBIO cdecl; external CLibSSL; function SSL_get_wbio(const s: PSSL): PBIO cdecl; external CLibSSL; function SSL_set_cipher_list(s: PSSL; const str: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_set_ciphersuites(ctx: PSSL_CTX; const str: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; function SSL_set_ciphersuites(s: PSSL; const str: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; function SSL_get_verify_mode(const s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_get_verify_depth(const s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_get_verify_callback(const s: PSSL): SSL_verify_cb cdecl; external CLibSSL; procedure SSL_set_read_ahead(s: PSSL; yes: TIdC_INT) cdecl; external CLibSSL; procedure SSL_set_verify(s: PSSL; mode: TIdC_INT; callback: SSL_verify_cb) cdecl; external CLibSSL; procedure SSL_set_verify_depth(s: PSSL; depth: TIdC_INT) cdecl; external CLibSSL; //void SSL_set_cert_cb(s: PSSL, TIdC_INT (*cb) (ssl: PSSL, void *arg), void *arg); function SSL_use_RSAPrivateKey(ssl: PSSL; rsa: PRSA): TIdC_INT cdecl; external CLibSSL; function SSL_use_RSAPrivateKey_ASN1(ssl: PSSL; const d: PByte; len: TIdC_LONG): TIdC_INT cdecl; external CLibSSL; function SSL_use_PrivateKey(ssl: PSSL; pkey: PEVP_PKEY): TIdC_INT cdecl; external CLibSSL; function SSL_use_PrivateKey_ASN1(pk: TIdC_INT; ssl: PSSL; const d: PByte; len: TIdC_LONG): TIdC_INT cdecl; external CLibSSL; function SSL_use_certificate(ssl: PSSL; x: PX509): TIdC_INT cdecl; external CLibSSL; function SSL_use_certificate_ASN1(ssl: PSSL; const d: PByte; len: TIdC_INT): TIdC_INT cdecl; external CLibSSL; //__owur TIdC_INT SSL_use_cert_and_key(ssl: PSSL, x509: PX509, EVP_PKEY *privatekey, // STACK_OF(X509) *chain, TIdC_INT override); (* Set serverinfo data for the current active cert. *) function SSL_CTX_use_serverinfo(ctx: PSSL_CTX; const serverinfo: PByte; serverinfo_length: TIdC_SIZET): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_use_serverinfo_ex(ctx: PSSL_CTX; version: TIdC_UINT; const serverinfo: PByte; serverinfo_length: TIdC_SIZET): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_use_serverinfo_file(ctx: PSSL_CTX; const file_: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; function SSL_use_RSAPrivateKey_file(ssl: PSSL; const file_: PIdAnsiChar; type_: TIdC_INT): TIdC_INT cdecl; external CLibSSL; function SSL_use_PrivateKey_file(ssl: PSSL; const file_: PIdAnsiChar; type_: TIdC_INT): TIdC_INT cdecl; external CLibSSL; function SSL_use_certificate_file(ssl: PSSL; const file_: PIdAnsiChar; type_: TIdC_INT): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_use_RSAPrivateKey_file(ctx: PSSL_CTX; const file_: PIdAnsiChar; type_: TIdC_INT): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_use_PrivateKey_file(ctx: PSSL_CTX; const file_: PIdAnsiChar; type_: TIdC_INT): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_use_certificate_file(ctx: PSSL_CTX; const file_: PIdAnsiChar; type_: TIdC_INT): TIdC_INT cdecl; external CLibSSL; (* PEM type *) function SSL_CTX_use_certificate_chain_file(ctx: PSSL_CTX; const file_: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; function SSL_use_certificate_chain_file(ssl: PSSL; const file_: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; //__owur STACK_OF(X509_NAME) *SSL_load_client_CA_file(const PIdAnsiChar *file); //__owur TIdC_INT SSL_add_file_cert_subjects_to_stack(STACK_OF(X509_NAME) *stackCAs, // const PIdAnsiChar *file); //TIdC_INT SSL_add_dir_cert_subjects_to_stack(STACK_OF(X509_NAME) *stackCAs, // const PIdAnsiChar *dir); //# if OPENSSL_API_COMPAT < 0x10100000L //# define SSL_load_error_strings() \ // OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS \ // | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL) //# endif function SSL_state_string(const s: PSSL): PIdAnsiChar cdecl; external CLibSSL; function SSL_rstate_string(const s: PSSL): PIdAnsiChar cdecl; external CLibSSL; function SSL_state_string_long(const s: PSSL): PIdAnsiChar cdecl; external CLibSSL; function SSL_rstate_string_long(const s: PSSL): PIdAnsiChar cdecl; external CLibSSL; function SSL_SESSION_get_time(const s: PSSL_SESSION): TIdC_LONG cdecl; external CLibSSL; function SSL_SESSION_set_time(s: PSSL_SESSION; t: TIdC_LONG): TIdC_LONG cdecl; external CLibSSL; function SSL_SESSION_get_timeout(const s: PSSL_SESSION): TIdC_LONG cdecl; external CLibSSL; function SSL_SESSION_set_timeout(s: PSSL_SESSION; t: TIdC_LONG): TIdC_LONG cdecl; external CLibSSL; function SSL_SESSION_get_protocol_version(const s: PSSL_SESSION): TIdC_INT cdecl; external CLibSSL; function SSL_SESSION_set_protocol_version(s: PSSL_SESSION; version: TIdC_INT): TIdC_INT cdecl; external CLibSSL; function SSL_SESSION_get0_hostname(const s: PSSL_SESSION): PIdAnsiChar cdecl; external CLibSSL; function SSL_SESSION_set1_hostname(s: PSSL_SESSION; const hostname: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; procedure SSL_SESSION_get0_alpn_selected(const s: PSSL_SESSION; const alpn: PPByte; len: PIdC_SIZET) cdecl; external CLibSSL; function SSL_SESSION_set1_alpn_selected(s: PSSL_SESSION; const alpn: PByte; len: TIdC_SIZET): TIdC_INT cdecl; external CLibSSL; function SSL_SESSION_get0_cipher(const s: PSSL_SESSION): PSSL_CIPHER cdecl; external CLibSSL; function SSL_SESSION_set_cipher(s: PSSL_SESSION; const cipher: PSSL_CIPHER): TIdC_INT cdecl; external CLibSSL; function SSL_SESSION_has_ticket(const s: PSSL_SESSION): TIdC_INT cdecl; external CLibSSL; function SSL_SESSION_get_ticket_lifetime_hint(const s: PSSL_SESSION): TIdC_ULONG cdecl; external CLibSSL; procedure SSL_SESSION_get0_ticket(const s: PSSL_SESSION; const tick: PPByte; len: PIdC_SIZET) cdecl; external CLibSSL; function SSL_SESSION_get_max_early_data(const s: PSSL_SESSION): TIdC_UINT32 cdecl; external CLibSSL; function SSL_SESSION_set_max_early_data(s: PSSL_SESSION; max_early_data: TIdC_UINT32): TIdC_INT cdecl; external CLibSSL; function SSL_copy_session_id(to_: PSSL; const from: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_SESSION_get0_peer(s: PSSL_SESSION): PX509 cdecl; external CLibSSL; function SSL_SESSION_set1_id_context(s: PSSL_SESSION; const sid_ctx: PByte; sid_ctx_len: TIdC_UINT): TIdC_INT cdecl; external CLibSSL; function SSL_SESSION_set1_id(s: PSSL_SESSION; const sid: PByte; sid_len: TIdC_UINT): TIdC_INT cdecl; external CLibSSL; function SSL_SESSION_is_resumable(const s: PSSL_SESSION): TIdC_INT cdecl; external CLibSSL; function SSL_SESSION_new: PSSL_SESSION cdecl; external CLibSSL; function SSL_SESSION_dup(src: PSSL_SESSION): PSSL_SESSION cdecl; external CLibSSL; function SSL_SESSION_get_id(const s: PSSL_SESSION; len: PIdC_UINT): PByte cdecl; external CLibSSL; function SSL_SESSION_get0_id_context(const s: PSSL_SESSION; len: PIdC_UINT): PByte cdecl; external CLibSSL; function SSL_SESSION_get_compress_id(const s: PSSL_SESSION): TIdC_UINT cdecl; external CLibSSL; function SSL_SESSION_print(fp: PBIO; const ses: PSSL_SESSION): TIdC_INT cdecl; external CLibSSL; function SSL_SESSION_print_keylog(bp: PBIO; const x: PSSL_SESSION): TIdC_INT cdecl; external CLibSSL; function SSL_SESSION_up_ref(ses: PSSL_SESSION): TIdC_INT cdecl; external CLibSSL; procedure SSL_SESSION_free(ses: PSSL_SESSION) cdecl; external CLibSSL; //__owur TIdC_INT i2d_SSL_SESSION(SSL_SESSION *in_, Byte **pp); function SSL_set_session(to_: PSSL; session: PSSL_SESSION): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_add_session(ctx: PSSL_CTX; session: PSSL_SESSION): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_remove_session(ctx: PSSL_CTX; session: PSSL_SESSION): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_set_generate_session_id(ctx: PSSL_CTX; cb: GEN_SESSION_CB): TIdC_INT cdecl; external CLibSSL; function SSL_set_generate_session_id(s: PSSL; cb: GEN_SESSION_CB): TIdC_INT cdecl; external CLibSSL; function SSL_has_matching_session_id(const s: PSSL; const id: PByte; id_len: TIdC_UINT): TIdC_INT cdecl; external CLibSSL; function d2i_SSL_SESSION(a: PPSSL_SESSION; const pp: PPByte; length: TIdC_LONG): PSSL_SESSION cdecl; external CLibSSL; function SSL_get_peer_certificate(const s: PSSL): PX509 cdecl; external CLibSSL; //__owur STACK_OF(X509) *SSL_get_peer_cert_chain(const s: PSSL); // function SSL_CTX_get_verify_mode(const ctx: PSSL_CTX): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_get_verify_depth(const ctx: PSSL_CTX): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_get_verify_callback(const ctx: PSSL_CTX): SSL_verify_cb cdecl; external CLibSSL; procedure SSL_CTX_set_verify(ctx: PSSL_CTX; mode: TIdC_INT; callback: SSL_verify_cb) cdecl; external CLibSSL; procedure SSL_CTX_set_verify_depth(ctx: PSSL_CTX; depth: TIdC_INT) cdecl; external CLibSSL; procedure SSL_CTX_set_cert_verify_callback(ctx: PSSL_CTX; cb: SSL_CTX_set_cert_verify_callback_cb; arg: Pointer) cdecl; external CLibSSL; procedure SSL_CTX_set_cert_cb(c: PSSL_CTX; cb: SSL_CTX_set_cert_cb_cb; arg: Pointer) cdecl; external CLibSSL; function SSL_CTX_use_RSAPrivateKey(ctx: PSSL_CTX; rsa: PRSA): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_use_RSAPrivateKey_ASN1(ctx: PSSL_CTX; const d: PByte; len: TIdC_LONG): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_use_PrivateKey(ctx: PSSL_CTX; pkey: PEVP_PKEY): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_use_PrivateKey_ASN1(pk: TIdC_INT; ctx: PSSL_CTX; const d: PByte; len: TIdC_LONG): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_use_certificate(ctx: PSSL_CTX; x: X509): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_use_certificate_ASN1(ctx: PSSL_CTX; len: TIdC_INT; const d: PByte): TIdC_INT cdecl; external CLibSSL; //function TIdC_INT SSL_CTX_use_cert_and_key(ctx: PSSL_CTX; x509: PX509; EVP_PKEY *privatekey; STACK_OF(X509) *chain; TIdC_INT override); procedure SSL_CTX_set_default_passwd_cb(ctx: PSSL_CTX; cb: pem_password_cb) cdecl; external CLibSSL; procedure SSL_CTX_set_default_passwd_cb_userdata(ctx: PSSL_CTX; u: Pointer) cdecl; external CLibSSL; function SSL_CTX_get_default_passwd_cb(ctx: PSSL_CTX): pem_password_cb cdecl; external CLibSSL; function SSL_CTX_get_default_passwd_cb_userdata(ctx: PSSL_CTX): Pointer cdecl; external CLibSSL; procedure SSL_set_default_passwd_cb(s: PSSL; cb: pem_password_cb) cdecl; external CLibSSL; procedure SSL_set_default_passwd_cb_userdata(s: PSSL; u: Pointer) cdecl; external CLibSSL; function SSL_get_default_passwd_cb(s: PSSL): pem_password_cb cdecl; external CLibSSL; function SSL_get_default_passwd_cb_userdata(s: PSSL): Pointer cdecl; external CLibSSL; function SSL_CTX_check_private_key(const ctx: PSSL_CTX): TIdC_INT cdecl; external CLibSSL; function SSL_check_private_key(const ctx: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_set_session_id_context(ctx: PSSL_CTX; const sid_ctx: PByte; sid_ctx_len: TIdC_UINT): TIdC_INT cdecl; external CLibSSL; function SSL_new(ctx: PSSL_CTX): PSSL cdecl; external CLibSSL; function SSL_up_ref(s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_is_dtls(const s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_set_session_id_context(ssl: PSSL; const sid_ctx: PByte; sid_ctx_len: TIdC_UINT): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_set_purpose(ctx: PSSL_CTX; purpose: TIdC_INT): TIdC_INT cdecl; external CLibSSL; function SSL_set_purpose(ssl: PSSL; purpose: TIdC_INT): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_set_trust(ctx: PSSL_CTX; trust: TIdC_INT): TIdC_INT cdecl; external CLibSSL; function SSL_set_trust(ssl: PSSL; trust: TIdC_INT): TIdC_INT cdecl; external CLibSSL; function SSL_set1_host(s: PSSL; const hostname: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; function SSL_add1_host(s: PSSL; const hostname: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; function SSL_get0_peername(s: PSSL): PIdAnsiChar cdecl; external CLibSSL; procedure SSL_set_hostflags(s: PSSL; flags: TIdC_UINT) cdecl; external CLibSSL; function SSL_CTX_dane_enable(ctx: PSSL_CTX): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_dane_mtype_set(ctx: PSSL_CTX; const md: PEVP_MD; mtype: TIdC_UINT8; ord: TIdC_UINT8): TIdC_INT cdecl; external CLibSSL; function SSL_dane_enable(s: PSSL; const basedomain: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; function SSL_dane_tlsa_add(s: PSSL; usage: TIdC_UINT8; selector: TIdC_UINT8; mtype: TIdC_UINT8; const data: PByte; dlen: TIdC_SIZET): TIdC_INT cdecl; external CLibSSL; function SSL_get0_dane_authority(s: PSSL; mcert: PPX509; mspki: PPEVP_PKEY): TIdC_INT cdecl; external CLibSSL; function SSL_get0_dane_tlsa(s: PSSL; usage: PIdC_UINT8; selector: PIdC_UINT8; mtype: PIdC_UINT8; const data: PPByte; dlen: PIdC_SIZET): TIdC_INT cdecl; external CLibSSL; (* * Bridge opacity barrier between libcrypt and libssl, also needed to support * offline testing in test/danetest.c *) function SSL_get0_dane(ssl: PSSL): PSSL_DANE cdecl; external CLibSSL; (* * DANE flags *) function SSL_CTX_dane_set_flags(ctx: PSSL_CTX; flags: TIdC_ULONG): TIdC_ULONG cdecl; external CLibSSL; function SSL_CTX_dane_clear_flags(ctx: PSSL_CTX; flags: TIdC_ULONG): TIdC_ULONG cdecl; external CLibSSL; function SSL_dane_set_flags(ssl: PSSL; flags: TIdC_ULONG): TIdC_ULONG cdecl; external CLibSSL; function SSL_dane_clear_flags(ssl: PSSL; flags: TIdC_ULONG): TIdC_ULONG cdecl; external CLibSSL; function SSL_CTX_set1_param(ctx: PSSL_CTX; vpm: PX509_VERIFY_PARAM): TIdC_INT cdecl; external CLibSSL; function SSL_set1_param(ssl: PSSL; vpm: PX509_VERIFY_PARAM): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_get0_param(ctx: PSSL_CTX): PX509_VERIFY_PARAM cdecl; external CLibSSL; function SSL_get0_param(ssl: PSSL): PX509_VERIFY_PARAM cdecl; external CLibSSL; function SSL_CTX_set_srp_username(ctx: PSSL_CTX; name: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_set_srp_password(ctx: PSSL_CTX; password: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_set_srp_strength(ctx: PSSL_CTX; strength: TIdC_INT): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_set_srp_client_pwd_callback(ctx: PSSL_CTX; cb: SSL_CTX_set_srp_client_pwd_callback_cb): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_set_srp_verify_param_callback(ctx: PSSL_CTX; cb: SSL_CTX_set_srp_verify_param_callback_cb): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_set_srp_username_callback(ctx: PSSL_CTX; cb: SSL_CTX_set_srp_username_callback_cb): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_set_srp_cb_arg(ctx: PSSL_CTX; arg: Pointer): TIdC_INT cdecl; external CLibSSL; function SSL_set_srp_server_param(s: PSSL; const N: PBIGNUm; const g: PBIGNUm; sa: PBIGNUm; v: PBIGNUm; info: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; function SSL_set_srp_server_param_pw(s: PSSL; const user: PIdAnsiChar; const pass: PIdAnsiChar; const grp: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; //__owur BIGNUM *SSL_get_srp_g(s: PSSL); //__owur BIGNUM *SSL_get_srp_N(s: PSSL); // //__owur PIdAnsiChar *SSL_get_srp_username(s: PSSL); //__owur PIdAnsiChar *SSL_get_srp_userinfo(s: PSSL); // ///* // * ClientHello callback and helpers. // */ procedure SSL_CTX_set_client_hello_cb(c: PSSL_CTX; cb: SSL_client_hello_cb_fn; arg: Pointer) cdecl; external CLibSSL; function SSL_client_hello_isv2(s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_client_hello_get0_legacy_version(s: PSSL): TIdC_UINT cdecl; external CLibSSL; function SSL_client_hello_get0_random(s: PSSL; const out_: PPByte): TIdC_SIZET cdecl; external CLibSSL; function SSL_client_hello_get0_session_id(s: PSSL; const out_: PPByte): TIdC_SIZET cdecl; external CLibSSL; function SSL_client_hello_get0_ciphers(s: PSSL; const out_: PPByte): TIdC_SIZET cdecl; external CLibSSL; function SSL_client_hello_get0_compression_methods(s: PSSL; const out_: PPByte): TIdC_SIZET cdecl; external CLibSSL; function SSL_client_hello_get1_extensions_present(s: PSSL; out_: PPIdC_INT; outlen: PIdC_SIZET): TIdC_INT cdecl; external CLibSSL; function SSL_client_hello_get0_ext(s: PSSL; type_: TIdC_UINT; const out_: PPByte; outlen: PIdC_SIZET): TIdC_INT cdecl; external CLibSSL; procedure SSL_certs_clear(s: PSSL) cdecl; external CLibSSL; procedure SSL_free(ssl: PSSL) cdecl; external CLibSSL; (* * Windows application developer has to include windows.h to use these. *) function SSL_waiting_for_async(s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_get_all_async_fds(s: PSSL; fds: POSSL_ASYNC_FD; numfds: PIdC_SIZET): TIdC_INT cdecl; external CLibSSL; function SSL_get_changed_async_fds(s: PSSL; addfd: POSSL_ASYNC_FD; numaddfds: PIdC_SIZET; delfd: POSSL_ASYNC_FD; numdelfds: PIdC_SIZET): TIdC_INT cdecl; external CLibSSL; function SSL_accept(ssl: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_stateless(s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_connect(ssl: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_read(ssl: PSSL; buf: Pointer; num: TIdC_INT): TIdC_INT cdecl; external CLibSSL; function SSL_read_ex(ssl: PSSL; buf: Pointer; num: TIdC_SIZET; readbytes: PIdC_SIZET): TIdC_INT cdecl; external CLibSSL; function SSL_read_early_data(s: PSSL; buf: Pointer; num: TIdC_SIZET; readbytes: PIdC_SIZET): TIdC_INT cdecl; external CLibSSL; function SSL_peek(ssl: PSSL; buf: Pointer; num: TIdC_INT): TIdC_INT cdecl; external CLibSSL; function SSL_peek_ex(ssl: PSSL; buf: Pointer; num: TIdC_SIZET; readbytes: PIdC_SIZET): TIdC_INT cdecl; external CLibSSL; function SSL_write(ssl: PSSL; const buf: Pointer; num: TIdC_INT): TIdC_INT cdecl; external CLibSSL; function SSL_write_ex(s: PSSL; const buf: Pointer; num: TIdC_SIZET; written: PIdC_SIZET): TIdC_INT cdecl; external CLibSSL; function SSL_write_early_data(s: PSSL; const buf: Pointer; num: TIdC_SIZET; written: PIdC_SIZET): TIdC_INT cdecl; external CLibSSL; function SSL_callback_ctrl(v1: PSSL; v2: TIdC_INT; v3: SSL_callback_ctrl_v3): TIdC_LONG cdecl; external CLibSSL; function SSL_ctrl(ssl: PSSL; cmd: TIdC_INT; larg: TIdC_LONG; parg: Pointer): TIdC_LONG cdecl; external CLibSSL; function SSL_CTX_ctrl(ctx: PSSL_CTX; cmd: TIdC_INT; larg: TIdC_LONG; parg: Pointer): TIdC_LONG cdecl; external CLibSSL; function SSL_CTX_callback_ctrl(v1: PSSL_CTX; v2: TIdC_INT; v3: SSL_CTX_callback_ctrl_v3): TIdC_LONG cdecl; external CLibSSL; function SSL_get_early_data_status(const s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_get_error(const s: PSSL; ret_code: TIdC_INT): TIdC_INT cdecl; external CLibSSL; function SSL_get_version(const s: PSSL): PIdAnsiChar cdecl; external CLibSSL; (* This sets the 'default' SSL version that SSL_new() will create *) function SSL_CTX_set_ssl_version(ctx: PSSL_CTX; const meth: PSSL_METHOD): TIdC_INT cdecl; external CLibSSL; ///* Negotiate highest available SSL/TLS version */ function TLS_method: PSSL_METHOD cdecl; external CLibSSL; function TLS_server_method: PSSL_METHOD cdecl; external CLibSSL; function TLS_client_method: PSSL_METHOD cdecl; external CLibSSL; //__owur const SSL_METHOD *DTLS_method(void); /* DTLS 1.0 and 1.2 */ //__owur const SSL_METHOD *DTLS_server_method(void); /* DTLS 1.0 and 1.2 */ //__owur const SSL_METHOD *DTLS_client_method(void); /* DTLS 1.0 and 1.2 */ // //__owur TIdC_SIZET DTLS_get_data_mtu(const s: PSSL); // //__owur STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const s: PSSL); //__owur STACK_OF(SSL_CIPHER) *SSL_CTX_get_ciphers(const ctx: PSSL_CTX); //__owur STACK_OF(SSL_CIPHER) *SSL_get_client_ciphers(const s: PSSL); //__owur STACK_OF(SSL_CIPHER) *SSL_get1_supported_ciphers(s: PSSL); // //__owur TIdC_INT SSL_do_handshake(s: PSSL); function SSL_key_update(s: PSSL; updatetype: TIdC_INT): TIdC_INT cdecl; external CLibSSL; function SSL_get_key_update_type(const s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_renegotiate(s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_renegotiate_abbreviated(s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_shutdown(s: PSSL): TIdC_INT cdecl; external CLibSSL; procedure SSL_CTX_set_post_handshake_auth(ctx: PSSL_CTX; val: TIdC_INT) cdecl; external CLibSSL; procedure SSL_set_post_handshake_auth(s: PSSL; val: TIdC_INT) cdecl; external CLibSSL; function SSL_renegotiate_pending(const s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_verify_client_post_handshake(s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_get_ssl_method(const ctx: PSSL_CTX): PSSL_METHOD cdecl; external CLibSSL; function SSL_get_ssl_method(const s: PSSL): PSSL_METHOD cdecl; external CLibSSL; function SSL_set_ssl_method(s: PSSL; const method: PSSL_METHOD): TIdC_INT cdecl; external CLibSSL; function SSL_alert_type_string_long(value: TIdC_INT): PIdAnsiChar cdecl; external CLibSSL; function SSL_alert_type_string(value: TIdC_INT): PIdAnsiChar cdecl; external CLibSSL; function SSL_alert_desc_string_long(value: TIdC_INT): PIdAnsiChar cdecl; external CLibSSL; function SSL_alert_desc_string(value: TIdC_INT): PIdAnsiChar cdecl; external CLibSSL; //void SSL_set0_CA_list(s: PSSL, STACK_OF(X509_NAME) *name_list); //void SSL_CTX_set0_CA_list(ctx: PSSL_CTX, STACK_OF(X509_NAME) *name_list); //__owur const STACK_OF(X509_NAME) *SSL_get0_CA_list(const s: PSSL); //__owur const STACK_OF(X509_NAME) *SSL_CTX_get0_CA_list(const ctx: PSSL_CTX); //__owur TIdC_INT SSL_add1_to_CA_list(ssl: PSSL, const X509 *x); //__owur TIdC_INT SSL_CTX_add1_to_CA_list(ctx: PSSL_CTX, const X509 *x); //__owur const STACK_OF(X509_NAME) *SSL_get0_peer_CA_list(const s: PSSL); //void SSL_set_client_CA_list(s: PSSL, STACK_OF(X509_NAME) *name_list); //void SSL_CTX_set_client_CA_list(ctx: PSSL_CTX, STACK_OF(X509_NAME) *name_list); //__owur STACK_OF(X509_NAME) *SSL_get_client_CA_list(const s: PSSL); //__owur STACK_OF(X509_NAME) *SSL_CTX_get_client_CA_list(const SSL_CTX *s); function SSL_add_client_CA(ssl: PSSL; x: PX509): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_add_client_CA(ctx: PSSL_CTX; x: PX509): TIdC_INT cdecl; external CLibSSL; procedure SSL_set_connect_state(s: PSSL) cdecl; external CLibSSL; procedure SSL_set_accept_state(s: PSSL) cdecl; external CLibSSL; //__owur TIdC_LONG SSL_get_default_timeout(const s: PSSL); // //# if OPENSSL_API_COMPAT < 0x10100000L //# define SSL_library_init() OPENSSL_init_ssl(0, NULL) //# endif //__owur PIdAnsiChar *SSL_CIPHER_description(const SSL_CIPHER *, PIdAnsiChar *buf, TIdC_INT size); //__owur STACK_OF(X509_NAME) *SSL_dup_CA_list(const STACK_OF(X509_NAME) *sk); function SSL_dup(ssl: PSSL): PSSL cdecl; external CLibSSL; function SSL_get_certificate(const ssl: PSSL): PX509 cdecl; external CLibSSL; (* * EVP_PKEY *) function SSL_get_privatekey(const ssl: PSSL): PEVP_PKEY cdecl; external CLibSSL; function SSL_CTX_get0_certificate(const ctx: PSSL_CTX): PX509 cdecl; external CLibSSL; function SSL_CTX_get0_privatekey(const ctx: PSSL_CTX): PEVP_PKEY cdecl; external CLibSSL; procedure SSL_CTX_set_quiet_shutdown(ctx: PSSL_CTX; mode: TIdC_INT) cdecl; external CLibSSL; function SSL_CTX_get_quiet_shutdown(const ctx: PSSL_CTX): TIdC_INT cdecl; external CLibSSL; procedure SSL_set_quiet_shutdown(ssl: PSSL; mode: TIdC_INT) cdecl; external CLibSSL; function SSL_get_quiet_shutdown(const ssl: PSSL): TIdC_INT cdecl; external CLibSSL; procedure SSL_set_shutdown(ssl: PSSL; mode: TIdC_INT) cdecl; external CLibSSL; function SSL_get_shutdown(const ssl: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_version(const ssl: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_client_version(const s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_set_default_verify_paths(ctx: PSSL_CTX): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_set_default_verify_dir(ctx: PSSL_CTX): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_set_default_verify_file(ctx: PSSL_CTX): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_load_verify_locations(ctx: PSSL_CTX; const CAfile: PIdAnsiChar; const CApath: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; //# define SSL_get0_session SSL_get_session/* just peek at pointer */ function SSL_get_session(const ssl: PSSL): PSSL_SESSION cdecl; external CLibSSL; (* obtain a reference count *) function SSL_get1_session(ssl: PSSL): PSSL_SESSION cdecl; external CLibSSL; function SSL_get_SSL_CTX(const ssl: PSSL): PSSL_CTX cdecl; external CLibSSL; function SSL_set_SSL_CTX(ssl: PSSL; ctx: PSSL_CTX): PSSL_CTX cdecl; external CLibSSL; procedure SSL_set_info_callback(ssl: PSSL; cb: SSL_info_callback) cdecl; external CLibSSL; function SSL_get_info_callback(const ssl: PSSL): SSL_info_callback cdecl; external CLibSSL; function SSL_get_state(const ssl: PSSL): OSSL_HANDSHAKE_STATE cdecl; external CLibSSL; procedure SSL_set_verify_result(ssl: PSSL; v: TIdC_LONG) cdecl; external CLibSSL; function SSL_get_verify_result(const ssl: PSSL): TIdC_LONG cdecl; external CLibSSL; //__owur STACK_OF(X509) *SSL_get0_verified_chain(const s: PSSL); function SSL_get_client_random(const ssl: PSSL; out_: PByte; outlen: TIdC_SIZET): TIdC_SIZET cdecl; external CLibSSL; function SSL_get_server_random(const ssl: PSSL; out_: PByte; outlen: TIdC_SIZET): TIdC_SIZET cdecl; external CLibSSL; function SSL_SESSION_get_master_key(const sess: PSSL_SESSION; out_: PByte; outlen: TIdC_SIZET): TIdC_SIZET cdecl; external CLibSSL; function SSL_SESSION_set1_master_key(sess: PSSL_SESSION; const in_: PByte; len: TIdC_SIZET): TIdC_INT cdecl; external CLibSSL; function SSL_SESSION_get_max_fragment_length(const sess: PSSL_SESSION): TIdC_UINT8 cdecl; external CLibSSL; //#define SSL_get_ex_new_index(l, p, newf, dupf, freef) \ // CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL, l, p, newf, dupf, freef) function SSL_set_ex_data(ssl: PSSL; idx: TIdC_INT; data: Pointer): TIdC_INT cdecl; external CLibSSL; function SSL_get_ex_data(const ssl: PSSL; idx: TIdC_INT): Pointer cdecl; external CLibSSL; //#define SSL_SESSION_get_ex_new_index(l, p, newf, dupf, freef) \ // CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_SESSION, l, p, newf, dupf, freef) function SSL_SESSION_set_ex_data(ss: PSSL_SESSION; idx: TIdC_INT; data: Pointer): TIdC_INT cdecl; external CLibSSL; function SSL_SESSION_get_ex_data(const ss: PSSL_SESSION; idx: TIdC_INT): Pointer cdecl; external CLibSSL; //#define SSL_CTX_get_ex_new_index(l, p, newf, dupf, freef) \ // CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_CTX, l, p, newf, dupf, freef) function SSL_CTX_set_ex_data(ssl: PSSL_CTX; idx: TIdC_INT; data: Pointer): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_get_ex_data(const ssl: PSSL_CTX; idx: TIdC_INT): Pointer cdecl; external CLibSSL; function SSL_get_ex_data_X509_STORE_CTX_idx: TIdC_INT cdecl; external CLibSSL; //# define SSL_CTX_get_default_read_ahead(ctx) SSL_CTX_get_read_ahead(ctx) //# define SSL_CTX_set_default_read_ahead(ctx,m) SSL_CTX_set_read_ahead(ctx,m) //# define SSL_CTX_get_read_ahead(ctx) \ // SSL_CTX_ctrl(ctx,SSL_CTRL_GET_READ_AHEAD,0,NULL) //# define SSL_CTX_set_read_ahead(ctx,m) \ // SSL_CTX_ctrl(ctx,SSL_CTRL_SET_READ_AHEAD,m,NULL) //# define SSL_CTX_get_max_cert_list(ctx) \ // SSL_CTX_ctrl(ctx,SSL_CTRL_GET_MAX_CERT_LIST,0,NULL) //# define SSL_CTX_set_max_cert_list(ctx,m) \ // SSL_CTX_ctrl(ctx,SSL_CTRL_SET_MAX_CERT_LIST,m,NULL) //# define SSL_get_max_cert_list(ssl) \ // SSL_ctrl(ssl,SSL_CTRL_GET_MAX_CERT_LIST,0,NULL) //# define SSL_set_max_cert_list(ssl,m) \ // SSL_ctrl(ssl,SSL_CTRL_SET_MAX_CERT_LIST,m,NULL) // //# define SSL_CTX_set_max_send_fragment(ctx,m) \ // SSL_CTX_ctrl(ctx,SSL_CTRL_SET_MAX_SEND_FRAGMENT,m,NULL) //# define SSL_set_max_send_fragment(ssl,m) \ // SSL_ctrl(ssl,SSL_CTRL_SET_MAX_SEND_FRAGMENT,m,NULL) //# define SSL_CTX_set_split_send_fragment(ctx,m) \ // SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SPLIT_SEND_FRAGMENT,m,NULL) //# define SSL_set_split_send_fragment(ssl,m) \ // SSL_ctrl(ssl,SSL_CTRL_SET_SPLIT_SEND_FRAGMENT,m,NULL) //# define SSL_CTX_set_max_pipelines(ctx,m) \ // SSL_CTX_ctrl(ctx,SSL_CTRL_SET_MAX_PIPELINES,m,NULL) //# define SSL_set_max_pipelines(ssl,m) \ // SSL_ctrl(ssl,SSL_CTRL_SET_MAX_PIPELINES,m,NULL) procedure SSL_CTX_set_default_read_buffer_len(ctx: PSSL_CTX; len: TIdC_SIZET) cdecl; external CLibSSL; procedure SSL_set_default_read_buffer_len(s: PSSL; len: TIdC_SIZET) cdecl; external CLibSSL; procedure SSL_CTX_set_tmp_dh_callback(ctx: PSSL_CTX; dh: SSL_CTX_set_tmp_dh_callback_dh) cdecl; external CLibSSL; procedure SSL_set_tmp_dh_callback(ssl: PSSL; dh: SSL_set_tmp_dh_callback_dh) cdecl; external CLibSSL; //__owur const COMP_METHOD *SSL_get_current_compression(const s: PSSL); //__owur const COMP_METHOD *SSL_get_current_expansion(const s: PSSL); //__owur const PIdAnsiChar *SSL_COMP_get_name(const COMP_METHOD *comp); //__owur const PIdAnsiChar *SSL_COMP_get0_name(const SSL_COMP *comp); //__owur TIdC_INT SSL_COMP_get_id(const SSL_COMP *comp); //STACK_OF(SSL_COMP) *SSL_COMP_get_compression_methods(void); //__owur STACK_OF(SSL_COMP) *SSL_COMP_set0_compression_methods(STACK_OF(SSL_COMP) // *meths); //# if OPENSSL_API_COMPAT < 0x10100000L //# define SSL_COMP_free_compression_methods() while(0) continue //# endif //__owur TIdC_INT SSL_COMP_add_compression_method(TIdC_INT id, COMP_METHOD *cm); function SSL_CIPHER_find(ssl: PSSL; const ptr: PByte): PSSL_CIPHER cdecl; external CLibSSL; function SSL_CIPHER_get_cipher_nid(const c: PSSL_CIPHEr): TIdC_INT cdecl; external CLibSSL; function SSL_CIPHER_get_digest_nid(const c: PSSL_CIPHEr): TIdC_INT cdecl; external CLibSSL; //TIdC_INT SSL_bytes_to_cipher_list(s: PSSL, const Byte *bytes, TIdC_SIZET len, // TIdC_INT isv2format, STACK_OF(SSL_CIPHER) **sk, // STACK_OF(SSL_CIPHER) **scsvs); (* TLS extensions functions *) function SSL_set_session_ticket_ext(s: PSSL; ext_data: Pointer; ext_len: TIdC_INT): TIdC_INT cdecl; external CLibSSL; // function SSL_set_session_ticket_ext_cb(s: PSSL; cb: tls_session_ticket_ext_cb_fn; arg: Pointer): TIdC_INT cdecl; external CLibSSL; ///* Pre-shared secret session resumption functions */ //__owur TIdC_INT SSL_set_session_secret_cb(s: PSSL, // tls_session_secret_cb_fn session_secret_cb, // void *arg); procedure SSL_CTX_set_not_resumable_session_callback(ctx: PSSL_CTX; cb: SSL_CTX_set_not_resumable_session_callback_cb) cdecl; external CLibSSL; procedure SSL_set_not_resumable_session_callback(ssl: PSSL; cb: SSL_set_not_resumable_session_callback_cb) cdecl; external CLibSSL; procedure SSL_CTX_set_record_padding_callback(ctx: PSSL_CTX; cb: SSL_CTX_set_record_padding_callback_cb) cdecl; external CLibSSL; procedure SSL_CTX_set_record_padding_callback_arg(ctx: PSSL_CTX; arg: Pointer) cdecl; external CLibSSL; function SSL_CTX_get_record_padding_callback_arg(const ctx: PSSL_CTX): Pointer cdecl; external CLibSSL; function SSL_CTX_set_block_padding(ctx: PSSL_CTX; block_size: TIdC_SIZET): TIdC_INT cdecl; external CLibSSL; procedure SSL_set_record_padding_callback(ssl: PSSL; cb: SSL_set_record_padding_callback_cb) cdecl; external CLibSSL; procedure SSL_set_record_padding_callback_arg(ssl: PSSL; arg: Pointer) cdecl; external CLibSSL; function SSL_get_record_padding_callback_arg(const ssl: PSSL): Pointer cdecl; external CLibSSL; function SSL_set_block_padding(ssl: PSSL; block_size: TIdC_SIZET): TIdC_INT cdecl; external CLibSSL; function SSL_set_num_tickets(s: PSSL; num_tickets: TIdC_SIZET): TIdC_INT cdecl; external CLibSSL; function SSL_get_num_tickets(const s: PSSL): TIdC_SIZET cdecl; external CLibSSL; function SSL_CTX_set_num_tickets(ctx: PSSL_CTX; num_tickets: TIdC_SIZET): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_get_num_tickets(const ctx: PSSL_CTX): TIdC_SIZET cdecl; external CLibSSL; //# if OPENSSL_API_COMPAT < 0x10100000L //# define SSL_cache_hit(s) SSL_session_reused(s) //# endif function SSL_session_reused(const s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_is_server(const s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_CONF_CTX_new: PSSL_CONF_CTX cdecl; external CLibSSL; function SSL_CONF_CTX_finish(cctx: PSSL_CONF_CTX): TIdC_INT cdecl; external CLibSSL; procedure SSL_CONF_CTX_free(cctx: PSSL_CONF_CTX) cdecl; external CLibSSL; function SSL_CONF_CTX_set_flags(cctx: PSSL_CONF_CTX; flags: TIdC_UINT): TIdC_UINT cdecl; external CLibSSL; function SSL_CONF_CTX_clear_flags(cctx: PSSL_CONF_CTX; flags: TIdC_UINT): TIdC_UINT cdecl; external CLibSSL; function SSL_CONF_CTX_set1_prefix(cctx: PSSL_CONF_CTX; const pre: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; function SSL_CONF_cmd(cctx: PSSL_CONF_CTX; const cmd: PIdAnsiChar; const value: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; function SSL_CONF_cmd_argv(cctx: PSSL_CONF_CTX; pargc: PIdC_INT; pargv: PPPIdAnsiChar): TIdC_INT cdecl; external CLibSSL; function SSL_CONF_cmd_value_type(cctx: PSSL_CONF_CTX; const cmd: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; procedure SSL_CONF_CTX_set_ssl(cctx: PSSL_CONF_CTX; ssl: PSSL) cdecl; external CLibSSL; procedure SSL_CONF_CTX_set_ssl_ctx(cctx: PSSL_CONF_CTX; ctx: PSSL_CTX) cdecl; external CLibSSL; procedure SSL_add_ssl_module cdecl; external CLibSSL; function SSL_config(s: PSSL; const name: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_config(ctx: PSSL_CTX; const name: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; procedure SSL_trace(write_p: TIdC_INT; version: TIdC_INT; content_type: TIdC_INT; const buf: Pointer; len: TIdC_SIZET; ssl: PSSL; arg: Pointer) cdecl; external CLibSSL; function DTLSv1_listen(s: PSSL; client: PBIO_ADDr): TIdC_INT cdecl; external CLibSSL; //# ifndef OPENSSL_NO_CT // ///* // * A callback for verifying that the received SCTs are sufficient. // * Expected to return 1 if they are sufficient, otherwise 0. // * May return a negative integer if an error occurs. // * A connection should be aborted if the SCTs are deemed insufficient. // */ //typedef TIdC_INT (*ssl_ct_validation_cb)(const CT_POLICY_EVAL_CTX *ctx, // const STACK_OF(SCT) *scts, void *arg); ///* // * Sets a |callback| that is invoked upon receipt of ServerHelloDone to validate // * the received SCTs. // * If the callback returns a non-positive result, the connection is terminated. // * Call this function before beginning a handshake. // * If a NULL |callback| is provided, SCT validation is disabled. // * |arg| is arbitrary userdata that will be passed to the callback whenever it // * is invoked. Ownership of |arg| remains with the caller. // * // * NOTE: A side-effect of setting a CT callback is that an OCSP stapled response // * will be requested. // */ //function SSL_set_ct_validation_callback(s: PSSL; callback: ssl_ct_validation_cb; arg: Pointer): TIdC_INT; //function SSL_CTX_set_ct_validation_callback(ctx: PSSL_CTX; callback: ssl_ct_validation_cb; arg: Pointer): TIdC_INT; //#define SSL_disable_ct(s) \ // ((void) SSL_set_validation_callback((s), NULL, NULL)) //#define SSL_CTX_disable_ct(ctx) \ // ((void) SSL_CTX_set_validation_callback((ctx), NULL, NULL)) ///* // * The validation type enumerates the available behaviours of the built-in SSL // * CT validation callback selected via SSL_enable_ct() and SSL_CTX_enable_ct(). // * The underlying callback is a static function in_ libssl. // */ ///* // * Enable CT by setting up a callback that implements one of the built-in // * validation variants. The SSL_CT_VALIDATION_PERMISSIVE variant always // * continues the handshake, the application can make appropriate decisions at // * handshake completion. The SSL_CT_VALIDATION_STRICT variant requires at // * least one valid SCT, or else handshake termination will be requested. The // * handshake may continue anyway if SSL_VERIFY_NONE is in_ effect. // */ function SSL_enable_ct(s: PSSL; validation_mode: TIdC_INT): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_enable_ct(ctx: PSSL_CTX; validation_mode: TIdC_INT): TIdC_INT cdecl; external CLibSSL; ///* // * Report whether a non-NULL callback is enabled. // */ function SSL_ct_is_enabled(const s: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_ct_is_enabled(const ctx: PSSL_CTX): TIdC_INT cdecl; external CLibSSL; ///* Gets the SCTs received from a connection */ //const STACK_OF(SCT) *SSL_get0_peer_scts(s: PSSL); function SSL_CTX_set_default_ctlog_list_file(ctx: PSSL_CTX): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_set_ctlog_list_file(ctx: PSSL_CTX; const path: PIdAnsiChar): TIdC_INT cdecl; external CLibSSL; procedure SSL_CTX_set0_ctlog_store(ctx: PSSL_CTX; logs: PCTLOG_STORE) cdecl; external CLibSSL; // const CTLOG_STORE *SSL_CTX_get0_ctlog_store(const ctx: PSSL_CTX); // # endif /* OPENSSL_NO_CT */ procedure SSL_set_security_level(s: PSSL; level: TIdC_INT) cdecl; external CLibSSL; ////__owur TIdC_INT SSL_get_security_level(const s: PSSL); procedure SSL_set_security_callback(s: PSSL; cb: SSL_security_callback) cdecl; external CLibSSL; function SSL_get_security_callback(const s: PSSL): SSL_security_callback cdecl; external CLibSSL; procedure SSL_set0_security_ex_data(s: PSSL; ex: Pointer) cdecl; external CLibSSL; function SSL_get0_security_ex_data(const s: PSSL): Pointer cdecl; external CLibSSL; procedure SSL_CTX_set_security_level(ctx: PSSL_CTX; level: TIdC_INT) cdecl; external CLibSSL; function SSL_CTX_get_security_level(const ctx: PSSL_CTX): TIdC_INT cdecl; external CLibSSL; //void SSL_CTX_set_security_callback(ctx: PSSL_CTX, // TIdC_INT (*cb) (const s: PSSL, const ctx: PSSL_CTX, // TIdC_INT op, TIdC_INT bits, TIdC_INT nid, // void *other, void *ex)); //TIdC_INT (*SSL_CTX_get_security_callback(const ctx: PSSL_CTX)) (const s: PSSL, // const ctx: PSSL_CTX, // TIdC_INT op, TIdC_INT bits, // TIdC_INT nid, // void *other, // void *ex); function SSL_CTX_get0_security_ex_data(const ctx: PSSL_CTX): Pointer cdecl; external CLibSSL; procedure SSL_CTX_set0_security_ex_data(ctx: PSSL_CTX; ex: Pointer) cdecl; external CLibSSL; function OPENSSL_init_ssl(opts: TIdC_UINT64; const settings: POPENSSL_INIT_SETTINGS): TIdC_INT cdecl; external CLibSSL; //# ifndef OPENSSL_NO_UNIT_TEST //__owur const struct openssl_ssl_test_functions *SSL_test_functions(void); //# endif function SSL_free_buffers(ssl: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_alloc_buffers(ssl: PSSL): TIdC_INT cdecl; external CLibSSL; function SSL_CTX_set_session_ticket_cb(ctx: PSSL_CTX; gen_cb: SSL_CTX_generate_session_ticket_fn; dec_cb: SSL_CTX_decrypt_session_ticket_fn; arg: Pointer): TIdC_INT cdecl; external CLibSSL; function SSL_SESSION_set1_ticket_appdata(ss: PSSL_SESSION; const data: Pointer; len: TIdC_SIZET): TIdC_INT cdecl; external CLibSSL; function SSL_SESSION_get0_ticket_appdata(ss: PSSL_SESSION; data: PPointer; len: PIdC_SIZET): TIdC_INT cdecl; external CLibSSL; //extern const PIdAnsiChar SSL_version_str[]; procedure DTLS_set_timer_cb(s: PSSL; cb: DTLS_timer_cb) cdecl; external CLibSSL; procedure SSL_CTX_set_allow_early_data_cb(ctx: PSSL_CTX; cb: SSL_allow_early_data_cb_fN; arg: Pointer) cdecl; external CLibSSL; procedure SSL_set_allow_early_data_cb(s: PSSL; cb: SSL_allow_early_data_cb_fN; arg: Pointer) cdecl; external CLibSSL; implementation //# define SSL_CTX_set_mode(ctx,op) SSL_CTX_ctrl((ctx),SSL_CTRL_MODE,(op),NULL) function SSL_CTX_set_mode(ctx: PSSL_CTX; op: TIdC_LONG): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_MODE, op, nil); end; //# define SSL_CTX_clear_mode(ctx,op) SSL_CTX_ctrl((ctx),SSL_CTRL_CLEAR_MODE,(op),NULL) function SSL_CTX_clear_mode(ctx: PSSL_CTX; op: TIdC_LONG): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_CLEAR_MODE, op, nil); end; //# define SSL_CTX_sess_set_cache_size(ctx,t) SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SESS_CACHE_SIZE,t,NULL) function SSL_CTX_sess_set_cache_size(ctx: PSSL_CTX; t: TIdC_LONG): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_SET_SESS_CACHE_SIZE, t, nil); end; //# define SSL_CTX_sess_get_cache_size(ctx) SSL_CTX_ctrl(ctx,SSL_CTRL_GET_SESS_CACHE_SIZE,0,NULL) function SSL_CTX_sess_get_cache_size(ctx: PSSL_CTX): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_GET_SESS_CACHE_SIZE, 0, nil); end; //# define SSL_CTX_set_session_cache_mode(ctx,m) SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SESS_CACHE_MODE,m,NULL) function SSL_CTX_set_session_cache_mode(ctx: PSSL_CTX; m: TIdC_LONG): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_SET_SESS_CACHE_MODE, m, nil); end; //# define SSL_CTX_get_session_cache_mode(ctx) SSL_CTX_ctrl(ctx,SSL_CTRL_GET_SESS_CACHE_MODE,0,NULL) function SSL_CTX_get_session_cache_mode(ctx: PSSL_CTX): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_GET_SESS_CACHE_MODE, 0, nil); end; //# define SSL_num_renegotiations(ssl) SSL_ctrl((ssl),SSL_CTRL_GET_NUM_RENEGOTIATIONS,0,NULL) function SSL_num_renegotiations(ssl: PSSL): TIdC_LONG; begin Result := SSL_ctrl(ssl, SSL_CTRL_GET_NUM_RENEGOTIATIONS, 0, nil); end; //# define SSL_clear_num_renegotiations(ssl) SSL_ctrl((ssl),SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS,0,NULL) function SSL_clear_num_renegotiations(ssl: PSSL): TIdC_LONG; begin Result := SSL_ctrl(ssl, SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS, 0, nil); end; //# define SSL_total_renegotiations(ssl) SSL_ctrl((ssl),SSL_CTRL_GET_TOTAL_RENEGOTIATIONS,0,NULL) function SSL_total_renegotiations(ssl: PSSL): TIdC_LONG; begin Result := SSL_ctrl(ssl, SSL_CTRL_GET_TOTAL_RENEGOTIATIONS, 0, nil); end; //# define SSL_CTX_set_tmp_dh(ctx,dh) SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_DH,0,(char *)(dh)) function SSL_CTX_set_tmp_dh(ctx: PSSL_CTX; dh: PByte): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TMP_DH, 0, dh); end; //# define SSL_CTX_set_tmp_ecdh(ctx,ecdh) SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_ECDH,0,(char *)(ecdh)) function SSL_CTX_set_tmp_ecdh(ctx: PSSL_CTX; ecdh: PByte): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TMP_ECDH, 0, ecdh); end; //# define SSL_CTX_set_dh_auto(ctx, onoff) SSL_CTX_ctrl(ctx,SSL_CTRL_SET_DH_AUTO,onoff,NULL) function SSL_CTX_set_dh_auto(ctx: PSSL_CTX; onoff: TIdC_LONG): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_SET_DH_AUTO, onoff, nil); end; //# define SSL_set_dh_auto(s, onoff) SSL_ctrl(s,SSL_CTRL_SET_DH_AUTO,onoff,NULL) function SSL_set_dh_auto(s: PSSL; onoff: TIdC_LONG): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_SET_DH_AUTO, onoff, nil); end; //# define SSL_set_tmp_dh(ssl,dh) SSL_ctrl(ssl,SSL_CTRL_SET_TMP_DH,0,(char *)(dh)) function SSL_set_tmp_dh(ssl: PSSL; dh: PByte): TIdC_LONG; begin Result := SSL_ctrl(ssl, SSL_CTRL_SET_TMP_DH, 0, dh); end; //# define SSL_set_tmp_ecdh(ssl,ecdh) SSL_ctrl(ssl,SSL_CTRL_SET_TMP_ECDH,0,(char *)(ecdh)) function SSL_set_tmp_ecdh(ssl: PSSL; ecdh: PByte): TIdC_LONG; begin Result := SSL_ctrl(ssl, SSL_CTRL_SET_TMP_ECDH, 0, ecdh); end; //# define SSL_CTX_add_extra_chain_cert(ctx,x509) SSL_CTX_ctrl(ctx,SSL_CTRL_EXTRA_CHAIN_CERT,0,(char *)(x509)) function SSL_CTX_add_extra_chain_cert(ctx: PSSL_CTX; x509: PByte): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_EXTRA_CHAIN_CERT, 0, x509); end; //# define SSL_CTX_get_extra_chain_certs(ctx,px509) SSL_CTX_ctrl(ctx,SSL_CTRL_GET_EXTRA_CHAIN_CERTS,0,px509) function SSL_CTX_get_extra_chain_certs(ctx: PSSL_CTX; px509: Pointer): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_GET_EXTRA_CHAIN_CERTS, 0, px509); end; //# define SSL_CTX_get_extra_chain_certs_only(ctx,px509) SSL_CTX_ctrl(ctx,SSL_CTRL_GET_EXTRA_CHAIN_CERTS,1,px509) function SSL_CTX_get_extra_chain_certs_only(ctx: PSSL_CTX; px509: Pointer): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_GET_EXTRA_CHAIN_CERTS, 1, px509); end; //# define SSL_CTX_clear_extra_chain_certs(ctx) SSL_CTX_ctrl(ctx,SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS,0,NULL) function SSL_CTX_clear_extra_chain_certs(ctx: PSSL_CTX): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS, 0, nil); end; //# define SSL_CTX_set0_chain(ctx,sk) SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN,0,(char *)(sk)) function SSL_CTX_set0_chain(ctx: PSSL_CTX; sk: PByte): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_CHAIN, 0, sk); end; //# define SSL_CTX_set1_chain(ctx,sk) SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN,1,(char *)(sk)) function SSL_CTX_set1_chain(ctx: PSSL_CTX; sk: PByte): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_CHAIN, 1, sk); end; //# define SSL_CTX_add0_chain_cert(ctx,x509) SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN_CERT,0,(char *)(x509)) function SSL_CTX_add0_chain_cert(ctx: PSSL_CTX; x509: PByte): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_CHAIN_CERT, 0, x509); end; //# define SSL_CTX_add1_chain_cert(ctx,x509) SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN_CERT,1,(char *)(x509)) function SSL_CTX_add1_chain_cert(ctx: PSSL_CTX; x509: PByte): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_CHAIN_CERT, 1, x509); end; //# define SSL_CTX_get0_chain_certs(ctx,px509) SSL_CTX_ctrl(ctx,SSL_CTRL_GET_CHAIN_CERTS,0,px509) function SSL_CTX_get0_chain_certs(ctx: PSSL_CTX; px509: Pointer): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_GET_CHAIN_CERTS, 0, px509); end; //# define SSL_CTX_clear_chain_certs(ctx) SSL_CTX_set0_chain(ctx,NULL) function SSL_CTX_clear_chain_certs(ctx: PSSL_CTX): TIdC_LONG; begin Result := SSL_CTX_set0_chain(ctx, nil); end; //# define SSL_CTX_build_cert_chain(ctx, flags) SSL_CTX_ctrl(ctx,SSL_CTRL_BUILD_CERT_CHAIN, flags, NULL) function SSL_CTX_build_cert_chain(ctx: PSSL_CTX; flags: TIdC_LONG): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_BUILD_CERT_CHAIN, flags, nil); end; //# define SSL_CTX_select_current_cert(ctx,x509) SSL_CTX_ctrl(ctx,SSL_CTRL_SELECT_CURRENT_CERT,0,(char *)(x509)) function SSL_CTX_select_current_cert(ctx: PSSL_CTX; x509: PByte): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_SELECT_CURRENT_CERT, 0, x509); end; //# define SSL_CTX_set_current_cert(ctx, op) SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CURRENT_CERT, op, NULL) function SSL_CTX_set_current_cert(ctx: PSSL_CTX; op: TIdC_LONG): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_SET_CURRENT_CERT, op, nil); end; //# define SSL_CTX_set0_verify_cert_store(ctx,st) SSL_CTX_ctrl(ctx,SSL_CTRL_SET_VERIFY_CERT_STORE,0,(char *)(st)) function SSL_CTX_set0_verify_cert_store(ctx: PSSL_CTX; st: Pointer): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_SET_VERIFY_CERT_STORE, 0, st); end; //# define SSL_CTX_set1_verify_cert_store(ctx,st) SSL_CTX_ctrl(ctx,SSL_CTRL_SET_VERIFY_CERT_STORE,1,(char *)(st)) function SSL_CTX_set1_verify_cert_store(ctx: PSSL_CTX; st: Pointer): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_SET_VERIFY_CERT_STORE, 1, st); end; //# define SSL_CTX_set0_chain_cert_store(ctx,st) SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CHAIN_CERT_STORE,0,(char *)(st)) function SSL_CTX_set0_chain_cert_store(ctx: PSSL_CTX; st: Pointer): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_SET_CHAIN_CERT_STORE, 0, st); end; //# define SSL_CTX_set1_chain_cert_store(ctx,st) SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CHAIN_CERT_STORE,1,(char *)(st)) function SSL_CTX_set1_chain_cert_store(ctx: PSSL_CTX; st: Pointer): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_SET_CHAIN_CERT_STORE, 1, st); end; //# define SSL_set0_chain(s,sk) SSL_ctrl(s,SSL_CTRL_CHAIN,0,(char *)(sk)) function SSL_set0_chain(s: PSSL; sk: PByte): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_CHAIN, 0, sk); end; //# define SSL_set1_chain(s,sk) SSL_ctrl(s,SSL_CTRL_CHAIN,1,(char *)(sk)) function SSL_set1_chain(s: PSSL; sk: PByte): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_CHAIN, 1, sk); end; //# define SSL_add0_chain_cert(s,x509) SSL_ctrl(s,SSL_CTRL_CHAIN_CERT,0,(char *)(x509)) function SSL_add0_chain_cert(s: PSSL; x509: PByte): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_CHAIN_CERT, 0, x509); end; //# define SSL_add1_chain_cert(s,x509) SSL_ctrl(s,SSL_CTRL_CHAIN_CERT,1,(char *)(x509)) function SSL_add1_chain_cert(s: PSSL; x509: PByte): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_CHAIN_CERT, 1, x509); end; //# define SSL_get0_chain_certs(s,px509) SSL_ctrl(s,SSL_CTRL_GET_CHAIN_CERTS,0,px509) function SSL_get0_chain_certs(s: PSSL; px509: Pointer): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_GET_CHAIN_CERTS, 0, px509); end; //# define SSL_clear_chain_certs(s) SSL_set0_chain(s,NULL) function SSL_clear_chain_certs(s: PSSL): TIdC_LONG; begin Result := SSL_set0_chain(s, nil); end; //# define SSL_build_cert_chain(s, flags) SSL_ctrl(s,SSL_CTRL_BUILD_CERT_CHAIN, flags, NULL) function SSL_build_cert_chain(s: PSSL; flags: TIdC_LONG): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_BUILD_CERT_CHAIN, flags, nil); end; //# define SSL_select_current_cert(s,x509) SSL_ctrl(s,SSL_CTRL_SELECT_CURRENT_CERT,0,(char *)(x509)) function SSL_select_current_cert(s: PSSL; x509: PByte): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_SELECT_CURRENT_CERT, 0, x509); end; //# define SSL_set_current_cert(s,op) SSL_ctrl(s,SSL_CTRL_SET_CURRENT_CERT, op, NULL) function SSL_set_current_cert(s: PSSL; op: TIdC_LONG): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_SET_CURRENT_CERT, op, nil); end; //# define SSL_set0_verify_cert_store(s,st) SSL_ctrl(s,SSL_CTRL_SET_VERIFY_CERT_STORE,0,(char *)(st)) function SSL_set0_verify_cert_store(s: PSSL; st: PByte): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_SET_VERIFY_CERT_STORE, 0, st); end; //# define SSL_set1_verify_cert_store(s,st) SSL_ctrl(s,SSL_CTRL_SET_VERIFY_CERT_STORE,1,(char *)(st)) function SSL_set1_verify_cert_store(s: PSSL; st: PByte): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_SET_VERIFY_CERT_STORE, 1, st); end; //# define SSL_set0_chain_cert_store(s,st) SSL_ctrl(s,SSL_CTRL_SET_CHAIN_CERT_STORE,0,(char *)(st)) function SSL_set0_chain_cert_store(s: PSSL; st: PByte): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_SET_CHAIN_CERT_STORE, 0, st); end; //# define SSL_set1_chain_cert_store(s,st) SSL_ctrl(s,SSL_CTRL_SET_CHAIN_CERT_STORE,1,(char *)(st)) function SSL_set1_chain_cert_store(s: PSSL; st: PByte): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_SET_CHAIN_CERT_STORE, 1, st); end; //# define SSL_get1_groups(s, glist) SSL_ctrl(s,SSL_CTRL_GET_GROUPS,0,(TIdC_INT*)(glist)) function SSL_get1_groups(s: PSSL; glist: PIdC_INT): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_GET_GROUPS, 0, glist); end; //# define SSL_CTX_set1_groups(ctx, glist, glistlen) SSL_CTX_ctrl(ctx,SSL_CTRL_SET_GROUPS,glistlen,(char *)(glist)) function SSL_CTX_set1_groups(ctx: PSSL_CTX; glist: PByte; glistlen: TIdC_LONG): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_SET_GROUPS, glistlen, glist); end; //# define SSL_CTX_set1_groups_list(ctx, s) SSL_CTX_ctrl(ctx,SSL_CTRL_SET_GROUPS_LIST,0,(char *)(s)) function SSL_CTX_set1_groups_list(ctx: PSSL_CTX; s: PByte): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_SET_GROUPS_LIST, 0, s); end; //# define SSL_set1_groups(s, glist, glistlen) SSL_ctrl(s,SSL_CTRL_SET_GROUPS,glistlen,(char *)(glist)) function SSL_set1_groups(s: PSSL; glist: PByte; glistlen: TIdC_LONG): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_SET_GROUPS, glistlen, glist); end; //# define SSL_set1_groups_list(s, str) SSL_ctrl(s,SSL_CTRL_SET_GROUPS_LIST,0,(char *)(str)) function SSL_set1_groups_list(s: PSSL; str: PByte): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_SET_GROUPS_LIST, 0, str); end; //# define SSL_get_shared_group(s, n) SSL_ctrl(s,SSL_CTRL_GET_SHARED_GROUP,n,NULL) function SSL_get_shared_group(s: PSSL; n: TIdC_LONG): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_GET_SHARED_GROUP, n, nil); end; //# define SSL_CTX_set1_sigalgs(ctx, slist, slistlen) SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SIGALGS,slistlen,(TIdC_INT *)(slist)) function SSL_CTX_set1_sigalgs(ctx: PSSL_CTX; slist: PIdC_INT; slistlen: TIdC_LONG): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_SET_SIGALGS, slistlen, slist); end; //# define SSL_CTX_set1_sigalgs_list(ctx, s) SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SIGALGS_LIST,0,(char *)(s)) function SSL_CTX_set1_sigalgs_list(ctx: PSSL_CTX; s: PByte): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_SET_SIGALGS_LIST, 0, s); end; //# define SSL_set1_sigalgs(s, slist, slistlen) SSL_ctrl(s,SSL_CTRL_SET_SIGALGS,slistlen,(TIdC_INT *)(slist)) function SSL_set1_sigalgs(s: PSSL; slist: PIdC_INT; slistlen: TIdC_LONG): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_SET_SIGALGS, slistlen, slist); end; //# define SSL_set1_sigalgs_list(s, str) SSL_ctrl(s,SSL_CTRL_SET_SIGALGS_LIST,0,(char *)(str)) function SSL_set1_sigalgs_list(s: PSSL; str: PByte): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_SET_SIGALGS_LIST, 0, str); end; //# define SSL_CTX_set1_client_sigalgs(ctx, slist, slistlen) SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CLIENT_SIGALGS,slistlen,(TIdC_INT *)(slist)) function SSL_CTX_set1_client_sigalgs(ctx: PSSL_CTX; slist: PIdC_INT; slistlen: TIdC_LONG): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_SET_CLIENT_SIGALGS, slistlen, slist); end; //# define SSL_CTX_set1_client_sigalgs_list(ctx, s) SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CLIENT_SIGALGS_LIST,0,(char *)(s)) function SSL_CTX_set1_client_sigalgs_list(ctx: PSSL_CTX; s: PByte): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_SET_CLIENT_SIGALGS_LIST, 0, s); end; //# define SSL_set1_client_sigalgs(s, slist, slistlen) SSL_ctrl(s,SSL_CTRL_SET_CLIENT_SIGALGS,slistlen,(TIdC_INT *)(slist)) function SSL_set1_client_sigalgs(s: PSSL; slist: PIdC_INT; slistlen: TIdC_LONG): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_SET_CLIENT_SIGALGS, slistlen, slist); end; //# define SSL_set1_client_sigalgs_list(s, str) SSL_ctrl(s,SSL_CTRL_SET_CLIENT_SIGALGS_LIST,0,(char *)(str)) function SSL_set1_client_sigalgs_list(s: PSSL; str: PByte): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_SET_CLIENT_SIGALGS_LIST, 0, str); end; //# define SSL_get0_certificate_types(s, clist) SSL_ctrl(s, SSL_CTRL_GET_CLIENT_CERT_TYPES, 0, (char *)(clist)) function SSL_get0_certificate_types(s: PSSL; clist: PByte): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_GET_CLIENT_CERT_TYPES, 0, clist); end; //# define SSL_CTX_set1_client_certificate_types(ctx, clist, clistlen) SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CLIENT_CERT_TYPES,clistlen, (char *)(clist)) function SSL_CTX_set1_client_certificate_types(ctx: PSSL_CTX; clist: PByte; clistlen: TIdC_LONG): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_SET_CLIENT_CERT_TYPES, clistlen, clist); end; //# define SSL_set1_client_certificate_types(s, clist, clistlen) SSL_ctrl(s,SSL_CTRL_SET_CLIENT_CERT_TYPES,clistlen,(char *)(clist)) function SSL_set1_client_certificate_types(s: PSSL; clist: PByte; clistlen: TIdC_LONG): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_SET_CLIENT_CERT_TYPES, clistlen, clist); end; //# define SSL_get_signature_nid(s, pn) SSL_ctrl(s,SSL_CTRL_GET_SIGNATURE_NID,0,pn) function SSL_get_signature_nid(s: PSSL; pn: Pointer): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_GET_SIGNATURE_NID, 0, pn); end; //# define SSL_get_peer_signature_nid(s, pn) SSL_ctrl(s,SSL_CTRL_GET_PEER_SIGNATURE_NID,0,pn) function SSL_get_peer_signature_nid(s: PSSL; pn: Pointer): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_GET_PEER_SIGNATURE_NID, 0, pn); end; //# define SSL_get_peer_tmp_key(s, pk) SSL_ctrl(s,SSL_CTRL_GET_PEER_TMP_KEY,0,pk) function SSL_get_peer_tmp_key(s: PSSL; pk: Pointer): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_GET_PEER_TMP_KEY, 0, pk); end; //# define SSL_get_tmp_key(s, pk) SSL_ctrl(s,SSL_CTRL_GET_TMP_KEY,0,pk) function SSL_get_tmp_key(s: PSSL; pk: Pointer): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_GET_TMP_KEY, 0, pk); end; //# define SSL_get0_raw_cipherlist(s, plst) SSL_ctrl(s,SSL_CTRL_GET_RAW_CIPHERLIST,0,plst) function SSL_get0_raw_cipherlist(s: PSSL; plst: Pointer): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_GET_RAW_CIPHERLIST, 0, plst); end; //# define SSL_get0_ec_point_formats(s, plst) SSL_ctrl(s,SSL_CTRL_GET_EC_POINT_FORMATS,0,plst) function SSL_get0_ec_point_formats(s: PSSL; plst: Pointer): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_GET_EC_POINT_FORMATS, 0, plst); end; //# define SSL_CTX_set_min_proto_version(ctx, version) SSL_CTX_ctrl(ctx, SSL_CTRL_SET_MIN_PROTO_VERSION, version, NULL) function SSL_CTX_set_min_proto_version(ctx: PSSL_CTX; version: TIdC_LONG): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_SET_MIN_PROTO_VERSION, version, nil); end; //# define SSL_CTX_set_max_proto_version(ctx, version) SSL_CTX_ctrl(ctx, SSL_CTRL_SET_MAX_PROTO_VERSION, version, NULL) function SSL_CTX_set_max_proto_version(ctx: PSSL_CTX; version: TIdC_LONG): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_SET_MAX_PROTO_VERSION, version, nil); end; //# define SSL_CTX_get_min_proto_version(ctx) SSL_CTX_ctrl(ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL) function SSL_CTX_get_min_proto_version(ctx: PSSL_CTX): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, nil); end; //# define SSL_CTX_get_max_proto_version(ctx) SSL_CTX_ctrl(ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL) function SSL_CTX_get_max_proto_version(ctx: PSSL_CTX): TIdC_LONG; begin Result := SSL_CTX_ctrl(ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, nil); end; //# define SSL_set_min_proto_version(s, version) SSL_ctrl(s, SSL_CTRL_SET_MIN_PROTO_VERSION, version, NULL) function SSL_set_min_proto_version(s: PSSL; version: TIdC_LONG): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_SET_MIN_PROTO_VERSION, version, nil); end; //# define SSL_set_max_proto_version(s, version) SSL_ctrl(s, SSL_CTRL_SET_MAX_PROTO_VERSION, version, NULL) function SSL_set_max_proto_version(s: PSSL; version: TIdC_LONG): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_SET_MAX_PROTO_VERSION, version, nil); end; //# define SSL_get_min_proto_version(s) SSL_ctrl(s, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL) function SSL_get_min_proto_version(s: PSSL): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, nil); end; //# define SSL_get_max_proto_version(s) SSL_ctrl(s, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL) function SSL_get_max_proto_version(s: PSSL): TIdC_LONG; begin Result := SSL_ctrl(s, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, nil); end; end.
unit fmMensajePageWizard; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, fmMensaje, ActnList, OleCtrls, Buttons, JvExControls, ExtCtrls, wizard, Readhtml, FramView, FramBrwz, JvXPCore, JvXPButtons; type TfMensajePageWizard = class(TfMensaje, IWizardPage) procedure HechoClick(Sender: TObject); private wizardMethods: TWizardMethods; procedure setWizardMethods(const wizardMethods: TWizardMethods); function getForm: TForm; public function hasMessage: boolean; end; implementation uses UserServerCalls; {$R *.dfm} { TfMensajePageWizard } function TfMensajePageWizard.getForm: TForm; begin result := Self; end; function TfMensajePageWizard.hasMessage: boolean; var serverCall: TMensajeServerCall; msg: string; begin serverCall := TMensajeServerCall.Create; try try msg := serverCall.Call; result := msg <> 'no'; if result then URI := msg; except on e: Exception do result := false; end; finally serverCall.Free; end; end; procedure TfMensajePageWizard.HechoClick(Sender: TObject); begin inherited; wizardMethods.Close; end; procedure TfMensajePageWizard.setWizardMethods( const wizardMethods: TWizardMethods); begin Self.wizardMethods := wizardMethods; end; end.
unit DCPEncrypt; // HMAC (Hash-based Message Authentication Code) // PBKDF1/PBKDF2 (Password-Based Key Derivation Function 1/2) // adapted from code found at http://keit.co/p/dcpcrypt-hmac-rfc2104/ interface uses DCPcrypt2, DCPsha1, DCPmd5, DCPsha512, DCPhaval, DCPmd4, DCPtiger, DCPripemd128, DCPripemd160, DCPsha256, Math; function CalcHMAC(message, key: string; hash: TDCP_hashclass): string; function PBKDF1(pass, salt: ansistring; count: Integer; hash: TDCP_hashclass): ansistring; function PBKDF2(pass, salt: ansistring; count, kLen: Integer; hash: TDCP_hashclass): ansistring; implementation function RPad(x: string; c: Char; s: Integer): string; var i: Integer; begin Result := x; if Length(x) < s then for i := 1 to s-Length(x) do Result := Result + c; end; function XorBlock(s, x: ansistring): ansistring; inline; var i: Integer; begin SetLength(Result, Length(s)); for i := 1 to Length(s) do Result[i] := Char(Byte(s[i]) xor Byte(x[i])); end; function CalcDigest(text: string; dig: TDCP_hashclass): string; var x: TDCP_hash; begin x := dig.Create(nil); try x.Init; x.UpdateStr(text); SetLength(Result, x.GetHashSize div 8); x.Final(Result[1]); finally x.Free; end; end; function CalcHMAC(message, key: string; hash: TDCP_hashclass): string; const blocksize_big = 128; blocksize_small = 64; var blocksize : Integer; begin // https://en.wikipedia.org/wiki/Comparison_of_cryptographic_hash_functions if (hash = TDCP_sha384) or (hash = TDCP_sha512) or (hash = TDCP_sha512base) or (hash = TDCP_haval) then begin blocksize := blocksize_big; end else if (hash = TDCP_sha256) or (hash = TDCP_sha1) or (hash = TDCP_ripemd128) or (hash = TDCP_ripemd160) or (hash = TDCP_tiger) or (hash = TDCP_md4) or (hash = TDCP_md5) then begin blocksize := blocksize_small; end else begin blocksize := blocksize_small; end; // Definition RFC 2104 if Length(key) > blocksize then key := CalcDigest(key, hash) else key := RPad(key, #0, blocksize); Result := CalcDigest(XorBlock(key, RPad('', #$36, blocksize)) + message, hash); Result := CalcDigest(XorBlock(key, RPad('', #$5c, blocksize)) + result, hash); end; function PBKDF1(pass, salt: ansistring; count: Integer; hash: TDCP_hashclass): ansistring; var i: Integer; begin Result := pass+salt; for i := 0 to count-1 do Result := CalcDigest(Result, hash); end; function PBKDF2(pass, salt: ansistring; count, kLen: Integer; hash: TDCP_hashclass): ansistring; function IntX(i: Integer): ansistring; inline; begin Result := Char(i shr 24) + Char(i shr 16) + Char(i shr 8) + Char(i); end; var D, I, J: Integer; T, F, U: ansistring; begin T := ''; D := Ceil(kLen / (hash.GetHashSize div 8)); for i := 1 to D do begin F := CalcHMAC(salt + IntX(i), pass, hash); U := F; for j := 2 to count do begin U := CalcHMAC(U, pass, hash); F := XorBlock(F, U); end; T := T + F; end; Result := Copy(T, 1, kLen); end;
unit KM_NetClientOverbyte; {$I KaM_Remake.inc} interface uses Classes, SysUtils, WSocket, WinSock; { This unit knows nothing about KaM, it's just a puppet in hands of KM_ClientControl, doing all the low level work on TCP. So we can replace this unit with other TCP client without KaM even noticing. } type TNotifyDataEvent = procedure(aData:pointer; aLength:cardinal)of object; TKMNetClientOverbyte = class private fSocket:TWSocket; fOnError:TGetStrProc; fOnConnectSucceed:TNotifyEvent; fOnConnectFailed:TGetStrProc; fOnSessionDisconnected:TNotifyEvent; fOnRecieveData:TNotifyDataEvent; procedure Connected(Sender: TObject; Error: Word); procedure Disconnected(Sender: TObject; Error: Word); procedure DataAvailable(Sender: TObject; Error: Word); public constructor Create; destructor Destroy; override; function MyIPString:string; procedure ConnectTo(const aAddress:string; const aPort:string); procedure Disconnect; procedure SendData(aData:pointer; aLength:cardinal); property OnError:TGetStrProc write fOnError; property OnConnectSucceed:TNotifyEvent write fOnConnectSucceed; property OnConnectFailed:TGetStrProc write fOnConnectFailed; property OnSessionDisconnected:TNotifyEvent write fOnSessionDisconnected; property OnRecieveData:TNotifyDataEvent write fOnRecieveData; end; implementation constructor TKMNetClientOverbyte.Create; var wsaData: TWSAData; begin Inherited Create; Assert(WSAStartup($101, wsaData) = 0, 'Error in Network'); end; destructor TKMNetClientOverbyte.Destroy; begin if fSocket<>nil then fSocket.Free; Inherited; end; function TKMNetClientOverbyte.MyIPString:string; begin if LocalIPList.Count >= 1 then Result := LocalIPList[0] //First address should be ours else Result := ''; end; procedure TKMNetClientOverbyte.ConnectTo(const aAddress:string; const aPort:string); begin fSocket := TWSocket.Create(nil); fSocket.Proto := 'tcp'; fSocket.Addr := aAddress; fSocket.Port := aPort; fSocket.OnSessionClosed := Disconnected; fSocket.OnSessionConnected := Connected; fSocket.OnDataAvailable := DataAvailable; fSocket.Connect; end; procedure TKMNetClientOverbyte.Disconnect; begin if fSocket <> nil then fSocket.Close; end; procedure TKMNetClientOverbyte.SendData(aData:pointer; aLength:cardinal); begin fSocket.Send(aData, aLength); end; procedure TKMNetClientOverbyte.Connected(Sender: TObject; Error: Word); begin if Error <> 0 then fOnConnectFailed('Error #' + IntToStr(Error)) else fOnConnectSucceed(Self); end; procedure TKMNetClientOverbyte.Disconnected(Sender: TObject; Error: Word); begin if Error <> 0 then fOnError('Client: Disconnection error #' + IntToStr(Error)) else fOnSessionDisconnected(Self); end; procedure TKMNetClientOverbyte.DataAvailable(Sender: TObject; Error: Word); const BufferSize = 10240; //10kb var P:pointer; L:integer; //L could be -1 when no data is available begin if Error <> 0 then begin fOnError('DataAvailable. Error #' + IntToStr(Error)); exit; end; GetMem(P, BufferSize+1); //+1 to avoid RangeCheckError when L = BufferSize L := TWSocket(Sender).Receive(P, BufferSize); if L > 0 then //if L=0 then exit; fOnRecieveData(P, L); FreeMem(P); end; end.
unit MPI_Matrix; interface type PMatrix = ^TMatrix; TMatrix = record nStrok, nStolb : Integer; Matrix : array of array of Extended; end; PMatrixArray = array of PMatrix; { PVector = ^TVector; TVector = record nStrok : Integer; Vector : array of array of Extended; end;} procedure SetMatrix(aStrok, aStolb : Integer; M : PMatrix); // -------- Математические операции -------- function MM (A, B : PMatrix):TMatrix; // Умножение матрицы на матрицу function SumM(A, B : PMatrix):TMatrix; // Сложение матриц function SubM(A, B : PMatrix):TMatrix; // Вычитание матриц // -------- Операции перобразований -------- function TM(M : PMatrix):TMatrix; // Транспонирование матрицы var MatrixArray : PMatrixArray; implementation //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure SetMatrix(aStrok, aStolb : Integer; M : PMatrix); var i, j : integer; begin M.nStrok := aStrok; M.nStolb := aStolb; SetLength(M.Matrix , aStrok, aStolb ); for i := 0 to M^.nStrok - 1 do for j := 0 to M^.nStolb - 1 do M^.Matrix[i][j] := 0; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++ Умножение матрицы на матрицу +++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function MM(A, B : PMatrix) : TMatrix; var k, i, j : Integer; CurSum : Extended; begin if A.nStolb <> B.nStrok then begin result.nStrok := -9999999; result.nStolb := -9999999; result.Matrix := nil; exit; end; //--------------------------------- result.nStrok := A.nStrok; result.nStolb := B.nStolb; SetLength(result.Matrix, A.nStrok, B.nStolb); //--------------------------------- for i:=0 to A.nStrok-1 do for j:=0 to B.nStolb-1 do begin CurSum := 0; for k:=0 to A.nStolb - 1 do CurSum := CurSum + A.MAtrix[i,k] * B.Matrix[k,j]; result.Matrix[i,j] := CurSum; end; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++ Сложение матриц +++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function SumM(A, B : PMatrix):TMatrix; // var i, j : Integer; begin if (A.nStrok <> B.nStrok) or (A.nStolb <> B.nStolb) then begin result.nStrok := -9999999; result.nStolb := -9999999; result.Matrix := nil; exit; end; //--------------------------------- result.nStrok := A.nStrok; result.nStolb := A.nStolb; SetLength(result.Matrix, A.nStrok, A.nStolb); //--------------------------------- for i:=0 to A.nStrok-1 do for j:=0 to A.nStolb-1 do result.Matrix[i,j] := A.Matrix[i,j] + B.Matrix[i,j]; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++ Вычитание матриц ++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function SubM(A, B : PMatrix):TMatrix; // var i, j : Integer; begin if (A.nStrok <> B.nStrok) or (A.nStolb <> B.nStolb) then begin result.nStrok := -9999999; result.nStolb := -9999999; result.Matrix := nil; exit; end; //--------------------------------- result.nStrok := A.nStrok; result.nStolb := A.nStolb; SetLength(result.Matrix, A.nStrok, A.nStolb); //--------------------------------- for i:=0 to A.nStrok-1 do for j:=0 to A.nStolb-1 do result.Matrix[i,j] := A.Matrix[i,j] - B.Matrix[i,j]; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++ Транспонирование матрицы ++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function TM(M : PMatrix):TMatrix; // Транспонирование матрицы var i,j : integer; begin //--------------------------------- result.nStrok := M.nStolb; result.nStolb := M.nStrok; SetLength(result.Matrix, result.nStrok, result.nStolb); //--------------------------------- for i:=0 to result.nStrok-1 do for j:=0 to result.nStolb-1 do result.Matrix[i,j] := M.Matrix[j,i]; end; end.
unit Controller.Clientes; interface uses Controller.Clientes.Interfaces, FireDAC.Comp.Client, System.SysUtils, Data.DB, Entidades.Clientes; type TCLIENTES = class(TInterfacedObject,iCLIENTES) private FConnection : TFDConnection; FQuery : TFDQuery; FDatasource : TDataSource; FEntidade : TCLIENTE; public constructor Create(aConnection : TFDConnection); destructor Destroy; override; class function New(aConnection : TFDConnection) : iCLIENTES; function Inserir : iCLIENTES; function Atualizar : iCLIENTES; function Excluir : iCLIENTES; function Datasource(aDatasource : TDatasource) : iCLIENTES; function Buscar : iCLIENTES; overload; function Buscar(filtro : string) : iCLIENTES; overload; function Buscar(codigo : integer) : iCLIENTES; overload; function CLIENTE : TCLIENTE; end; implementation { TCLIENTES } function TCLIENTES.Atualizar: iCLIENTES; var sql : string; begin Result := Self; FQuery.Close; FQuery.SQL.Clear; sql := 'update clientes set NOME = :NOME, CIDADE = :CIDADE, UF = :UF where CODIGO = :CODIGO'; try FQuery.SQL.Add(sql); FQuery.ParamByName('CODIGO').Value := FEntidade.CODIGO; FQuery.ParamByName('NOME').Value := FEntidade.NOME; FQuery.ParamByName('CIDADE').Value := FEntidade.CIDADE; FQuery.ParamByName('UF').Value := FEntidade.UF; FQuery.ExecSQL; except raise Exception.Create('Erro na atualização'); end; end; function TCLIENTES.Buscar(filtro: string): iCLIENTES; var sql, ordem : string; aux : integer; begin Result := Self; FQuery.Close; FQuery.SQL.Clear; sql := 'select * from clientes'; ordem := ' order by NOME'; if filtro <> '' then begin try aux := StrToInt(filtro); sql := sql + ' where CODIGO = '+(filtro); except sql := sql + ' where NOME LIKE '+QuotedStr('%'+filtro+'%'); end; end; try FQuery.Open(sql + ordem); except raise Exception.Create('Erro na busca de dados'); end; end; function TCLIENTES.Buscar: iCLIENTES; begin Result := Self; FQuery.Close; FQuery.SQL.Clear; try FQuery.Open('select * from clientes order by NOME'); except raise Exception.Create('Erro na busca de dados'); end; end; function TCLIENTES.Buscar(codigo: integer): iCLIENTES; begin Result := Self; FQuery.Close; FQuery.SQL.Clear; try FQuery.Open('select * from clientes where CODIGO = '+IntToStr(codigo)); FEntidade.CODIGO := FQuery.FieldByName('CODIGO').Value; FEntidade.NOME := FQuery.FieldByName('NOME').Value; FEntidade.CIDADE := FQuery.FieldByName('CIDADE').Value; FEntidade.UF := FQuery.FieldByName('UF').Value; except raise Exception.Create('Erro na busca de dados'); end; end; function TCLIENTES.CLIENTE: TCLIENTE; begin Result := FEntidade; end; constructor TCLIENTES.Create(aConnection : TFDConnection); begin FConnection := aConnection; FQuery := TFDQuery.Create(nil); FQuery.Connection := FConnection; FEntidade := TCLIENTE.Create; end; function TCLIENTES.Datasource(aDatasource: TDatasource): iCLIENTES; begin Result := Self; FDataSource := aDataSource; FDatasource.DataSet := FQuery; end; destructor TCLIENTES.Destroy; begin FreeAndNil(FQuery); FreeAndNil(FEntidade); inherited; end; function TCLIENTES.Excluir: iCLIENTES; var sql : string; begin Result := Self; FQuery.Close; FQuery.SQL.Clear; sql := 'delete from clientes where CODIGO = :CODIGO'; try FQuery.SQL.Add(sql); FQuery.ParamByName('CODIGO').Value := FEntidade.CODIGO; FQuery.ExecSQL; except raise Exception.Create('Erro na exclusão'); end; end; function TCLIENTES.Inserir: iCLIENTES; var sql : string; begin Result := Self; FQuery.Close; FQuery.SQL.Clear; sql := 'insert into clientes (NOME, CIDADE, UF) values (:NOME, :CIDADE, :UF)'; try FQuery.SQL.Add(sql); FQuery.ParamByName('NOME').Value := FEntidade.NOME; FQuery.ParamByName('CIDADE').Value := FEntidade.CIDADE; FQuery.ParamByName('UF').Value := FEntidade.UF; FQuery.ExecSQL; except raise Exception.Create('Erro na inserção'); end; end; class function TCLIENTES.New(aConnection : TFDConnection) : iCLIENTES; begin Result := Self.Create(aConnection); end; end.
unit RepositorioIpiNt; interface uses DB, Repositorio; type TRepositorioIpiNt = class(TRepositorio) protected function Get (Dataset :TDataSet) :TObject; overload; override; function GetNomeDaTabela :String; override; function GetIdentificador(Objeto :TObject) :Variant; override; function GetRepositorio :TRepositorio; override; protected function SQLGet :String; override; function SQLSalvar :String; override; function SQLGetAll :String; override; function SQLRemover :String; override; protected function IsInsercao(Objeto :TObject) :Boolean; override; function IsComponente :Boolean; override; protected procedure SetParametros (Objeto :TObject ); override; end; implementation uses IpiNt, SysUtils; { TRepositorioIpiNt } function TRepositorioIpiNt.Get(Dataset: TDataSet): TObject; begin result := TIpiNt.Create; end; function TRepositorioIpiNt.GetIdentificador(Objeto: TObject): Variant; begin result := TIpiNt(Objeto).CodigoItem; end; function TRepositorioIpiNt.GetNomeDaTabela: String; begin result := 'itens_nf_ipi_nt'; end; function TRepositorioIpiNt.GetRepositorio: TRepositorio; begin result := TRepositorioIpiNt.Create; end; function TRepositorioIpiNt.IsComponente: Boolean; begin result := true; end; function TRepositorioIpiNt.IsInsercao(Objeto: TObject): Boolean; begin result := true; end; procedure TRepositorioIpiNt.SetParametros(Objeto: TObject); var Obj :TIpiNt; begin Obj := (Objeto as TIpiNt); inherited SetParametro('codigo_item', Obj.CodigoItem); end; function TRepositorioIpiNt.SQLGet: String; begin result := 'select * from '+self.GetNomeDaTabela+' where codigo_item = :codigo_item'; end; function TRepositorioIpiNt.SQLGetAll: String; begin result := 'select * from '+self.GetNomeDaTabela; end; function TRepositorioIpiNt.SQLRemover: String; begin result := 'delete from '+self.GetNomeDaTabela+' where codigo_item = :codigo_item'; end; function TRepositorioIpiNt.SQLSalvar: String; begin result := ' update or insert into ' + self.GetNomeDaTabela + ' (codigo_item) '+ ' values (:codigo_item) '; end; end.
{***************************************************************************} { } { DelphiUIAutomation } { } { Copyright 2015 JHC Systems Limited } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DelphiUIAutomation.ComboBox; interface uses generics.collections, DelphiUIAutomation.Base, DelphiUIAutomation.ListItem, UIAutomationClient_TLB; type IAutomationComboBox = interface (IAutomationBase) ['{531C8646-A605-4D6D-BEE0-89E1719D6321}'] ///<summary> /// Gets the text associated with this combobox ///</summary> function getText: string; ///<summary> /// Sets the text associated with this combobox ///</summary> procedure setText(const Value: string); ///<summary> /// Gets or sets the text associated with this combobox ///</summary> property Text : string read getText write setText; end; /// <summary> /// Represents a combobox control /// </summary> TAutomationComboBox = class (TAutomationBase, IAutomationComboBox) strict private FItems : TObjectList<TAutomationListItem>; FExpandCollapsePattern : IUIAutomationExpandCollapsePattern; FValuePattern : IUIAutomationValuePattern; private ///<summary> /// Gets the text associated with this combobox ///</summary> function getText: string; ///<summary> /// Sets the text associated with this combobox ///</summary> procedure setText(const Value: string); function getItems: TObjectList<TAutomationListItem>; procedure InitialiseList; public ///<summary> /// Gets or sets the text associated with this combobox ///</summary> property Text : string read getText write setText; ///<summary> /// Gets the list of items associated with this combobox ///</summary> property Items : TObjectList<TAutomationListItem> read getItems; /// <summary> /// Call the expand property /// </summary> function Expand : HRESULT; /// <summary> /// Call the collapse property /// </summary> function Collapse : HRESULT; /// <summary> /// Constructor for comboboxes. /// </summary> constructor Create(element : IUIAutomationElement); override; /// <summary> /// Destructor for comboboxes. /// </summary> destructor Destroy; override; end; implementation uses ActiveX, DelphiUIAutomation.Exception, DelphiUIAutomation.Automation, DelphiUIAutomation.ControlTypeIDs, DelphiUIAutomation.PropertyIDs, DelphiUIAutomation.PatternIDs, sysutils; { TAutomationComboBox } constructor TAutomationComboBox.Create(element: IUIAutomationElement); begin inherited Create(element); FExpandCollapsePattern := GetExpandCollapsePattern; FValuePattern := GetValuePattern; self.Expand; // Have to expand for the list to be available InitialiseList; end; destructor TAutomationComboBox.Destroy; begin FItems.free; inherited; end; procedure TAutomationComboBox.InitialiseList; var collection : IUIAutomationElementArray; itemElement : IUIAutomationElement; count : integer; length : integer; retVal : integer; item : TAutomationListItem; begin FItems := TObjectList<TAutomationListItem>.create; // Find the elements collection := self.FindAll(TreeScope_Children); collection.Get_Length(length); for count := 0 to length -1 do begin collection.GetElement(count, itemElement); itemElement.Get_CurrentControlType(retVal); if (retVal = UIA_ListItemControlTypeId) then begin item := TAutomationListItem.Create(itemElement); FItems.Add(item); end; end; end; function TAutomationComboBox.Expand: HRESULT; begin if assigned(FExpandCollapsePattern) then result := self.FExpandCollapsePattern.Expand else result := -1; end; function TAutomationComboBox.Collapse: HRESULT; begin result := self.FExpandCollapsePattern.Collapse; end; function TAutomationComboBox.getItems : TObjectList<TAutomationListItem>; begin result := self.FItems; end; function TAutomationComboBox.getText: string; var value : widestring; begin FValuePattern.Get_CurrentValue(value); Result := trim(value); end; procedure TAutomationComboBox.setText(const Value: string); begin FValuePattern.SetValue(value); end; end.
unit uMemory; interface Uses System.SysUtils; function getMemoryAllocated : UInt64; implementation function getMemoryAllocated : UInt64; var st: TMemoryManagerState; sb: TSmallBlockTypeState; begin GetMemoryManagerState(st); result := st.TotalAllocatedMediumBlockSize + st.TotalAllocatedLargeBlockSize; for sb in st.SmallBlockTypeStates do result := result + sb.UseableBlockSize * sb.AllocatedBlockCount; end; end.
{**********************************************************************} { } { "The contents of this file are subject to the Mozilla Public } { License Version 1.1 (the "License"); you may not use this } { file except in compliance with the License. You may obtain } { a copy of the License at http://www.mozilla.org/MPL/ } { } { Software distributed under the License is distributed on an } { "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express } { or implied. See the License for the specific language } { governing rights and limitations under the License. } { } { Copyright Creative IT. } { Current maintainer: Eric Grange } { } {**********************************************************************} unit dwsWebLibModule; interface uses SysUtils, Classes, StrUtils, dwsUtils, dwsComp, dwsExprs, dwsWebEnvironment, dwsExprList, dwsSymbols, SynZip, SynCrtSock, SynCommons; type TdwsWebLib = class(TDataModule) dwsWeb: TdwsUnit; procedure dwsWebClassesWebRequestMethodsURLEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebRequestMethodsMethodEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebRequestMethodsPathInfoEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebRequestMethodsQueryStringEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebRequestMethodsRemoteIPEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebResponseMethodsContentDataEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebResponseMethodsContentTypeEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebResponseMethodsContentEncodingEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebRequestMethodsHeaderEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebRequestMethodsHeadersEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebRequestMethodsCookieEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebRequestMethodsCookiesEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebRequestMethodsQueryFieldEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebRequestMethodsQueryFieldsEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebResponseMethodsSetContentTextEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebRequestMethodsSecureEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebRequestMethodsUserAgentEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebRequestMethodsAuthenticatedUserEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebResponseMethodsSetStatusCodeEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebResponseMethodsSetHeaderEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebRequestMethodsAuthenticationEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebResponseMethodsRequestAuthenticationEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebRequestMethodsHasQueryFieldEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebResponseMethodsSetCookieEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebResponseMethodsSetCookie2Eval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebResponseMethodsSetCompressionEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebRequestMethodsContentTypeEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebRequestMethodsContentDataEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebRequestMethodsContentLengthEval( Info: TProgramInfo; ExtObject: TObject); function dwsWebFunctionsDeflateCompressFastEval( const args: TExprBaseListExec): Variant; function dwsWebFunctionsDeflateDecompressionFastEval( const args: TExprBaseListExec): Variant; procedure dwsWebClassesWebRequestMethodsGetContentFieldEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebRequestMethodsHasContentFieldEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesHttpQueryMethodsGetDataEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesHttpQueryMethodsGetTextEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesHttpQueryMethodsPostDataEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebRequestMethodsIfModifiedSinceEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsWebClassesWebResponseMethodsSetLastModifiedEval( Info: TProgramInfo; ExtObject: TObject); private { Private declarations } public { Public declarations } end; implementation {$R *.dfm} type THttpQueryMethod = (hqmGET, hqmPOST); function HttpQuery(method : THttpQueryMethod; const url : RawByteString; const requestData : RawByteString; const requestContentType : RawByteString; var replyData : String; asText : Boolean) : Integer; overload; const cContentType : RawUTF8 = 'Content-Type:'; var query : TWinHTTP; uri : TURI; headers, buf, mimeType : RawByteString; p1, p2 : Integer; begin if uri.From(url) then begin query:=TWinHTTP.Create(uri.Server, uri.Port, uri.Https); try case method of hqmGET : begin Assert(requestData=''); Result:=query.Request(uri.Address, 'GET', 0, '', '', '', headers, buf); end; hqmPOST : begin Result:=query.Request(uri.Address, 'POST', 0, '', requestData, requestContentType, headers, buf); end; else Result:=0; Assert(False); end; if asText then begin p1:=Pos(cContentType, RawUTF8(headers)); if p1>0 then begin Inc(p1, Length(cContentType)); p2:=PosEx(#13, headers, p1); if p2>p1 then mimeType:=Copy(headers, p1, p2-p1); end; if StrIEndsWithA(mimeType, 'charset=utf-8') then replyData:=UTF8DecodeToUnicodeString(buf) else RawByteStringToScriptString(buf, replyData); end else RawByteStringToScriptString(buf, replyData); finally query.Free; end; end else Result:=0; end; function HttpQuery(method : THttpQueryMethod; const url : RawByteString; var replyData : String; asText : Boolean) : Integer; overload; begin Result:=HttpQuery(method, url, '', '', replyData, asText); end; procedure TdwsWebLib.dwsWebClassesHttpQueryMethodsGetDataEval( Info: TProgramInfo; ExtObject: TObject); var buf : String; begin Info.ResultAsInteger:=HttpQuery(hqmGET, Info.ParamAsDataString[0], buf, False); Info.ParamAsString[1]:=buf; end; procedure TdwsWebLib.dwsWebClassesHttpQueryMethodsGetTextEval( Info: TProgramInfo; ExtObject: TObject); var buf : String; begin Info.ResultAsInteger:=HttpQuery(hqmGET, Info.ParamAsDataString[0], buf, True); Info.ParamAsString[1]:=buf; end; procedure TdwsWebLib.dwsWebClassesHttpQueryMethodsPostDataEval( Info: TProgramInfo; ExtObject: TObject); var buf : String; begin Info.ResultAsInteger:=HttpQuery(hqmPOST, Info.ParamAsDataString[0], Info.ParamAsDataString[1], Info.ParamAsDataString[2], buf, False); Info.ParamAsString[3]:=buf; end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsAuthenticatedUserEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=Info.WebRequest.AuthenticatedUser; end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsAuthenticationEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsInteger:=Ord(Info.WebRequest.Authentication); end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsContentDataEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsDataString:=Info.WebRequest.ContentData; end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsContentLengthEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsInteger:=Length(Info.WebRequest.ContentData); end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsContentTypeEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsDataString:=Info.WebRequest.ContentType; end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsCookieEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=Info.WebRequest.Cookies.Values[Info.ParamAsString[0]]; end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsCookiesEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=Info.WebRequest.Cookies.Text; end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsGetContentFieldEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=Info.WebRequest.ContentFields.Values[Info.ParamAsString[0]]; end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsHasContentFieldEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsBoolean:=Info.WebRequest.HasContentField(Info.ParamAsString[0]); end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsHasQueryFieldEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsBoolean:=Info.WebRequest.HasQueryField(Info.ParamAsString[0]); end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsHeaderEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=Info.WebRequest.Header(Info.ParamAsString[0]); end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsHeadersEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=Info.WebRequest.Headers.Text; end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsIfModifiedSinceEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsFloat:=Info.WebRequest.IfModifiedSince; end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsMethodEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=Info.WebRequest.Method; end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsPathInfoEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=Info.WebRequest.PathInfo; end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsQueryFieldEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=Info.WebRequest.QueryFields.Values[Info.ParamAsString[0]]; end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsQueryFieldsEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=Info.WebRequest.QueryFields.Text; end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsQueryStringEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=Info.WebRequest.QueryString; end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsRemoteIPEval( Info: TProgramInfo; ExtObject: TObject); var cloudflareIP : String; begin cloudflareIP:=Info.WebRequest.Header('CF-Connecting-IP'); if cloudflareIP<>'' then Info.ResultAsString:=cloudflareIP else Info.ResultAsString:=Info.WebRequest.RemoteIP; end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsSecureEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=Info.WebRequest.Security; end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsURLEval(Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=Info.WebRequest.URL; end; procedure TdwsWebLib.dwsWebClassesWebRequestMethodsUserAgentEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=Info.WebRequest.UserAgent; end; procedure TdwsWebLib.dwsWebClassesWebResponseMethodsContentDataEval( Info: TProgramInfo; ExtObject: TObject); begin Info.WebResponse.ContentData:=Info.ParamAsDataString[0]; end; procedure TdwsWebLib.dwsWebClassesWebResponseMethodsContentEncodingEval( Info: TProgramInfo; ExtObject: TObject); begin Info.WebResponse.ContentEncoding:=Info.ParamAsDataString[0]; end; procedure TdwsWebLib.dwsWebClassesWebResponseMethodsContentTypeEval( Info: TProgramInfo; ExtObject: TObject); begin Info.WebResponse.ContentType:=Info.ParamAsDataString[0]; end; procedure TdwsWebLib.dwsWebClassesWebResponseMethodsRequestAuthenticationEval( Info: TProgramInfo; ExtObject: TObject); var wra : TWebRequestAuthentication; begin wra:=TWebRequestAuthentication(Info.ParamAsInteger[0]); Info.WebResponse.Headers.Values['WWW-Authenticate']:=cWebRequestAuthenticationToString[wra]; Info.WebResponse.StatusCode:=401; end; procedure TdwsWebLib.dwsWebClassesWebResponseMethodsSetCompressionEval( Info: TProgramInfo; ExtObject: TObject); begin Info.WebResponse.Compression:=Info.ParamAsBoolean[0]; end; procedure TdwsWebLib.dwsWebClassesWebResponseMethodsSetContentTextEval( Info: TProgramInfo; ExtObject: TObject); begin Info.WebResponse.ContentText[Info.ParamAsDataString[0]]:=Info.ParamAsString[1]; end; procedure TdwsWebLib.dwsWebClassesWebResponseMethodsSetCookieEval( Info: TProgramInfo; ExtObject: TObject); var cookie : TWebResponseCookie; begin cookie:=Info.WebResponse.Cookies.AddCookie(Info.ParamAsString[0]); cookie.Value:=Info.ParamAsString[1]; cookie.ExpiresGMT:=Info.ParamAsFloat[2]; end; procedure TdwsWebLib.dwsWebClassesWebResponseMethodsSetCookie2Eval( Info: TProgramInfo; ExtObject: TObject); var cookie : TWebResponseCookie; begin cookie:=Info.WebResponse.Cookies.AddCookie(Info.ParamAsString[0]); cookie.Value:=Info.ParamAsString[1]; cookie.ExpiresGMT:=Info.ParamAsFloat[2]; cookie.Path:=Info.ParamAsString[3]; cookie.Domain:=Info.ParamAsString[4]; cookie.Flags:=Info.ParamAsInteger[5]; end; procedure TdwsWebLib.dwsWebClassesWebResponseMethodsSetHeaderEval( Info: TProgramInfo; ExtObject: TObject); begin Info.WebResponse.Headers.Values[Info.ParamAsString[0]]:=Info.ParamAsString[1]; end; procedure TdwsWebLib.dwsWebClassesWebResponseMethodsSetLastModifiedEval( Info: TProgramInfo; ExtObject: TObject); begin Info.WebResponse.LastModified:=Info.ParamAsFloat[0]; end; procedure TdwsWebLib.dwsWebClassesWebResponseMethodsSetStatusCodeEval( Info: TProgramInfo; ExtObject: TObject); begin Info.WebResponse.StatusCode:=Info.ParamAsInteger[0]; end; // DeflateCompress // procedure DeflateCompress(var data : RawByteString; compressionLevel : Integer); var strm : TZStream; tmp : RawByteString; begin strm.Init; strm.next_in := Pointer(data); strm.avail_in := Length(data); SetString(tmp, nil, strm.avail_in+256+strm.avail_in shr 3); // max mem required strm.next_out := Pointer(tmp); strm.avail_out := Length(tmp); if deflateInit2_(strm, compressionLevel, Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, ZLIB_VERSION, SizeOf(strm))<0 then raise Exception.Create('deflateInit2_ failed'); try Check(deflate(strm,Z_FINISH),[Z_STREAM_END]); finally deflateEnd(strm); end; SetString(data, PAnsiChar(Pointer(tmp)), strm.total_out); end; // DeflateDecompress // procedure DeflateDecompress(var data : RawByteString); var strm : TZStream; code, len : integer; tmp : RawByteString; begin strm.Init; strm.next_in := Pointer(data); strm.avail_in := Length(data); len := (strm.avail_in*20) shr 3; // initial chunk size = comp. ratio of 60% SetString(tmp,nil,len); strm.next_out := Pointer(tmp); strm.avail_out := len; if inflateInit2_(strm, -MAX_WBITS, ZLIB_VERSION, SizeOf(strm))<0 then raise Exception.Create('inflateInit2_ failed'); try repeat code := Check(inflate(strm, Z_FINISH),[Z_OK,Z_STREAM_END,Z_BUF_ERROR]); if strm.avail_out=0 then begin // need to increase buffer by chunk SetLength(tmp,length(tmp)+len); strm.next_out := PAnsiChar(pointer(tmp))+length(tmp)-len; strm.avail_out := len; end; until code=Z_STREAM_END; finally inflateEnd(strm); end; SetString(data, PAnsiChar(Pointer(tmp)), strm.total_out); end; function TdwsWebLib.dwsWebFunctionsDeflateCompressFastEval( const args: TExprBaseListExec): Variant; var data : RawByteString; lvl : Integer; begin data:=args.AsDataString[0]; lvl := args.AsInteger[1]; if (lvl<0) or (lvl>9) then raise Exception.CreateFmt('Invalid deflate compression level %d', [lvl]); DeflateCompress(data, lvl); Result:=RawByteStringToScriptString(data); end; function TdwsWebLib.dwsWebFunctionsDeflateDecompressionFastEval( const args: TExprBaseListExec): Variant; var data : RawByteString; begin data:=args.AsDataString[0]; DeflateDecompress(data); Result:=RawByteStringToScriptString(data); end; end.
unit Vs.Pedido.Venda.Repositorio.Memoria; interface uses // Vs Vs.Pedido.Venda.Repositorio; function PedidoVendaRepositorioMemoria: IPedidoVendaRepositorio; implementation uses System.Generics.Collections, // Vs Vs.Pedido.Venda.Entidade; type TPedidoVendaRepositorioMemoria = class(TInterfacedObject, IPedidoVendaRepositorio) strict private FListaPedidoVenda: TList<TPedidoVenda>; public constructor Create; destructor Destroy; override; class function Instancia: IPedidoVendaRepositorio; function Salvar(APedidoVenda: TPedidoVenda): Integer; end; function PedidoVendaRepositorioMemoria: IPedidoVendaRepositorio; begin Result := TPedidoVendaRepositorioMemoria.Instancia; end; { TPedidoVendaRepositorioMemoria } constructor TPedidoVendaRepositorioMemoria.Create; begin inherited Create; FListaPedidoVenda := TList<TPedidoVenda>.Create; end; destructor TPedidoVendaRepositorioMemoria.Destroy; begin FListaPedidoVenda.Free; inherited; end; class function TPedidoVendaRepositorioMemoria.Instancia: IPedidoVendaRepositorio; begin Result := Self.Create; end; function TPedidoVendaRepositorioMemoria.Salvar(APedidoVenda: TPedidoVenda): Integer; begin FListaPedidoVenda.Add(APedidoVenda); Result := FListaPedidoVenda.Count; end; end.
(*NIM/Nama : 16515034/Mikhael Artur Darmakesuma *) (*Nama file : lingkaran.pas *) (*Topik : Modular Programming *) (*Tanggal : 6 April 2016 *) (*Deskripsi : unit bernama upecahan yang mengandung deklarasi type pecahan (merepresentasikan pecahan non-negatif) berikut operasi-operasinya (dalam bentuk fungsi/prosedur). *) unit upecahan; interface { Type pecahan } type pecahan = record n,d: integer; end; { Deklarasi Fungsi/Prosedur } function IsPecahanValid (n, d: integer): boolean; { Menghasilkan true jika n dan d dapat membentuk pecahan yang valid dengan n sebagai pembilang dan d sebagai penyebut, yaitu jika n >= 0 dan d > 0 } procedure TulisPecahan (var P: pecahan); { Menuliskan pecahan P ke layar dalam bentuk "P.n/P.d" } { Tidak diawali, diselangi, atau diakhiri dengan karakter apa pun, termasuk spasi atau pun enter } { I.S.: P terdefinisi } { F.S.: P tercetak di layar dalam bentuk "P.n/P.d" } function IsLebihKecil (P1, P2: pecahan): boolean; { Menghasilkan true jika P1 lebih kecil dari P2 } { pecahan <n1,d1> lebih kecil dari pecahan <n2,d2> jika dan hanya jika: n1*d2 < n2*d1 } function Selisih (P1, P2 :pecahan): pecahan; { Menghasilkan pecahan selisih antara P1 dengan P2 atau P1 - P2 } { Selisih pecahan <n1,d1> dengan <n2,d2> menghasilkan pecahan <n3,d3> dengan: n3 = n1*d2 - n2*d1 dan d3 = d1*d2. } { Prekondisi : P1 >= P2 } implementation function IsPecahanValid (n, d: integer): boolean; { Menghasilkan true jika n dan d dapat membentuk pecahan yang valid dengan n sebagai pembilang dan d sebagai penyebut, yaitu jika n >= 0 dan d > 0 } begin IsPecahanValid := ((n >= 0) and (d >0)); end; procedure TulisPecahan (var P: pecahan); { Menuliskan pecahan P ke layar dalam bentuk "P.n/P.d" } { Tidak diawali, diselangi, atau diakhiri dengan karakter apa pun, termasuk spasi atau pun enter } { I.S.: P terdefinisi } { F.S.: P tercetak di layar dalam bentuk "P.n/P.d" } begin write (P.n,'/',P.d); end; function IsLebihKecil (P1, P2: pecahan): boolean; { Menghasilkan true jika P1 lebih kecil dari P2 } { pecahan <n1,d1> lebih kecil dari pecahan <n2,d2> jika dan hanya jika: n1*d2 < n2*d1 } begin IsLebihKecil := ((P1.n*P2.d) < (P1.d*P2.n)); end; function Selisih (P1, P2 :pecahan): pecahan; { Menghasilkan pecahan selisih antara P1 dengan P2 atau P1 - P2 } { Selisih pecahan <n1,d1> dengan <n2,d2> menghasilkan pecahan <n3,d3> dengan: n3 = n1*d2 - n2*d1 dan d3 = d1*d2. } { Prekondisi : P1 >= P2 } begin Selisih.n := (P1.n*P2.d) - (P1.d*P2.n); Selisih.d := (P1.d * P2.d); end; end.
unit uTypes; interface uses winApi.windows, winApi.Messages, System.Classes, System.SysUtils, System.IOUtils, System.Types, TagsLibrary, Vcl.Graphics,Vcl.Forms, strUtils, Generics.Defaults, Generics.collections, XSuperObject; const WM_REFRESH_COVER = WM_USER + 2000; WM_OPEN_ROLLOUTS = WM_USER + 2001; WM_ATTACH = WM_USER + 2002; WM_STARTSEARCH = WM_USER + 2003; WM_PLAY_PREVIOUS = WM_USER + 3000; WM_PLAY_NEXT = WM_USER + 3010; WM_STOP = WM_USER + 3020; WM_PLAY = WM_USER + 3030; WM_PAUSE = WM_USER + 3040; sValidExtensions = '.MP3.MP4.FLAC.OGG.WAV.M4A'; aValidExtensions: TArray<string> = ['.MP3', '.MP4', '.FLAC', '.OGG', '.WAV', '.M4A']; cArtist = 'Artist'; cTitle = 'Title'; cAlbum = 'Album'; cFileName = 'Filename'; col_on = clRed; col_off = clNavy; type TacFrame = class of TFrame; TCmpData = record Caption, Hint: string; ImgIndex, GroupIndex, ImgListIndex: integer; FrameType: TacFrame; end; PCmpData = ^TCmpData; TCmpsArray = array [0..1] of TCmpData; PCmpsArray = ^TCmpsArray; tTagKey = class sTAG: String; sCol: Integer; end; tOptionsSearch = class Public class var bWord: Boolean; bDir : Boolean; end; tExpr = class sExpr: String; end; tMediaFile = class(tPersistent) private fFileName: String; fTempFileName: String; public bModified: Boolean; tags: TTags; property fileName: String read fFileName write fFileName; property tempFileName: String read fTempFileName write fTempFileName; constructor create; overload; constructor create(aFileName: string); overload; destructor Destroy; overload; procedure SaveTags; Procedure LoadTags(pFile: String); end; tMediaImg = class(tPersistent) public tnLink: String; Link: String; BitMap: tPicture; constructor create; overload; destructor Destroy; override; end; tMediaUtils = class public class function isValidExtension(sFile: String): Boolean; static; class function isValidExtension2(sFile: String): Integer; static; class function getExtension(sFile: String): string; static; end; function FindTag(iCol: Integer): String; var isRegistered: Boolean; dTags: TDictionary<String, tTagKey>; dExpressions: TDictionary<String, tExpr>; dGoogleSearchResults : tDictionary<Integer, tStrings>; implementation function FindTag(iCol: Integer): String; var value: tTagKey; begin result := ''; for value in dTags.Values do begin if value.sCol = iCol then begin result := value.sTAG; break; end; end; end; { tMediaFile } constructor tMediaFile.create(aFileName: string); begin // // inherited create; self.create; bModified := false; filename := aFileName; tags := TTags.create; tags.ParseCoverArts := true; tags.LoadFromFile(aFileName); end; constructor tMediaFile.create; begin inherited create; bModified := false; tags := TTags.create; end; destructor tMediaFile.Destroy; begin tags.Free; // inherited Free; inherited Destroy; end; procedure tMediaFile.LoadTags(pFile: String); begin tags.Clear; bModified := false; tags.LoadFromFile(pFile); end; procedure tMediaFile.SaveTags; begin tags.SaveToFile(tags.fileName); bModified := false; end; { tMediaImg } constructor tMediaImg.create; begin inherited create; BitMap := Nil; end; destructor tMediaImg.Destroy; begin if BitMap <> nil then FreeAndNil(BitMap); inherited Destroy; end; { tMediaUtils } class function tMediaUtils.getExtension(sFile: String): string; var i: Integer; begin result := 'unknown'; i := isValidExtension2(sFile); if i > -1 then result := aValidExtensions[i]; end; class function tMediaUtils.isValidExtension(sFile: String): Boolean; var sExt: String; begin sExt := tpath.getExtension(sFile); result := (pos(uppercase(sExt), sValidExtensions) > 0); end; class function tMediaUtils.isValidExtension2(sFile: String): Integer; var sExt: String; i: Integer; begin sExt := uppercase(tpath.getExtension(sFile)); i := 0; result := -1; for i := low(aValidExtensions) to High(aValidExtensions) do begin if SameText(aValidExtensions[i], sExt) then begin result := i; break; end; end; end; Initialization var dTagKey: tTagKey; begin dExpressions := TDictionary<String, tExpr>.create; dTags := TDictionary<String, tTagKey>.create; dTagKey := tTagKey.create; dTagKey.sTAG := 'ARTIST'; dTagKey.sCol := 2; dTags.Add(cArtist, dTagKey); dTagKey := tTagKey.create; dTagKey.sTAG := 'TITLE'; dTagKey.sCol := 3; dTags.Add(cTitle, dTagKey); dTagKey := tTagKey.create; dTagKey.sTAG := 'ALBUM'; dTagKey.sCol := 4; dTags.Add(cAlbum, dTagKey); dTagKey := tTagKey.create; dTagKey.sTAG := 'NONE'; dTagKey.sCol := -1; dTags.Add('N/A', dTagKey); end; Finalization begin dTags.Clear; dTags.Free; dExpressions.Clear; dExpressions.Free; end; end.
// Fit4Delphi Copyright (C) 2008. Sabre Inc. // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software Foundation; // either version 2 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with this program; // if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // Derived from Fixture.java by Martin Chernenkoff, CHI Software Design // Ported to Delphi by Michal Wojcik. // unit Simulator; interface uses SysUtils, ActionFixture; type TSimulator = class public constructor Create; procedure Advance(future : TDateTime); procedure delay(seconds : double); function nextEvent(bound : TDateTime) : TDateTime; procedure perform; function sooner(soon, event : TDateTime) : TDateTime; procedure waitPlayComplete; procedure waitSearchComplete; procedure failLoadJam; end; var time : TDateTime; nextSearchComplete : TDateTime = 0; nextPlayStarted : TDateTime = 0; nextPlayComplete : TDateTime = 0; function schedule(seconds : double) : TDateTime; implementation uses MusicLibrary, MusicPlayer, Dialog, Fixture; function schedule(seconds : double) : TDateTime; begin (* static long schedule(double seconds){ return time + (long)(1000 * seconds); } *) result := time + (seconds/(60*60*24)); end; { TSimulator } procedure TSimulator.Advance(future: TDateTime); begin (* void advance (long future) { while (time < future) { time = nextEvent(future); perform(); } } *) while time < future do begin time := nextEvent(future); perform(); end; end; constructor TSimulator.Create; begin time := Now(); end; procedure TSimulator.delay(seconds: double); begin (* void delay (double seconds) { advance(schedule(seconds)); } *) advance(schedule(seconds)); end; procedure TSimulator.failLoadJam; begin (* public void failLoadJam() { ActionFixture.actor = new Dialog("load jamed", ActionFixture.actor); } *) ActionFixture.actor := TDialog.Create('load jamed', ActionFixture.actor); end; function TSimulator.nextEvent(bound: TDateTime): TDateTime; begin (* long nextEvent(long bound) { long result = bound; result = sooner(result, nextSearchComplete); result = sooner(result, nextPlayStarted); result = sooner(result, nextPlayComplete); return result; } *) result := bound; result := sooner(result, nextSearchComplete); result := sooner(result, nextPlayStarted); result := sooner(result, nextPlayComplete); end; procedure TSimulator.perform; begin (* void perform() { if (time == nextSearchComplete) {MusicLibrary.searchComplete();} if (time == nextPlayStarted) {MusicPlayer.playStarted();} if (time == nextPlayComplete) {MusicPlayer.playComplete();} } *) if time = nextSearchComplete then MusicLibrary.searchComplete; if time = nextPlayStarted then MusicPlayer.playStarted; if time = nextPlayComplete then MusicPlayer.playComplete; end; function TSimulator.sooner(soon, event: TDateTime): TDateTime; begin (* long sooner (long soon, long event) { return event > time && event < soon ? event : soon; } *) if (event > time) and (event < soon) then result := event else result := soon; end; procedure TSimulator.waitPlayComplete; begin (* public void waitPlayComplete() { advance(nextPlayComplete); } *) advance(nextPlayComplete); end; procedure TSimulator.waitSearchComplete; begin (* public void waitSearchComplete() { advance(nextSearchComplete); } *) advance(nextSearchComplete); end; initialization nextSearchComplete := 0; nextPlayStarted := 0; nextPlayComplete := 0; end.
unit TSTODownloader; interface Uses HsInterfaceEx, TSTOPackageList; Type IHttpProgress = Interface(IInterfaceEx) ['{4B61686E-29A0-2112-880A-00CC652497B1}'] Function GetMaxProgress() : Integer; Procedure SetMaxProgress(Const Value: Integer); Function GetCurProgress() : Integer; Procedure SetCurProgress(Const Value: Integer); Procedure SetCurOperation(Const Value: String); Procedure Show(); Procedure Hide(); Property MaxProgress : Integer Read GetMaxProgress Write SetMaxProgress; Property CurProgress : Integer Read GetCurProgress Write SetCurProgress; Property CurOperation : String Write SetCurOperation; End; ITSTODownloader = Interface(IInterfaceEx) ['{4B61686E-29A0-2112-9555-B31ED1BC32B6}'] Function GetServerName() : String; Procedure SetServerName(Const AServerName : String); Function GetDownloadPath() : String; Procedure SetDownloadPath(Const ADownloadPath : String); Procedure AddFile(Const AFileName : String); Procedure DownloadFile(); OverLoad; Procedure DownloadFile(Const AShowProgress : Boolean; Const AConfirmOverWrite : Boolean = True); OverLoad; Procedure DownloadFiles(AFileList : ITSTOPackageNodes); Procedure DownloadDlcIndex(); OverLoad; Procedure DownloadDlcIndex(Var ADlcIndexFileName : String; Const AShowProgress : Boolean = True; Const AOverWriteIndex : Boolean = True); OverLoad; Property ServerName : String Read GetServerName Write SetServerName; Property DownloadPath : String Read GetDownloadPath Write SetDownloadPath; End; TTSTODownloader = Class(TObject) Public Class Function CreateDownloader() : ITSTODownloader; End; implementation Uses Classes, Forms, StdCtrls, ComCtrls, ExtCtrls, SysUtils, Controls, Dialogs, HsHttpEx, HsStreamEx, HsStringListEx, HsZipUtils, HsXmlDocEx, HsFunctionsEx; Type THttpDownloadProgress = Class(TInterfacedObjectEx, IHttpProgress) Private Type THttpDownloadProgressImpl = Class(TForm) Private FlblStatus : TLabel; FProgressBar : TProgressBar; Function GetMaxProgress() : Integer; Procedure SetMaxProgress(Const Value: Integer); Function GetCurProgress() : Integer; Procedure SetCurProgress(Const Value: Integer); Procedure SetCurOperation(Const Value: String); Protected Procedure DoClose(Var Action : TCloseAction); OverRide; Public Constructor Create(AOwner : TComponent); OverRide; End; Private FDownloadFrm : THttpDownloadProgressImpl; Function GetImpl() : THttpDownloadProgressImpl; Protected Property IntfImpl : THttpDownloadProgressImpl Read GetImpl Implements IHttpProgress; Procedure Created(); OverRide; Public Destructor Destroy(); OverRide; End; (* THttpDownloadProgress = Class(TForm, IHttpProgress) Private FIntfImpl : TInterfaceExImplementor; FlblStatus : TLabel; FProgressBar : TProgressBar; Function GetMaxProgress() : Integer; Procedure SetMaxProgress(Const Value: Integer); Function GetCurProgress() : Integer; Procedure SetCurProgress(Const Value: Integer); Procedure SetCurOperation(Const Value: String); Function GetImpl() : TInterfaceExImplementor; Protected Property IntfImpl : TInterfaceExImplementor Read GetImpl Implements IHttpProgress; Procedure DoClose(Var Action : TCloseAction); OverRide; Public Constructor Create(AOwner : TComponent); OverRide; End; *) TTSTODownloaderImpl = Class(TInterfacedObjectEx, ITSTODownloader) Private FServerName : String; FDownloadPath : String; FHttp : IHsIdHTTPEx; FProgress : IHttpProgress; FFileList : IHsStringListEx; Procedure OnDownloadProgress(Const AFileName : String; Const ACurProgress, AMaxValue : Int64); Protected Function GetServerName() : String; Procedure SetServerName(Const AServerName : String); Function GetDownloadPath() : String; Procedure SetDownloadPath(Const ADownloadPath : String); Procedure AddFile(Const AFileName : String); Procedure DownloadFile(Const AShowProgress : Boolean; Const AConfirmOverWrite : Boolean = True); OverLoad; Procedure DownloadFile(); OverLoad; Procedure DownloadFiles(AFileList : ITSTOPackageNodes); Procedure DownloadDlcIndex(); OverLoad; Procedure DownloadDlcIndex(Var ADlcIndexFileName : String; Const AShowProgress : Boolean = True; Const AOverWriteIndex : Boolean = True); OverLoad; Public Destructor Destroy(); OverRide; End; Class Function TTSTODownloader.CreateDownloader() : ITSTODownloader; Begin Result := TTSTODownloaderImpl.Create(); End; Procedure THttpDownloadProgress.Created(); Begin FDownloadFrm := THttpDownloadProgressImpl.Create(Nil); End; Destructor THttpDownloadProgress.Destroy(); Begin FreeAndNil(FDownloadFrm); InHerited Destroy(); End; Function THttpDownloadProgress.GetImpl() : THttpDownloadProgressImpl; Begin Result := FDownloadFrm; End; Constructor THttpDownloadProgress.THttpDownloadProgressImpl.Create(AOwner : TComponent); Var lPanel : TPanel; Begin CreateNew(AOwner); Name := 'FrmProgress'; Caption := 'Progress...'; Width := 350; Height := 95; Position := poOwnerFormCenter; FormStyle := fsStayOnTop; BorderIcons := []; lPanel := TPanel.Create(Self); With lPanel Do Begin Parent := Self; Left := 8; Top := 15; Width := 319; Height := 37; BevelOuter := bvNone; Caption := ''; End; FlblStatus := TLabel.Create(Self); With FlblStatus Do Begin Name := 'lblStatus'; Parent := lPanel; Left := 0; Top := 0; Width := 3; Height := 13; AutoSize := True; End; FProgressBar := TProgressBar.Create(Self); With FProgressBar Do Begin Name := 'PBar'; Parent := lPanel; Left := 0; Top := 19; Width := 317; Height := 16; Smooth := True; End; End; Procedure THttpDownloadProgress.THttpDownloadProgressImpl.DoClose(Var Action : TCloseAction); Begin Action := caFree; End; Function THttpDownloadProgress.THttpDownloadProgressImpl.GetMaxProgress() : Integer; Begin Result := FProgressBar.Max; End; Procedure THttpDownloadProgress.THttpDownloadProgressImpl.SetMaxProgress(Const Value: Integer); Begin FProgressBar.Max := Value; End; Function THttpDownloadProgress.THttpDownloadProgressImpl.GetCurProgress() : Integer; Begin Result := FProgressBar.Position; End; Procedure THttpDownloadProgress.THttpDownloadProgressImpl.SetCurProgress(Const Value: Integer); Begin FProgressBar.Position := Value; End; Procedure THttpDownloadProgress.THttpDownloadProgressImpl.SetCurOperation(Const Value: String); Begin FlblStatus.Caption := Value; End; Destructor TTSTODownloaderImpl.Destroy(); Begin FFileList := Nil; InHerited Destroy(); End; Procedure TTSTODownloaderImpl.OnDownloadProgress(Const AFileName : String; Const ACurProgress, AMaxValue : Int64); Var lPrc : Integer; Begin If Assigned(FProgress) Then Begin lPrc := Round(ACurProgress / AMaxValue * 100); FProgress.CurOperation := 'Downloading ' + AFileName + ' - ' + IntToStr(lPrc) + ' %'; FProgress.CurProgress := lPrc; Application.ProcessMessages(); End; End; Function TTSTODownloaderImpl.GetServerName() : String; Begin Result := FServerName; End; Procedure TTSTODownloaderImpl.SetServerName(Const AServerName : String); Begin FServerName := AServerName; End; Function TTSTODownloaderImpl.GetDownloadPath() : String; Begin Result := FDownloadPath; End; Procedure TTSTODownloaderImpl.SetDownloadPath(Const ADownloadPath : String); Begin FDownloadPath := ADownloadPath; End; Procedure TTSTODownloaderImpl.AddFile(Const AFileName : String); Begin If Not Assigned(FFileList) Then FFileList := THsStringListEx.CreateList(); FFileList.Add(AFileName); End; Procedure TTSTODownloaderImpl.DownloadFile(Const AShowProgress : Boolean; Const AConfirmOverWrite : Boolean = True); Var X : Integer; lMem : IMemoryStreamEx; lCurPath : String; lConfirm : TModalResult; Begin If Assigned(FFileList) And (FFileList.Count > 0) Then Begin FHttp := THsIdHTTPEx.Create(); lMem := TMemoryStreamEx.Create(); Try If AShowProgress Then Begin FHttp.OnProgress := OnDownloadProgress; FProgress := THttpDownloadProgress.Create(); FProgress.MaxProgress := 100; FProgress.Show(); End; If AConfirmOverWrite Then lConfirm := mrNone Else lConfirm := mrYesToAll; For X := 0 To FFileList.Count - 1 Do Begin lMem.Clear(); Application.ProcessMessages(); Try If Not (lConfirm In [mrYesToAll, mrNoToAll]) Then If FileExists(FDownloadPath + StringReplace(FFileList[X], '/', '\', [rfReplaceAll, rfIgnoreCase])) Then Begin FProgress.Hide(); lConfirm := MessageDlg('The file ' + ExtractFileName(StringReplace(FFileList[X], '/', '\', [rfReplaceAll, rfIgnoreCase])) + ' aleready exist.'#$D#$A'Do you want to overwrite it?', mtConfirmation, [mbYes, mbNo, mbYesToAll, mbNoToAll], 0); FProgress.Show(); End; If lConfirm In [mrNone, mrYes, mrYesToAll] Then Begin FHttp.Get(FServerName + FFileList[X], TStream(lMem.InterfaceObject)); FFileList[X] := StringReplace(FFileList[X], '/', '\', [rfReplaceAll, rfIgnoreCase]); lCurPath := FDownloadPath + ExtractFilePath(FFileList[X]); If Not DirectoryExists( lCurPath ) Then ForceDirectories(lCurPath); lMem.SaveToFile(FDownloadPath + FFileList[X]); End; Except AppLogFile('Failed to download : ' + FFileList[X]); End; Application.ProcessMessages(); End; FFileList.Clear(); Finally FProgress := Nil; FHttp := Nil; lMem := Nil; End; End; End; Procedure TTSTODownloaderImpl.DownloadFile(); Begin DownloadFile(True); End; Procedure TTSTODownloaderImpl.DownloadFiles(AFileList : ITSTOPackageNodes); Var X : Integer; Begin For X := 0 To AFileList.Count - 1 Do AddFile(StringReplace(AFileList[X].FileName, '\', '/', [rfReplaceAll, rfIgnoreCase])); DownloadFile(); End; Procedure TTSTODownloaderImpl.DownloadDlcIndex(Var ADlcIndexFileName : String; Const AShowProgress : Boolean = True; Const AOverWriteIndex : Boolean = True); Var lZip : IHsMemoryZipper; lXml : IXmlDocumentEx; lDlcIndex : String; lNode : IXmlNodeEx; lStrStream : IStringStreamEx; Begin lZip := THsMemoryZipper.Create(); lStrStream := TStringStreamEx.Create(); Try AddFile('dlc/DLCIndex.zip'); DownloadFile(AShowProgress, False); If FileExists(FDownloadPath + '\dlc\DLCIndex.zip') Then Begin lZip.LoadFromFile(FDownloadPath + '\dlc\DLCIndex.zip'); lZip.ExtractToStream(lZip[0].FileName, TStream(lStrStream.InterfaceObject)); lXml := LoadXmlData(lStrStream.DataString); Try lNode := lXml.SelectNode('//IndexFile[1]/@index'); If Assigned(lNode) Then Try lDlcIndex := StringReplace(lNode.Text, ':', '/', [rfReplaceAll, rfIgnoreCase]); Finally lNode := Nil; End; Finally lXml := Nil; End; If AOverWriteIndex Or Not FileExists(FDownloadPath + lDlcIndex) Then Begin AddFile(lDlcIndex); DownloadFile(AShowProgress, False); End; ADlcIndexFileName := {FDownloadPath +} ExtractFileName(StringReplace(lDlcIndex, '/', '\', [rfReplaceAll])); End; Finally lStrStream := Nil; lZip := Nil; End; End; Procedure TTSTODownloaderImpl.DownloadDlcIndex(); Var lDummy : String; Begin DownloadDlcIndex(lDummy); End; end.
unit nxMath3D; {$I nxInc.inc} interface { TODO: - Recheck MatrixOnPlane } uses nxMath, nxTypes; { General 3D Functions } function Angle(const v1,v2: TVector; axis: integer): single; overload; function Angle(v1, v2: TVector): single; overload; function Bezier(const a,b: TVector; const delta: single): TVector; overload; function Bezier(const p: array of TVector; const count: word; const delta: single): TVector; overload; function Catmull(const a,b,c,d: TVector; const delta: single): TVector; overload; stdcall;{$IFDEF CanInline}inline;{$ENDIF} function ClosestPointOnLine(const l1,l2,p: TVector): TVector; function CrossProduct(const a,b: TVector): TVector;{$IFDEF CanInline}inline;{$ENDIF} function Dot(const a,b: TVector): single; overload;{$IFDEF CanInline}inline;{$ENDIF} function GetAvgNormal(const n1,n2,n3,n4: PVector): TVector; function HalfBezier(const a,b,c: TVector; const delta: single): TVector; function Hypot3f(const x,y,z: single): single;{$IFDEF CanInline}inline;{$ENDIF} function Hypot3d(const x,y,z: double): double;{$IFDEF CanInline}inline;{$ENDIF} function Interpolate(const v1,v2: TVector; const s: single): TVector; overload; function Invert(const v: TVector): TVector; overload; function Multiply(const a,b: TVector): TVector; overload; function NearTriPoint(t1, t2, t3, p: PVector): TVector; procedure Norm(var x,y,z: single; const h: PSingle = nil); overload; procedure Norm(var x,y,z: double; const h: PDouble = nil); overload; function Norm(const v: TVector; const h: PSingle = nil): TVector; overload;stdcall;{$IFDEF CanInline}inline;{$ENDIF} function PointInSphere(const p,sphere: TVector; const radius: single): boolean; function RayPlaneIntersect(const rayOrigin, rayDirection, planeOrigin, planeNormal: TVector; intersection: PVector): single; function RaySphereIntersect(const rayStart: TVector; rayDirection: TVector; const sphereCenter: TVector; const sphereRadius: Single; const i1, i2: PVector): longint; function RayTriangleIntersect(const rayStart, rayDirection: TVector; const p1, p2, p3: TVector; BothSided: boolean; intersect: PVector = nil; intersectNormal: PVector = nil): Boolean;{$IFDEF CanInline}inline;{$ENDIF} function Reflect(const rayStart, rayDir, wallPoint: TVector): TVector; overload; function Reflect(const rayDir, wallNormal: TVector): TVector; overload; function Rotate(const v: TVector; const radians: single; axis: TVector): TVector; overload; function Scale(const v: TVector; s: single): TVector; overload; function Tangent(const a, b, c: TVector): TVector; overload;stdcall;{$IFDEF CanInline}inline;{$ENDIF} function VectorAdd(const a, b: TVector): TVector; overload; function VectorCombine(const V1, V2: TVector; const F2: Single): TVector; function VectorDist(const a, b: TVector): single; stdcall;{$IFDEF CanInline}inline;{$ENDIF} function VectorDiv(const v: TVector; s: single): TVector; function VectorXYFromAngle(const radians: single; const radius: single=1.0): TVector; function VectorXZFromAngle(const radians: single; const radius: single=1.0): TVector; function VectorZYFromAngle(const radians: single; const radius: single=1.0): TVector; function VectorMatch(const a, b: TVector; delta: single=0.01): boolean; overload; function VectorLen(const v: TVector): single; stdcall; function VectorSqr(const v: TVector): single; overload; function VectorSub(const a, b: TVector): TVector; overload; { Matrix Functions } function CreateMatrix(const axis: TVector; const radians: Single): TMatrix; overload;stdcall;{$IFDEF CanInline}inline;{$ENDIF} function CreateMatrix(const x,y,z: TVector): TMatrix; overload; function CreateMatrix(const rotation: TMatrix; const p: TVector): TMatrix; overload; function CreateMatrix(const rotation: TMatrix3f; const p: TVector): TMatrix; overload; function CreateMatrix2(const x,y,z: TVector): TMatrix; function CreateMatrix3f(const x,y,z: TVector): TMatrix3f; function CreateTranslateMatrix(const p: TVector): TMatrix; function Determinant(const M: TMatrix): Single; function GetAngle(const M: TMatrix; const axis: integer): single; function GetRotation(const mat: TMatrix): TMatrix; function GetRotation3(const mat: TMatrix): TMatrix3f; function GetVector(const M: TMatrix; const axis: integer): TVector; stdcall; overload;{$IFDEF CanInline}inline;{$ENDIF} function GetVector(const M: TMatrix3f; const axis: integer): TVector; stdcall; overload; function Interpolate(const a, b: TMatrix; s: single): TMatrix; overload; stdcall;{$IFDEF CanInline}inline;{$ENDIF} function Invert(const M: TMatrix): TMatrix; overload; function Invert(m: TMatrix3f): TMatrix3f; overload; function LookAt(const eye, target, up: TVector): TMatrix; stdcall; function Matrix(const mat: TMatrix3f): TMatrix; stdcall; overload;{$IFDEF CanInline}inline;{$ENDIF} function Matrix(const mat: TMatrix4d): TMatrix; stdcall; overload;{$IFDEF CanInline}inline;{$ENDIF} function MatrixOnPlane(const cPos,cDir: TVector; radians: single = 0): TMatrix; function Multiply(const A,B: TMatrix): TMatrix; stdcall;{$IFDEF CanInline}inline;{$ENDIF}overload; function Multiply(const A,B: TMatrix3f): TMatrix3f; stdcall;{$IFDEF CanInline}inline;{$ENDIF}overload; function Multiply(const A: TMatrix; const B: TMatrix3f): TMatrix; stdcall;{$IFDEF CanInline}inline;{$ENDIF}overload; function Multiply(const A: TMatrix3f; const B: TMatrix): TMatrix; stdcall;{$IFDEF CanInline}inline;{$ENDIF}overload; function MultiplyRotation(const A,B: TMatrix): TMatrix; stdcall;{$IFDEF CanInline}inline;{$ENDIF} function Multiply(const V: TVector; const M: TMatrix): TVector; overload; stdcall;{$IFDEF CanInline}inline;{$ENDIF} function Multiply(const V: TVector; const M: TMatrix3f): TVector; overload; stdcall;{$IFDEF CanInline}inline;{$ENDIF} function Rotate(const M: TMatrix; const axis: TVector; const radians: Single; withPos: boolean = true): TMatrix; overload; stdcall;{$IFDEF CanInline}inline;{$ENDIF} function Rotate(const M: TMatrix; const axis: integer; const radians: Single; withPos: boolean = true): TMatrix; overload; function Scale(const M: TMatrix; const s: Single): TMatrix; overload; function Scale(const M: TMatrix; const v: TVector): TMatrix; overload; procedure SetVector(var M: TMatrix; const v: TVector; const axis: integer); function Slerp(const a, b: TMatrix; s: single): TMatrix; overload; stdcall;{$IFDEF CanInline}inline;{$ENDIF} function Translate(const M: TMatrix; const v: TVector): TMatrix; stdcall;{$IFDEF CanInline}inline;{$ENDIF} { Quaternions } function Dot(const a, b: TQuaternion): single; overload; function Lerp(const a, b: TQuaternion; s: single): TQuaternion; overload; function Multiply(const q: TQuaternion; s: single): TQuaternion; overload; function Multiply(const a, b: TQuaternion): TQuaternion; overload; function NewQuaternion: TQuaternion; function Norm(const q: TQuaternion): TQuaternion; overload; function Quaternion(x, y, z, w: single): TQuaternion; overload; function Quaternion(const M: TMatrix): TQuaternion; overload; stdcall;{$IFDEF CanInline}inline;{$ENDIF} function Quaternion(const x, y, z: TVector): TQuaternion; overload; function Quaternion(const x, y, z: single): TQuaternion; overload; function Quaternion(const axis: TVector; radians: single): TQuaternion; overload; function QuaternionAdd(const a, b: TQuaternion): TQuaternion; function QuaternionSub(const a, b: TQuaternion): TQuaternion; function QuaternionToMat(const q: TQuaternion; const position: TVector): TMatrix; stdcall;{$IFDEF CanInline}inline;{$ENDIF} function Slerp(a, b: TQuaternion; s: single): TQuaternion; overload; stdcall; { Operator overloading } { Note: Delphi VER170 onwards may support operator overloading through records "class operators". } {$IFDEF fpc} operator :=(const v: TVector2f): TVector; operator +(const a, b: TVector): TVector; operator -(const a, b: TVector): TVector; operator *(const a, b: TVector): TVector;{$IFDEF CanInline}inline;{$ENDIF} operator *(const a: TVector; const n: single): TVector; operator *(const n: single; const a: TVector): TVector; operator /(const a: TVector; const n: single): TVector; operator *(const a, b: TMatrix): TMatrix;{$IFDEF CanInline}inline;{$ENDIF} operator *(const a, b: TMatrix3f): TMatrix3f;{$IFDEF CanInline}inline;{$ENDIF} operator *(const a: TMatrix; const b: TMatrix3f): TMatrix;{$IFDEF CanInline}inline;{$ENDIF} operator *(const v: TVector; const m: TMatrix): TVector;{$IFDEF CanInline}inline;{$ENDIF} operator +(const m: TMatrix; const v: TVector): TMatrix; operator -(const m: TMatrix; const v: TVector): TMatrix; operator :=(const q: TQuaternion): TMatrix;{$IFDEF CanInline}inline;{$ENDIF} operator :=(const m: TMatrix): TQuaternion;{$IFDEF CanInline}inline;{$ENDIF} operator +(const a, b: TQuaternion): TQuaternion; operator -(const a, b: TQuaternion): TQuaternion; operator *(const a, b: TQuaternion): TQuaternion; operator *(const a: TQuaternion; s: single): TQuaternion; {$ENDIF} var NewMatrix: TMatrix; NewMatrix3f: TMatrix3f; nullVector: TVector; implementation uses math; { Internal functions } function getNewMatrix: TMatrix; var i, j: integer; begin for i:=0 to 3 do for j:=0 to 3 do if i=j then result[i,j]:=1 else result[i,j]:=0; end; function getNewMatrix3f: TMatrix3f; var i, j: integer; begin for i:=0 to 2 do for j:=0 to 2 do if i=j then result[i,j]:=1 else result[i,j]:=0; end; function PointProject(const p, origin, direction: TVector): Single; begin Result:= direction.x*(p.x-origin.x) +direction.y*(p.y-origin.y) +direction.z*(p.z-origin.z); end; function VectorCombine(const V1, V2: TVector; const F2: Single): TVector; begin result.x:=V1.x + (F2 * V2.x); result.y:=V1.y + (F2 * V2.y); result.z:=V1.z + (F2 * V2.z); end; function VectorDistance2(const v1, v2: TVector): Single; begin result:=Sqr(v2.x-v1.x)+Sqr(v2.y-v1.y)+Sqr(v2.z-v1.z); end; { 3D Functions } // X, Y or Z component angle between 2 vectors, in radians function Angle(const v1, v2: TVector; axis: integer): single; overload; begin case axis of 0: result:=nxMath.angle(v1.x,v1.z, v2.x,v2.z); // X (horizontal angle) 1: result:=nxMath.angle(v1.z,v1.y, v2.z,v2.y); // Y (vertical angle) else result:=nxMath.angle(v1.x,v1.y, v2.x,v2.y); // Z (roll) end; end; // Angle between 2 vectors in radians function Angle(v1, v2: TVector): single; begin norm(v1.x, v1.y, v1.z); norm(v2.x, v2.y, v2.z); result:=arccos(dot(v1, v2)); end; // delta = 0..1 function Bezier(const a,b: TVector; const delta: single): TVector; var d1: single; begin d1:=1-delta; Bezier.x:=a.x*d1+b.x*delta; Bezier.y:=a.y*d1+b.y*delta; Bezier.z:=a.z*d1+b.z*delta; end; // Always call with count >= 2 function Bezier(const p: array of TVector; const count: word; const delta: single): TVector; var v: array of TVector; i: longint; begin if count>2 then begin setlength(v,count-1); for i:=0 to count-2 do v[i]:=Bezier(p[i],p[i+1],delta); Bezier:=Bezier(v,count-1,delta); end else if count=2 then Bezier:=Bezier(p[0],p[1],delta); end; function Catmull(const a,b,c,d: TVector; const delta: single): TVector; stdcall;{$IFDEF CanInline}inline;{$ENDIF} begin result.x:=nxMath.Catmull(a.x, b.x, c.x, d.x, delta); result.y:=nxMath.Catmull(a.y, b.y, c.y, d.y, delta); result.z:=nxMath.Catmull(a.z, b.z, c.z, d.z, delta); end; function ClosestPointOnLine(const l1, l2, p: TVector): TVector; var c,v: TVector; d,t: single; begin // Determine the length of the vector from a to b c:=VectorSub(p,l1); v:=VectorSub(l2,l1); v:=Norm(v,@d); t:=Dot(v, c); // Check to see if ‘t’ is beyond the extents of the line segment if t<0 then begin result:=l1; exit; end else if t>d then begin result:=l2; exit; end; // Return the point between ‘a’ and ‘b’ result.x:=v.x*t+l1.x; result.y:=v.y*t+l1.y; result.z:=v.z*t+l1.z; end; // Returns tangent that is against plane that is formed by A and B function CrossProduct(const a,b: TVector): TVector;{$IFDEF CanInline}inline;{$ENDIF} begin Result.x:=a.y*b.z-a.z*b.y; Result.y:=a.z*b.x-a.x*b.z; Result.z:=a.x*b.y-a.y*b.x; end; // Example: returns square of A if A = B, or // -2*square A if B is inverse and twice as long // Using normalized vectors returns 1 if A = B function Dot(const a, b: TVector): single;{$IFDEF CanInline}inline;{$ENDIF} begin result:=a.x*b.x + a.y*b.y + a.z*b.z; end; function GetAvgNormal(const n1, n2, n3, n4: PVector): TVector; var n: integer; begin result.x:=0; result.y:=0; result.z:=0; n:=0; if n1<>nil then begin result.x:=result.x+n1^.x; result.y:=result.y+n1^.y; result.z:=result.z+n1^.z; inc(n); if n2<>nil then begin result.x:=result.x+n2^.x; result.y:=result.y+n2^.y; result.z:=result.z+n2^.z; inc(n); if n3<>nil then begin // Up to triangle result.x:=result.x+n3^.x; result.y:=result.y+n3^.y; result.z:=result.z+n3^.z; inc(n); if n4<>nil then begin // Up to quad result.x:=result.x+n4^.x; result.y:=result.y+n4^.y; result.z:=result.z+n4^.z; inc(n); end; end; end; end; if n>0 then result:=norm(result) else result.y:=1; end; function HalfBezier(const a,b,c: TVector; const delta: single): TVector; var i,j,b1,b2: TVector; begin i.x:=(a.x+b.x)/2; i.y:=(a.y+b.y)/2; i.z:=(a.z+b.z)/2; j.x:=(b.x+c.x)/2; j.y:=(b.y+c.y)/2; j.z:=(b.z+c.z)/2; b1:=Bezier(i,b,delta); b2:=Bezier(b,j,delta); HalfBezier:=Bezier(b1,b2,delta); end; function Hypot3f(const x,y,z: single): single;{$IFDEF CanInline}inline;{$ENDIF} begin result:=sqrt(x*x+y*y+z*z); end; function Hypot3d(const x, y, z: double): double;{$IFDEF CanInline}inline;{$ENDIF} begin result:=sqrt(x*x+y*y+z*z); end; function Interpolate(const v1,v2: TVector; const s: single): TVector; begin result.x:=v1.x+s*(v2.x-v1.x); result.y:=v1.y+s*(v2.y-v1.y); result.z:=v1.z+s*(v2.z-v1.z); end; function Invert(const v: TVector): TVector; begin result.x:=-v.x; result.y:=-v.y; result.z:=-v.z; end; function Multiply(const a, b: TVector): TVector; begin result.x:=a.x*b.x; result.y:=a.y*b.y; result.z:=a.z*b.z; end; // Finds point inside or at the edge of triangle that // is nearest to point p. function NearTriPoint(t1, t2, t3, p: PVector): TVector; var pp, TriN, n1, n2, n3, is1, is2, is3: TVector; d1, d2, d3: single; begin TriN:=Tangent(t1^, t2^, t3^); RayPlaneIntersect(p^, TriN, t1^, TriN, @pp); n1:=CrossProduct(TriN, Vector(t1^.x-t2^.x, t1^.y-t2^.y, t1^.z-t2^.z)); n2:=CrossProduct(TriN, Vector(t2^.x-t3^.x, t2^.y-t3^.y, t2^.z-t3^.z)); n3:=CrossProduct(TriN, Vector(t3^.x-t1^.x, t3^.y-t1^.y, t3^.z-t1^.z)); d1:=RayPlaneIntersect(pp, n1, t1^, n1, @is1); d2:=RayPlaneIntersect(pp, n2, t2^, n2, @is2); d3:=RayPlaneIntersect(pp, n3, t3^, n3, @is3); if (d1>=0) and (d2>=0) and (d3>=0) then result:=pp else if (d1<0) and (d3<0) then result:=t1^ else if (d2<0) and (d1<0) then result:=t2^ else if (d3<0) and (d2<0) then result:=t3^ else if d1<0 then result:=ClosestPointOnLine(t1^, t2^, p^) else if d2<0 then result:=ClosestPointOnLine(t2^, t3^, p^) else if d3<0 then result:=ClosestPointOnLine(t3^, t1^, p^) else result:=t1^; end; procedure Norm(var x,y,z: single; const h: PSingle); var _h: single; begin _h:=Hypot3f(x,y,z); if h<>nil then h^:=_h; if _h>0 then begin _h:=1/_h; x:=x*_h; y:=y*_h; z:=z*_h; end else begin x:=1; y:=0; z:=0; end; end; procedure Norm(var x,y,z: double; const h: PDouble); var _h: double; begin _h:=Hypot3d(x,y,z); if h<>nil then h^:=_h; if _h>0 then begin _h:=1/_h; x:=x*_h; y:=y*_h; z:=z*_h; end else begin x:=1; y:=0; z:=0; end; end; function Norm(const v: TVector; const h: PSingle): TVector;stdcall;{$IFDEF CanInline}inline;{$ENDIF} var _h: single; begin _h:=Hypot3f(v.x,v.y,v.z); if h<>nil then h^:=_h; if _h>0 then begin _h:=1/_h; result.x:=v.x*_h; result.y:=v.y*_h; result.z:=v.z*_h; end else begin result.x:=1; result.y:=0; result.z:=0; end; end; function PointInSphere(const p,sphere: TVector; const radius: single): boolean; var x,y,z: single; begin x:=sphere.x-p.x; y:=sphere.y-p.y; z:=sphere.z-p.z; PointInSphere:=(x*x+y*y+z*z)<(radius*radius); end; // Result >= 0 if intersection happens function RayPlaneIntersect(const rayOrigin, rayDirection, planeOrigin, planeNormal: TVector; intersection: PVector): single; var d,numer,denom: single; begin d:=planeNormal.x*planeOrigin.x+planeNormal.y*planeOrigin.y+planeNormal.z*planeOrigin.z; numer:=-planeNormal.x*rayOrigin.x-planeNormal.y*rayOrigin.y-planeNormal.z*rayOrigin.z+d; denom:=planeNormal.x*rayDirection.x+planeNormal.y*rayDirection.y+planeNormal.z*rayDirection.z; if denom=0 then begin result:=-1; exit; end; result:=numer/denom; if intersection<>nil then begin intersection^.x:=rayOrigin.x+result*rayDirection.x; intersection^.y:=rayOrigin.y+result*rayDirection.y; intersection^.z:=rayOrigin.z+result*rayDirection.z; end; end; { Calculates the intersections between a sphere and a ray.<p> Returns 0 if no intersection is found (i1 and i2 untouched), 1 if one intersection was found (i1 defined, i2 untouched), 2 is two intersections were found (i1 and i2 defined). Doesn't look ray backwards. (old note, untested) } function RaySphereIntersect(const rayStart: TVector; rayDirection: TVector; const sphereCenter: TVector; const sphereRadius: Single; const i1, i2: PVector): longint; var lf, s: single; h: TVector; begin result:=0; rayDirection:=norm(rayDirection); h := VectorSub(sphereCenter, rayStart); lf := dot(rayDirection, h); s := sqr(sphereRadius)-dot(h, h)+sqr(lf); if s < 0.0 then exit; s := sqrt(s); if lf < s then begin if lf+s >= 0 then begin s := -s; result := 1; end; end else result := 2; if i1<>nil then i1^:=VectorCombine(rayStart, rayDirection, lf-s); if i2<>nil then i2^:=VectorCombine(rayStart, rayDirection, lf+s); end; // Tests intersection for line and triangle function RayTriangleIntersect(const rayStart, rayDirection: TVector; const p1, p2, p3: TVector; BothSided: boolean; intersect: PVector; intersectNormal: PVector): Boolean;{$IFDEF CanInline}inline;{$ENDIF} const EPSILON2 = 1e-30; var pvec, v1, v2, qvec, tvec: TVector; t, u, v, det, invDet: Single; begin v1:=VectorSub(p2, p1); v2:=VectorSub(p3, p1); if not BothSided then begin pvec:=CrossProduct(v1, v2); if Dot(pvec, rayDirection)>0 then begin // Ray is coming from behind the triangle result:=false; exit; end; end; pvec:=CrossProduct(rayDirection, v2); det:=Dot(v1, pvec); if (det<EPSILON2) and (det>-EPSILON2) then begin // vector is parallel to triangle's plane Result:=False; Exit; end; invDet:=1/det; tvec:=VectorSub(rayStart, p1); u:=Dot(tvec, pvec)*invDet; if (u<0) or (u>1) then Result:=False else begin qvec:=CrossProduct(tvec, v1); v:=Dot(rayDirection, qvec)*invDet; Result:=(v>=0) and (u+v<=1); if Result then begin t:=Dot(v2, qvec)*invDet; if t>0 then begin if intersect<>nil then intersect^:=VectorCombine(rayStart, rayDirection, t); if intersectNormal<>nil then intersectNormal^:=norm(CrossProduct(v1, v2)); end else Result:=False; end; end; end; // Returns direction vector after reflection function Reflect(const rayStart, rayDir, wallPoint: TVector): TVector; var n: TVector; begin n.x:=rayStart.x-wallPoint.x; n.y:=rayStart.y-wallPoint.y; n.z:=rayStart.z-wallPoint.z; result:=Reflect(rayDir, norm(n)); end; // Returns direction vector after reflection function Reflect(const rayDir, wallNormal: TVector): TVector; var temp: single; begin temp:=2*(rayDir.x*wallNormal.x+rayDir.y*wallNormal.y+rayDir.z*wallNormal.z); result.x:=rayDir.x-wallNormal.x*temp; result.y:=rayDir.y-wallNormal.y*temp; result.z:=rayDir.z-wallNormal.z*temp; end; function Rotate(const v: TVector; const radians: single; axis: TVector): TVector; var costheta, sintheta,px,py,pz: single; begin if radians=0 then begin result:=v; exit; end; axis:=Norm(axis); px:=v.x; py:=v.y; pz:=v.z; costheta := cos(radians); sintheta := sin(radians); result.x:=px*( axis.x*axis.x * ( 1.0 - costheta ) + costheta) + py*( axis.x*axis.y * ( 1.0 - costheta ) - axis.z * sintheta) + pz*( axis.x*axis.z * ( 1.0 - costheta ) + axis.y * sintheta); result.y:=px*( axis.y*axis.x * ( 1.0 - costheta ) + axis.z * sintheta) + py*( axis.y*axis.y * ( 1.0 - costheta ) + costheta) + pz*( axis.y*axis.z * ( 1.0 - costheta ) - axis.x * sintheta); result.z:=px*( axis.z*axis.x * ( 1.0 - costheta ) - axis.y * sintheta) + py*( axis.z*axis.y * ( 1.0 - costheta ) + axis.x * sintheta) + pz*( axis.z*axis.z * ( 1.0 - costheta ) + costheta); end; function Tangent(const a,b,c: TVector): TVector; stdcall;{$IFDEF CanInline}inline;{$ENDIF} begin result.x:=(b.y-a.y)*(c.z-a.z)-(b.z-a.z)*(c.y-a.y); result.y:=-((b.x-a.x)*(c.z-a.z)-(b.z-a.z)*(c.x-a.x)); result.z:=((b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x)); // --Z (OpenGL compatible) result:=Norm(result); end; // Returns V1 + V2 function VectorAdd(const a, b: TVector): TVector; begin result.x:=a.x+b.x; result.y:=a.y+b.y; result.z:=a.z+b.z; end; function VectorDist(const a, b: TVector): single; stdcall;{$IFDEF CanInline}inline;{$ENDIF} begin result:=hypot3f(a.x-b.x, a.y-b.y, a.z-b.z); end; function VectorDiv(const v: TVector; s: single): TVector; begin result.x:=v.x/s; result.y:=v.y/s; result.z:=v.z/s; end; // Returns V * Scale function Scale(const v: TVector; s: single): TVector; begin result.x:=v.x*s; result.y:=v.y*s; result.z:=v.z*s; end; function VectorXYFromAngle(const radians: single; const radius: single): TVector; begin result.x:=cos(radians)*radius; result.y:=sin(radians)*radius; result.z:=0; end; function VectorXZFromAngle(const radians: single; const radius: single): TVector; begin result.x:=cos(radians)*radius; result.y:=0; result.z:=sin(radians)*radius; end; function VectorZYFromAngle(const radians: single; const radius: single): TVector; begin result.x:=0; result.y:=sin(radians)*radius; result.z:=cos(radians)*radius; end; function VectorMatch(const a, b: TVector; delta: single): boolean; begin result:=(abs(a.x-b.x)<delta) and (abs(a.y-b.y)<delta) and (abs(a.z-b.z)<delta); end; function VectorLen(const v: TVector): single; stdcall; begin result:=hypot3d(v.x, v.y, v.z); end; // Vector squared function VectorSqr(const v: TVector): single; begin result:=v.x*v.x + v.y*v.y + v.z*v.z; end; // Returns V1 - V2 function VectorSub(const a, b: TVector): TVector; begin result.x:=a.x-b.x; result.y:=a.y-b.y; result.z:=a.z-b.z; end; { Matrix functions } // Before use, make sure that axis vector length is 1 function CreateMatrix(const axis: TVector; const radians: Single): TMatrix;stdcall;{$IFDEF CanInline}inline;{$ENDIF} var c, s, t, tx, ty, tz, sx, sy, sz: single; begin // Same as: result:=QuaternionToMat(Quaternion(axis, radians), vector(0,0,0)); c := cos(radians); s := sin(radians); t := 1.0 - c; tx := t * axis.X; ty := t * axis.Y; tz := t * axis.Z; sx := s * axis.X; sy := s * axis.Y; sz := s * axis.Z; Result[0, 0]:=tx * axis.X + c; Result[0, 1]:=tx * axis.Y + sz; Result[0, 2]:=tx * axis.Z - sy; Result[0, 3]:=0; Result[1, 0]:=ty * axis.X - sz; Result[1, 1]:=ty * axis.Y + c; Result[1, 2]:=ty * axis.Z + sx; Result[1, 3]:=0; Result[2, 0]:=tz * axis.X + sy; Result[2, 1]:=tz * axis.Y - sx; Result[2, 2]:=tz * axis.Z + c; Result[2, 3]:=0; Result[3, 0]:=0; Result[3, 1]:=0; Result[3, 2]:=0; Result[3, 3]:=1; end; // Create a rotation matrix function CreateMatrix(const x, y, z: TVector): TMatrix; begin result[0,0]:=x.x; result[0,1]:=x.y; result[0,2]:=x.z; result[0,3]:=0; result[1,0]:=y.x; result[1,1]:=y.y; result[1,2]:=y.z; result[1,3]:=0; result[2,0]:=z.x; result[2,1]:=z.y; result[2,2]:=z.z; result[2,3]:=0; result[3,0]:=0; result[3,1]:=0; result[3,2]:=0; result[3,3]:=1; end; function CreateMatrix(const rotation: TMatrix; const p: TVector): TMatrix; begin result:=rotation; result[3,0]:=p.x; result[3,1]:=p.y; result[3,2]:=p.z; end; function CreateMatrix(const rotation: TMatrix3f; const p: TVector): TMatrix; begin result:=Matrix(rotation); result[0,3]:=p.x; result[1,3]:=p.y; result[2,3]:=p.z; end; // Rotation matrix written with rows and columns switched function CreateMatrix2(const x, y, z: TVector): TMatrix; begin result[0,0]:=x.x; result[1,0]:=x.y; result[2,0]:=x.z; result[3,0]:=0; result[0,1]:=y.x; result[1,1]:=y.y; result[2,1]:=y.z; result[3,1]:=0; result[0,2]:=z.x; result[1,2]:=z.y; result[2,2]:=z.z; result[3,2]:=0; result[0,3]:=0; result[1,3]:=0; result[2,3]:=0; result[3,3]:=1; end; function CreateMatrix3f(const x, y, z: TVector): TMatrix3f; begin result[0,0]:=x.x; result[0,1]:=x.y; result[0,2]:=x.z; result[1,0]:=y.x; result[1,1]:=y.y; result[1,2]:=y.z; result[2,0]:=z.x; result[2,1]:=z.y; result[2,2]:=z.z; end; function CreateTranslateMatrix(const p: TVector): TMatrix; begin result:=NewMatrix; result[3,0]:=p.x; result[3,1]:=p.y; result[3,2]:=p.z; end; function MatrixDet(const a1, a2, a3, b1, b2, b3, c1, c2, c3: Single): Single; begin Result:= a1 * (b2 * c3 - b3 * c2) - b1 * (a2 * c3 - a3 * c2) + c1 * (a2 * b3 - a3 * b2); end; function Determinant(const M: TMatrix): Single; begin Result:= M[0, 0]*MatrixDet(M[1, 1], M[2, 1], M[3, 1], M[1, 2], M[2, 2], M[3, 2], M[1, 3], M[2, 3], M[3, 3]) -M[0, 1]*MatrixDet(M[1, 0], M[2, 0], M[3, 0], M[1, 2], M[2, 2], M[3, 2], M[1, 3], M[2, 3], M[3, 3]) +M[0, 2]*MatrixDet(M[1, 0], M[2, 0], M[3, 0], M[1, 1], M[2, 1], M[3, 1], M[1, 3], M[2, 3], M[3, 3]) -M[0, 3]*MatrixDet(M[1, 0], M[2, 0], M[3, 0], M[1, 1], M[2, 1], M[3, 1], M[1, 2], M[2, 2], M[3, 2]); end; // Axis vector angle given in radians function GetAngle(const M: TMatrix; const axis: integer): single; begin case axis of 0: result:=nxMath.angle(0,0,M[0,0],M[0,2]); // X (horizontal rotation) 1: result:=nxMath.angle(0,0,M[2,2],M[2,1]); // Y (vertical angle) else result:=nxMath.angle(0,0,M[0,0],M[0,1]); // Z (roll) end; end; function GetRotation(const mat: TMatrix): TMatrix; var i, j: integer; begin for j:=0 to 2 do begin for i:=0 to 2 do result[i,j]:=mat[i, j]; result[j, 3]:=0; result[3, j]:=0; end; result[3, 3]:=1; end; function GetRotation3(const mat: TMatrix): TMatrix3f; var i, j: integer; begin for j:=0 to 2 do for i:=0 to 2 do result[i, j]:=mat[i, j]; end; function GetVector(const M: TMatrix; const axis: integer): TVector;stdcall;{$IFDEF CanInline}inline;{$ENDIF} begin result.x:=M[axis,0]; result.y:=M[axis,1]; result.z:=M[axis,2]; end; function GetVector(const M: TMatrix3f; const axis: integer): TVector; stdcall; begin result.x:=M[axis,0]; result.y:=M[axis,1]; result.z:=M[axis,2]; end; function Interpolate(const a, b: TMatrix; s: single): TMatrix;stdcall;{$IFDEF CanInline}inline;{$ENDIF} var i, j: integer; begin for j:=0 to 3 do for i:=0 to 3 do result[i, j]:=interpolate(a[i, j], b[i, j], s); end; function Invert(const M: TMatrix): TMatrix; var det, a1, a2, a3, a4, b1, b2, b3, b4, c1, c2, c3, c4, d1, d2, d3, d4: Single; begin det:=Determinant(M); if Abs(Det)<EPSILON then result:=NewMatrix else begin a1:= M[0, 0]; b1:= M[0, 1]; c1:= M[0, 2]; d1:= M[0, 3]; a2:= M[1, 0]; b2:= M[1, 1]; c2:= M[1, 2]; d2:= M[1, 3]; a3:= M[2, 0]; b3:= M[2, 1]; c3:= M[2, 2]; d3:= M[2, 3]; a4:= M[3, 0]; b4:= M[3, 1]; c4:= M[3, 2]; d4:= M[3, 3]; result[0, 0]:= MatrixDet(b2, b3, b4, c2, c3, c4, d2, d3, d4); result[1, 0]:=-MatrixDet(a2, a3, a4, c2, c3, c4, d2, d3, d4); result[2, 0]:= MatrixDet(a2, a3, a4, b2, b3, b4, d2, d3, d4); result[3, 0]:=-MatrixDet(a2, a3, a4, b2, b3, b4, c2, c3, c4); result[0, 1]:=-MatrixDet(b1, b3, b4, c1, c3, c4, d1, d3, d4); result[1, 1]:= MatrixDet(a1, a3, a4, c1, c3, c4, d1, d3, d4); result[2, 1]:=-MatrixDet(a1, a3, a4, b1, b3, b4, d1, d3, d4); result[3, 1]:= MatrixDet(a1, a3, a4, b1, b3, b4, c1, c3, c4); result[0, 2]:= MatrixDet(b1, b2, b4, c1, c2, c4, d1, d2, d4); result[1, 2]:=-MatrixDet(a1, a2, a4, c1, c2, c4, d1, d2, d4); result[2, 2]:= MatrixDet(a1, a2, a4, b1, b2, b4, d1, d2, d4); result[3, 2]:=-MatrixDet(a1, a2, a4, b1, b2, b4, c1, c2, c4); result[0, 3]:=-MatrixDet(b1, b2, b3, c1, c2, c3, d1, d2, d3); result[1, 3]:= MatrixDet(a1, a2, a3, c1, c2, c3, d1, d2, d3); result[2, 3]:=-MatrixDet(a1, a2, a3, b1, b2, b3, d1, d2, d3); result[3, 3]:= MatrixDet(a1, a2, a3, b1, b2, b3, c1, c2, c3); result:=Scale(result, 1/det); end; end; function Invert(m: TMatrix3f): TMatrix3f; var det: single; begin //result:=GetRotation3(invert(matrix(m))); exit; det:= m[0,0]*(m[1,1]*m[2,2]-m[2,1]*m[1,2]) -m[0,1]*(m[1,0]*m[2,2]-m[1,2]*m[2,0]) +m[0,2]*(m[1,0]*m[2,1]-m[1,1]*m[2,0]); if abs(det)<EPSILON then begin result:=m; exit; // Doesn't have inverse end; det:=1/det; // Inverse determinant result[0,0]:= (m[1,1]*m[2,2]-m[2,1]*m[1,2])*det; result[1,0]:= -(m[0,1]*m[2,2]-m[0,2]*m[2,1])*det; result[2,0]:= (m[0,1]*m[1,2]-m[0,2]*m[1,1])*det; result[0,1]:= -(m[1,0]*m[2,2]-m[1,2]*m[2,0])*det; result[1,1]:= (m[0,0]*m[2,2]-m[0,2]*m[2,0])*det; result[2,1]:= -(m[0,0]*m[1,2]-m[1,0]*m[0,2])*det; result[0,2]:= (m[1,0]*m[2,1]-m[2,0]*m[1,1])*det; result[1,2]:= -(m[0,0]*m[2,1]-m[2,0]*m[0,1])*det; result[2,2]:= (m[0,0]*m[1,1]-m[1,0]*m[0,1])*det; end; function LookAt(const eye, target, up: TVector): TMatrix; stdcall; var x,y,z: TVector; begin z:=norm(VectorSub(eye, target)); x:=norm(crossproduct(up, z)); y:=crossproduct(z, x); result:=CreateMatrix2(x, y, z); SetVector(result, vector(-dot(eye, x), -dot(eye, y), -dot(eye, z)), 3); end; function Matrix(const mat: TMatrix3f): TMatrix; stdcall; var i, j: integer; begin for j:=0 to 2 do begin for i:=0 to 2 do result[i, j]:=mat[i, j]; result[j, 3]:=0; result[3, j]:=0; end; result[3, 3]:=1; end; function Matrix(const mat: TMatrix4d): TMatrix; stdcall;{$IFDEF CanInline}inline;{$ENDIF} var i, j: integer; begin for j:=0 to 3 do for i:=0 to 3 do result[i, j]:=mat[i, j]; end; function MatrixOnPlane(const cPos, cDir: TVector; radians: single): TMatrix; var x,y,z: TVector; begin // This function could be made better by creating vectors first by (0,1,0) and // then rotating them to cDir. Current setup looks good mainly, but rotation // with different angles looks like "slowing down" a little on certain directions. y:=norm(cDir); if y.y<>0 then z:=norm(crossproduct( vector(cos(radians),0,sin(radians)), y )) else if y.x<>0 then z:=norm(crossproduct( vector(0,cos(radians),sin(radians)), y )) else z:=norm(crossproduct( vector(cos(radians),sin(radians),0), y )); x:=norm(crossproduct(y,z)); result:=CreateMatrix(x,y,z); // This works //result:=CreateMatrix(norm(cDir), angle); // Why does this not work? SetVector(result, cPos, 3); end; function Multiply(const A,B: TMatrix): TMatrix; stdcall; {$IFDEF CanInline}inline;{$ENDIF} var I, J: Integer; begin for I := 0 to 3 do for J := 0 to 3 do Result[I, J] := A[I, 0] * B[0, J] + A[I, 1] * B[1, J] + A[I, 2] * B[2, J] + A[I, 3] * B[3, J]; end; function Multiply(const A, B: TMatrix3f): TMatrix3f; stdcall; {$IFDEF CanInline}inline;{$ENDIF} var I, J: Integer; begin for I := 0 to 2 do for J := 0 to 2 do Result[I, J] := A[I, 0] * B[0, J] + A[I, 1] * B[1, J] + A[I, 2] * B[2, J]; end; function Multiply(const A: TMatrix; const B: TMatrix3f): TMatrix; stdcall; {$IFDEF CanInline}inline;{$ENDIF} var I, J: Integer; begin for I := 0 to 2 do begin for J := 0 to 2 do Result[I, J] := A[I, 0] * B[0, J] + A[I, 1] * B[1, J] + A[I, 2] * B[2, J]; result[3, I]:=A[3, I]; result[I, 3]:=A[I, 3]; end; result[3, 3]:=A[3, 3]; end; function Multiply(const A: TMatrix3f; const B: TMatrix): TMatrix; stdcall;{$IFDEF CanInline}inline;{$ENDIF}overload; var I, J: Integer; begin for I := 0 to 2 do begin for J := 0 to 2 do Result[I, J] := A[I, 0] * B[0, J] + A[I, 1] * B[1, J] + A[I, 2] * B[2, J]; result[3, I]:=b[3, I]; result[I, 3]:=b[I, 3]; end; result[3, 3]:=b[3, 3]; end; function MultiplyRotation(const A, B: TMatrix): TMatrix;stdcall;{$IFDEF CanInline}inline;{$ENDIF} var I, J: Integer; begin for I := 0 to 2 do begin for J := 0 to 2 do Result[I, J] := A[I, 0] * B[0, J] + A[I, 1] * B[1, J] + A[I, 2] * B[2, J]; result[3, I]:=A[3, I]; result[I, 3]:=A[I, 3]; end; result[3, 3]:=A[3, 3]; end; function Multiply(const V: TVector; const M: TMatrix): TVector;stdcall;{$IFDEF CanInline}inline;{$ENDIF} begin Result.x:=V.x * M[0, 0] + V.y * M[1, 0] + V.z * M[2, 0] + M[3, 0]; Result.y:=V.x * M[0, 1] + V.y * M[1, 1] + V.z * M[2, 1] + M[3, 1]; Result.z:=V.x * M[0, 2] + V.y * M[1, 2] + V.z * M[2, 2] + M[3, 2]; end; function Multiply(const V: TVector; const M: TMatrix3f): TVector; stdcall;{$IFDEF CanInline}inline;{$ENDIF} begin Result.x:=V.x * M[0, 0] + V.y * M[1, 0] + V.z * M[2, 0]; Result.y:=V.x * M[0, 1] + V.y * M[1, 1] + V.z * M[2, 1]; Result.z:=V.x * M[0, 2] + V.y * M[1, 2] + V.z * M[2, 2]; end; // Make sure that axis vector length is 1 function Rotate(const M: TMatrix; const axis: TVector; const radians: Single; withPos: boolean): TMatrix;stdcall;{$IFDEF CanInline}inline;{$ENDIF} begin if not withPos then result:=MultiplyRotation(M, CreateMatrix(axis, radians)) else result:=Multiply(M, CreateMatrix(axis, radians)); end; function Rotate(const M: TMatrix; const axis: integer; const radians: Single; withPos: boolean): TMatrix; begin case axis of 1: result:=rotate(M, vector(1,0,0), radians, withPos); 2: result:=rotate(M, vector(0,0,1), radians, withPos); else result:=rotate(M, vector(0,1,0), radians, withPos); end; end; function Scale(const M: TMatrix; const s: Single): TMatrix; var i: Integer; begin for i:=0 to 2 do begin result[i, 0]:=M[i, 0] * s; result[i, 1]:=M[i, 1] * s; result[i, 2]:=M[i, 2] * s; result[i, 3]:=M[i, 3]; result[3, i]:=M[3, i]; end; result[3, 3]:=M[3, 3]; end; function Scale(const M: TMatrix; const v: TVector): TMatrix; overload; begin result:=NewMatrix; result[0,0]:=v.x; result[1,1]:=v.y; result[2,2]:=v.z; result:=Multiply(M, result); end; procedure SetVector(var M: TMatrix; const v: TVector; const axis: integer); begin M[axis,0]:=v.x; M[axis,1]:=v.y; M[axis,2]:=v.z; end; function Slerp(const a, b: TMatrix; s: single): TMatrix; stdcall;{$IFDEF CanInline}inline;{$ENDIF} var q1, q2: TQuaternion; v1, v2: TVector; begin v1:=GetVector(a, 3); v2:=GetVector(b, 3); q1:=Quaternion(a); q2:=Quaternion(b); result:=QuaternionToMat(Slerp(q1, q2, s), Interpolate(v1, v2, s)); end; function Translate(const M: TMatrix; const v: TVector): TMatrix;stdcall;{$IFDEF CanInline}inline;{$ENDIF} begin result:=Multiply(M, CreateTranslateMatrix(v)); end; { Quaternions } function NewQuaternion: TQuaternion; begin result.x:=0; result.y:=0; result.z:=0; result.w:=1; end; function Dot(const a, b: TQuaternion): single; begin result:=(a.X * b.X) + (a.Y * b.Y) + (a.Z * b.Z) + (a.W * b.W); end; function Lerp(const a, b: TQuaternion; s: single): TQuaternion; begin result:=Norm(QuaternionAdd(Multiply(a, 1.0-s), Multiply(b, s))); end; function Multiply(const q: TQuaternion; s: single): TQuaternion; begin result.x:=q.x*s; result.y:=q.y*s; result.z:=q.z*s; result.w:=q.w*s; end; function Multiply(const a, b: TQuaternion): TQuaternion; begin result.X := (b.W * a.X) + (b.X * a.W) + (b.Y * a.Z) - (b.Z * a.Y); result.Y := (b.W * a.Y) - (b.X * a.Z) + (b.Y * a.W) + (b.Z * a.X); result.Z := (b.W * a.Z) + (b.X * a.Y) - (b.Y * a.X) + (b.Z * a.W); result.W := (b.W * a.W) - (b.X * a.X) - (b.Y * a.Y) - (b.Z * a.Z); end; function Norm(const q: TQuaternion): TQuaternion; var n: single; begin n := q.X*q.X + q.Y*q.Y + q.Z*q.Z + q.W*q.W; if n=1.0 then result:=q else result:=Multiply(q, 1.0/sqrt(n)); // Reciprocal squareroot end; function Quaternion(x, y, z, w: single): TQuaternion; begin result.x:=x; result.y:=y; result.z:=z; result.w:=w; end; // Make new quaternion from matrix function Quaternion(const M: TMatrix): TQuaternion;stdcall;{$IFDEF CanInline}inline;{$ENDIF} begin result:=Quaternion(PVector(@M[0, 0])^, PVector(@M[1, 0])^, PVector(@M[2, 0])^); end; // Make new quaternion from rotation vectors function Quaternion(const x, y, z: TVector): TQuaternion; var diag, scale: single; begin diag := x.x + y.y + z.z + 1; if (diag>0.0) then begin scale := sqrt(diag) * 2.0; result.X := (y.z - z.y) / scale; result.Y := (z.x - x.z) / scale; result.Z := (x.y - y.x) / scale; result.W := 0.25 * scale; end else if (x.x>y.y) and (x.x>z.z) then begin scale := sqrt(1.0 + x.x - y.y - z.z) * 2.0; result.X := 0.25 * scale; result.Y := (y.x + x.y) / scale; result.Z := (x.z + z.x) / scale; result.W := (y.z - z.y) / scale; end else if (y.y>z.z) then begin scale := sqrt(1.0 + y.y - x.x - z.z) * 2.0; result.X := (x.y + y.x) / scale; result.Y := 0.25 * scale; result.Z := (z.y + y.z) / scale; result.W := (z.x - x.z) / scale; end else begin scale := sqrt(1.0 + 1.0 - x.x - y.y) * 2.0; result.X := (z.x + x.z) / scale; result.Y := (z.y + y.z) / scale; result.Z := 0.25 * scale; result.W := (x.y - y.x) / scale; end; result:=norm(result); end; // Make new quaternion from euler angles function Quaternion(const x, y, z: single): TQuaternion; var a, sr, cr, sp, cp, sy, cy, cpcy, spcy, cpsy, spsy: single; begin a := x * 0.5; sr := sin(a); cr := cos(a); a := y * 0.5; sp := sin(a); cp := cos(a); a := z * 0.5; sy := sin(a); cy := cos(a); cpcy := cp * cy; spcy := sp * cy; cpsy := cp * sy; spsy := sp * sy; result.X := sr * cpcy - cr * spsy; result.Y := cr * spcy + sr * cpsy; result.Z := cr * cpsy - sr * spcy; result.W := cr * cpcy + sr * spsy; result:=norm(result); end; function Quaternion(const axis: TVector; radians: single): TQuaternion; var fHalfAngle, fSin: single; begin fHalfAngle := 0.5*radians; fSin := sin(fHalfAngle); result.W := cos(fHalfAngle); result.X := fSin*axis.X; result.Y := fSin*axis.Y; result.Z := fSin*axis.Z; end; function QuaternionAdd(const a, b: TQuaternion): TQuaternion; begin result.x:=a.x+b.x; result.y:=a.y+b.y; result.z:=a.z+b.z; result.w:=a.w+b.w; end; function QuaternionSub(const a, b: TQuaternion): TQuaternion; begin result.x:=a.x-b.x; result.y:=a.y-b.y; result.z:=a.z-b.z; result.w:=a.w-b.w; end; function QuaternionToMat(const q: TQuaternion; const position: TVector): TMatrix;stdcall;{$IFDEF CanInline}inline;{$ENDIF} var xx, yy, zz: single; begin xx:=q.X*q.X; yy:=q.Y*q.Y; zz:=q.Z*q.Z; result[0, 0] := 1.0 - 2.0*(yy + zz); result[0, 1] := 2.0*(q.X*q.Y + q.Z*q.W); result[0, 2] := 2.0*(q.X*q.Z - q.Y*q.W); result[0, 3] := 0.0; result[1, 0] := 2.0*(q.X*q.Y - q.Z*q.W); result[1, 1] := 1.0 - 2.0*(xx + zz); result[1, 2] := 2.0*(q.Z*q.Y + q.X*q.W); result[1, 3] := 0.0; result[2, 0] := 2.0*(q.X*q.Z + q.Y*q.W); result[2, 1] := 2.0*(q.Z*q.Y - q.X*q.W); result[2, 2] := 1.0 - 2.0*(xx + yy); result[2, 3] := 0.0; result[3, 0] := position.x; result[3, 1] := position.y; result[3, 2] := position.z; result[3, 3] := 1.0; end; function Slerp(a, b: TQuaternion; s: single): TQuaternion; stdcall; var angle, theta: single; invsintheta, scale, invscale: single; //q: TQuaternion; theta2: single; begin angle := dot(a, b); if angle < 0.0 then begin a:=Multiply(a, -1.0); angle:=-angle; end; if angle <= 0.9995 then begin // Style 1 theta := arccos(angle); invsintheta := 1/sin(theta); scale := sin(theta * (1.0-s)) * invsintheta; invscale := sin(theta * s) * invsintheta; result := QuaternionAdd(Multiply(a, scale), Multiply(b, invscale)); // Style 2 {theta := arccos(angle); theta2 := theta*s; q:=norm(QuaternionSub(b, Multiply(a, angle))); result := QuaternionAdd(Multiply(a, cos(theta2)), Multiply(q, sin(theta2)));} end else // linear interpolation result:=lerp(a, b, s); end; { Operator overloading } {$IFDEF fpc} operator:=(const v: TVector2f): TVector; begin result.x:=v.x; result.y:=v.y; result.z:=0; end; operator+(const a, b: TVector): TVector; begin result.x:=a.x+b.x; result.y:=a.y+b.y; result.z:=a.z+b.z; end; operator-(const a, b: TVector): TVector; begin result.x:=a.x-b.x; result.y:=a.y-b.y; result.z:=a.z-b.z; end; operator*(const a, b: TVector): TVector;{$IFDEF CanInline}inline;{$ENDIF} begin result:=CrossProduct(a, b); end; operator*(const a: TVector; const n: single): TVector; begin result.x:=a.x*n; result.y:=a.y*n; result.z:=a.z*n; end; operator*(const n: single; const a: TVector): TVector; begin result.x:=a.x*n; result.y:=a.y*n; result.z:=a.z*n; end; operator/(const a: TVector; const n: single): TVector; begin result.x:=a.x/n; result.y:=a.y/n; result.z:=a.z/n; end; operator*(const a, b: TMatrix): TMatrix;{$IFDEF CanInline}inline;{$ENDIF} begin result:=multiply(a, b); end; operator*(const a, b: TMatrix3f): TMatrix3f;{$IFDEF CanInline}inline;{$ENDIF} begin result:=multiply(a, b); end; operator*(const a: TMatrix; const b: TMatrix3f): TMatrix;{$IFDEF CanInline}inline;{$ENDIF} begin result:=multiply(a, b); end; operator*(const v: TVector; const m: TMatrix): TVector;{$IFDEF CanInline}inline;{$ENDIF} begin result:=Multiply(v, m); end; operator+(const m: TMatrix; const v: TVector): TMatrix; begin result:=m; result[3,0]:=M[3,0]+v.x; result[3,1]:=M[3,1]+v.y; result[3,2]:=M[3,2]+v.z; end; operator-(const m: TMatrix; const v: TVector): TMatrix; begin result:=m; result[3,0]:=M[3,0]-v.x; result[3,1]:=M[3,1]-v.y; result[3,2]:=M[3,2]-v.z; end; operator:=(const q: TQuaternion): TMatrix;{$IFDEF CanInline}inline;{$ENDIF} begin result:=QuaternionToMat(q, nullVector); end; operator:=(const m: TMatrix): TQuaternion;{$IFDEF CanInline}inline;{$ENDIF} begin result:=Quaternion(m); end; operator+(const a, b: TQuaternion): TQuaternion; begin result:=QuaternionAdd(a, b); end; operator-(const a, b: TQuaternion): TQuaternion; begin result:=QuaternionSub(a, b); end; operator*(const a, b: TQuaternion): TQuaternion; begin result:=Multiply(a, b); end; operator*(const a: TQuaternion; s: single): TQuaternion; begin result:=Multiply(a, s); end; {$ENDIF} initialization nullVector:=vector(0, 0, 0); NewMatrix:=getNewMatrix; NewMatrix3f:=getNewMatrix3f; end.
unit MainForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.EditBox, FMX.NumberBox, FMX.Edit, KerbalSpaceCtrl.ViewModel, KerbalSpaceControls; type TformName = class(TForm) editHost: TEdit; numPort: TNumberBox; lblStatus: TLabel; grpViewModelTests: TGroupBox; btnConnect: TButton; btnDisconnect: TButton; grpHost: TGroupBox; btnStage: TButton; procedure DoControl( const Ctrl: TKSPControl; const StrValue: string); procedure FormCreate(Sender: TObject); procedure FormClose( Sender: TObject; var Action: TCloseAction); procedure btnConnectClick(Sender: TObject); procedure btnStageClick(Sender: TObject); private FCtrlViewModel: TKerbalSpaceCtrlViewModel; FIsConnected: boolean; procedure ConnectionControlsEnabled(const Value: boolean); procedure OnConnectionChanged(Sender: TObject); function GetHost: string; function GetPort: Integer; procedure SetHost(const Value: string); procedure SetPort(const Value: Integer); function GetIsConnected: boolean; procedure SetIsConnected(const Value: boolean); public property Host: string read GetHost write SetHost; property IsConnected: boolean read GetIsConnected write SetIsConnected; property Port: Integer read GetPort write SetPort; end; var formName: TformName; implementation {$R *.fmx} procedure TformName.btnConnectClick(Sender: TObject); begin // disable controls while waiting for connection ConnectionControlsEnabled(False); FCtrlViewModel.ConnectToServer(editHost.Text, Trunc(numPort.Value)); end; procedure TformName.btnStageClick(Sender: TObject); begin DoControl(kcStaging, ''); end; procedure TformName.ConnectionControlsEnabled(const Value: boolean); begin grpHost.Enabled := Value; grpViewModelTests.Enabled := Value; end; procedure TformName.DoControl( const Ctrl: TKSPControl; const StrValue: string); begin // add the control event to the queue FCtrlViewModel.AddToControlQueue(Ctrl, StrValue); end; procedure TformName.FormClose( Sender: TObject; var Action: TCloseAction); begin FCtrlViewModel.Free; end; procedure TformName.FormCreate(Sender: TObject); begin {$IFDEF DEBUG} TThread.NameThreadForDebugging('MainGUI'); {$ENDIF} FCtrlViewModel := TKerbalSpaceCtrlViewModel.Create; FCtrlViewModel.OnConnectionChanged := OnConnectionChanged; IsConnected := False; end; function TformName.GetHost: string; begin Result := editHost.Text; end; function TformName.GetIsConnected: boolean; begin Result := FIsConnected; end; function TformName.GetPort: Integer; begin Result := Trunc(numPort.Value); end; procedure TformName.OnConnectionChanged(Sender: TObject); begin IsConnected := FCtrlViewModel.IsConnected; if not IsConnected then begin lblStatus.Text := 'no connection: ' + FCtrlViewModel.LastConnectionError; end else begin lblStatus.Text := 'connected to ' + FCtrlViewModel.ServerVersion; end; end; procedure TformName.SetHost(const Value: string); begin editHost.Text := Value; end; procedure TformName.SetIsConnected(const Value: boolean); begin ConnectionControlsEnabled(True); FIsConnected := Value; btnConnect.Enabled := not Value; btnDisconnect.Enabled := Value; grpHost.Enabled := not Value; end; procedure TformName.SetPort(const Value: Integer); begin numPort.Value := Value; end; end.
unit MultiBuilder.Engine; interface uses MultiBuilder.Engine.Intf; function CreateMultiBuilderEngine: IMultiBuilderEngine; implementation uses System.SysUtils, System.StrUtils, System.Classes, System.IniFiles, System.Generics.Defaults, System.Generics.Collections, System.Threading, MultiBuilder.Platform; type TMultiBuilderEngine = class(TInterfacedObject, IMultiBuilderEngine) strict private const CGlobalSectionName = 'Global'; // used always CDefaultSectionName = 'Default'; // used only if environment-specific section doesn't exist CWorkingFolderKeyName = 'Folder'; CCommandKeyName = 'Cmd'; CForceDirKeyName = 'ForceDir'; CEnvironmentMacro = 'EnvironmentName'; type TEnvVarTable = TDictionary<string, string>; TProjectConfig = record WorkDir : string; Commands: TArray<string>; procedure Append(const values: TStringList); function Execute: TExecuteResult; end; var FCountRunners : integer; FEnvironments : TArray<string>; FOnJobDone : TJobDoneEvent; FOnRunCompleted: TRunCompletedEvent; FProject : TMemIniFile; FSections : TStringList; FVariables : TEnvVarTable; strict protected procedure CreateFolders(const environment: string); function EvaluateMacro(const environment, name: string): string; function GetOnJobDone: TJobDoneEvent; function GetOnRunCompleted: TRunCompletedEvent; procedure LoadFromIni(memIni: TMemIniFile); procedure PrepareProjectConfig(const environment: string; var projectConfig: TProjectConfig); procedure ReplaceMacros(const environment: string; values: TStringList); overload; function ReplaceMacros(const environment, value: string): string; overload; procedure JobDone(const environment: string; const result: TExecuteResult); procedure SetOnJobDone(const value: TJobDoneEvent); procedure SetOnRunCompleted(const value: TRunCompletedEvent); procedure StartRunner(const environment: string; const projectConfig: TProjectConfig); protected class function Split(const kv: string; var key, value: string): boolean; public procedure AfterConstruction; override; procedure BeforeDestruction; override; procedure ClearProject; function Environments: TArray<string>; function LoadFrom(const iniFile: string): boolean; function LoadProject(const projFile: string): boolean; procedure Run; procedure RunSelected(const environment: string); property OnJobDone: TJobDoneEvent read GetOnJobDone write SetOnJobDone; property OnRunCompleted: TRunCompletedEvent read GetOnRunCompleted write SetOnRunCompleted; end; { exports } function CreateMultiBuilderEngine: IMultiBuilderEngine; begin Result := TMultiBuilderEngine.Create; end; procedure TMultiBuilderEngine.AfterConstruction; begin inherited; FSections := TStringList.Create; FVariables := TEnvVarTable.Create(TIStringComparer.Ordinal); end; procedure TMultiBuilderEngine.BeforeDestruction; begin ClearProject; FreeAndNil(FSections); FreeAndNil(FVariables); inherited; end; procedure TMultiBuilderEngine.ClearProject; begin FreeAndNil(FProject); end; procedure TMultiBuilderEngine.CreateFolders(const environment: string); var folder : string; folders: TArray<string>; begin folders := EvaluateMacro(environment, CForceDirKeyName).Split([';'], '"', '"'); for folder in folders do ForceDirectories(ReplaceMacros(environment, folder)); end; function TMultiBuilderEngine.Environments: TArray<string>; begin Result := FEnvironments; end; function TMultiBuilderEngine.EvaluateMacro(const environment, name: string): string; begin if SameText(name, CEnvironmentMacro) then Result := environment else if (not FVariables.TryGetValue(environment + '/' + name, Result)) and (not FVariables.TryGetValue(CDefaultSectionName + '/' + name, Result)) and (not FVariables.TryGetValue(CGlobalSectionName + '/' + name, Result)) then Result := ''; end; function TMultiBuilderEngine.GetOnJobDone: TJobDoneEvent; begin Result := FOnJobDone; end; function TMultiBuilderEngine.GetOnRunCompleted: TRunCompletedEvent; begin Result := FOnRunCompleted; end; procedure TMultiBuilderEngine.JobDone(const environment: string; const result: TExecuteResult); begin if assigned(OnJobDone) then OnJobDone(environment, result); Dec(FCountRunners); if (FCountRunners = 0) and assigned(OnRunCompleted) then OnRunCompleted(); end; function TMultiBuilderEngine.LoadFrom(const iniFile: string): boolean; var memIni: TMemIniFile; begin FSections.Clear; SetLength(FEnvironments, 0); if not FileExists(iniFile) then Exit(true); try memIni := TMemIniFile.Create(iniFile); except Result := false; Exit; end; try LoadFromIni(memIni); finally FreeAndNil(memIni); end; Result := true; end; procedure TMultiBuilderEngine.LoadFromIni(memIni: TMemIniFile); var iEnv : integer; sEnv : string; sName : string; sNameVar: string; sVar : string; values : TStringList; begin memIni.ReadSections(FSections); SetLength(FEnvironments, FSections.Count); FVariables.Clear; iEnv := 0; values := TStringList.Create; try for sEnv in FSections do begin if not (SameText(sEnv, CGlobalSectionName) or SameText(sEnv, CDefaultSectionName)) then begin FEnvironments[iEnv] := sEnv; Inc(iEnv); end; memIni.ReadSectionValues(sEnv, values); for sNameVar in values do begin if Split(sNameVar, sName, sVar) then FVariables.Add(sEnv + '/' + sName, sVar); end; end; finally FreeAndNil(values); end; SetLength(FEnvironments, iEnv); end; function TMultiBuilderEngine.LoadProject(const projFile: string): boolean; begin Result := true; ClearProject; if not FileExists(projFile) then Exit(true); try FProject := TMemIniFile.Create(projFile); except ClearProject; Result := false; end; end; procedure TMultiBuilderEngine.PrepareProjectConfig(const environment: string; var projectConfig: TProjectConfig); var section: string; values : TStringList; begin values := TStringList.Create; try projectConfig := Default(TProjectConfig); FProject.ReadSectionValues(CGlobalSectionName, values); ReplaceMacros(environment, values); projectConfig.Append(values); if FProject.SectionExists(environment) then section := environment else section := CDefaultSectionName; FProject.ReadSectionValues(section, values); ReplaceMacros(environment, values); projectConfig.Append(values); finally FreeAndNil(values); end; end; procedure TMultiBuilderEngine.ReplaceMacros(const environment: string; values: TStringList); var i: integer; begin for i := 0 to values.Count - 1 do values[i] := ReplaceMacros(environment, values[i]); end; function TMultiBuilderEngine.ReplaceMacros(const environment, value: string): string; var name: string; p1 : integer; p2 : integer; begin Result := value; p1 := 1; repeat p1 := PosEx('$(', Result, p1); if p1 <= 0 then break; //repeat p2 := PosEx(')', Result, p1); if p2 <= 0 then break; //repeat name := Copy(Result, p1 + 2, p2 - p1 - 2); Delete(Result, p1, p2 - p1 + 1); Insert(EvaluateMacro(environment, name), Result, p1); until false; end; procedure TMultiBuilderEngine.Run; var sEnv: string; begin if (not assigned(FProject)) or (Length(FEnvironments) = 0) then begin if assigned(OnRunCompleted) then OnRunCompleted(); Exit; end; FCountRunners := Length(FEnvironments); for sEnv in FEnvironments do RunSelected(sEnv); end; procedure TMultiBuilderEngine.RunSelected(const environment: string); var projConfig: TProjectConfig; begin PrepareProjectConfig(environment, projConfig); try CreateFolders(environment); StartRunner(environment, projConfig); except on E: Exception do JobDone(environment, TExecuteResult.Create('', 255, E.Message)); end; end; procedure TMultiBuilderEngine.SetOnJobDone(const value: TJobDoneEvent); begin FOnJobDone := value; end; procedure TMultiBuilderEngine.SetOnRunCompleted(const value: TRunCompletedEvent); begin FOnRunCompleted := value; end; class function TMultiBuilderEngine.Split(const kv: string; var key, value: string): boolean; var p: integer; begin p := Pos('=', kv); Result := (p > 0); if Result then begin key := Copy(kv, 1, p-1); value := kv; Delete(value, 1, p); end; end; procedure TMultiBuilderEngine.StartRunner(const environment: string; const projectConfig: TProjectConfig); var future : IFuture<TExecuteResult>; threadConfig: TProjectConfig; begin threadConfig := projectConfig; threadConfig.WorkDir := ReplaceMacros(environment, threadConfig.WorkDir); future := TFuture<TExecuteResult>.Create(TObject(nil), TFunctionEvent<TExecuteResult>(nil), function: TExecuteResult begin Result := threadConfig.Execute; TThread.Queue(nil, procedure begin JobDone(environment, future.Value); future := nil; end); end, TThreadPool.Default); future.Start; end; procedure TMultiBuilderEngine.TProjectConfig.Append(const values: TStringList); var kv : string; name : string; value: string; begin for kv in values do begin if not TMultiBuilderEngine.Split(kv, name, value) then continue; //for if SameText(name, CWorkingFolderKeyName) then WorkDir := value else if SameText(name, CCommandKeyName) then begin SetLength(Commands, Length(Commands) + 1); Commands[High(Commands)] := value; end; end; end; function TMultiBuilderEngine.TProjectConfig.Execute: TExecuteResult; var cmd : string; exitCode: integer; output : string; begin for cmd in Commands do begin MBPlatform.Execute(WorkDir, cmd, exitCode, output); if exitCode <> 0 then Exit(TExecuteResult.Create(cmd, exitCode, output)); end; Result := TExecuteResult.Create('', 0, ''); end; end.
// // syscall.pas // // This unit contains the syscall interface. // // Copyright (c) 2003-2022 Matias Vara <matiasevara@gmail.com> // All Rights Reserved // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // Unit Syscall; interface const NR_SYSCALL = 50; var syscall_table:array [0..NR_SYSCALL] of pointer; procedure Syscall_Init; implementation uses arch, process, memory, filesystem; procedure kernel_entry;assembler; asm push eax push es push ds push ebp push edi push esi push edx push ecx push ebx mov edx, KERNEL_DATA_SEL mov ds , dx mov es , dx cmp eax , NR_SYSCALL jg @error shl eax, 2 lea edi, syscall_table mov ebx, dword [edi + eax] sti call ebx jmp @ret_to_user_mode @error: mov eax , -EINVAL @ret_to_user_mode: mov dword [esp+32], eax pop ebx pop ecx pop edx pop esi pop edi pop ebp pop ds pop es pop eax iret end; procedure Syscall_Init; var m: dword; begin Set_Int_Gate_User(50,@kernel_entry); for m := 0 to 34 do syscall_table[m] := nil; syscall_table[0]:= @Sys_MountRoot; Syscall_Table[1]:= @Sys_Exit; Syscall_Table[2]:= @Sys_Fork;{ Syscall_Table[3]:= @Sys_Mkdir; Syscall_Table[4]:= @Sys_Mknod; Syscall_Table[5]:= @Sys_Create; }Syscall_Table[6]:= @Sys_Open; SYSCALL_Table[7]:= @Sys_WaitPid; Syscall_Table[8]:= @Sys_Read; Syscall_Table[9]:= @Sys_Write; {Syscall_Table[10]:= @Sys_Close; Syscall_Table[12]:= @Sys_Chmod; Syscall_Table[13]:= @Sys_Time; Syscall_Table[14]:= @Sys_Rename; Syscall_Table[15]:= @Sys_Mount; Syscall_Table[16]:= @Sys_Unmount; Syscall_Table[17]:= @Sys_sleep; Syscall_Table[18]:= @sys_setitimer; Syscall_Table[19]:= @Sys_GetPid; Syscall_Table[20]:= @Sys_GetPPid; Syscall_Table[21]:= @Sys_Detener;} Syscall_Table[22] := @Sys_Stat;{ Syscall_Table[23] := @Sys_Utime; Syscall_Table[24] := @Sys_Stime ; }Syscall_Table[25]:= @SysExec; {Syscall_Table[26] := @sys_getitimer;} Syscall_Table[27] := @Sys_chdir ; Syscall_Table[28] := @Sys_ReadErrno ;{ syscall_Table[29] := @sys_setscheduler ; syscall_table[31] := @sys_getscheduler ; Syscall_Table[36]:= @Sys_Sync; }Syscall_Table[45]:= @Sys_Brk; {Syscall_Table[37]:= @Sys_Kill; Syscall_Table[48]:= @Sys_Signal; } Syscall_Table[30]:= @Sys_Seek; syscall_table [33] := @Sys_Ioctl; {syscall_table[32] := @Reboot ; syscall_table[34] := @sys_rmdir;} end; end.
unit BuilderPizzaExample.Util.Utils; interface type TUtils = class public class function IIF(ACondition: Boolean; AValueA, AValueB: Variant): Variant; end; TConstants = class public class function EMPTY_STRING : string; end; implementation { TUtils } class function TUtils.IIF(ACondition: Boolean; AValueA, AValueB: Variant): Variant; begin if ACondition then Result := AValueA else Result := AValueB; end; { TConstants } class function TConstants.EMPTY_STRING: string; begin Result := ''; end; end.