text
stringlengths
14
6.51M
unit OverlayMainWindow; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DDraw, Menus, ExtDlgs; type TOverlayMainForm = class(TForm) OpenPictureDialog: TOpenPictureDialog; MainMenu: TMainMenu; File1: TMenuItem; Load: TMenuItem; procedure FormShow(Sender: TObject); procedure FormPaint(Sender: TObject); procedure LoadClick(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } fDirectDraw : IDirectDraw4; fPrimarySurface : IDirectDrawSurface4; fOverlay : IDirectDrawSurface4; //fBackBuffer : IDirectDrawSurface4; fClipper : IDirectDrawClipper; fOverlayVisible : boolean; fBitmap : TBitmap; fBitmapSurface : IDirectDrawSurface4; procedure WMMove(var Msg : TWMMove); message WM_MOVE; procedure UpdateOverlayClipper; public { Public declarations } end; var OverlayMainForm: TOverlayMainForm; implementation {$R *.DFM} uses ComObj, LogFile; function CopyBitmapToSurface(Bitmap : TBitmap; const Surface : IDirectDrawSurface4; x, y : integer) : boolean; var dc : HDC; memdc : HDC; begin Result := false; if Surface.GetDC(dc) = DD_OK then try memdc := CreateCompatibleDC(dc); if memdc <> 0 then try SelectObject(memdc, Bitmap.Handle); if not BitBlt(dc, x, y, Bitmap.Width, Bitmap.Height, memdc, 0, 0, SRCCOPY) then LogThis('BitBlt FAILED') else Result := true; finally DeleteDC(memdc); end else LogThis('CreateCompatibleDC FAILED'); finally Surface.ReleaseDC(dc); end else LogThis('GetDC FAILED'); end; const cMaxPixelFormats = 4; const cFormatIdx = 1; const cPixelFormats : array [0..pred(cMaxPixelFormats)] of TDDPixelFormat = ( (dwSize : sizeof(TDDPixelFormat); dwFlags : DDPF_RGB; dwFourCC : 0; dwRGBBitCount : 16; dwRBitMask : $7C00; dwGBitMask : $03e0; dwBBitMask : $001F; dwRGBAlphaBitMask : 0), // 16-bit RGB 5:5:5 (dwSize : sizeof(TDDPixelFormat); dwFlags : DDPF_RGB; dwFourCC : 0; dwRGBBitCount : 16; dwRBitMask : $F800; dwGBitMask : $07e0; dwBBitMask : $001F; dwRGBAlphaBitMask : 0), // 16-bit RGB 5:6:5 (dwSize : sizeof(TDDPixelFormat); dwFlags : DDPF_RGB; dwFourCC : 0; dwRGBBitCount : 24; dwRBitMask : $FF0000; dwGBitMask : $00FF00; dwBBitMask : $0000FF; dwRGBAlphaBitMask : 0), // 24-bit RGB 8:8:8 (dwSize : sizeof(TDDPixelFormat); dwFlags : DDPF_RGB; dwFourCC : 0; dwRGBBitCount : 24; dwRBitMask : $FF0000; dwGBitMask : $00FF00; dwBBitMask : $0000FF; dwRGBAlphaBitMask : 0), // 24-bit RGB 8:8:8 (dwSize : sizeof(TDDPixelFormat); dwFlags : DDPF_RGB; dwFourCC : 0; dwRGBBitCount : 24; dwRBitMask : $FF0000; dwGBitMask : $00FF00; dwBBitMask : $0000FF; dwRGBAlphaBitMask : 0), // 32-bit RGB 8:8:8 (dwSize : sizeof(TDDPixelFormat); dwFlags : DDPF_RGB; dwFourCC : 0; dwRGBBitCount : 24; dwRBitMask : $FF0000; dwGBitMask : $00FF00; dwBBitMask : $0000FF; dwRGBAlphaBitMask : 0) // 22-bit RGB 8:8:8 ); function CreateFlippingOverlay(const DirectDraw : IDirectDraw4; Control : TWinControl; out BackBuffer : IDirectDrawSurface4) : IDirectDrawSurface4; var hRet : HRESULT; ddsd : TDDSurfaceDesc2; ddscaps : TDDSCaps2; devcaps : TDDCaps; HELcaps : TDDCaps; begin if DirectDraw <> nil then if (DirectDraw.GetCaps(@devcaps, @HELCaps) = DD_OK) and ((devcaps.dwCaps and DDCAPS_OVERLAY) <> 0) then begin fillchar(ddsd, sizeof(ddsd), 0); ddsd.dwSize := sizeof(ddsd); ddsd.dwFlags := DDSD_CAPS or DDSD_HEIGHT or DDSD_WIDTH or DDSD_BACKBUFFERCOUNT or DDSD_PIXELFORMAT; ddsd.ddsCaps.dwCaps := DDSCAPS_OVERLAY or DDSCAPS_FLIP or DDSCAPS_COMPLEX or DDSCAPS_VIDEOMEMORY; ddsd.dwWidth := Control.ClientWidth; ddsd.dwHeight := Control.ClientHeight; ddsd.dwBackBufferCount := 2; ddsd.ddpfPixelFormat := cPixelFormats[cFormatIdx]; hRet := DirectDraw.CreateSurface(ddsd, Result, nil); if hRet <> DD_OK then Result := nil; if Result <> nil then begin ddscaps.dwCaps := DDSCAPS_BACKBUFFER; hRet := Result.GetAttachedSurface(ddscaps, BackBuffer); if hRet <> DD_OK then begin LogThis('GetAttachedSurface FAILED'); Result := nil; BackBuffer := nil; end; end; end else Result := nil else Result := nil; end; function CreateOverlay(const DirectDraw : IDirectDraw4; Control : TWinControl) : IDirectDrawSurface4; var hRet : HRESULT; ddsd : TDDSurfaceDesc2; devcaps : TDDCaps; HELcaps : TDDCaps; begin if DirectDraw <> nil then begin fillchar(devcaps, sizeof(devcaps), 0); devcaps.dwSize := sizeof(devcaps); fillchar(HELCaps, sizeof(HELCaps), 0); HELCaps.dwSize := sizeof(HELCaps); if DirectDraw.GetCaps(@devcaps, @HELCaps) = DD_OK then if devcaps.dwCaps and DDCAPS_OVERLAY <> 0 then begin fillchar(ddsd, sizeof(ddsd), 0); ddsd.dwSize := sizeof(ddsd); ddsd.dwFlags := DDSD_CAPS or DDSD_HEIGHT or DDSD_WIDTH or DDSD_PIXELFORMAT; ddsd.ddsCaps.dwCaps := DDSCAPS_OVERLAY or DDSCAPS_VIDEOMEMORY; ddsd.dwWidth := Control.ClientWidth; ddsd.dwHeight := Control.ClientHeight; ddsd.ddpfPixelFormat := cPixelFormats[cFormatIdx]; hRet := DirectDraw.CreateSurface(ddsd, Result, nil); if hRet <> DD_OK then Result := nil end else Result := nil else Result := nil; end else Result := nil; end; function HideOverlay(const PrimarySurface, Overlay : IDirectDrawSurface4) : boolean; begin Result := Overlay.UpdateOverlay(nil, PrimarySurface, nil, DDOVER_HIDE, nil) = DD_OK; end; function ResizeOverlay(const DirectDraw : IDirectDraw4; Control : TWinControl; const PrimarySurface : IDirectDrawSurface4; var Overlay : IDirectDrawSurface4) : boolean; begin //HideOverlay(PrimarySurface, Overlay); Overlay := CreateOverlay(DirectDraw, Control); Result := Overlay <> nil; end; function ShowOverlay(Control : TWinControl; const Overlay, Primary : IDirectDrawSurface4) : boolean; var SrcRect : TRect; DestRect : TRect; ScPt : TPoint; begin SrcRect := Rect(0, 0, pred(Control.ClientWidth), pred(Control.ClientHeight)); DestRect := SrcRect; ScPt := Control.ClientToScreen(Point(0, 0)); OffsetRect(DestRect, ScPt.x, ScPt.y); // fix rects to account for strecth factors as well as size and alignment restrictions if Overlay.UpdateOverlay(@SrcRect, Primary, @DestRect, DDOVER_SHOW, nil) <> DD_OK then begin LogThis('UpdateOverlay FAILED'); Result := false; end else Result := true; end; function MoveOverlay(Control : TWinControl; const Overlay : IDirectDrawSurface4) : boolean; var ScPt : TPoint; begin ScPt := Control.ClientToScreen(Point(0, 0)); // adjust position accounting for destination alignment restrictions Result := Overlay.SetOverlayPosition(ScPt.x, ScPt.y) = DD_OK; end; function CreateClipper(const DirectDraw : IDirectDraw4; Control : TWinControl) : IDirectDrawClipper; var hRet : HRESULT; begin if DirectDraw <> nil then begin hRet := DirectDraw.CreateClipper(0, Result, nil); if hRet <> DD_OK then Result := nil; end else Result := nil; end; function FillSurface(const Surface : IDirectDrawSurface4; rgbColor : integer) : boolean; var DDBltFx : TDDBltFx; begin fillchar(DDBltFx, sizeof(DDBltFx), 0); DDBltFx.dwSize := sizeof(DDBltFx); DDBltFx.dwFillColor := rgbColor; Result := Surface.Blt(nil, nil, nil, DDBLT_COLORFILL, @DDBltFx) = DD_OK; end; procedure TOverlayMainForm.FormShow(Sender: TObject); var ddsd : TDDSurfaceDesc2; //ddscaps : TDDSCAPS2; hRet : HRESULT; pDD : IDirectDraw; begin hRet := DirectDrawCreate(nil, pDD, nil); if hRet <> DD_OK then LogThis('DirectDrawCreate FAILED') else begin hRet := pDD.QueryInterface(IID_IDirectDraw4, fDirectDraw); if hRet <> DD_OK then LogThis('QueryInterface FAILED') else begin hRet := fDirectDraw.SetCooperativeLevel(Handle, DDSCL_NORMAL); if hRet <> DD_OK then LogThis('SetCooperativeLevel FAILED') else begin fillchar(ddsd, sizeof(ddsd), 0); ddsd.dwSize := sizeof(ddsd); ddsd.dwFlags := DDSD_CAPS; ddsd.ddsCaps.dwCaps := DDSCAPS_PRIMARYSURFACE; hRet := fDirectDraw.CreateSurface(ddsd, fPrimarySurface, nil); if hRet <> DD_OK then LogThis('CreateSurface FAILED'); end; end; end; end; procedure TOverlayMainForm.FormPaint(Sender: TObject); function DoBlit(const Src, Dest : IDirectDrawSurface4; x, y : integer; Clip : boolean) : boolean; var BltEfx : TDDBltFX; DestRect : TRect; SrcRect : TRect; begin fillchar(BltEfx, sizeof(BltEfx), 0); BltEfx.dwSize := sizeof(BltEfx); DestRect := Rect(x, y, pred(x + fBitmap.Width), pred(y + fBitmap.Height)); SrcRect := Rect(0, 0, pred(fBitmap.Width), pred(fBitmap.Height)); if Clip then begin IntersectRect(DestRect, DestRect, ClientRect); IntersectRect(SrcRect, SrcRect, ClientRect); end; Result := Dest.Blt(@DestRect, Src, @SrcRect, DDBLT_WAIT, @BltEfx) = DD_OK; end; function DoFastBlit(const Src, Dest : IDirectDrawSurface4; x, y : integer; Clip : boolean) : boolean; var DestRect : TRect; SrcRect : TRect; begin DestRect := Rect(x, y, pred(x + fBitmap.Width), pred(y + fBitmap.Height)); SrcRect := Rect(0, 0, pred(fBitmap.Width), pred(fBitmap.Height)); if Clip then begin IntersectRect(DestRect, DestRect, ClientRect); IntersectRect(SrcRect, SrcRect, ClientRect); end; Result := Dest.BltFast(x, y, Src, @SrcRect, DDBLTFAST_WAIT) = DD_OK; end; var ScPt : TPoint; begin if (fBitmap <> nil) and ((fOverlay <> nil) or (fClipper <> nil)) then begin ScPt := ClientToScreen(Point(0, 0)); if fOverlay <> nil then begin if not fOverlayVisible then fOverlayVisible := ShowOverlay(Self, fOverlay, fPrimarySurface); FillSurface(fOverlay, RGB(0, 0, 0)); DoBlit(fBitmapSurface, fOverlay, 0, 0, true); end else DoBlit(fBitmapSurface, fPrimarySurface, ScPt.x, ScPt.y, false); end; end; procedure TOverlayMainForm.LoadClick(Sender: TObject); function CreateBitmapSurface(Width, Height : integer) : IDirectDrawSurface4; var hRet : HRESULT; ddsd : TDDSurfaceDesc2; begin fillchar(ddsd, sizeof(ddsd), 0); ddsd.dwSize := sizeof(ddsd); ddsd.dwFlags := DDSD_CAPS or DDSD_WIDTH or DDSD_HEIGHT or DDSD_PIXELFORMAT; ddsd.ddsCaps.dwCaps := DDSCAPS_OFFSCREENPLAIN; ddsd.dwWidth := Width; ddsd.dwHeight := Height; ddsd.ddpfPixelFormat := cPixelFormats[cFormatIdx]; hRet := fDirectDraw.CreateSurface(ddsd, Result, nil); if hRet <> DD_OK then Result := nil; end; var hRet : HRESULT; begin if OpenPictureDialog.Execute then begin fBitmapSurface := nil; fBitmap.Free; fBitmap := nil; fBitmap := TBitmap.Create; try fBitmap.LoadFromFile(OpenPictureDialog.FileName); fBitmapSurface := CreateBitmapSurface(fBitmap.Width, fBitmap.Height); if fBitmapSurface <> nil then CopyBitmapToSurface(fBitmap, fBitmapSurface, 0, 0) else begin fBitmap.Free; fBitmap := nil; end; if (fOverlay = nil) and (fClipper = nil) then begin fOverlay := CreateOverlay(fDirectDraw, Self); fClipper := CreateClipper(fDirectDraw, Self); if fClipper <> nil then if fOverlay <> nil then begin UpdateOverlayClipper; hRet := fOverlay.SetClipper(fClipper); if hRet <> DD_OK then LogThis('SetClipper FAILED'); end else begin hRet := fClipper.SetHWnd(0, Handle); if hRet <> DD_OK then LogThis('SetHWnd FAILED'); hRet := fPrimarySurface.SetClipper(fClipper); if hRet <> DD_OK then LogThis('SetClipper FAILED'); end; end; Refresh; except fBitmap.Free; fBitmap := nil; end; end; end; procedure TOverlayMainForm.FormResize(Sender: TObject); begin if fOverlay <> nil then UpdateOverlayClipper; end; procedure TOverlayMainForm.WMMove(var Msg : TWMMove); begin inherited; if fOverlay <> nil then begin MoveOverlay(Self, fOverlay); UpdateOverlayClipper; end; end; procedure TOverlayMainForm.UpdateOverlayClipper; type PRegionData = ^TRegionData; TRegionData = record Header : TRgnDataHeader; Rect : TRect; end; var RgnData : PRgnData; RegionData : PRegionData absolute RgnData; R : TRect; begin getmem(RgnData, sizeof(TRegionData)); if fClipper <> nil then begin R := Rect(0, 0, pred(fBitmap.Width), pred(fBitmap.Height)); IntersectRect(R, R, ClientRect); RegionData.Header.dwSize := sizeof(RegionData.Header); RegionData.Header.iType := RDH_RECTANGLES; RegionData.Header.nCount := 1; RegionData.Header.nRgnSize := sizeof(RegionData.Rect); RegionData.Header.rcBound := R; RegionData.Rect := R; if fClipper.SetClipList(RgnData, 0) <> DD_OK then raise Exception.Create('SetClipList FAILED'); end; end; procedure TOverlayMainForm.FormCreate(Sender: TObject); begin SetBounds(0, 0, 700, 500); end; initialization SetLogFile('C:\Tmp\Overlay.log'); end.
{******************************************************************************} { } { Delphi FB4D Library } { Copyright (c) 2018-2023 Christoph Schneider } { Schneider Infosystems AG, Switzerland } { https://github.com/SchneiderInfosystems/FB4D } { } {******************************************************************************} { } { 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 PhotoThreads; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Threading, System.Generics.Collections, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.ListBox, FMX.StdCtrls, FMX.Consts, REST.Types, FB4D.Interfaces, FB4D.VisionMLDefinition; type TPhotoInterpretation = class; TPhotoThread = class(TThread) public const cCollectionID = 'photos'; cStorageFolder = 'photos'; public type TOnSuccess = procedure(Item: TListBoxItem) of object; TOnFailed = procedure(Item: TListBoxItem; const Msg: string) of object; TDirection = (Upload, Download); private const {$IFDEF MSWINDOWS} cVisionMLFileExt = STIFFImageExtension; cVisionMLContentType = CONTENTTYPE_IMAGE_TIFF; {$ENDIF} {$IFDEF ANDROID} cVisionMLFileExt = SGIFImageExtension; cVisionMLContentType = CONTENTTYPE_IMAGE_GIF; {$ENDIF} cMaxResults = 5; private fConfig: IFirebaseConfiguration; fDirection: TDirection; fDocID: string; fUID: string; fBase64: string; fItem: TListBoxItem; fImage: TMemoryStream; fThumbnail: TBitmap; fContentType: TRESTContentType; fPhotoInterpretation: TPhotoInterpretation; fOnSuccess: TOnSuccess; fOnFailed: TOnFailed; // For Upload procedure UploadPhotoInThread; procedure VisionML; function CreateDocument(Item: TListBoxItem): IFirestoreDocument; procedure UploadImageToStorage; function ConvertImageForImageClass(Bmp: TBitmap; const Ext: string): TMemoryStream; // For Download procedure DownloadPhotoInThread; function DownloadImageFromStorage: TBitmap; protected procedure Execute; override; public constructor CreateForUpload(const Config: IFirebaseConfiguration; const UID: string; Image: TBitmap; Item: TListBoxItem); constructor CreateForDownload(const Config: IFirebaseConfiguration; const UID: string; lstPhotoList: TListBox; Doc: IFirestoreDocument); destructor Destroy; override; procedure StartThread(OnSuccess: TOnSuccess; fOnFailed: TOnFailed); class function ThumbSize: TPoint; class function SearchItem(lstPhotoList: TListBox; const DocID: string): TListBoxItem; class function CreateThumbnail(Bmp: TBitmap): TBitmap; class function GetStorageObjName(const DocID, UID: string): string; end; TPhotoInterpretation = class private const cMinScore = 0.66; private fLabels: TStringList; fTexts: TStringList; class var FRefList: TList<TPhotoInterpretation>; function GetLabelInfo: string; function GetFullInfo: string; public class constructor ClassCreate; class destructor ClassDestroy; constructor Create(Labels: TAnnotationList; FullText: TTextAnnotation); overload; constructor Create(Labels, Texts: TStringDynArray); overload; destructor Destroy; override; procedure SetLabels(Labels: TStringDynArray); procedure SetTexts(Texts: TStringDynArray); property FullInfo: string read GetFullInfo; property LabelInfo: string read GetLabelInfo; property Labels: TStringList read fLabels; property Texts: TStringList read fTexts; end; implementation uses System.SyncObjs, System.NetEncoding, System.JSON, FMX.Surfaces, FB4D.VisionML, FB4D.Helpers, FB4D.Document; resourcestring rsVisionMLFailed = 'Vision ML failed: '; rsVisionMLNotAvailable = 'Vision ML not available'; rsLabels = 'Labels: '; rsNoLabels = 'No labels found'; rsTexts = 'Texts: '; rsNoTexts = 'No texts found'; { TPhotoThread } {$REGION 'Helpers as class functions'} class function TPhotoThread.ThumbSize: TPoint; const Size: TPoint = (X: 256; Y: 256); begin result := Size; end; class function TPhotoThread.CreateThumbnail(Bmp: TBitmap): TBitmap; var W, H: single; begin Assert(Bmp.Width > 0, 'CreateThumbnail failed by width <= 0'); Assert(Bmp.Height > 0, 'CreateThumbnail failed by height <= 0'); if Bmp.Width / Bmp.Height > ThumbSize.X / ThumbSize.Y then begin // Larger width than height W := ThumbSize.X; H := Bmp.Height / Bmp.Width * W; end else begin // Larger height than width H := ThumbSize.Y; W := Bmp.Width / Bmp.Height * H; end; Result := TBitmap.Create(trunc(W), trunc(H)); if Result.Canvas.BeginScene then begin try Result.Canvas.DrawBitmap(Bmp, RectF(0, 0, Bmp.Width, Bmp.Height), RectF(0, 0, W, H), 1); finally Result.Canvas.EndScene; end; end; end; class function TPhotoThread.SearchItem(lstPhotoList: TListBox; const DocID: string): TListBoxItem; var c: integer; begin result := nil; for c := 0 to lstPhotoList.Items.Count - 1 do if lstPhotoList.ItemByIndex(c).TagString = DocID then exit(lstPhotoList.ItemByIndex(c)); end; {$ENDREGION} {$REGION 'Upload'} constructor TPhotoThread.CreateForUpload(const Config: IFirebaseConfiguration; const UID: string; Image: TBitmap; Item: TListBoxItem); var Img: TMemoryStream; Base64: TStringStream; begin inherited Create(true); fConfig := Config; fDirection := Upload; fUID := UID; fItem := Item; fImage := TMemoryStream.Create; Image.SaveToStream(fImage); fImage.Position := 0; fContentType := TFirebaseHelpers.ImageStreamToContentType(fImage); {$IF CompilerVersion < 35} // Delphi 10.4 and before if fContentType = ctNone then {$ELSE} if length(fContentType) = 0 then {$ENDIF} begin // Unsupported image type: Convert to JPG! fImage.Free; fImage := ConvertImageForImageClass(Image, SJPGImageExtension); fContentType := TRESTContentType.ctIMAGE_JPEG; end; try Img := ConvertImageForImageClass(Image, cVisionMLFileExt); Base64 := TStringStream.Create; try if assigned(Img) then begin Img.Position := 0; TNetEncoding.Base64.Encode(Img, Base64); fBase64 := Base64.DataString; end; finally Img.Free; Base64.Free; end; except fBase64 := ''; end; FreeOnTerminate := true; end; function TPhotoThread.ConvertImageForImageClass(Bmp: TBitmap; const Ext: string): TMemoryStream; var Surface: TBitmapSurface; begin result := TMemoryStream.Create; Surface := TBitmapSurface.Create; try Surface.Assign(Bmp); if not TBitmapCodecManager.SaveToStream(result, Surface, Ext) then FreeAndNil(result); finally Surface.Free; end; end; procedure TPhotoThread.VisionML; var Resp: IVisionMLResponse; begin if fBase64.IsEmpty then fPhotoInterpretation := TPhotoInterpretation.Create([], [rsVisionMLNotAvailable]) else begin try Resp := fConfig.VisionML.AnnotateFileSynchronous(fBase64, cVisionMLContentType, [vmlLabelDetection, vmlDocTextDetection], cMaxResults); fPhotoInterpretation := TPhotoInterpretation.Create(Resp.LabelAnnotations, Resp.FullTextAnnotations); except on e: exception do // fall back when ML fails fPhotoInterpretation := TPhotoInterpretation.Create([], [rsVisionMLFailed + e.Message]); end; end; end; function TPhotoThread.CreateDocument(Item: TListBoxItem): IFirestoreDocument; var Arr: TFirestoreArr; c: integer; begin Assert(assigned(fPhotoInterpretation), 'PhotoInterpretation missing'); fDocID := TFirebaseHelpers.CreateAutoID(PUSHID); TThread.Synchronize(nil, procedure begin if not Application.Terminated then Item.TagString := fDocID; end); result := TFirestoreDocument.Create([cCollectionID, fDocID], fConfig.ProjectID); result.AddOrUpdateField(TJSONObject.SetString('fileName', Item.Text)); SetLength(Arr, fPhotoInterpretation.Labels.Count); for c := 0 to length(Arr) - 1 do Arr[c] := TJSONObject.SetStringValue(fPhotoInterpretation.Labels[c]); result.AddOrUpdateField(TJSONObject.SetArray('labels', Arr)); SetLength(Arr, fPhotoInterpretation.Texts.Count); for c := 0 to length(Arr) - 1 do Arr[c] := TJSONObject.SetStringValue(fPhotoInterpretation.Texts[c]); result.AddOrUpdateField(TJSONObject.SetArray('texts', Arr)); result.AddOrUpdateField(TJSONObject.SetString('createdBy', fUID)); result.AddOrUpdateField(TJSONObject.SetTimeStamp('DateTime', now)); {$IFDEF DEBUG} TFirebaseHelpers.Log('Doc: ' + result.AsJSON.ToJSON); {$ENDIF} end; procedure TPhotoThread.UploadImageToStorage; var Obj: IStorageObject; Path: string; begin Path := GetStorageObjName(fDocID, fUID); Obj := fConfig.Storage.UploadSynchronousFromStream(fImage, Path, fContentType); end; procedure TPhotoThread.UploadPhotoInThread; var Doc: IFirestoreDocument; begin // 1st: Analyse image by VisionML VisionML; // 2nd: Create document Doc := CreateDocument(fItem); // 3rd: Upload storage UploadImageToStorage; // 4th: Upload document fConfig.Database.InsertOrUpdateDocumentSynchronous( [cCollectionID, Doc.DocumentName(false)], Doc); end; {$ENDREGION} {$REGION 'Download'} constructor TPhotoThread.CreateForDownload(const Config: IFirebaseConfiguration; const UID: string; lstPhotoList: TListBox; Doc: IFirestoreDocument); var PhotoInterpretation: TPhotoInterpretation; begin inherited Create(true); fConfig := Config; fDirection := Download; fDocID := Doc.DocumentName(false); fUID := UID; fItem := SearchItem(lstPhotoList, fDocID); if assigned(fItem) then begin fItem.Text := Doc.GetStringValue('fileName'); {$IFDEF DEBUG} fItem.Text := fItem.Text + ' (ID: ' + fDocID + ')'; {$ENDIF} if assigned(fItem.Data) then begin PhotoInterpretation := fItem.Data as TPhotoInterpretation; PhotoInterpretation.SetLabels(Doc.GetArrayStringValues('labels')); PhotoInterpretation.SetTexts(Doc.GetArrayStringValues('texts')); end else begin PhotoInterpretation := TPhotoInterpretation.Create( Doc.GetArrayStringValues('labels'), Doc.GetArrayStringValues('texts')); fItem.Data := PhotoInterpretation; end; fItem.ItemData.Detail := PhotoInterpretation.GetLabelInfo; end else begin fItem := TListBoxItem.Create(lstPhotoList); fItem.Text := Doc.GetStringValue('fileName'); {$IFDEF DEBUG} fItem.Text := fItem.Text + ' (ID: ' + fDocID + ')'; {$ENDIF} if not SameText(Doc.GetStringValue('createdBy'), UID) then raise Exception.Create('Unerlaubtes Photo empfangen'); PhotoInterpretation := TPhotoInterpretation.Create( Doc.GetArrayStringValues('labels'), Doc.GetArrayStringValues('texts')); fItem.Data := PhotoInterpretation; fItem.ItemData.Detail := PhotoInterpretation.GetLabelInfo; fItem.TagString := Doc.DocumentName(false); lstPhotoList.AddObject(fItem); // add new item to end of list end; fImage := TMemoryStream.Create; FreeOnTerminate := true; end; function TPhotoThread.DownloadImageFromStorage: TBitmap; var Obj: IStorageObject; Path: string; begin Path := GetStorageObjName(fDocID, fUID); Obj := fConfig.Storage.GetAndDownloadSynchronous(Path, fImage); result := TBitmap.Create; fImage.Position := 0; result.LoadFromStream(fImage); end; procedure TPhotoThread.DownloadPhotoInThread; var Image: TBitmap; begin Image := DownloadImageFromStorage; try fThumbnail := CreateThumbnail(Image); finally Image.Free; end; end; {$ENDREGION} {$REGION 'Upload and Download'} destructor TPhotoThread.Destroy; begin fThumbnail.Free; fImage.Free; inherited; end; class function TPhotoThread.GetStorageObjName(const DocID, UID: string): string; begin result := cStorageFolder + '/' + UID + '/' + DocID; end; procedure TPhotoThread.StartThread(OnSuccess: TOnSuccess; fOnFailed: TOnFailed); begin fOnSuccess := OnSuccess; fOnFailed := fOnFailed; Start; end; procedure TPhotoThread.Execute; begin inherited; try case fDirection of Upload: UploadPhotoInThread; Download: DownloadPhotoInThread; end; if not Application.Terminated then TThread.Synchronize(nil, procedure begin case fDirection of Upload: begin fItem.Data := fPhotoInterpretation; fItem.ItemData.Detail := fPhotoInterpretation.GetLabelInfo; end; Download: begin fItem.ItemData.Bitmap.Assign(fThumbnail); end; end; fOnSuccess(fItem); end); except on e: exception do if not Application.Terminated then TThread.Synchronize(nil, procedure begin fOnFailed(fItem, e.Message); end); end; end; {$ENDREGION} { TPhotoInterpretation } class constructor TPhotoInterpretation.ClassCreate; begin FRefList := TList<TPhotoInterpretation>.Create; end; class destructor TPhotoInterpretation.ClassDestroy; var PI: TPhotoInterpretation; begin for PI in FRefList do PI.Free; FRefList.Free; end; constructor TPhotoInterpretation.Create(Labels: TAnnotationList; FullText: TTextAnnotation); const cMinConf = 0.66; var Ent: TEntityAnnotation; begin fLabels := TStringList.Create; fTexts := TStringList.Create; for Ent in Labels do if Ent.Score > cMinScore then fLabels.Add(Ent.Description); fTexts.Text := FullText.GetText(cMinConf); FRefList.Add(self); // Automatically destroy this object at application end end; constructor TPhotoInterpretation.Create(Labels, Texts: TStringDynArray); var s: string; begin fLabels := TStringList.Create; fTexts := TStringList.Create; for s in Labels do fLabels.Add(s); for s in Texts do fTexts.Add(s); FRefList.Add(self); // Automatically destroy this object at application end end; destructor TPhotoInterpretation.Destroy; begin fTexts.Free; fLabels.Free; inherited; end; procedure TPhotoInterpretation.SetLabels(Labels: TStringDynArray); var s: string; begin fLabels.Clear; for s in Labels do fLabels.Add(s); end; procedure TPhotoInterpretation.SetTexts(Texts: TStringDynArray); var s: string; begin fTexts.Clear; for s in Texts do fTexts.Add(s); end; function TPhotoInterpretation.GetFullInfo: string; begin if fLabels.Count > 0 then result := rsLabels + fLabels.CommaText else result := rsNoLabels; result := result + #13#10; if fTexts.Count = 0 then result := result + rsNoTexts else result := result + rsTexts + #13#10 + fTexts.Text; end; function TPhotoInterpretation.GetLabelInfo: string; begin fLabels.Delimiter := ','; fLabels.QuoteChar := #0; result := fLabels.DelimitedText; if fTexts.Count > 0 then begin if not result.IsEmpty then result := result + ','; result := result + 'Text: "' + trim(fTexts[0]) + '"'; end; end; end.
unit wardner_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,controls_engine,gfx_engine,tms32010,ym_3812, rom_engine,pal_engine,sound_engine; function iniciar_wardnerhw:boolean; implementation const wardner_rom:array[0..3] of tipo_roms=( (n:'wardner.17';l:$8000;p:0;crc:$c5dd56fd),(n:'b25-18.rom';l:$10000;p:$8000;crc:$9aab8ee2), (n:'b25-19.rom';l:$10000;p:$18000;crc:$95b68813),(n:'wardner.20';l:$8000;p:$28000;crc:$347f411b)); wardner_snd_rom:tipo_roms=(n:'b25-16.rom';l:$8000;p:0;crc:$e5202ff8); wardner_char:array[0..2] of tipo_roms=( (n:'wardner.07';l:$4000;p:0;crc:$1392b60d),(n:'wardner.06';l:$4000;p:$4000;crc:$0ed848da), (n:'wardner.05';l:$4000;p:$8000;crc:$79792c86)); wardner_sprites:array[0..3] of tipo_roms=( (n:'b25-01.rom';l:$10000;p:0;crc:$42ec01fb),(n:'b25-02.rom';l:$10000;p:$10000;crc:$6c0130b7), (n:'b25-03.rom';l:$10000;p:$20000;crc:$b923db99),(n:'b25-04.rom';l:$10000;p:$30000;crc:$8059573c)); wardner_fg_tiles:array[0..3] of tipo_roms=( (n:'b25-12.rom';l:$8000;p:0;crc:$15d08848),(n:'b25-15.rom';l:$8000;p:$8000;crc:$cdd2d408), (n:'b25-14.rom';l:$8000;p:$10000;crc:$5a2aef4f),(n:'b25-13.rom';l:$8000;p:$18000;crc:$be21db2b)); wardner_bg_tiles:array[0..3] of tipo_roms=( (n:'b25-08.rom';l:$8000;p:0;crc:$883ccaa3),(n:'b25-11.rom';l:$8000;p:$8000;crc:$d6ebd510), (n:'b25-10.rom';l:$8000;p:$10000;crc:$b9a61e81),(n:'b25-09.rom';l:$8000;p:$18000;crc:$585411b7)); wardner_mcu_rom:array[0..7] of tipo_roms=( (n:'82s137.1d';l:$400;p:0;crc:$cc5b3f53),(n:'82s137.1e';l:$400;p:$400;crc:$47351d55), (n:'82s137.3d';l:$400;p:$800;crc:$70b537b9),(n:'82s137.3e';l:$400;p:$c00;crc:$6edb2de8), (n:'82s131.3b';l:$200;p:$1000;crc:$9dfffaff),(n:'82s131.3a';l:$200;p:$1200;crc:$712bad47), (n:'82s131.2a';l:$200;p:$1400;crc:$ac843ca6),(n:'82s131.1a';l:$200;p:$1600;crc:$50452ff8)); wardner_dip_a:array [0..5] of def_dip=( (mask:$1;name:'Cabinet';number:2;dip:((dip_val:$1;dip_name:'Upright'),(dip_val:$0;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$2;name:'Flip Screen';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$2;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$8;name:'Demo Sounds';number:2;dip:((dip_val:$8;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Coin A';number:4;dip:((dip_val:$30;dip_name:'4C 1C'),(dip_val:$20;dip_name:'3C 1C'),(dip_val:$10;dip_name:'2C 1C'),(dip_val:$0;dip_name:'1C 1C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c0;name:'Coin B';number:4;dip:((dip_val:$0;dip_name:'1C 2C'),(dip_val:$40;dip_name:'1C 3C'),(dip_val:$80;dip_name:'1C 4C'),(dip_val:$c0;dip_name:'1C 6C'),(),(),(),(),(),(),(),(),(),(),(),())),()); wardner_dip_b:array [0..3] of def_dip=( (mask:$3;name:'Difficulty';number:4;dip:((dip_val:$1;dip_name:'Easy'),(dip_val:$0;dip_name:'Normal'),(dip_val:$2;dip_name:'Hard'),(dip_val:$3;dip_name:'Very Hard'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Bonus Life';number:4;dip:((dip_val:$0;dip_name:'30k 80k 50k+'),(dip_val:$4;dip_name:'50k 100k 50k+'),(dip_val:$8;dip_name:'30k'),(dip_val:$c;dip_name:'50k'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Lives';number:4;dip:((dip_val:$30;dip_name:'1'),(dip_val:$0;dip_name:'3'),(dip_val:$10;dip_name:'4'),(dip_val:$20;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())),()); var mem_rom:array[0..7,0..$7fff] of byte; rom_bank:byte; int_enable,wardner_dsp_BIO,dsp_execute,video_ena:boolean; txt_ram:array[0..$7ff] of word; bg_ram:array[0..$1fff] of word; fg_ram:array[0..$fff] of word; txt_offs,bg_offs,fg_offs,bg_bank,fg_bank,main_ram_seg,dsp_addr_w:word; txt_scroll_x,txt_scroll_y,bg_scroll_x,bg_scroll_y,fg_scroll_x,fg_scroll_y:word; procedure update_video_wardner; var f,nchar,x,y,atrib:word; color:byte; procedure draw_sprites(priority:word); var f,nchar,atrib,x,y:word; flipx,flipy:boolean; color:byte; begin for f:=0 to $1ff do begin atrib:=memoria[$8002+(f shl 3)]+(memoria[$8003+(f shl 3)] shl 8); if ((atrib and $0c00)=priority) then begin y:=(memoria[$8006+(f shl 3)]+(memoria[$8007+(f shl 3)] shl 8)) shr 7; if (y and $1ff)>$100 then continue; nchar:=(memoria[$8000+(f shl 3)]+(memoria[$8001+(f shl 3)] shl 8)) and $7ff; color:=atrib and $3f; x:=(memoria[$8004+(f shl 3)]+(memoria[$8005+(f shl 3)] shl 8)) shr 7; flipx:=(atrib and $100)<>0; if flipx then x:=x-14; // should really be 15 flipy:=(atrib and $200)<>0; put_gfx_sprite(nchar,color shl 4,flipx,flipy,3); actualiza_gfx_sprite(x-32,y-16,4,3); end; end; end; begin if video_ena then begin for f:=$7ff downto 0 do begin //Chars atrib:=txt_ram[f]; color:=(atrib and $f800) shr 11; if (gfx[0].buffer[f] or buffer_color[color]) then begin x:=(f and $3f) shl 3; y:=(f shr 6) shl 3; nchar:=atrib and $7ff; put_gfx_trans(x,y,nchar,(color shl 3)+$600,1,0); gfx[0].buffer[f]:=false; end; end; for f:=0 to $fff do begin atrib:=bg_ram[f+bg_bank]; color:=(atrib and $f000) shr 12; if (gfx[2].buffer[f+bg_bank] or buffer_color[color+$30]) then begin //background x:=(f and $3f) shl 3; y:=(f shr 6) shl 3; nchar:=atrib and $fff; put_gfx(x,y,nchar,(color shl 4)+$400,3,2); gfx[2].buffer[f+bg_bank]:=false; end; atrib:=fg_ram[f]; color:=(atrib and $f000) shr 12; if (gfx[1].buffer[f] or buffer_color[color+$20]) then begin //foreground x:=(f and $3f) shl 3; y:=(f shr 6) shl 3; nchar:=(atrib and $fff)+fg_bank; put_gfx_trans(x,y,nchar and $fff,(color shl 4)+$500,2,1); gfx[1].buffer[f]:=false; end; end; scroll_x_y(3,4,bg_scroll_x+55,bg_scroll_y+30); draw_sprites($400); scroll_x_y(2,4,fg_scroll_x+55,fg_scroll_y+30); draw_sprites($800); scroll_x_y(1,4,512-txt_scroll_x-55,256-txt_scroll_y-30); draw_sprites($c00); end else fill_full_screen(4,$800); actualiza_trozo_final(0,0,320,240,4); fillchar(buffer_color,MAX_COLOR_BUFFER,0); end; procedure eventos_wardner; begin if event.arcade then begin //P1 if arcade_input.up[0] then marcade.in1:=(marcade.in1 or $1) else marcade.in1:=(marcade.in1 and $fe); if arcade_input.down[0] then marcade.in1:=(marcade.in1 or $2) else marcade.in1:=(marcade.in1 and $fd); if arcade_input.left[0] then marcade.in1:=(marcade.in1 or $4) else marcade.in1:=(marcade.in1 and $fb); if arcade_input.right[0] then marcade.in1:=(marcade.in1 or $8) else marcade.in1:=(marcade.in1 and $f7); if arcade_input.but1[0] then marcade.in1:=(marcade.in1 or $10) else marcade.in1:=(marcade.in1 and $ef); if arcade_input.but0[0] then marcade.in1:=(marcade.in1 or $20) else marcade.in1:=(marcade.in1 and $df); //P2 if arcade_input.up[1] then marcade.in2:=(marcade.in2 or $1) else marcade.in2:=(marcade.in2 and $fe); if arcade_input.down[1] then marcade.in2:=(marcade.in2 or $2) else marcade.in2:=(marcade.in2 and $fd); if arcade_input.left[1] then marcade.in2:=(marcade.in2 or $4) else marcade.in2:=(marcade.in2 and $fb); if arcade_input.right[1] then marcade.in2:=(marcade.in2 or $8) else marcade.in2:=(marcade.in2 and $f7); if arcade_input.but1[1] then marcade.in2:=(marcade.in2 or $10) else marcade.in2:=(marcade.in2 and $ef); if arcade_input.but0[1] then marcade.in2:=(marcade.in2 or $20) else marcade.in2:=(marcade.in2 and $df); //SYS if arcade_input.coin[0] then marcade.in0:=(marcade.in0 or $8) else marcade.in0:=(marcade.in0 and $f7); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 or $10) else marcade.in0:=(marcade.in0 and $ef); if arcade_input.start[0] then marcade.in0:=(marcade.in0 or $20) else marcade.in0:=(marcade.in0 and $df); if arcade_input.start[1] then marcade.in0:=(marcade.in0 or $40) else marcade.in0:=(marcade.in0 and $bf); end; end; procedure wardnerhw_principal; var f:word; frame_m,frame_s,frame_mcu:single; begin init_controls(false,false,false,true); frame_m:=z80_0.tframes; frame_s:=z80_1.tframes; frame_mcu:=tms32010_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to 285 do begin //MAIN CPU z80_0.run(frame_m); frame_m:=frame_m+z80_0.tframes-z80_0.contador; //SND CPU z80_1.run(frame_s); frame_s:=frame_s+z80_1.tframes-z80_1.contador; //MCU tms32010_0.run(frame_mcu); frame_mcu:=frame_mcu+tms32010_0.tframes-tms32010_0.contador; case f of 0:marcade.in0:=marcade.in0 and $7f; 239:begin marcade.in0:=marcade.in0 or $80; if int_enable then begin z80_0.change_irq(HOLD_LINE); int_enable:=false; end; update_video_wardner; end; end; end; eventos_wardner; video_sync; end; end; function wardner_dsp_r:word; begin // DSP can read data from main CPU RAM via DSP IO port 1 case main_ram_seg of $7000,$8000,$a000:wardner_dsp_r:=memoria[main_ram_seg+(dsp_addr_w+0)] or (memoria[main_ram_seg+(dsp_addr_w+1)] shl 8); else wardner_dsp_r:=0; end; end; procedure wardner_dsp_w(valor:word); begin // Data written to main CPU RAM via DSP IO port 1 dsp_execute:=false; case main_ram_seg of $7000:begin if ((dsp_addr_w<3) and (valor=0)) then dsp_execute:=true; memoria[main_ram_seg+dsp_addr_w]:=valor and $ff; memoria[main_ram_seg+(dsp_addr_w+1)]:=(valor shr 8) and $ff; end; $8000,$a000:begin memoria[main_ram_seg+dsp_addr_w]:=valor and $ff; memoria[main_ram_seg+(dsp_addr_w+1)]:=(valor shr 8) and $ff; end; end; end; procedure wardner_dsp_addrsel_w(valor:word); begin main_ram_seg:=valor and $e000; dsp_addr_w:=(valor and $7ff) shl 1; if (main_ram_seg=$6000) then main_ram_seg:=$7000; end; procedure wardner_dsp_bio_w(valor:word); begin if (valor and $8000)<>0 then wardner_dsp_BIO:=false; if (valor=0) then begin if dsp_execute then begin z80_0.change_halt(CLEAR_LINE); dsp_execute:=false; end; wardner_dsp_BIO:=true; end; end; function wardner_BIO_r:boolean; begin wardner_BIO_r:=wardner_dsp_BIO; end; function wardner_snd_getbyte(direccion:word):byte; begin case direccion of 0..$807f,$c800..$cfff:wardner_snd_getbyte:=mem_snd[direccion]; $c000..$c7ff:wardner_snd_getbyte:=memoria[direccion]; end; end; procedure wardner_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$7fff:; $8000..$807f,$c800..$cfff:mem_snd[direccion]:=valor; $c000..$c7ff:memoria[direccion]:=valor; end; end; function wardner_snd_inbyte(puerto:word):byte; begin if (puerto and $ff)=0 then wardner_snd_inbyte:=ym3812_0.status; end; procedure wardner_snd_outbyte(puerto:word;valor:byte); begin case (puerto and $ff) of $0:ym3812_0.control(valor); $1:ym3812_0.write(valor); end; end; procedure snd_irq(irqstate:byte); begin z80_1.change_irq(irqstate); end; function wardner_getbyte(direccion:word):byte; begin case direccion of 0..$7fff:wardner_getbyte:=memoria[direccion]; $8000..$ffff:if rom_bank=0 then begin case (direccion and $7fff) of 0..$1fff,$3000..$7fff:wardner_getbyte:=memoria[direccion]; $2000..$2fff:wardner_getbyte:=buffer_paleta[direccion and $fff]; end; end else wardner_getbyte:=mem_rom[rom_bank,direccion and $7fff]; end; end; procedure wardner_putbyte(direccion:word;valor:byte); procedure cambiar_color(numero:word); var tmp_color:word; color:tcolor; begin tmp_color:=(buffer_paleta[numero+1] shl 8)+buffer_paleta[numero]; color.b:=pal5bit(tmp_color shr 10); color.g:=pal5bit(tmp_color shr 5); color.r:=pal5bit(tmp_color); numero:=numero shr 1; set_pal_color(color,numero); case numero of $400..$4ff:buffer_color[((numero shr 4) and $f)+$30]:=true; $500..$5ff:buffer_color[((numero shr 4) and $f)+$20]:=true; $600..$6ff:buffer_color[(numero shr 3) and $1f]:=true; end; end; begin case direccion of 0..$6fff:; $7000..$7fff:memoria[direccion]:=valor; $8000..$ffff:if rom_bank=0 then begin case (direccion and $7fff) of 0..$fff,$4000..$47ff:memoria[direccion]:=valor; $1000..$1fff,$3000..$3fff,$4800..$7fff:; $2000..$2fff:if buffer_paleta[direccion and $fff]<>valor then begin buffer_paleta[direccion and $fff]:=valor; cambiar_color(direccion and $ffe); end; end; end; end; end; function wardner_inbyte(puerto:word):byte; begin case (puerto and $ff) of $50:wardner_inbyte:=marcade.dswa; $52:wardner_inbyte:=marcade.dswb; $54:wardner_inbyte:=marcade.in1; $56:wardner_inbyte:=marcade.in2; $58:wardner_inbyte:=marcade.in0; $60:wardner_inbyte:=txt_ram[txt_offs] and $ff; $61:wardner_inbyte:=txt_ram[txt_offs] shr 8; $62:wardner_inbyte:=bg_ram[bg_offs+bg_bank] and $ff; $63:wardner_inbyte:=bg_ram[bg_offs+bg_bank] shr 8; $64:wardner_inbyte:=fg_ram[fg_offs] and $ff; $65:wardner_inbyte:=fg_ram[fg_offs] shr 8; end; end; procedure wardner_outbyte(puerto:word;valor:byte); begin case (puerto and $ff) of $10:txt_scroll_x:=(txt_scroll_x and $ff00) or valor; $11:txt_scroll_x:=(txt_scroll_x and $00ff) or ((valor and $1) shl 8); $12:txt_scroll_y:=(txt_scroll_y and $ff00) or valor; $13:txt_scroll_y:=(txt_scroll_y and $00ff) or ((valor and $1) shl 8); $14:txt_offs:=(txt_offs and $ff00) or valor; $15:txt_offs:=(txt_offs and $00ff) or ((valor and $7) shl 8); $20:bg_scroll_x:=(bg_scroll_x and $ff00) or valor; $21:bg_scroll_x:=(bg_scroll_x and $00ff) or ((valor and $1) shl 8); $22:bg_scroll_y:=(bg_scroll_y and $ff00) or valor; $23:bg_scroll_y:=(bg_scroll_y and $00ff) or ((valor and $1) shl 8); $24:bg_offs:=(bg_offs and $ff00) or valor; $25:bg_offs:=(bg_offs and $00ff) or ((valor and $f) shl 8); $30:fg_scroll_x:=(fg_scroll_x and $ff00) or valor; $31:fg_scroll_x:=(fg_scroll_x and $00ff) or ((valor and $1) shl 8); $32:fg_scroll_y:=(fg_scroll_y and $ff00) or valor; $33:fg_scroll_y:=(fg_scroll_y and $00ff) or ((valor and $1) shl 8); $34:fg_offs:=(fg_offs and $ff00) or valor; $35:fg_offs:=(fg_offs and $00ff) or ((valor and $f) shl 8); $5a:case (valor and $f) of $0:begin tms32010_0.change_halt(CLEAR_LINE); z80_0.change_halt(ASSERT_LINE); tms32010_0.change_irq(ASSERT_LINE); end; $1:begin tms32010_0.change_irq(CLEAR_LINE); tms32010_0.change_halt(ASSERT_LINE); end; end; $5c:case (valor and $f) of $4:int_enable:=false; $5:int_enable:=true; $6:main_screen.flip_main_screen:=false; $7:main_screen.flip_main_screen:=true; $8:bg_bank:=0; $9:bg_bank:=$1000; $a:fg_bank:=0; $b:fg_bank:=$1000; $c:video_ena:=false; $d:begin if not(video_ena) then begin fillchar(gfx[0].buffer,$800,1); fillchar(gfx[1].buffer,$1000,1); fillchar(gfx[2].buffer,$2000,1); end; video_ena:=true; end; end; $60:if (txt_ram[txt_offs] and $ff)<>valor then begin txt_ram[txt_offs]:=(txt_ram[txt_offs] and $ff00) or valor; gfx[0].buffer[txt_offs]:=true; end; $61:if (txt_ram[txt_offs] and $ff00)<>(valor shl 8) then begin txt_ram[txt_offs]:=(txt_ram[txt_offs] and $ff) or (valor shl 8); gfx[0].buffer[txt_offs]:=true; end; $62:if (bg_ram[bg_offs+bg_bank] and $ff)<>valor then begin bg_ram[bg_offs+bg_bank]:=(bg_ram[bg_offs+bg_bank] and $ff00) or valor; gfx[2].buffer[bg_offs+bg_bank]:=true; end; $63:if (bg_ram[bg_offs+bg_bank] and $ff00)<>(valor shl 8) then begin bg_ram[bg_offs+bg_bank]:=(bg_ram[bg_offs+bg_bank] and $ff) or (valor shl 8); gfx[2].buffer[bg_offs+bg_bank]:=true; end; $64:if (fg_ram[fg_offs] and $ff)<>valor then begin fg_ram[fg_offs]:=(fg_ram[fg_offs] and $ff00) or valor; gfx[1].buffer[fg_offs]:=true; end; $65:if (fg_ram[fg_offs] and $ff00)<>(valor shl 8) then begin fg_ram[fg_offs]:=(fg_ram[fg_offs] and $ff) or (valor shl 8); gfx[1].buffer[fg_offs]:=true; end; $70:rom_bank:=valor; end; end; procedure wardner_sound_update; begin ym3812_0.update; end; //Main procedure reset_wardnerhw; begin z80_0.reset; z80_1.reset; tms32010_0.reset; ym3812_0.reset; reset_audio; txt_scroll_x:=0; txt_scroll_y:=0; bg_scroll_x:=0; bg_scroll_y:=0; fg_scroll_x:=0; fg_scroll_y:=0; marcade.in0:=0; marcade.in1:=0; marcade.in2:=0; rom_bank:=0; txt_offs:=0; bg_offs:=0; fg_offs:=0; bg_bank:=0; fg_bank:=0; int_enable:=false; video_ena:=true; wardner_dsp_BIO:=false; dsp_execute:=false; main_ram_seg:=0; dsp_addr_w:=0; end; function iniciar_wardnerhw:boolean; var f:word; memoria_temp:array[0..$3ffff] of byte; rom:array[0..$fff] of word; const pc_y:array[0..7] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8); ps_x:array[0..15] of dword=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); ps_y:array[0..15] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16, 8*16, 9*16, 10*16, 11*16, 12*16, 13*16, 14*16, 15*16); begin llamadas_maquina.bucle_general:=wardnerhw_principal; llamadas_maquina.reset:=reset_wardnerhw; llamadas_maquina.fps_max:=(14000000/2)/(446*286); iniciar_wardnerhw:=false; iniciar_audio(false); screen_init(1,512,256,true); screen_mod_scroll(1,512,512,511,256,256,255); screen_init(2,512,512,true); screen_mod_scroll(2,512,512,511,512,256,511); screen_init(3,512,512); screen_mod_scroll(3,512,512,511,512,256,511); screen_init(4,512,512,false,true); iniciar_video(320,240); //Main CPU z80_0:=cpu_z80.create(24000000 div 4,286); z80_0.change_ram_calls(wardner_getbyte,wardner_putbyte); z80_0.change_io_calls(wardner_inbyte,wardner_outbyte); //Sound CPU z80_1:=cpu_z80.create(14000000 div 4,286); z80_1.change_ram_calls(wardner_snd_getbyte,wardner_snd_putbyte); z80_1.change_io_calls(wardner_snd_inbyte,wardner_snd_outbyte); z80_1.init_sound(wardner_sound_update); //TMS MCU tms32010_0:=cpu_tms32010.create(14000000,286); tms32010_0.change_io_calls(wardner_BIO_r,nil,wardner_dsp_r,nil,nil,nil,nil,nil,nil,wardner_dsp_addrsel_w,wardner_dsp_w,nil,wardner_dsp_bio_w,nil,nil,nil,nil); //Sound Chips ym3812_0:=ym3812_chip.create(YM3812_FM,14000000 div 4); ym3812_0.change_irq_calls(snd_irq); //cargar roms if not(roms_load(@memoria_temp,wardner_rom)) then exit; //Mover las ROMS a su sitio copymemory(@memoria,@memoria_temp[$0],$8000); for f:=0 to 3 do copymemory(@mem_rom[f+2,0],@memoria_temp[$8000+(f*$8000)],$8000); copymemory(@mem_rom[7,0],@memoria_temp[$28000],$8000); //cargar ROMS sonido if not(roms_load(@mem_snd,wardner_snd_rom)) then exit; //cargar ROMS MCU y organizarlas if not(roms_load(@memoria_temp,wardner_mcu_rom)) then exit; for f:=0 to $3ff do rom[f]:=(((memoria_temp[f] and $f) shl 4+(memoria_temp[f+$400] and $f)) shl 8) or (memoria_temp[f+$800] and $f) shl 4+(memoria_temp[f+$c00] and $f); for f:=0 to $1ff do //1024-2047 rom[f+$400]:=(((memoria_temp[f+$1000] and $f) shl 4+(memoria_temp[f+$1200] and $f)) shl 8) or (memoria_temp[f+$1400] and $f) shl 4+(memoria_temp[f+$1600] and $f); copymemory(tms32010_0.get_rom_addr,@rom[0],$1000); //convertir chars if not(roms_load(@memoria_temp,wardner_char)) then exit; init_gfx(0,8,8,2048); gfx[0].trans[0]:=true; gfx_set_desc_data(3,0,8*8,0*2048*8*8,1*2048*8*8,2*2048*8*8); convert_gfx(0,0,@memoria_temp,@ps_x,@pc_y,false,false); //convertir tiles fg if not(roms_load(@memoria_temp,wardner_fg_tiles)) then exit; init_gfx(1,8,8,4096); gfx[1].trans[0]:=true; gfx_set_desc_data(4,0,8*8,0*4096*8*8,1*4096*8*8,2*4096*8*8,3*4096*8*8); convert_gfx(1,0,@memoria_temp,@ps_x,@pc_y,false,false); //convertir tiles bg if not(roms_load(@memoria_temp,wardner_bg_tiles)) then exit; init_gfx(2,8,8,4096); convert_gfx(2,0,@memoria_temp,@ps_x,@pc_y,false,false); //convertir tiles sprites if not(roms_load(@memoria_temp,wardner_sprites)) then exit; init_gfx(3,16,16,2048); gfx[3].trans[0]:=true; gfx_set_desc_data(4,0,32*8,0*2048*32*8,1*2048*32*8,2*2048*32*8,3*2048*32*8); convert_gfx(3,0,@memoria_temp,@ps_x,@ps_y,false,false); //DIP marcade.dswa:=1; marcade.dswb:=0; marcade.dswa_val:=@wardner_dip_a; marcade.dswb_val:=@wardner_dip_b; //final reset_wardnerhw; iniciar_wardnerhw:=true; end; end.
{ Subroutine SST_R_SYO_EXPRESSION (JTARG, SYM_MFLAG) * * Process EXPRESSION syntax. } module sst_r_syo_expression; define sst_r_syo_expression; %include 'sst_r_syo.ins.pas'; procedure sst_r_syo_expression ( {process EXPRESSION syntax} in out jtarg: jump_targets_t; {execution block jump targets info} in sym_mflag: sst_symbol_t); {desc of parent MFLAG variable symbol} val_param; var tag: sys_int_machine_t; {tag from syntax tree} str_h: syo_string_t; {handle to string from input file} jt: jump_targets_t; {jump targets for nested routines} begin syo_level_down; {down into EXPRESSION syntax} syo_push_pos; {save current syntax position} syo_get_tag_msg ( {get expression format tag} tag, str_h, 'sst_syo_read', 'syerr_define', nil, 0); syo_pop_pos; {restore position to start of EXPRESSION} case tag of { ************************************** * * Expression form is: * ITEM EXPRESSION } 1: begin sst_r_syo_jtargets_make ( {make jump targets for nested routine} jtarg, {template jump targets} jt, {output jump targets} lab_fall_k, {YES action} lab_same_k, {NO action} lab_same_k); {ERR action} sst_r_syo_item (jt, sym_mflag); {process ITEM syntax} sst_r_syo_jtargets_done (jt); {define any implicit labels} syo_get_tag_msg ( {get tag for nested expression} tag, str_h, 'sst_syo_read', 'syerr_define', nil, 0); sst_r_syo_expression (jtarg, sym_mflag); {process EXPRESSION after ITEM} end; { ************************************** * * Expression form is: * ITEM .or EXPRESSION } 2: begin sst_r_syo_jtargets_make ( {make jump targets for nested routine} jtarg, {template jump targets} jt, {output jump targets} lab_same_k, {YES action} lab_fall_k, {NO action} lab_same_k); {ERR action} sst_r_syo_item (jt, sym_mflag); {process ITEM syntax} sst_r_syo_jtargets_done (jt); {define any implicit labels} syo_get_tag_msg ( {get tag for nested expression} tag, str_h, 'sst_syo_read', 'syerr_define', nil, 0); sst_r_syo_expression (jtarg, sym_mflag); {process EXPRESSION after ITEM} end; { ************************************** * * Expression form is: * ITEM } 3: begin sst_r_syo_item (jtarg, sym_mflag); end; { ************************************** * * Unexpected expression format tag value. } otherwise syo_error_tag_unexp (tag, str_h); end; {end of expression format cases} syo_level_up; {back up from EXPRESSION syntax} end;
unit csMisspellCorrectTask; interface uses csProcessTask, Classes, DT_Types; type TcsMisspellCorrectTask = class(TddProcessTask) private f_SABStream: TStream; protected procedure Cleanup; override; function GetDescription: AnsiString; override; procedure LoadFrom(aStream: TStream; aIsPipe: Boolean); override; public constructor Create(aOwner: TObject; aUserID: TUserID); override; procedure SaveTo(aStream: TStream; aIsPipe: Boolean); override; property SABStream: TStream read f_SABStream write f_SABStream; end; implementation uses csTaskTypes, ddServerTask, l3TempMemoryStream, SysUtils; { ****************************** TcsMisspellCorrectTask ******************************* } constructor TcsMisspellCorrectTask.Create(aOwner: TObject; aUserID: TUserID); begin inherited; TaskType := cs_ttMisspellCorrect; Version:= 1; f_SABStream := Tl3TempMemoryStream.Create; end; procedure TcsMisspellCorrectTask.Cleanup; begin inherited; FreeAndNil(f_SABStream); end; function TcsMisspellCorrectTask.GetDescription: AnsiString; begin Result := 'Исправление опечаток'; end; procedure TcsMisspellCorrectTask.LoadFrom(aStream: TStream; aIsPipe: Boolean); var l_Value: Integer; begin inherited; with aStream do begin Read(l_Value, SizeOf(Integer)); if l_Value > 0 then begin f_SABStream.Seek(0, 0); l_Value := f_SABStream.CopyFrom(aStream, l_Value); f_SABStream.Seek(0, 0); end; end; end; procedure TcsMisspellCorrectTask.SaveTo(aStream: TStream; aIsPipe: Boolean); var l_Value: Integer; begin inherited; with aStream do begin (* %<---Потом нужно удалить--->% *) l_Value := f_SABStream.Size; Write(l_Value, SizeOf(l_Value)); f_SABStream.Seek(0, 0); CopyFrom(f_SABStream, l_Value); f_SABStream.Seek(0, 0); end; // with aStream end; end.
//Exercício 6: Escreva um algoritmo que receba o nome de uma pessoa e o ano de seu nascimento. Calcule e exiba a idade //e o nome. { Solução em Portugol Algoritmo Exercicio6; Const ano = 2020; // Basta atualizar para o ano atual. Exemplificando o uso de constantes. Var ano_nascimento, idade: inteiro; nome: caracter; Inicio exiba("Programa que calcula a idade de uma pessoa."); exiba("Digite o ano de nascimento da pessoa: "); leia(ano_nascimento); exiba("Digite o nome da pessoa: "); leia(nome); idade <- ano - ano_nascimento; exiba(nome," tem ",idade, " anos."); Fim. } // Solução em Pascal Program Exercicio; uses crt; const ano = 2020; var ano_nascimento, idade: integer; nome: string; begin clrscr; writeln('Programa que calcula a idade de uma pessoa.'); writeln('Digite o ano de nascimento da pessoa: '); readln(ano_nascimento); writeln('Digite o nome da pessoa: '); readln(nome); idade := ano - ano_nascimento; writeln(nome,' tem ',idade, ' anos.'); repeat until keypressed; end. // OBS:Não se preocupe com idade negativa por enquanto. // Mais para frente aprenderemos a lidar com consistência de dados. =)
unit Globals; interface uses SysUtils, Data.DB, FIBDataSet, pFIBDataSet; function DatePart(ADate: TDateTime; APart: Char): Word; function DatePartStr(ADate: TDateTime; APart: Char): String; function FieldByName(ADataSet: TpFIBDataSet; AFieldName: string): string; function DSisEOF(ADataSet: TpFIBDataSet): Boolean; function DSisBOF(ADataSet: TpFIBDataSet): Boolean; function DSIsEmpty(ADataSet: TpFIBDataSet): Boolean; function DSRecCount(ADataSet: TpFIBDataSet): Integer; function DSRecNo(ADataSet: TpFIBDataSet): Integer; function ifFalse(AValue: Boolean; AResultString: string): string; function ifTrue(AValue: Boolean; AResultString: string): string; function ifSingle(ACheckValue: integer; AResultString: string): string; function ifNone(ACheckValue: integer; AResultString: string): string; function ifMore(ACheckValue: integer; AResultString: string): string; function ifAny(ACheckValue: integer; AResultString: string): string; function ifFieldEq(ADataSet: TpFIBDataSet; AFieldName: string; AValue: string; AResultString: string): string; function Count(ADataSet: TpFIBDataSet): Integer; implementation function DatePart(ADate: TDateTime; APart: Char): Word; var Year, Month, Day: Word; begin DecodeDate(ADate, Year, Month, Day); case APart of 'Y': Result := Year; 'M': Result := Month; 'D': Result := Day; end; end; function DatePartStr(ADate: TDateTime; APart: Char): String; var Year, Month, Day: Word; begin DecodeDate(ADate, Year, Month, Day); case APart of 'Y': Result := IntToStr(Year); 'M': Result := IntToStr(Month); 'D': Result := IntToStr(Day); end; end; function FieldByName(ADataSet: TpFIBDataSet; AFieldName: string): string; begin Result := ADataSet.FieldByName(AFieldName).AsString; end; function Count(ADataSet: TpFIBDataSet): Integer; begin Result := ADataSet.RecordCount; end; function DSisEOF(ADataSet: TpFIBDataSet): Boolean; begin //Result := ADataSet.Eof; Result := ADataSet.RecNo = ADataSet.RecordCount; end; function DSisBOF(ADataSet: TpFIBDataSet): Boolean; begin Result := ADataSet.Bof; // Result := ADataSet.RecNo = 1; end; function DSIsEmpty(ADataSet: TpFIBDataSet): Boolean; begin Result := ADataSet.AllRecordCount = 0; end; function DSRecCount(ADataSet: TpFIBDataSet): Integer; begin Result := ADataSet.RecordCount; end; function DSRecNo(ADataSet: TpFIBDataSet): Integer; begin Result := ADataSet.RecNo; end; function ifFalse(AValue: Boolean; AResultString: string): string; begin if AValue = False then Result := AResultString else Result := ''; end; function ifTrue(AValue: Boolean; AResultString: string): string; begin if AValue = True then Result := AResultString else Result := ''; end; function ifSingle(ACheckValue: integer; AResultString: string): string; begin if ACheckValue = 1 then Result := AResultString else Result := ''; end; function ifNone(ACheckValue: integer; AResultString: string): string; begin if ACheckValue = 0 then Result := AResultString else Result := ''; end; function ifMore(ACheckValue: integer; AResultString: string): string; begin if ACheckValue > 1 then Result := AResultString else Result := ''; end; function ifAny(ACheckValue: integer; AResultString: string): string; begin if ACheckValue > 0 then Result := AResultString else Result := ''; end; function ifFieldEq(ADataSet: TpFIBDataSet; AFieldName: string; AValue: string; AResultString: string): string; begin if ADataSet.FieldByName(AFieldName).AsString = AValue then Result := AResultString else Result := ''; end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls; type { TForm1 } TForm1 = class(TForm) Panel1: TPanel; procedure FormCreate(Sender: TObject); procedure FormPaint(Sender: TObject); private procedure DoOut(c: TCanvas; const s: string; x, y: integer); public end; var Form1: TForm1; implementation uses LCLIntf, LCLProc, LCLType; {$R *.lfm} var Emoji: string = 'emoji<😀😃+😄😁>end'; { TForm1 } function IsCharSurrogate(ch: widechar): boolean; begin Result:= (ch>=#$D800) and (ch<=#$DFFF); end; type TATIntArray = array of integer; procedure _CalcCharSizesUtf8FromWidestring(const S: UnicodeString; const DxIn: TATIntArray; var DxOut: TATIntArray); var NSize, i: integer; begin SetLength(DxOut, 0); i:= 0; repeat Inc(i); if i>Length(S) then Break; if i>=Length(DxIn) then Break; if IsCharSurrogate(S[i]) then begin NSize:= DxIn[i-1]+DxIn[i]; Inc(i); end else NSize:= DxIn[i-1]; SetLength(DxOut, Length(DxOut)+1); DxOut[Length(DxOut)-1]:= NSize; until false; end; procedure TForm1.DoOut(c: TCanvas; const s: string; x,y: integer); var sw: UnicodeString; dx, dx2: TATIntArray; i, NSize: integer; r: TRect; cell: integer; begin c.Brush.Color:= clMoneyGreen; sw:= UTF8Decode(s); cell:= c.TextWidth('2'); setlength(dx, 0); for i:= 1 to length(sw) do begin setlength(dx, length(dx)+1); if IsCharSurrogate(sw[i]) then dx[length(dx)-1]:= cell*3 div 2 else dx[length(dx)-1]:= cell; end; _CalcCharSizesUtf8FromWidestring(sw, dx, dx2); r:= rect(0, 0, 500, 60); ExtTextOut(c.Handle, x, y, ETO_OPAQUE, nil, PChar(s), Length(s), @dx2[0] ); end; procedure TForm1.FormCreate(Sender: TObject); begin caption:= Emoji; panel1.caption:= 'caption: '+Emoji; font.name:= 'Courier New'; panel1.font.name:= 'Courier New'; end; procedure TForm1.FormPaint(Sender: TObject); begin DoOut(Canvas, 'norm', 10, 10); DoOut(Canvas, Emoji, 70, 10); end; end.
unit QRNewXLSXFilt; //////////////////////////////////////////////////////////////////////////// // Unit : QRNewXLSXFilt // // TQRNewXMLSSAbstractExportFilter -> TQRXLSXDocumentFilter // // The XLSX Export document for XL spreadsheet - // // (c) 2014 QBS Software // // // 19/05/2016 increased field widths in sortstring to %7d max 9999999 items //////////////////////////////////////////////////////////////////////////// {$include QRDefs.inc} {.$define QRDEMO} interface uses windows, classes, controls, stdctrls, sysutils, graphics, buttons, forms, extctrls, dialogs, printers, db, ComCtrls, QRPrntr, Quickrpt, QR6Const, qrctrls, grids{$ifndef DXE}, system.UITypes, system.zip{$endif}; const CRLF = chr($0D) + chr($0A); // ascii ORD0 = ord('0'); ORDA = ord('A'); type XLXSTextItem = record row, col : integer; X,Y : extended; text, fontname : string; exportAs : TExporttype; fontbold, fontitalic, fontstrike : boolean; fontsize : integer; fontcolor : TColor; controlName : string; XLNumFormat : TXLNumFormat; end; TQXLSXAbstractExportFilter = class(TQRExportFilter) private FStream : TStream; FLineCount, FColCount : integer; FPageProcessed : boolean; protected function GetText(X, Y : extended; var Font : graphics.TFont) : string; function GetFilterName : string; override; function GetDescription : string; override; function GetExtension : string; override; procedure WriteToStream(const AText : string); procedure WriteLnToStream(const AText : string); procedure CreateStream(Filename : string); virtual; procedure CloseStream; virtual; procedure ProcessPage; virtual; procedure StorePage; virtual; property Stream : TStream read FStream write FStream; property PageProcessed : boolean read FPageProcessed write FPageProcessed; property LineCount : integer read FLineCount write FLineCount; property ColCount : integer read FColCount write FColCount; public constructor Create( filename : string );override; procedure Start(PaperWidth, PaperHeight : integer; Font : TFont); override; procedure Finish; override; procedure EndPage; override; procedure NewPage; override; //procedure TextOut(X, Y : extended; Text : string; exportAs : TExportType; xlColumn : integer);virtual; end; TQRXLSXDocumentFilter = class(TQXLSXAbstractExportFilter) private FFreeStream : boolean; // doc filter properties FLastRecordNum : longint; FPagenumber : longint; //FDocType : string; //FCreator : string; FTitle : string; //FAuthor, FLastAuthor, FCreated, FLastSaved, FXLStyleURL : string; FConcatenating : boolean; FXLEncoding: string; FItems : array of XLXSTextItem; FSortList : TStringlist; FStylenames : TStringlist; FFontTags : TStringlist; FItemcount : integer; // the xml files requited for xlsx Content_Types : TStringlist;// in /root ([Content_Types].xml dotrels : TStringlist; // /root/_rels (.rels is xml ) app : TStringlist; // /root/docProps core : TStringlist; // /root/docProps sharedStrings : TStringlist; // /root/xl styles : TStringlist; // /root/xl workbook : TStringlist;// /root/xl theme1 : TStringlist; // /root/xl/theme sheet1 : TStringlist; // /root/xl/worksheets workbook_xml_rels : TStringlist; // /root/xl/.rels celldupcheck : TStringlist; FPageYOffset : extended; FMaxYValue : extended; rowno, colno, maxcols : integer; procedure SetWorkSheetName( value : string); function getWorkSheetName: string; {$ifdef NOT_USED_YET} procedure SetCreator( value : string); function getCreator: string; function getAuthor: string; procedure SetAuthor( value : string); procedure SetCompany( value : string); function getCompany: string; procedure SetOpenWidth( value : integer); function getOpenWidth: integer; function getOpenHeight: integer; procedure SetOpenHeight( value : integer); {$endif} protected function GetFilterName : string; override; function GetDescription : string; override; function GetExtension : string; override; function GetStreaming : boolean; override; procedure CreateStream(Filename : string); override; procedure CloseStream; override; procedure ProcessItems; procedure LoadProlog; procedure ProcessPage; override; public constructor Create( filename : string );override; destructor Destroy; override; procedure TextOutRec( ExportInfo : TExportInfoRec); override; procedure NewDocument( doclist : TStringlist; PaperWidth, PaperHeight : double; Papername, orient : string); //procedure TextOut(X, Y : extended; Text : string; exportAs : TExportType; xlColumn : integer);override; procedure SetColWidths( startcol, endcol : integer; cwidth : extended ); procedure Start(PaperWidth, PaperHeight : integer; Font : graphics.TFont); override; procedure EndConcat; procedure Finish; override; procedure NewPage; override; procedure EndPage; override; procedure SetDocumentProperties( author, title, company : string ); property Stream; property FreeStream : boolean read FFreeStream write FFreeStream; property Title : string read FTitle write FTitle; property LastAuthor : string read FLastAuthor write FLastAuthor; property Created : string read FCreated write FCreated; property LastSaved : string read FLastSaved write FLastSaved; property XLEncoding: string read FXLEncoding write FXLEncoding; property XLStyleURL : string read FXLStyleURL write FXLStyleURL; property Concatenating : boolean read FConcatenating write FConcatenating; {$ifdef NOT_USED_YET} property OpenWidth : integer read getOpenWidth write setOpenWidth; property OpenHeight : integer read getOpenHeight write setOpenHeight; property Creator : string read getCreator write setCreator; property Author : string read getAuthor write setAuthor; property Company : string read getCompany write setCompany; {$endif} property WorkSheetname : string read getWorkSheetname write setWorkSheetname; end; TQRXLSXFilter = class(TComponent) private procedure SetWorkSheetName( value : string); function getWorkSheetName: string; {$ifdef NOT_USED_YET} procedure SetCreator( value : string); function getCreator: string; function getAuthor: string; procedure SetAuthor( value : string); procedure SetCompany( value : string); function getCompany: string; procedure SetOpenWidth( value : integer); function getOpenWidth: integer; function getOpenHeight: integer; procedure SetOpenHeight( value : integer); {$endif} public constructor Create(AOwner : TComponent); override; destructor Destroy; override; published {$ifdef NOT_USED_YET} property OpenWidth : integer read getOpenWidth write setOpenWidth; property OpenHeight : integer read getOpenHeight write setOpenHeight; property Creator : string read getCreator write setCreator; property Author : string read getAuthor write setAuthor; property Company : string read getCompany write setCompany; } {$endif} property WorkSheetname : string read getWorkSheetname write setWorkSheetname; end; function EntityReplace( var ctext : string ) : string; function ColTrans( ct : TColor ) : string; implementation uses QRNewXLSXFiltProcs; var {xmlCreator, xmlAuthor, xmlCompany, }xmlWorkSheetname : string; //xmlOpenWidth, xmlOpenHeight : integer; //------------------------------------------- procedure TQRXLSXDocumentFilter.SetWorkSheetName( value : string); begin xmlWorkSheetName := value; end; function TQRXLSXDocumentFilter.getWorkSheetName: string; begin result := xmlWorkSheetName; end; {$ifdef NOT_USED_YET} function TQRXLSXDocumentFilter.getCreator: string; begin result := xmlCreator; end; procedure TQRXLSXDocumentFilter.SetCreator( value : string); begin xmlCreator := value; end; function TQRXLSXDocumentFilter.getAuthor: string; begin result := xmlAuthor; end; procedure TQRXLSXDocumentFilter.SetAuthor( value : string); begin xmlCreator := value; end; procedure TQRXLSXDocumentFilter.SetCompany( value : string); begin xmlCompany := value; end; function TQRXLSXDocumentFilter.getCompany: string; begin result := xmlCompany; end; procedure TQRXLSXDocumentFilter.SetOpenWidth( value : integer); begin xmlOpenWidth := value; end; function TQRXLSXDocumentFilter.getOpenWidth: integer; begin result := xmlOpenWidth; end; procedure TQRXLSXDocumentFilter.SetOpenHeight( value : integer); begin xmlOpenHeight := value; end; function TQRXLSXDocumentFilter.getOpenHeight: integer; begin result := xmlOpenHeight; end; //--------------------------------------------- {$endif} constructor TQRXLSXFilter.Create(AOwner : TComponent); begin inherited Create(AOwner); QRExportFilterLibrary.AddFilter(TQRXLSXDocumentFilter); end; destructor TQRXLSXFilter.Destroy; begin QRExportFilterLibrary.RemoveFilter(TQRXLSXDocumentFilter); inherited Destroy; end; //------------------------------------------- procedure TQRXLSXFilter.SetWorkSheetName( value : string); begin xmlWorkSheetName := value; end; function TQRXLSXFilter.getWorkSheetName: string; begin result := xmlWorkSheetName; end; {$ifdef NOT_USED_YET} function TQRXLSXFilter.getCreator: string; begin result := xmlCreator; end; procedure TQRXLSXFilter.SetCreator( value : string); begin xmlCreator := value; end; function TQRXLSXFilter.getAuthor: string; begin result := xmlAuthor; end; procedure TQRXLSXFilter.SetAuthor( value : string); begin xmlCreator := value; end; procedure TQRXLSXFilter.SetCompany( value : string); begin xmlCompany := value; end; function TQRXLSXFilter.getCompany: string; begin result := xmlCompany; end; procedure TQRXLSXFilter.SetOpenWidth( value : integer); begin xmlOpenWidth := value; end; function TQRXLSXFilter.getOpenWidth: integer; begin result := xmlOpenWidth; end; procedure TQRXLSXFilter.SetOpenHeight( value : integer); begin xmlOpenHeight := value; end; function TQRXLSXFilter.getOpenHeight: integer; begin result := xmlOpenHeight; end; //--------------------------------------------- {$endif} {TQXLSXAbstractExportFilter} constructor TQXLSXAbstractExportFilter.Create( filename : string); begin inherited Create(filename); end; function TQXLSXAbstractExportFilter.GetFilterName : string; begin result := 'QRAbstract'; // Do not translate end; function TQXLSXAbstractExportFilter.GetDescription : string; begin Result := ''; end; function TQXLSXAbstractExportFilter.GetExtension : string; begin Result := 'xlsx'; end; procedure TQXLSXAbstractExportFilter.Start(PaperWidth, PaperHeight : integer; Font : graphics.TFont); begin Active := true; end; procedure TQXLSXAbstractExportFilter.CreateStream(Filename : string); begin end; procedure TQXLSXAbstractExportFilter.CloseStream; begin end; procedure TQXLSXAbstractExportFilter.WriteToStream(const AText : string); begin end; procedure TQXLSXAbstractExportFilter.WriteLnToStream(const AText : string); begin end; procedure TQXLSXAbstractExportFilter.Finish; begin inherited Finish; end; procedure TQXLSXAbstractExportFilter.NewPage; begin FPageProcessed := False; inherited NewPage; end; procedure TQXLSXAbstractExportFilter.EndPage; begin ProcessPage; inherited EndPage; end; procedure TQXLSXAbstractExportFilter.ProcessPage; begin FPageProcessed := True; end; procedure TQXLSXAbstractExportFilter.StorePage; begin end; function TQXLSXAbstractExportFilter.GetText(X, Y : extended; var Font : graphics.TFont) : string; begin end; {TQRXLSXDocumentFilter} function TQRXLSXDocumentFilter.GetFilterName : string; begin Result := SqrXLSXDocument; end; function TQRXLSXDocumentFilter.GetDescription : string; begin Result := SqrXLSXDocument; end; function TQRXLSXDocumentFilter.GetExtension : string; begin Result := 'xlsx'; // Do not translate end; function TQRXLSXDocumentFilter.GetStreaming : boolean; begin Result := false;// stream multipage report mode end; procedure TQRXLSXDocumentFilter.CreateStream(Filename : string); begin if Filename = '' then begin FStream := TMemoryStream.Create; FreeStream := false; end else begin FreeStream := true; inherited CreateStream(Filename); end; end; procedure TQRXLSXDocumentFilter.CloseStream; begin // the stream is not freed if it's a memory stream if FreeStream then inherited CloseStream; end; constructor TQRXLSXDocumentFilter.Create( filename : string ); begin inherited Create( filename); FItemcount := 0; FSortList := TStringlist.Create; FSortlist.Sorted := true; FSortlist.Duplicates := dupAccept; FStylenames := TStringlist.Create; FFontTags := TStringlist.Create; FMaxYValue := 0.0; FLastRecordNum := 0; FPagenumber := 1; { xmlCreator := 'QRXLSXDocumentFilter'; xmlOpenWidth := 1000; xmlOpenHeight := 600; } FCreated := datetostr( date ); FLastsaved := FCreated; FXLEncoding := 'UTF-8';// west europe latin, 1250 is east europe. // xlsx component files dotrels := TStringlist.Create; core := TStringlist.Create; app := TStringlist.Create; Content_Types := TStringlist.Create; workbook_xml_rels := TStringlist.Create; workbook := TStringlist.Create; sheet1 := TStringlist.Create; sharedStrings := TStringlist.Create; styles := TStringlist.Create; theme1 := TStringlist.Create; fontlist := TStringlist.Create; styleslist := TStringlist.Create; fillslist := TStringlist.Create; colwidths := TStringlist.Create; celldupcheck := TStringlist.Create; appParams.sheetname := xmlWorkSheetname; fontlist.add('<font><sz val="10"/><name val="Arial"/><color rgb="FF000000"/></font>'); styleslist.Add('<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>'); fillslist.Add('<fill><patternFill patternType="none"/></fill>'); fillslist.Add('<fill><patternFill patternType="solid"><fgColor rgb="BADBADEF"/></patternFill></fill>'); fillslist.Add('<fill><patternFill patternType="solid"><fgColor rgb="FADEFADE"/></patternFill></fill>'); end; destructor TQRXLSXDocumentFilter.Destroy; begin FSortList.Free; FStylenames.Free; FFonttags.Free; dotrels.Free; core.Free; app.Free; Content_Types.Free; workbook_xml_rels.Free; workbook.Free; sheet1.Free; sharedStrings.Free; styles.Free; theme1.Free; fontlist.Free; styleslist.Free; fillslist.Free; colwidths.Free; celldupcheck.Free; inherited Destroy; end; procedure TQRXLSXDocumentFilter.ProcessPage; begin FPageProcessed := True; StorePage; end; procedure TQRXLSXDocumentFilter.SetDocumentProperties( author, title, company : string ); begin {xmlAuthor := author; FTitle := title; xmlCompany := company; } end; procedure TQRXLSXDocumentFilter.LoadProlog; begin end; // places a blank document in the stringlist procedure TQRXLSXDocumentFilter.NewDocument( doclist : TStringlist; PaperWidth, PaperHeight : double; Papername, orient : string); begin end; // Overridden Start procedure TQRXLSXDocumentFilter.Start(PaperWidth, PaperHeight : integer; Font : graphics.TFont); begin inherited; end; function GetY( pstr : string ) : integer; var tstr : string; p, ec : integer; begin p := pos(':', pstr); tstr := copy( pstr,1,p-1); val( tstr, p, ec); result := p; end; // CAUTION : these routines are sensitive to the layout of FSortlist. function GetItem( pstr : string ) : integer; var tstr : string; p, ec : integer; begin tstr := copy( pstr,17,7);// %7d:%7d:%7d val( tstr, p, ec); result := p; end; procedure TQRXLSXDocumentFilter.SetColWidths( startcol, endcol : integer; cwidth : extended ); begin if (endcol < startcol) or (cwidth < 0.0) then exit; colwidths.Add(' <x:col min="'+inttostr(startcol)+'" max="'+inttostr(endcol)+'" width="'+floattostr(cwidth)+'" />'); end; procedure TQRXLSXDocumentFilter.ProcessItems; var currY, currItem, k, stylenum : integer; currText, cellREF : string; currExpType : TExportType; reqCol : integer; {$ifndef DXE} zipFile : TZipfile; zstream : TMemorystream; zcomp : TZipCompression; {$endif} begin {$ifdef QRDEMO} exit; {$endif} Load_sheet1prolog(sheet1);// this should be in 'Start' to allow concatenating //FSortList.SaveToFile('sortlist.txt'); // debugging if FSortList.count = 0 then exit; rowno := 1; colno := 0; k := 0; maxcols := 0; currY := getY( FSortList[0]); sheet1.add(' <x:row>'); while k < FSortlist.count do begin currItem := GetItem( FSortList[k]); currText := FItems[currItem].text; currExpType := FItems[currItem].exportAs; reqCol := FItems[currItem].col; stylenum := FItems[currItem].fontsize; cellRef := num2XLCol(reqCol)+inttostr(rowno); if celldupcheck.IndexOf(cellRef ) <> -1 then begin showmessage('Duplicate cell reference detected - please check ''XLColumn'' properties'); exit; end; celldupcheck.Add(cellRef); if currExpType = exptText then sheet1.add(' <x:c r="'+cellRef+'" t="inlineStr" s="'+inttostr(stylenum)+'"><x:is><x:t>'+currText+'</x:t> </x:is></x:c>') else if currExpType = exptNumeric then sheet1.add(' <x:c r="'+cellRef+'" s="'+inttostr(stylenum)+'"><x:v>'+currText+'</x:v></x:c>') else if currExpType = exptFormula then sheet1.add(' <x:c r="'+cellRef+'" s="'+inttostr(stylenum)+'"><x:f>'+currText+'</x:f></x:c>'); inc(colno); if colno > maxcols then maxcols := colno; inc(k); if k = FSortlist.Count then break; if currY <> getY( FSortList[k]) then begin currY := getY( FSortList[k]); sheet1.add(' </x:row>'); inc(rowno); sheet1.add(' <x:row>'); colno := 0; end; end; appParams.LastCell := num2XLCol(colno-1)+inttostr(rowno); // from here on the code should be in Finish to allow concatenating into the same worksheet sheet1.add(' </x:row>'); sheet1.add(' </x:sheetData>'); sheet1.add(' </x:worksheet>'); Load_ContentTypes_file(Content_Types); Load_dotrels_file(dotrels); Load_workbookdotrels_file(workbook_xml_rels); Load_workbook_file(workbook, worksheetname); MakeStyles(styles); {$ifndef DXE} zcomp := TZipCompression.zcDeflate; zipfile := TZipfile.Create; zipfile.Open(filename,Tzipmode.zmWrite); zstream := TMemorystream.Create; Content_Types.SaveToStream(zstream, TEncoding.UTF8); zstream.Position := 0; zipfile.Add(zstream, '[Content_Types].xml', zcomp); zstream.Clear; dotrels.SaveToStream(zstream, TEncoding.UTF8); zstream.Position := 0; zipfile.Add(zstream, '_rels/.rels', zcomp); zstream.Clear; workbook_xml_rels.SaveToStream(zstream, TEncoding.UTF8); zstream.Position := 0; zipfile.Add(zstream, 'xl/_rels/workbook.xml.rels', zcomp); zstream.Clear; workbook.SaveToStream(zstream, TEncoding.UTF8); zstream.Position := 0; zipfile.Add(zstream, 'xl/workbook.xml', zcomp); zstream.Clear; styles.SaveToStream(zstream, TEncoding.UTF8); zstream.Position := 0; zipfile.Add(zstream, 'xl/styles.xml', zcomp); zstream.Clear; sheet1.SaveToStream(zstream, TEncoding.UTF8); zstream.Position := 0; zipfile.Add(zstream, 'xl/worksheets/sheet.xml', zcomp); zstream.Free; zipfile.Close; zipfile.Free; {$endif} end; // overridden Finish procedure TQRXLSXDocumentFilter.Finish; begin if fconcatenating then exit; ProcessItems; inherited; end; procedure TQRXLSXDocumentFilter.EndConcat; begin fconcatenating := false; Finish; end; procedure TQRXLSXDocumentFilter.TextOutRec( ExportInfo : TExportInfoRec); var //I : integer; nItem : XLXSTextItem; sortstr, colorstr, xlsxcolstr, boldstr, italicstr, xfontstr, xstylestr, xfillstr, hastr : string; xfindex, xsindex, xfillind : integer; begin nItem.col := ExportInfo.Column; nItem.X := ExportInfo.Xpos; nItem.Y := ExportInfo.Ypos + FPageYOffset; if nItem.Y > FMaxYValue then FMaxYValue := nItem.Y; nItem.text := EntityReplace(ExportInfo.Text); nItem.exportAs := ExportInfo.exportAs; nItem.XLNumFormat := ExportInfo.XLNumFormat; nItem.controlName := ExportInfo.controlName; // old style stuff ? nItem.fontname := ExportInfo.Font.Name; nItem.fontsize := ExportInfo.Font.Size; nItem.fontbold := fsBold in ExportInfo.Font.Style; nItem.fontitalic := fsItalic in ExportInfo.Font.Style; nItem.fontstrike := fsStrikeout in ExportInfo.Font.Style; nItem.fontcolor := ExportInfo.Font.Color; colorstr := colTrans(Nitem.fontcolor); if nItem.fontcolor<0 then nItem.fontcolor := 0; if trim(nItem.controlName)='' then nItem.controlName := 'noname'; //xlsx style stuff // <font><i/><b/><sz val="10"/><name val="Arial"/><color rgb="FF7F7F7F"/></font> xlsxcolstr := colorstr; boldstr := ''; if nItem.fontbold then boldstr := '<b/>'; italicstr := ''; if nItem.fontitalic then italicstr := '<i/>'; xfontstr := '<font>'+boldstr+italicstr+'<sz val="'+inttostr(nItem.fontsize)+'"/><name val="'+nItem.fontname+'"/><color rgb="'+xlsxcolstr+'"/></font>'; xfindex := fontlist.IndexOf(xfontstr); if xfindex = -1 then begin fontlist.Add(xfontstr); xfindex := fontlist.Count-1; end; xfillind := 0; if exportinfo.BGColor<>clWhite then begin xfillstr := '<fill><patternFill patternType="solid"><fgColor rgb="'+colTrans(exportinfo.BGColor)+'"/></patternFill></fill>'; xfillind := fillslist.IndexOf(xfillstr); if xfillind = -1 then begin fillslist.Add(xfillstr); xfillind := fillslist.Count-1; end; end; if exportInfo.Alignment=taLeftJustify then hastr := 'left' else if exportInfo.Alignment=taRightJustify then hastr := 'right' else hastr := 'center'; xstylestr := '<xf numFmtId="'+inttostr(integer(nItem.XLNumFormat))+'" fontId="'+inttostr(xfindex)+'" fillId="'+inttostr(xfillind)+'" borderId="0" xfId="0">'+ '<alignment vertical="center" horizontal="'+hastr+'"/></xf>'; xsindex := styleslist.IndexOf(xstylestr); if xsindex = -1 then begin styleslist.Add(xstylestr); xsindex := styleslist.Count-1; end; nitem.fontsize := xsindex;// fontsize is now the style index setlength(FItems,FItemcount+1); FItems[FItemcount] := nItem; sortstr := format( '%7d:%7d:%7d',[trunc(nItem.Y), nItem.col, FItemcount]); sortstr := stringreplace( sortstr, ' ','0',[rfReplaceall]); sortstr := sortstr+':'+nItem.text; FSortList.Add(sortstr); inc(FItemcount); end; procedure TQRXLSXDocumentFilter.EndPage; begin //do nothing; end; procedure TQRXLSXDocumentFilter.NewPage; begin inc(FPagenumber); FPageYoffset := FMaxYvalue; end; function EntityReplace( var ctext : string ) : string; begin ctext := stringreplace( ctext, '&', '&amp;', [rfReplaceAll] ); // must be first ctext := stringreplace( ctext, '<', '&lt;', [rfReplaceAll] ); ctext := stringreplace( ctext, '>', '&gt;', [rfReplaceAll] ); ctext := stringreplace( ctext, '''', '&apos;', [rfReplaceAll] ); ctext := stringreplace( ctext, '"', '&quot;', [rfReplaceAll] ); result := ctext; end; function ColTrans( ct : TColor ) : string; var tempstr : string; begin if ct < 0 then begin ct := ct and $FFFFFF; end; tempstr := format ( '%6.6x', [longint(ct)]); result := 'FF' + copy( tempstr, 5, 2 ) +copy( tempstr, 3, 2 ) +copy( tempstr, 1, 2 ) ; end; // strip off file extension function basename( fname : string ) : string; var p : integer; ps,fs : string; begin basename := fname; ps:=sysutils.ExtractFilePath(fname); fs:=sysutils.ExtractFileName(fname); p := pos( '.', fs ); if p = 0 then exit; basename := ps + copy( fs, 1, p - 1 ); end; initialization xmlWorkSheetname := 'Untitled Sheet'; end.
unit RequestFilterForma; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DBGridEh, DBCtrlsEh, StdCtrls, Mask, DBLookupEh, DB, FIBDataSet, pFIBDataSet, Buttons, ExtCtrls, ActnList, DBCtrls, PrjConst, System.Actions, MemTableEh, Vcl.ComCtrls, PropFilerEh, PropStorageEh; type TRequestFilterForm = class(TForm) pnlOKCancel: TPanel; SpeedButton3: TSpeedButton; dsStreets: TpFIBDataSet; srcStreets: TDataSource; dsHomes: TpFIBDataSet; srcHomes: TDataSource; dsArea: TpFIBDataSet; srcArea: TDataSource; dsSubArea: TpFIBDataSet; srcSubArea: TDataSource; dsRequestType: TpFIBDataSet; srcRequestType: TDataSource; dsExecutor: TpFIBDataSet; srcExecutor: TDataSource; srcWORKAREA: TDataSource; dsWORKAREA: TpFIBDataSet; dsWORKGROUP: TpFIBDataSet; srcWORKGROUP: TDataSource; srcANALYS: TDataSource; dsANALYS: TpFIBDataSet; chkDefaultFilter: TCheckBox; pnlBtns: TPanel; lbl4: TLabel; lbl5: TLabel; dbnvgr1: TDBNavigator; chk1: TDBCheckBoxEh; btnAnd: TButton; btnOR: TButton; btnLoad: TSpeedButton; btnSave: TSpeedButton; dlgOpen: TOpenDialog; dsOrg: TpFIBDataSet; srcOrg: TDataSource; srcMH: TDataSource; dsMH: TpFIBDataSet; dsWorks: TpFIBDataSet; srcWorks: TDataSource; dsResult: TpFIBDataSet; srcResult: TDataSource; dsErrors: TpFIBDataSet; srcErrors: TDataSource; bbOk: TBitBtn; bbCancel: TBitBtn; pgcFilter: TPageControl; tsMain: TTabSheet; srcFilter: TDataSource; actlst: TActionList; actOk: TAction; tsList: TTabSheet; mmoListBids: TDBMemoEh; lblOrAND: TLabel; cbbWhose: TDBComboBoxEh; luDBLookupComboBox1: TDBLookupComboboxEh; luResult: TDBLookupComboboxEh; luAnalysGrp: TDBLookupComboboxEh; luType: TDBLookupComboboxEh; Label2: TLabel; edExpired: TDBNumberEditEh; dePLANTO: TDBDateTimeEditEh; dePLANFROM: TDBDateTimeEditEh; luUpCuststreetFilter: TDBLookupComboboxEh; lucbb1: TDBLookupComboboxEh; lbl1: TLabel; lbl8: TLabel; lbl12: TLabel; lbl11: TLabel; lbl3: TLabel; lblResult: TLabel; lbl10: TLabel; lbl17: TLabel; cbbSUBAREA: TDBLookupComboboxEh; lbl9: TLabel; lblHE: TLabel; luHE: TDBLookupComboboxEh; luOgz: TDBLookupComboboxEh; lblOgz: TLabel; lblWork: TLabel; luWork: TDBLookupComboboxEh; luTemplate: TDBLookupComboboxEh; Label1: TLabel; lbl16: TLabel; deTimeFrom: TDBDateTimeEditEh; lbl15: TLabel; deTimeTo: TDBDateTimeEditEh; DBCheckBoxEh1: TDBCheckBoxEh; edAfter: TDBNumberEditEh; lbl14: TLabel; edTo: TDBNumberEditEh; lbl13: TLabel; lbl7: TLabel; luHouseNo: TDBLookupComboboxEh; lbl6: TLabel; ed1: TDBEditEh; lucbb2: TDBLookupComboboxEh; lbl2: TLabel; PropStorageEh1: TPropStorageEh; procedure SpeedButton3Click(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure actOkExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnAndClick(Sender: TObject); procedure btnORClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure btnLoadClick(Sender: TObject); procedure srcFilterDataChange(Sender: TObject; Field: TField); procedure luWorkEnter(Sender: TObject); private { Private declarations } procedure SaveFilter(const filename: string); procedure CheckDateAndCorrect(); public { Public declarations } end; var RequestFilterForm: TRequestFilterForm; implementation uses DM, RequestsForma, MAIN, AtrCommon; {$R *.dfm} procedure TRequestFilterForm.SaveFilter(const filename: string); var s: string; begin if Length(filename) = 0 then exit; s := A4MainForm.GetUserFilterFolder + filename + '.JRF'; if srcFilter.DataSet.State in [dsEdit, dsInsert] then srcFilter.DataSet.post; DatasetToJson(srcFilter.DataSet, s); end; procedure TRequestFilterForm.btnAndClick(Sender: TObject); begin if srcFilter.DataSet.State in [dsEdit, dsInsert] then srcFilter.DataSet.post; srcFilter.DataSet.Append; srcFilter.DataSet['next_condition'] := 1; end; procedure TRequestFilterForm.btnORClick(Sender: TObject); begin if srcFilter.DataSet.State in [dsEdit, dsInsert] then srcFilter.DataSet.post; srcFilter.DataSet.Append; srcFilter.DataSet['next_condition'] := 0; end; procedure TRequestFilterForm.btnLoadClick(Sender: TObject); begin dlgOpen.InitialDir := A4MainForm.GetUserFilterFolder; if dlgOpen.Execute then begin srcFilter.DataSet.DisableControls; if not srcFilter.DataSet.Active then srcFilter.DataSet.Open; (srcFilter.DataSet as TMemTableEh).EmptyTable; DatasetFromJson(srcFilter.DataSet, dlgOpen.filename); srcFilter.DataSet.EnableControls; end; end; procedure TRequestFilterForm.btnSaveClick(Sender: TObject); var filename: string; begin filename := InputBox(rsInputFilterName, rsTitle, rsFilter); if Length(filename) = 0 then exit; SaveFilter(rsRequests + filename); end; procedure TRequestFilterForm.FormClose(Sender: TObject; var Action: TCloseAction); begin if dsStreets.Active then dsStreets.Close; if dsHomes.Active then dsHomes.Close; if dsArea.Active then dsArea.Close; if dsSubArea.Active then dsSubArea.Close; if dsRequestType.Active then dsRequestType.Close; if dsExecutor.Active then dsExecutor.Close; if dsWORKAREA.Active then dsWORKAREA.Close; if dsWORKGROUP.Active then dsWORKGROUP.Close; if dsANALYS.Active then dsANALYS.Close; if dsOrg.Active then dsOrg.Close; if dsMH.Active then dsMH.Close; if dsWorks.Active then dsWorks.Close; if dsErrors.Active then dsErrors.Open; end; procedure TRequestFilterForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) then actOkExecute(Sender); end; procedure TRequestFilterForm.FormKeyPress(Sender: TObject; var Key: Char); var go: boolean; begin if (Key = #13) then begin go := true; if (ActiveControl is TDBLookupComboboxEh) then go := not(ActiveControl as TDBLookupComboboxEh).ListVisible; if (ActiveControl is TDBGridEh) then go := False; if go then begin Key := #0; // eat enter key PostMessage(Self.Handle, WM_NEXTDLGCTL, 0, 0); end; end; end; procedure TRequestFilterForm.FormShow(Sender: TObject); begin dsStreets.Open; dsHomes.Open; dsArea.Open; dsSubArea.Open; dsRequestType.Open; dsExecutor.Open; dsWORKAREA.Open; dsWORKGROUP.Open; dsANALYS.Open; dsOrg.Open; dsMH.Open; dsWorks.Open; dsResult.Open; dsErrors.Open; if srcFilter.DataSet.RecordCount > 1 then srcFilter.DataSet.First; if ((not srcFilter.DataSet.FieldByName('ListBids').IsNull) and (srcFilter.DataSet.FieldByName('ListBids').AsString <> '')) then pgcFilter.ActivePage := tsList; end; procedure TRequestFilterForm.luWorkEnter(Sender: TObject); begin if (Sender is TDBLookupComboboxEh) then begin if not(Sender as TDBLookupComboboxEh).ListSource.DataSet.Active then (Sender as TDBLookupComboboxEh).ListSource.DataSet.Open; end; end; procedure TRequestFilterForm.SpeedButton3Click(Sender: TObject); begin with srcFilter.DataSet do begin DisableControls; if not Active then Open; (srcFilter.DataSet as TMemTableEh).EmptyTable; EnableControls; end; end; procedure TRequestFilterForm.srcFilterDataChange(Sender: TObject; Field: TField); begin if srcFilter.DataSet['next_condition'] = 0 then lblOrAND.Caption := rsOR else lblOrAND.Caption := rsAND; lblOrAND.Visible := srcFilter.DataSet.RecNo > 1; end; procedure TRequestFilterForm.CheckDateAndCorrect(); var d1, d2: TDate; begin if (not srcFilter.DataSet.FieldByName('DATE_FROM').IsNull and not srcFilter.DataSet.FieldByName('DATE_TO').IsNull) then begin if (srcFilter.DataSet['DATE_FROM'] > srcFilter.DataSet['DATE_TO']) then begin d1 := srcFilter.DataSet['DATE_FROM']; d2 := srcFilter.DataSet['DATE_TO']; srcFilter.DataSet.Edit; srcFilter.DataSet['DATE_TO'] := d1; srcFilter.DataSet['DATE_FROM'] := d2; srcFilter.DataSet.post; end; end; end; procedure TRequestFilterForm.actOkExecute(Sender: TObject); begin if srcFilter.DataSet.State in [dsEdit, dsInsert] then srcFilter.DataSet.post; CheckDateAndCorrect(); if chkDefaultFilter.Checked then SaveFilter('RDefault'); ModalResult := mrOk; end; end.
unit RegisterProc; interface type TLicType = ( licNonCom, licPersonal, licBusiness, licSite ); const cLicName: array[TLicType] of string = ( 'Non-commercial license', 'Personal license', 'Business license (7 computers)', 'Site license (unlim. num of computers)' ); const cRName = 'Русская регистрация'; //function EnterRegistrationInfo(const Name, Key: string): boolean; //function ReadRegistrationInfo(var RegName: string; var RegDaysLeft: integer; var LicType: TLicType): boolean; //function IsUSSR: boolean; implementation uses Windows, SysUtils, Forms, Graphics, DateUtils; //-------------------------------------------------------------------------- const RDays: array[1..7] of string = ('понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота', 'воскресенье'); (* function EnterRegistrationInfo(const Name, Key: string): boolean; var AKey: string; begin {$I aspr_crypt_begin1.inc} AKey:= Key; if (Name = cRName) and (Key = RDays[ DayOfTheWeek(Now) ]) then AKey:= cRKey; Result:= CheckKeyAndDecrypt(PChar(AKey), PChar(Name), true); {$I aspr_crypt_end1.inc} end; *) //-------------------------------------------------------------------------- function SDeleteLast(var S: string; const SubStr: string): boolean; var N: integer; begin Result:= false; N:= Pos(SubStr, S); if (N > 0) and (N = Length(S) - Length(SubStr) + 1) then begin Result:= true; Delete(S, N, MaxInt); end; end; function CheckLicType(var S: string): TLicType; begin if S = cRName then Result:= licNonCom else if SDeleteLast(S, '[B]') then Result:= licBusiness else if SDeleteLast(S, '[S]') then Result:= licSite else Result:= licPersonal; end; //-------------------------------------------------------------------------- (* function ReadRegistrationInfo(var RegName: string; var RegDaysLeft: integer; var LicType: TLicType): boolean; var UserKey: PChar; UserName: PChar; ModeName: PChar; TrialDaysTotal: DWORD; TrialDaysLeft: DWORD; begin Result:= false; RegName:= ''; RegDaysLeft:= 0; LicType:= licPersonal; //{$I aspr_crypt_begin1.inc} UserKey:= nil; UserName:= nil; ModeName:= nil; TrialDaysTotal:= DWORD(-1); TrialDaysLeft:= DWORD(-1); GetRegistrationInformation(0, UserKey, UserName); if (UserKey <> nil) and (StrLen(UserKey) > 0) then begin Result:= true; RegName:= StrPas(UserName); LicType:= CheckLicType(RegName); //GetModeInformation(0, ModeName, ModeStatus); //Mode info not needed yet end else begin if GetTrialDays(0, TrialDaysTotal, TrialDaysLeft) then RegDaysLeft:= TrialDaysLeft - 50 {!}; end; {$I aspr_crypt_end1.inc} end; *) function GetUserDefaultUILanguage: Word; stdcall; external 'kernel32.dll'; //-------------------------------------------------------------------------- function IsUSSR: boolean; var _xAPag: word; //ANSI Code Page, для нас = 1251 _xOPag: word; //OEM Code Page, для нас = 866 _xLCID: integer; //Windows Locale ID, для нас = 1049 ($0419) u1, u2: Word; begin _xAPag := GetACP; _xOPag := GetOEMCP; _xLCID := GetSystemDefaultLCID; u1:= GetUserDefaultUILanguage; u2:= GetUserDefaultLangID; Result:= (_xAPag = 1251) and (_xOPag = 866) and (_xLCID = 1049) and (u1 = 1049) and (u2 = 1049) { and (_xLFormats.LongMonthNames[11] = 'Ноябрь') and (_xLFormats.ShortMonthNames[5] = 'май') and (_xLFormats.LongDayNames[4] = 'среда') }; end; end.
unit DAO.AssinantesJornal; interface uses DAO.Base, Generics.Collections, System.Classes, Model.AssinaturaJornal; type TAssinantesJornalDAO = class(TDAO) public function Insert(aAssinaturas: Model.AssinaturaJornal.TAssinaturaJornal): Boolean; function Update(aAssinaturas: Model.AssinaturaJornal.TAssinaturaJornal): Boolean; function Delete(iId: Integer): Boolean; function FindById(iId: Integer): TObjectList<Model.AssinaturaJornal.TAssinaturaJornal>; function FindByCodigo(sCodigo: String): TObjectList<Model.AssinaturaJornal.TAssinaturaJornal>; function FindByNome(sNome: String): TObjectList<Model.AssinaturaJornal.TAssinaturaJornal>; function FindByModalidade(iModalidade: Integer): TObjectList<Model.AssinaturaJornal.TAssinaturaJornal>; function FindByProduto(sProduto: String): TObjectList<Model.AssinaturaJornal.TAssinaturaJornal>; function FindByEndereco(sEndereco: String): TObjectList<Model.AssinaturaJornal.TAssinaturaJornal>; function FindByCEP(sCEP: String): TObjectList<Model.AssinaturaJornal.TAssinaturaJornal>; function FindByRoteiro(sRoteiro: String): TObjectList<Model.AssinaturaJornal.TAssinaturaJornal>; function FindByAssinatura(sCodigo: String; iModalidade: Integer; sProduto: String): TObjectList<Model.AssinaturaJornal.TAssinaturaJornal>; end; const TABLENAME = 'jor_assinantes_jornal'; implementation uses System.SysUtils, FireDAC.Comp.Client, Data.DB; function TAssinantesJornalDAO.Insert(aAssinaturas: Model.AssinaturaJornal.TAssinaturaJornal): Boolean; var sSQL : System.string; begin Result := False; aAssinaturas.ID := GetKeyValue(TABLENAME,'ID_ASSINANTE'); sSQL := 'INSERT INTO ' + TABLENAME + ' '+ '(ID_ASSINANTE, COD_ASSINANTE, COD_MODALIDADE, COD_PRODUTO, NUM_ORDEM, QTD_EXEMPLARES, NOM_ASSINANTE, ' + 'DES_TIPO_LOGRADOURO, DES_LOGRADOURO, NUM_LOGRADOURO, DES_COMPLEMENTO, NOM_BAIRRO, NOM_CIDADE, UF_ESTADO, ' + 'NUM_CEP, DES_REFERENCIA, DES_ROTEIRO, DES_LOG) ' + 'VALUES ' + '(:pID_ASSINANTE, :pCOD_ASSINANTE, :pCOD_MODALIDADE, :pCOD_PRODUTO, :pNUM_ORDEM, :pQTD_EXEMPLARES, :pNOM_ASSINANTE, ' + ':pDES_TIPO_LOGRADOURO, :pDES_LOGRADOURO, :pNUM_LOGRADOURO, :pDES_COMPLEMENTO, :pNOM_BAIRRO, :pNOM_CIDADE, ' + ':pUF_ESTADO, :pNUM_CEP, :pDES_REFERENCIA, :pDES_ROTEIRO, :pDES_LOG);'; Connection.ExecSQL(sSQL,[aAssinaturas.ID, aAssinaturas.Codigo, aAssinaturas.Modalidade, aAssinaturas.Produto, aAssinaturas.Ordem, aAssinaturas.Qtde, aAssinaturas.Nome, aAssinaturas.TipoLogradouro, aAssinaturas.NomeLogradouro, aAssinaturas.NumeroLogradouro, aAssinaturas.Complemento, aAssinaturas.Bairro, aAssinaturas.Cidade, aAssinaturas.Estado, aAssinaturas.CEP, aAssinaturas.Referencia, aAssinaturas.Roteiro, aAssinaturas.Log], [ftInteger, ftInteger, ftString, ftInteger, ftInteger, ftString, ftString, ftString, ftString, ftString, ftString, ftString, ftString, ftString, ftString, ftString, ftString]); Result := True; end; function TAssinantesJornalDAO.Update(aAssinaturas: TAssinaturaJornal): Boolean; var sSQL : System.string; begin Result := False; sSQL := 'UPDATE ' + TABLENAME + ' SET '+ 'COD_ASSINANTE = :pCOD_ASSINANTE, ' + 'COD_MODALIDADE = :pCOD_MODALIDADE, ' + 'COD_PRODUTO = :pCOD_PRODUTO, ' + 'NUM_ORDEM = :pNUM_ORDEM, ' + 'QTD_EXEMPLARES = :pQTD_EXEMPLARES, ' + 'NOM_ASSINANTE = :pNOM_ASSINANTE, ' + 'DES_TIPO_LOGRADOURO = :pDES_TIPO_LOGRADOURO, ' + 'DES_LOGRADOURO = :pDES_LOGRADOURO, ' + 'NUM_LOGRADOURO = :pNUM_LOGRADOURO, ' + 'DES_COMPLEMENTO = :pDES_COMPLEMENTO, ' + 'NOM_BAIRRO = :pNOM_BAIRRO, ' + 'NOM_CIDADE = :pNOM_CIDADE, ' + 'UF_ESTADO = :pUF_ESTADO, ' + 'NUM_CEP = :pNUM_CEP, ' + 'DES_REFERENCIA = :pDES_REFERENCIA, ' + 'DES_ROTEIRO = :pDES_ROTEIRO, ' + 'DES_LOG = :pDES_LOG ' + 'WHERE ID_ASSINANTE = :pID_ASSINANTE;'; Connection.ExecSQL(sSQL,[aAssinaturas.Codigo, aAssinaturas.Modalidade, aAssinaturas.Produto, aAssinaturas.Ordem, aAssinaturas.Qtde, aAssinaturas.Nome, aAssinaturas.TipoLogradouro, aAssinaturas.NomeLogradouro, aAssinaturas.NumeroLogradouro, aAssinaturas.Complemento, aAssinaturas.Bairro, aAssinaturas.Cidade, aAssinaturas.Estado, aAssinaturas.CEP, aAssinaturas.Referencia, aAssinaturas.Roteiro, aAssinaturas.Log, aAssinaturas.ID], [ftInteger, ftString, ftInteger, ftInteger, ftString, ftString, ftString, ftString, ftString, ftString, ftString, ftString, ftString, ftString, ftString, ftString, ftInteger]); Result := True; end; function TAssinantesJornalDAO.Delete(iId: Integer): Boolean; var sSQL : String; begin Result := False; sSQL := 'DELETE FROM ' + TABLENAME + ' WHERE ID_ASSINANTE = :pID_ASSINANTE;'; Connection.ExecSQL(sSQL,[iId],[ftInteger]); Result := True; end; function TAssinantesJornalDAO.FindById(iId: Integer): TObjectList<TAssinaturaJornal>; var FDQuery: TFDQuery; assinantes: TObjectList<TAssinaturaJornal>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); FDQuery.SQL.Add('WHERE ID_ASSINANTE = :pID_ASSINANTE'); FDQuery.ParamByName('pID_ASSINANTE').AsInteger := iId; FDQuery.Open(); assinantes := TObjectList<TAssinaturaJornal>.Create(); while not FDQuery.Eof do begin assinantes.Add(TAssinaturaJornal.Create(FDQuery.FieldByName('ID_ASSINANTE').AsInteger, FDQuery.FieldByName('COD_ASSINANTE').AsString, FDQuery.FieldByName('COD_MODALIDADE').AsInteger, FDQuery.FieldByName('COD_PRODUTO').AsString, FDQuery.FieldByName('NUM_ORDEM').AsInteger, FDQuery.FieldByName('QTD_EXEMPLARES').AsInteger, FDQuery.FieldByName('NOM_ASSINANTE').AsString, FDQuery.FieldByName('DES_TIPO_LOGRADOURO').AsString, FDQuery.FieldByName('DES_LOGRADOURO').AsString, FDQuery.FieldByName('NUM_LOGRADOURO').AsString, FDQuery.FieldByName('DES_COMPLEMENTO').AsString, FDQuery.FieldByName('NOM_BAIRRO').AsString, FDQuery.FieldByName('NOM_CIDADE').AsString, FDQuery.FieldByName('UF_ESTADO').AsString, FDQuery.FieldByName('NUM_CEP').AsString, FDQuery.FieldByName('DES_REFERENCIA').AsString, FDQuery.FieldByName('DES_ROTEIRO').AsString, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := assinantes; end; function TAssinantesJornalDAO.FindByCodigo(sCodigo: string): TObjectList<TAssinaturaJornal>; var FDQuery: TFDQuery; assinantes: TObjectList<TAssinaturaJornal>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); FDQuery.SQL.Add('WHERE COD_ASSINANTE = :pCOD_ASSINANTE'); FDQuery.ParamByName('pCOD_ASSINANTE').AsString := sCodigo; FDQuery.Open(); assinantes := TObjectList<TAssinaturaJornal>.Create(); while not FDQuery.Eof do begin assinantes.Add(TAssinaturaJornal.Create(FDQuery.FieldByName('ID_ASSINANTE').AsInteger, FDQuery.FieldByName('COD_ASSINANTE').AsString, FDQuery.FieldByName('COD_MODALIDADE').AsInteger, FDQuery.FieldByName('COD_PRODUTO').AsString, FDQuery.FieldByName('NUM_ORDEM').AsInteger, FDQuery.FieldByName('QTD_EXEMPLARES').AsInteger, FDQuery.FieldByName('NOM_ASSINANTE').AsString, FDQuery.FieldByName('DES_TIPO_LOGRADOURO').AsString, FDQuery.FieldByName('DES_LOGRADOURO').AsString, FDQuery.FieldByName('NUM_LOGRADOURO').AsString, FDQuery.FieldByName('DES_COMPLEMENTO').AsString, FDQuery.FieldByName('NOM_BAIRRO').AsString, FDQuery.FieldByName('NOM_CIDADE').AsString, FDQuery.FieldByName('UF_ESTADO').AsString, FDQuery.FieldByName('NUM_CEP').AsString, FDQuery.FieldByName('DES_REFERENCIA').AsString, FDQuery.FieldByName('DES_ROTEIRO').AsString, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := assinantes; end; function TAssinantesJornalDAO.FindByNome(sNome: string): TObjectList<TAssinaturaJornal>; var FDQuery: TFDQuery; assinantes: TObjectList<TAssinaturaJornal>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); FDQuery.SQL.Add('WHERE NOM_ASSINANTE LIKE :pNOM_ASSINANTE'); FDQuery.ParamByName('pNOM_ASSINANTE').AsString := sNome; FDQuery.Open(); assinantes := TObjectList<TAssinaturaJornal>.Create(); while not FDQuery.Eof do begin assinantes.Add(TAssinaturaJornal.Create(FDQuery.FieldByName('ID_ASSINANTE').AsInteger, FDQuery.FieldByName('COD_ASSINANTE').AsString, FDQuery.FieldByName('COD_MODALIDADE').AsInteger, FDQuery.FieldByName('COD_PRODUTO').AsString, FDQuery.FieldByName('NUM_ORDEM').AsInteger, FDQuery.FieldByName('QTD_EXEMPLARES').AsInteger, FDQuery.FieldByName('NOM_ASSINANTE').AsString, FDQuery.FieldByName('DES_TIPO_LOGRADOURO').AsString, FDQuery.FieldByName('DES_LOGRADOURO').AsString, FDQuery.FieldByName('NUM_LOGRADOURO').AsString, FDQuery.FieldByName('DES_COMPLEMENTO').AsString, FDQuery.FieldByName('NOM_BAIRRO').AsString, FDQuery.FieldByName('NOM_CIDADE').AsString, FDQuery.FieldByName('UF_ESTADO').AsString, FDQuery.FieldByName('NUM_CEP').AsString, FDQuery.FieldByName('DES_REFERENCIA').AsString, FDQuery.FieldByName('DES_ROTEIRO').AsString, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := assinantes; end; function TAssinantesJornalDAO.FindByModalidade(iModalidade: Integer): TObjectList<TAssinaturaJornal>; var FDQuery: TFDQuery; assinantes: TObjectList<TAssinaturaJornal>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); FDQuery.SQL.Add('WHERE COD_MODALIDADE = :pCOD_MODALIDADE'); FDQuery.ParamByName('pCOD_MODALIDADE').AsInteger := iModalidade; FDQuery.Open(); assinantes := TObjectList<TAssinaturaJornal>.Create(); while not FDQuery.Eof do begin assinantes.Add(TAssinaturaJornal.Create(FDQuery.FieldByName('ID_ASSINANTE').AsInteger, FDQuery.FieldByName('COD_ASSINANTE').AsString, FDQuery.FieldByName('COD_MODALIDADE').AsInteger, FDQuery.FieldByName('COD_PRODUTO').AsString, FDQuery.FieldByName('NUM_ORDEM').AsInteger, FDQuery.FieldByName('QTD_EXEMPLARES').AsInteger, FDQuery.FieldByName('NOM_ASSINANTE').AsString, FDQuery.FieldByName('DES_TIPO_LOGRADOURO').AsString, FDQuery.FieldByName('DES_LOGRADOURO').AsString, FDQuery.FieldByName('NUM_LOGRADOURO').AsString, FDQuery.FieldByName('DES_COMPLEMENTO').AsString, FDQuery.FieldByName('NOM_BAIRRO').AsString, FDQuery.FieldByName('NOM_CIDADE').AsString, FDQuery.FieldByName('UF_ESTADO').AsString, FDQuery.FieldByName('NUM_CEP').AsString, FDQuery.FieldByName('DES_REFERENCIA').AsString, FDQuery.FieldByName('DES_ROTEIRO').AsString, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := assinantes; end; function TAssinantesJornalDAO.FindByProduto(sProduto: string): TObjectList<TAssinaturaJornal>; var FDQuery: TFDQuery; assinantes: TObjectList<TAssinaturaJornal>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); FDQuery.SQL.Add('WHERE COD_PRODUTO = :pCOD_PRODUTO'); FDQuery.ParamByName('pCOD_PRODUTO').AsString := sProduto; FDQuery.Open(); assinantes := TObjectList<TAssinaturaJornal>.Create(); while not FDQuery.Eof do begin assinantes.Add(TAssinaturaJornal.Create(FDQuery.FieldByName('ID_ASSINANTE').AsInteger, FDQuery.FieldByName('COD_ASSINANTE').AsString, FDQuery.FieldByName('COD_MODALIDADE').AsInteger, FDQuery.FieldByName('COD_PRODUTO').AsString, FDQuery.FieldByName('NUM_ORDEM').AsInteger, FDQuery.FieldByName('QTD_EXEMPLARES').AsInteger, FDQuery.FieldByName('NOM_ASSINANTE').AsString, FDQuery.FieldByName('DES_TIPO_LOGRADOURO').AsString, FDQuery.FieldByName('DES_LOGRADOURO').AsString, FDQuery.FieldByName('NUM_LOGRADOURO').AsString, FDQuery.FieldByName('DES_COMPLEMENTO').AsString, FDQuery.FieldByName('NOM_BAIRRO').AsString, FDQuery.FieldByName('NOM_CIDADE').AsString, FDQuery.FieldByName('UF_ESTADO').AsString, FDQuery.FieldByName('NUM_CEP').AsString, FDQuery.FieldByName('DES_REFERENCIA').AsString, FDQuery.FieldByName('DES_ROTEIRO').AsString, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := assinantes; end; function TAssinantesJornalDAO.FindByEndereco(sEndereco: string): TObjectList<Model.AssinaturaJornal.TAssinaturaJornal>; var FDQuery: TFDQuery; assinantes: TObjectList<TAssinaturaJornal>; sCampos: TStringList; i: Integer; bFiltro: Boolean; begin FDQuery := TFDQuery.Create(nil); if sEndereco.IsEmpty then begin Exit; end; sCampos.Delimiter := ';'; sCampos.StrictDelimiter := True; sCampos.DelimitedText := sEndereco; bFiltro := False; try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME + ' WHERE '); for i := 0 to sCampos.Count - 1 do begin if not sCampos[i].IsEmpty then begin if i = 0 then begin FDQuery.SQL.Add('DES_TIPO_LOGRADOURO LIKE :pDES_TIPO_LOGRADOURO'); FDQuery.ParamByName('pDES_TIPO_LOGRADOURO').AsString := sCampos[i]; bFiltro := True; end; if i = 1 then begin if bFiltro then begin FDQuery.SQL.Add(' OR DES_LOGRADOURO LIKE :pDES_LOGRADOURO'); end else begin FDQuery.SQL.Add('DES_LOGRADOURO LIKE :pDES_LOGRADOURO'); end; FDQuery.ParamByName('pDES_LOGRADOURO').AsString := sCampos[i]; end; if i = 2 then begin if bFiltro then begin FDQuery.SQL.Add(' OR NUM_LOGRADOURO LIKE :pNUM_LOGRADOURO'); end else begin FDQuery.SQL.Add('NUM_LOGRADOURO LIKE :pNUM_LOGRADOURO'); end; FDQuery.ParamByName('pNUM_LOGRADOURO').AsString := sCampos[i]; end; end; end; FDQuery.Open(); assinantes := TObjectList<TAssinaturaJornal>.Create(); while not FDQuery.Eof do begin assinantes.Add(TAssinaturaJornal.Create(FDQuery.FieldByName('ID_ASSINANTE').AsInteger, FDQuery.FieldByName('COD_ASSINANTE').AsString, FDQuery.FieldByName('COD_MODALIDADE').AsInteger, FDQuery.FieldByName('COD_PRODUTO').AsString, FDQuery.FieldByName('NUM_ORDEM').AsInteger, FDQuery.FieldByName('QTD_EXEMPLARES').AsInteger, FDQuery.FieldByName('NOM_ASSINANTE').AsString, FDQuery.FieldByName('DES_TIPO_LOGRADOURO').AsString, FDQuery.FieldByName('DES_LOGRADOURO').AsString, FDQuery.FieldByName('NUM_LOGRADOURO').AsString, FDQuery.FieldByName('DES_COMPLEMENTO').AsString, FDQuery.FieldByName('NOM_BAIRRO').AsString, FDQuery.FieldByName('NOM_CIDADE').AsString, FDQuery.FieldByName('UF_ESTADO').AsString, FDQuery.FieldByName('NUM_CEP').AsString, FDQuery.FieldByName('DES_REFERENCIA').AsString, FDQuery.FieldByName('DES_ROTEIRO').AsString, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := assinantes; end; function TAssinantesJornalDAO.FindByCEP(sCEP: string): TObjectList<TAssinaturaJornal>; var FDQuery: TFDQuery; assinantes: TObjectList<TAssinaturaJornal>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); FDQuery.SQL.Add('WHERE NOM_ASSINANTE LIKE :pNUM_CEP'); FDQuery.ParamByName('pNUM_CEP').AsString := sCEP; FDQuery.Open(); assinantes := TObjectList<TAssinaturaJornal>.Create(); while not FDQuery.Eof do begin assinantes.Add(TAssinaturaJornal.Create(FDQuery.FieldByName('ID_ASSINANTE').AsInteger, FDQuery.FieldByName('COD_ASSINANTE').AsString, FDQuery.FieldByName('COD_MODALIDADE').AsInteger, FDQuery.FieldByName('COD_PRODUTO').AsString, FDQuery.FieldByName('NUM_ORDEM').AsInteger, FDQuery.FieldByName('QTD_EXEMPLARES').AsInteger, FDQuery.FieldByName('NOM_ASSINANTE').AsString, FDQuery.FieldByName('DES_TIPO_LOGRADOURO').AsString, FDQuery.FieldByName('DES_LOGRADOURO').AsString, FDQuery.FieldByName('NUM_LOGRADOURO').AsString, FDQuery.FieldByName('DES_COMPLEMENTO').AsString, FDQuery.FieldByName('NOM_BAIRRO').AsString, FDQuery.FieldByName('NOM_CIDADE').AsString, FDQuery.FieldByName('UF_ESTADO').AsString, FDQuery.FieldByName('NUM_CEP').AsString, FDQuery.FieldByName('DES_REFERENCIA').AsString, FDQuery.FieldByName('DES_ROTEIRO').AsString, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := assinantes; end; function TAssinantesJornalDAO.FindByRoteiro(sRoteiro: String): TObjectList<TAssinaturaJornal>; var FDQuery: TFDQuery; assinantes: TObjectList<TAssinaturaJornal>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); FDQuery.SQL.Add('WHERE DES_ROTEIRO = :pDES_ROTEIRO'); FDQuery.ParamByName('pDES_ROTEIRO').AsString := sRoteiro; FDQuery.Open(); assinantes := TObjectList<TAssinaturaJornal>.Create(); while not FDQuery.Eof do begin assinantes.Add(TAssinaturaJornal.Create(FDQuery.FieldByName('ID_ASSINANTE').AsInteger, FDQuery.FieldByName('COD_ASSINANTE').AsString, FDQuery.FieldByName('COD_MODALIDADE').AsInteger, FDQuery.FieldByName('COD_PRODUTO').AsString, FDQuery.FieldByName('NUM_ORDEM').AsInteger, FDQuery.FieldByName('QTD_EXEMPLARES').AsInteger, FDQuery.FieldByName('NOM_ASSINANTE').AsString, FDQuery.FieldByName('DES_TIPO_LOGRADOURO').AsString, FDQuery.FieldByName('DES_LOGRADOURO').AsString, FDQuery.FieldByName('NUM_LOGRADOURO').AsString, FDQuery.FieldByName('DES_COMPLEMENTO').AsString, FDQuery.FieldByName('NOM_BAIRRO').AsString, FDQuery.FieldByName('NOM_CIDADE').AsString, FDQuery.FieldByName('UF_ESTADO').AsString, FDQuery.FieldByName('NUM_CEP').AsString, FDQuery.FieldByName('DES_REFERENCIA').AsString, FDQuery.FieldByName('DES_ROTEIRO').AsString, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := assinantes; end; function TAssinantesJornalDAO.FindByAssinatura(sCodigo: string; iModalidade: Integer; sProduto: string): TObjectList<TAssinaturaJornal>; var FDQuery: TFDQuery; assinantes: TObjectList<TAssinaturaJornal>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); FDQuery.SQL.Add('WHERE COD_ASSINANTE = :pCOD_ASSINANTE AND COD_MODALIDADE = :pCOD_MODALIDADE AND COD_PRODUTO = :pCOD_PRODUTO'); FDQuery.ParamByName('pCOD_ASSINANTE').AsString := sCodigo; FDQuery.ParamByName('pCOD_MODALIDADE').AsInteger := iModalidade; FDQuery.ParamByName('pCOD_PRODUTO').AsString := sProduto; FDQuery.Open(); assinantes := TObjectList<TAssinaturaJornal>.Create(); while not FDQuery.Eof do begin assinantes.Add(TAssinaturaJornal.Create(FDQuery.FieldByName('ID_ASSINANTE').AsInteger, FDQuery.FieldByName('COD_ASSINANTE').AsString, FDQuery.FieldByName('COD_MODALIDADE').AsInteger, FDQuery.FieldByName('COD_PRODUTO').AsString, FDQuery.FieldByName('NUM_ORDEM').AsInteger, FDQuery.FieldByName('QTD_EXEMPLARES').AsInteger, FDQuery.FieldByName('NOM_ASSINANTE').AsString, FDQuery.FieldByName('DES_TIPO_LOGRADOURO').AsString, FDQuery.FieldByName('DES_LOGRADOURO').AsString, FDQuery.FieldByName('NUM_LOGRADOURO').AsString, FDQuery.FieldByName('DES_COMPLEMENTO').AsString, FDQuery.FieldByName('NOM_BAIRRO').AsString, FDQuery.FieldByName('NOM_CIDADE').AsString, FDQuery.FieldByName('UF_ESTADO').AsString, FDQuery.FieldByName('NUM_CEP').AsString, FDQuery.FieldByName('DES_REFERENCIA').AsString, FDQuery.FieldByName('DES_ROTEIRO').AsString, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := assinantes; end; end.
unit test1; interface // *********************************** // classes for test1.proto // generated by ProtoBufGenerator // kami-soft 2016-2017 // *********************************** uses SysUtils, Classes, Generics.Collections, pbInput, pbOutput, pbPublic, uAbstractProtoBufClasses, TestImport1; type //enumeration TEnumG0=( g1 = 1, g2 = 2 ); //nested enumeration TEnum1=( Val1 = 1, Val2 = 2 ); //simple message TTestMsg0 = class(TAbstractProtoBufClass) public const tag_Field1 = 1; const tag_Field2 = 2; strict private FField1: Integer; FField2: Int64; procedure SetField1(Tag: Integer; const Value: Integer); procedure SetField2(Tag: Integer; const Value: Int64); strict protected function LoadSingleFieldFromBuf(ProtoBuf: TProtoBufInput; FieldNumber: Integer; WireType: Integer): Boolean; override; procedure SaveFieldsToBuf(ProtoBuf: TProtoBufOutput); override; public constructor Create; override; destructor Destroy; override; property Field1: Integer index tag_Field1 read FField1 write SetField1; property Field2: Int64 index tag_Field2 read FField2 write SetField2; end; //nested message TTestNested1 = class(TAbstractProtoBufClass) public const tag_Field1 = 1; strict private FField1: Integer; procedure SetField1(Tag: Integer; const Value: Integer); strict protected function LoadSingleFieldFromBuf(ProtoBuf: TProtoBufInput; FieldNumber: Integer; WireType: Integer): Boolean; override; procedure SaveFieldsToBuf(ProtoBuf: TProtoBufOutput); override; public property Field1: Integer index tag_Field1 read FField1 write SetField1; end; TTestMsg1 = class(TAbstractProtoBufClass) public const tag_DefField1 = 1; const tag_DefField2 = 2; const tag_DefField3 = 3; const tag_DefField4 = 4; const tag_DefField5 = 5; const tag_DefField6 = 6; const tag_DefField7 = 7; const tag_DefField8 = 8; const tag_DefField9 = 9; const tag_FieldMsg1 = 20; const tag_FieldE1 = 21; const tag_FieldE2 = 22; const tag_FieldNested1 = 30; const tag_FieldNested2 = 31; const tag_FieldArr1List = 40; const tag_FieldArr2List = 41; const tag_FieldArr3List = 42; const tag_FieldArrE1List = 43; const tag_FieldMArr2List = 44; const tag_FieldImp1 = 50; const tag_FieldImp2 = 51; strict private FDefField1: Integer; FDefField2: Int64; FDefField3: string; FDefField4: Double; FDefField5: Boolean; FDefField6: TEnumG0; FDefField7: Int64; FDefField8: Integer; FDefField9: Single; FFieldMsg1: TTestMsg0; FFieldE1: TEnum1; FFieldE2: TEnum1; FFieldNested1: TTestNested1; FFieldNested2: TTestNested1; FFieldArr1List: TList<Integer>; FFieldArr2List: TList<Integer>; FFieldArr3List: TList<string>; FFieldArrE1List: TList<TEnum1>; FFieldMArr2List: TProtoBufClassList<TTestMsg0>; FFieldImp1: TEnumGlobal; FFieldImp2: TEnumGlobal; procedure SetDefField1(Tag: Integer; const Value: Integer); procedure SetDefField2(Tag: Integer; const Value: Int64); procedure SetDefField3(Tag: Integer; const Value: string); procedure SetDefField4(Tag: Integer; const Value: Double); procedure SetDefField5(Tag: Integer; const Value: Boolean); procedure SetDefField6(Tag: Integer; const Value: TEnumG0); procedure SetDefField7(Tag: Integer; const Value: Int64); procedure SetDefField8(Tag: Integer; const Value: Integer); procedure SetDefField9(Tag: Integer; const Value: Single); procedure SetFieldE1(Tag: Integer; const Value: TEnum1); procedure SetFieldE2(Tag: Integer; const Value: TEnum1); procedure SetFieldNested2(Tag: Integer; const Value: TTestNested1); procedure SetFieldImp1(Tag: Integer; const Value: TEnumGlobal); procedure SetFieldImp2(Tag: Integer; const Value: TEnumGlobal); strict protected function LoadSingleFieldFromBuf(ProtoBuf: TProtoBufInput; FieldNumber: Integer; WireType: Integer): Boolean; override; procedure SaveFieldsToBuf(ProtoBuf: TProtoBufOutput); override; public constructor Create; override; destructor Destroy; override; //fields with defaults property DefField1: Integer index tag_DefField1 read FDefField1 write SetDefField1 default 2; property DefField2: Int64 index tag_DefField2 read FDefField2 write SetDefField2 default -1; property DefField3: string index tag_DefField3 read FDefField3 write SetDefField3; // default 'yes'; property DefField4: Double index tag_DefField4 read FDefField4 write SetDefField4; // default 1.1; property DefField5: Boolean index tag_DefField5 read FDefField5 write SetDefField5; // default true; property DefField6: TEnumG0 index tag_DefField6 read FDefField6 write SetDefField6 default g2; property DefField7: Int64 index tag_DefField7 read FDefField7 write SetDefField7 default 100; property DefField8: Integer index tag_DefField8 read FDefField8 write SetDefField8 default 1; property DefField9: Single index tag_DefField9 read FDefField9 write SetDefField9; // default 1.23e1; //field of message type property FieldMsg1: TTestMsg0 read FFieldMsg1; //fields of nested enumeration type property FieldE1: TEnum1 index tag_FieldE1 read FFieldE1 write SetFieldE1; property FieldE2: TEnum1 index tag_FieldE2 read FFieldE2 write SetFieldE2 default Val2; //fields of nested message type property FieldNested1: TTestNested1 read FFieldNested1; property FieldNested2: TTestNested1 index tag_FieldNested2 read FFieldNested2 write SetFieldNested2; //repeated fields property FieldArr1List: TList<Integer> read FFieldArr1List; property FieldArr2List: TList<Integer> read FFieldArr2List; property FieldArr3List: TList<string> read FFieldArr3List; property FieldArrE1List: TList<TEnum1> read FFieldArrE1List; property FieldMArr2List: TProtoBufClassList<TTestMsg0> read FFieldMArr2List; //fields of imported types property FieldImp1: TEnumGlobal index tag_FieldImp1 read FFieldImp1 write SetFieldImp1; property FieldImp2: TEnumGlobal index tag_FieldImp2 read FFieldImp2 write SetFieldImp2; end; //test proto identifier name conversion TTestMsg1Extension1 = class(TTestMsg1) public const tag_field_name_test_1 = 187; const tag_field_Name_test_2 = 220; strict private Ffield_name_test_1: Integer; Ffield_Name_test_2: Integer; procedure Setfield_name_test_1(Tag: Integer; const Value: Integer); procedure Setfield_Name_test_2(Tag: Integer; const Value: Integer); strict protected function LoadSingleFieldFromBuf(ProtoBuf: TProtoBufInput; FieldNumber: Integer; WireType: Integer): Boolean; override; procedure SaveFieldsToBuf(ProtoBuf: TProtoBufOutput); override; public property field_name_test_1: Integer index tag_field_name_test_1 read Ffield_name_test_1 write Setfield_name_test_1; property field_Name_test_2: Integer index tag_field_Name_test_2 read Ffield_Name_test_2 write Setfield_Name_test_2; end; implementation { TTestMsg0 } constructor TTestMsg0.Create; begin inherited; RegisterRequiredField(tag_Field1); RegisterRequiredField(tag_Field2); end; destructor TTestMsg0.Destroy; begin inherited; end; function TTestMsg0.LoadSingleFieldFromBuf(ProtoBuf: TProtoBufInput; FieldNumber: Integer; WireType: Integer): Boolean; begin Result := inherited; if Result then Exit; Result := True; case FieldNumber of tag_Field1: Field1 := ProtoBuf.readInt32; tag_Field2: Field2 := ProtoBuf.readInt64; else Result := False; end; end; procedure TTestMsg0.SaveFieldsToBuf(ProtoBuf: TProtoBufOutput); begin inherited; if FieldHasValue[tag_Field1] then ProtoBuf.writeInt32(tag_Field1, FField1); if FieldHasValue[tag_Field2] then ProtoBuf.writeInt64(tag_Field2, FField2); end; procedure TTestMsg0.SetField1(Tag: Integer; const Value: Integer); begin FField1:= Value; FieldHasValue[Tag]:= True; end; procedure TTestMsg0.SetField2(Tag: Integer; const Value: Int64); begin FField2:= Value; FieldHasValue[Tag]:= True; end; { TTestNested1 } function TTestNested1.LoadSingleFieldFromBuf(ProtoBuf: TProtoBufInput; FieldNumber: Integer; WireType: Integer): Boolean; begin Result := inherited; if Result then Exit; Result := True; case FieldNumber of tag_Field1: Field1 := ProtoBuf.readInt32; else Result := False; end; end; procedure TTestNested1.SaveFieldsToBuf(ProtoBuf: TProtoBufOutput); begin inherited; if FieldHasValue[tag_Field1] then ProtoBuf.writeInt32(tag_Field1, FField1); end; procedure TTestNested1.SetField1(Tag: Integer; const Value: Integer); begin FField1:= Value; FieldHasValue[Tag]:= True; end; { TTestMsg1 } constructor TTestMsg1.Create; begin inherited; DefField1 := 2; DefField2 := -1; DefField3 := 'yes'; DefField4 := 1.1; DefField5 := true; DefField6 := g2; DefField7 := 100; DefField8 := 1; DefField9 := 1.23e1; FFieldMsg1 := TTestMsg0.Create; FieldE2 := Val2; FFieldNested1 := TTestNested1.Create; FFieldArr1List := TList<Integer>.Create; FFieldArr2List := TList<Integer>.Create; FFieldArr3List := TList<string>.Create; FFieldArrE1List := TList<TEnum1>.Create; FFieldMArr2List := TProtoBufClassList<TTestMsg0>.Create; end; destructor TTestMsg1.Destroy; begin FFieldMsg1.Free; FFieldNested1.Free; FFieldArr1List.Free; FFieldArr2List.Free; FFieldArr3List.Free; FFieldArrE1List.Free; FFieldMArr2List.Free; inherited; end; function TTestMsg1.LoadSingleFieldFromBuf(ProtoBuf: TProtoBufInput; FieldNumber: Integer; WireType: Integer): Boolean; var tmpBuf: TProtoBufInput; begin Result := inherited; if Result then Exit; Result := True; tmpBuf:= nil; try case FieldNumber of tag_DefField1: DefField1 := ProtoBuf.readInt32; tag_DefField2: DefField2 := ProtoBuf.readInt64; tag_DefField3: DefField3 := ProtoBuf.readString; tag_DefField4: DefField4 := ProtoBuf.readDouble; tag_DefField5: DefField5 := ProtoBuf.readBoolean; tag_DefField6: DefField6 := TEnumG0(ProtoBuf.readEnum); tag_DefField7: DefField7 := ProtoBuf.readSInt64; tag_DefField8: DefField8 := ProtoBuf.readFixed32; tag_DefField9: DefField9 := ProtoBuf.readFloat; tag_FieldMsg1: begin tmpBuf := ProtoBuf.ReadSubProtoBufInput; FFieldMsg1.LoadFromBuf(tmpBuf); end; tag_FieldE1: FieldE1 := TEnum1(ProtoBuf.readEnum); tag_FieldE2: FieldE2 := TEnum1(ProtoBuf.readEnum); tag_FieldNested1: begin tmpBuf := ProtoBuf.ReadSubProtoBufInput; FFieldNested1.LoadFromBuf(tmpBuf); end; tag_FieldNested2: FieldNested2 := TTestNested1(ProtoBuf.readEnum); tag_FieldArr1List: FFieldArr1List.Add(ProtoBuf.readInt32); tag_FieldArr2List: begin if WireType = WIRETYPE_LENGTH_DELIMITED then begin tmpBuf:=ProtoBuf.ReadSubProtoBufInput; while tmpBuf.getPos < tmpBuf.BufSize do FFieldArr2List.Add(tmpBuf.readRawVarint32); end else FFieldArr2List.Add(ProtoBuf.readRawVarint32); end; tag_FieldArr3List: FFieldArr3List.Add(ProtoBuf.readString); tag_FieldArrE1List: FFieldArrE1List.Add(TEnum1(ProtoBuf.readEnum)); tag_FieldMArr2List: FFieldMArr2List.AddFromBuf(ProtoBuf, fieldNumber); tag_FieldImp1: FieldImp1 := TEnumGlobal(ProtoBuf.readEnum); tag_FieldImp2: FieldImp2 := TEnumGlobal(ProtoBuf.readEnum); else Result := False; end; finally tmpBuf.Free end; end; procedure TTestMsg1.SaveFieldsToBuf(ProtoBuf: TProtoBufOutput); var tmpBuf: TProtoBufOutput; i: Integer; begin inherited; tmpBuf:= TProtoBufOutput.Create; try if FieldHasValue[tag_DefField1] then ProtoBuf.writeInt32(tag_DefField1, FDefField1); if FieldHasValue[tag_DefField2] then ProtoBuf.writeInt64(tag_DefField2, FDefField2); if FieldHasValue[tag_DefField3] then ProtoBuf.writeString(tag_DefField3, FDefField3); if FieldHasValue[tag_DefField4] then ProtoBuf.writeDouble(tag_DefField4, FDefField4); if FieldHasValue[tag_DefField5] then ProtoBuf.writeBoolean(tag_DefField5, FDefField5); if FieldHasValue[tag_DefField6] then ProtoBuf.writeInt32(tag_DefField6, Integer(FDefField6)); if FieldHasValue[tag_DefField7] then ProtoBuf.writeSInt64(tag_DefField7, FDefField7); if FieldHasValue[tag_DefField8] then ProtoBuf.writeFixed32(tag_DefField8, FDefField8); if FieldHasValue[tag_DefField9] then ProtoBuf.writeFloat(tag_DefField9, FDefField9); if FieldHasValue[tag_FieldMsg1] then begin FFieldMsg1.SaveToBuf(tmpBuf); ProtoBuf.writeMessage(tag_FieldMsg1, tmpBuf); end; if FieldHasValue[tag_FieldE1] then ProtoBuf.writeInt32(tag_FieldE1, Integer(FFieldE1)); if FieldHasValue[tag_FieldE2] then ProtoBuf.writeInt32(tag_FieldE2, Integer(FFieldE2)); if FieldHasValue[tag_FieldNested1] then begin FFieldNested1.SaveToBuf(tmpBuf); ProtoBuf.writeMessage(tag_FieldNested1, tmpBuf); end; if FieldHasValue[tag_FieldNested2] then ProtoBuf.writeInt32(tag_FieldNested2, Integer(FFieldNested2)); if FieldHasValue[tag_FieldArr1List] then for i := 0 to FFieldArr1List.Count-1 do ProtoBuf.writeInt32(tag_FieldArr1List, FFieldArr1List[i]); if FieldHasValue[tag_FieldArr2List] then begin for i := 0 to FFieldArr2List.Count-1 do tmpBuf.writeRawVarint32(FFieldArr2List[i]); ProtoBuf.writeMessage(tag_FieldArr2List, tmpBuf); end; if FieldHasValue[tag_FieldArr3List] then for i := 0 to FFieldArr3List.Count-1 do ProtoBuf.writeString(tag_FieldArr3List, FFieldArr3List[i]); if FieldHasValue[tag_FieldArrE1List] then for i := 0 to FFieldArrE1List.Count-1 do ProtoBuf.writeInt32(tag_FieldArrE1List, Integer(FFieldArrE1List[i])); if FieldHasValue[tag_FieldMArr2List] then FFieldMArr2List.SaveToBuf(ProtoBuf, tag_FieldMArr2List); if FieldHasValue[tag_FieldImp1] then ProtoBuf.writeInt32(tag_FieldImp1, Integer(FFieldImp1)); if FieldHasValue[tag_FieldImp2] then ProtoBuf.writeInt32(tag_FieldImp2, Integer(FFieldImp2)); finally tmpBuf.Free end; end; procedure TTestMsg1.SetDefField1(Tag: Integer; const Value: Integer); begin FDefField1:= Value; FieldHasValue[Tag]:= True; end; procedure TTestMsg1.SetDefField2(Tag: Integer; const Value: Int64); begin FDefField2:= Value; FieldHasValue[Tag]:= True; end; procedure TTestMsg1.SetDefField3(Tag: Integer; const Value: string); begin FDefField3:= Value; FieldHasValue[Tag]:= True; end; procedure TTestMsg1.SetDefField4(Tag: Integer; const Value: Double); begin FDefField4:= Value; FieldHasValue[Tag]:= True; end; procedure TTestMsg1.SetDefField5(Tag: Integer; const Value: Boolean); begin FDefField5:= Value; FieldHasValue[Tag]:= True; end; procedure TTestMsg1.SetDefField6(Tag: Integer; const Value: TEnumG0); begin FDefField6:= Value; FieldHasValue[Tag]:= True; end; procedure TTestMsg1.SetDefField7(Tag: Integer; const Value: Int64); begin FDefField7:= Value; FieldHasValue[Tag]:= True; end; procedure TTestMsg1.SetDefField8(Tag: Integer; const Value: Integer); begin FDefField8:= Value; FieldHasValue[Tag]:= True; end; procedure TTestMsg1.SetDefField9(Tag: Integer; const Value: Single); begin FDefField9:= Value; FieldHasValue[Tag]:= True; end; procedure TTestMsg1.SetFieldE1(Tag: Integer; const Value: TEnum1); begin FFieldE1:= Value; FieldHasValue[Tag]:= True; end; procedure TTestMsg1.SetFieldE2(Tag: Integer; const Value: TEnum1); begin FFieldE2:= Value; FieldHasValue[Tag]:= True; end; procedure TTestMsg1.SetFieldNested2(Tag: Integer; const Value: TTestNested1); begin FFieldNested2:= Value; FieldHasValue[Tag]:= True; end; procedure TTestMsg1.SetFieldImp1(Tag: Integer; const Value: TEnumGlobal); begin FFieldImp1:= Value; FieldHasValue[Tag]:= True; end; procedure TTestMsg1.SetFieldImp2(Tag: Integer; const Value: TEnumGlobal); begin FFieldImp2:= Value; FieldHasValue[Tag]:= True; end; { TTestMsg1Extension1 } function TTestMsg1Extension1.LoadSingleFieldFromBuf(ProtoBuf: TProtoBufInput; FieldNumber: Integer; WireType: Integer): Boolean; begin Result := inherited; if Result then Exit; Result := True; case FieldNumber of tag_field_name_test_1: field_name_test_1 := ProtoBuf.readInt32; tag_field_Name_test_2: field_Name_test_2 := ProtoBuf.readInt32; else Result := False; end; end; procedure TTestMsg1Extension1.SaveFieldsToBuf(ProtoBuf: TProtoBufOutput); begin inherited; if FieldHasValue[tag_field_name_test_1] then ProtoBuf.writeInt32(tag_field_name_test_1, Ffield_name_test_1); if FieldHasValue[tag_field_Name_test_2] then ProtoBuf.writeInt32(tag_field_Name_test_2, Ffield_Name_test_2); end; procedure TTestMsg1Extension1.Setfield_name_test_1(Tag: Integer; const Value: Integer); begin Ffield_name_test_1:= Value; FieldHasValue[Tag]:= True; end; procedure TTestMsg1Extension1.Setfield_Name_test_2(Tag: Integer; const Value: Integer); begin Ffield_Name_test_2:= Value; FieldHasValue[Tag]:= True; end; end.
unit Unit10; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm10 = class(TForm) Memo1: TMemo; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form10: TForm10; implementation {$R *.dfm} uses System.uJson, System.Json, Data.Db_store; type TMeuRecord = record codigo:string; data:TDateTime; valor1:double; hora:TTime; valor2:Currency; valor3:Double; verdadeiro:boolean; Endereco:string; end; procedure TForm10.FormCreate(Sender: TObject); var r :TMeuRecord; begin memo1.Lines.clear; memo1.Lines.Add('Valor4 esta no JSON e nao existe no RECORD'); // carrega o JSON para um RECORD (TMeuRecord) memo1.Lines.Add('-----------------------------------------'); memo1.Lines.Add('JSON para RECORD'); memo1.Lines.Add('-----------------------------------------'); r := TJsonObject.ToRecord<TMeuRecord>('{"codigo":"1","data":"2016-09-03T00:00:00","hora":"23:00:00", "valor1":10, "valor2":2, "valor3":3, "valor4":9999, "verdadeiro":"False"} '); memo1.Lines.Add('Endereco existe no RECORD e nao esta no JSON'); memo1.Lines.Add('-----------------------------------------'); memo1.Lines.Add('RECORD para JSON'); memo1.Lines.Add('-----------------------------------------'); // converte o RECORD para JSON memo1.Lines.add( TJsonObject.FromRecord ( r ).ToJSON); end; end.
unit CompStartup; { Inno Setup Copyright (C) 1997-2004 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Compiler Startup form $jrsoftware: issrc/Projects/CompStartup.pas,v 1.11 2004/07/22 19:49:39 jr Exp $ } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, UIStateForm, StdCtrls, ExtCtrls; type TStartupFormResult = (srNone, srEmpty, srWizard, srOpenFile, srOpenDialog, srOpenDialogExamples); TStartupForm = class(TUIStateForm) OKButton: TButton; CancelButton: TButton; GroupBox1: TGroupBox; GroupBox2: TGroupBox; EmptyRadioButton: TRadioButton; WizardRadioButton: TRadioButton; OpenRadioButton: TRadioButton; OpenListBox: TListBox; StartupCheck: TCheckBox; NewImage: TImage; OpenImage: TImage; procedure RadioButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure DblClick_(Sender: TObject); procedure OpenListBoxClick(Sender: TObject); procedure OKButtonClick(Sender: TObject); private FResult: TStartupFormResult; FResultFileName: TFileName; procedure SetMRUList(const MRUList: TStringList); public property MRUList: TStringList write SetMRUList; property Result: TStartupFormResult read FResult; property ResultFileName: TFileName read FResultFileName; end; implementation uses CompMsgs, CmnFunc, CmnFunc2, CompForm; {$R *.DFM} procedure TStartupForm.SetMRUList(const MRUList: TStringList); var I: Integer; begin for I := 0 to MRUList.Count-1 do OpenListBox.Items.Add(MRUList[I]); UpdateHorizontalExtent(OpenListBox); end; procedure TStartupForm.FormCreate(Sender: TObject); begin FResult := srNone; InitFormFont(Self); OpenListBox.Items.Add(SCompilerExampleScripts); OpenListBox.Items.Add(SCompilerMoreFiles); OpenListBox.ItemIndex := 0; UpdateHorizontalExtent(OpenListBox); ActiveControl := OpenRadioButton; end; procedure TStartupForm.RadioButtonClick(Sender: TObject); begin EmptyRadioButton.Checked := Sender = EmptyRadioButton; WizardRadioButton.Checked := Sender = WizardRadioButton; OpenRadioButton.Checked := Sender = OpenRadioButton; if Sender = OpenRadioButton then begin if OpenListBox.ItemIndex = -1 then OpenListBox.ItemIndex := 0; end else OpenListBox.ItemIndex := -1; end; procedure TStartupForm.DblClick_(Sender: TObject); begin if OkButton.Enabled then OkButton.Click; end; procedure TStartupForm.OpenListBoxClick(Sender: TObject); begin OpenRadioButton.Checked := True; end; procedure TStartupForm.OKButtonClick(Sender: TObject); begin if EmptyRadioButton.Checked then FResult := srEmpty else if WizardRadioButton.Checked then FResult := srWizard else { if OpenRadioButton.Checked then } begin if OpenListBox.ItemIndex = 0 then FResult := srOpenDialogExamples else if OpenListBox.ItemIndex > 1 then begin FResult := srOpenFile; FResultFileName := OpenListBox.Items[OpenListBox.ItemIndex]; end else FResult := srOpenDialog; end; end; end.
unit CustomPngImageListEditor; interface uses Windows, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ExtDlgs, pngimage, PngFunctions, PngBitBtn, PngImageList, Buttons; type TCustomPngImageListEditorDlg = class(TForm) cmbBackgroundColor: TComboBox; cmbPreviewBackground: TComboBox; dlgColor: TColorDialog; dlgOpenPicture: TOpenPictureDialog; edtName: TEdit; gbxImageInfo: TGroupBox; gbxProperties: TGroupBox; lblBackgroundColor: TLabel; lblColorDepth: TLabel; lblColorDepthValue: TLabel; lblCompression: TLabel; lblCompressionValue: TLabel; lblDimensions: TLabel; lblDimensionsValue: TLabel; lblFiltering: TLabel; lblFilteringValue: TLabel; lblName: TLabel; lblTransparency: TLabel; lblTransparencyValue: TLabel; lbxImages: TListBox; pnlActionButtons: TPanel; pnlBackgroundColor: TPanel; pnlMain: TPanel; btnAdd: TButton; btnDelete: TButton; btnReplace: TButton; btnClear: TButton; btnUp: TButton; btnDown: TButton; Images: TPngImageCollection; pnlButtons: TPanel; pnlModalButtons: TPanel; btnOK: TButton; btnCancel: TButton; chkUseFilenames: TCheckBox; procedure btnAddClick(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnDownClick(Sender: TObject); procedure btnReplaceClick(Sender: TObject); procedure btnUpClick(Sender: TObject); procedure cmbBackgroundColorChange(Sender: TObject); procedure cmbBackgroundColorDblClick(Sender: TObject); procedure cmbBackgroundColorExit(Sender: TObject); procedure cmbPreviewBackgroundChange(Sender: TObject); procedure cmbPreviewBackgroundDrawItem(Control: TWinControl; Index: Integer; ARect: TRect; State: TOwnerDrawState); procedure edtNameChange(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormShow(Sender: TObject); procedure lbxImagesClick(Sender: TObject); procedure lbxImagesDblClick(Sender: TObject); procedure lbxImagesDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure lbxImagesDrawItem(Control: TWinControl; Index: Integer; ARect: TRect; State: TOwnerDrawState); procedure lbxImagesEnter(Sender: TObject); procedure lbxImagesExit(Sender: TObject); procedure lbxImagesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure lbxImagesMeasureItem(Control: TWinControl; Index: Integer; var Height: Integer); procedure lbxImagesMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure lbxImagesStartDrag(Sender: TObject; var DragObject: TDragObject); private FDraggingIndex: Integer; FImageHeight: Integer; FImageWidth: Integer; FMaxWidth: Integer; FSelectionBodyColor: TColor; FSelectionBorderColor: TColor; function ConformDimensions(Png: TPngImage): Boolean; function ConformAdjustDimensions(Png: TPngImage; const AFileName: string): Boolean; function FirstSelected: Integer; function LastSelected: Integer; procedure DrawBackground(Canvas: TCanvas; const ARect: TRect; ScrollPos, Index: Integer; BlendColor: TColor = clNone; IgnoreScrollPos: Boolean = False); procedure GetColorProc(const S: string); procedure ParseBackgroundColor(Sender: TObject; CanDisplayError, CanChangeText: Boolean); procedure SelectBackgroundColor(Sender: TObject; Color: TColor); public property ImageHeight: Integer read FImageHeight write FImageHeight; property ImageWidth: Integer read FImageWidth write FImageWidth; end; var PngImageListEditorDlg: TCustomPngImageListEditorDlg; implementation uses SysUtils, Math; resourcestring SAreYouSureYouWantToDelete = 'Are you sure you want to delete %s?'; SAnd = ' and '; SThisWillClearTheEntireImageList = 'This will clear the entire image list. Are you sure you want to do this?'; SIsNotAValidColorValue = '"%s" is not a valid color value'; {$R *.dfm} //For calculating OfficeXP colors const WeightR: single = 0.764706; WeightG: single = 1.52941; WeightB: single = 0.254902; const SIncorrectSize = 'The selected PNG "%s" must be %dx%d in size, while its actual size is %dx%d'; SAgustSize = 'Adjust size of imagelist to match loaded image?'; var ResX, ResY: Integer; { Globals } function Blend(C1, C2: TColor; W1: Integer): TColor; var W2, A1, A2, D, F, G: Integer; begin if C1 < 0 then C1 := GetSysColor(C1 and $FF); if C2 < 0 then C2 := GetSysColor(C2 and $FF); if W1 >= 100 then D := 1000 else D := 100; W2 := D - W1; F := D div 2; A2 := C2 shr 16 * W2; A1 := C1 shr 16 * W1; G := (A1 + A2 + F) div D and $FF; Result := G shl 16; A2 := (C2 shr 8 and $FF) * W2; A1 := (C1 shr 8 and $FF) * W1; G := (A1 + A2 + F) div D and $FF; Result := Result or G shl 8; A2 := (C2 and $FF) * W2; A1 := (C1 and $FF) * W1; G := (A1 + A2 + F) div D and $FF; Result := Result or G; end; function ColorDistance(C1, C2: Integer): Single; var DR, DG, DB: Integer; begin DR := (C1 and $FF) - (C2 and $FF); Result := Sqr(DR * WeightR); DG := (C1 shr 8 and $FF) - (C2 shr 8 and $FF); Result := Result + Sqr(DG * WeightG); DB := (C1 shr 16) - (C2 shr 16); Result := Result + Sqr(DB * WeightB); Result := Sqrt(Result); end; function GetAdjustedThreshold(BkgndIntensity, Threshold: Single): Single; begin if BkgndIntensity < 220 then Result := (2 - BkgndIntensity / 220) * Threshold else Result := Threshold; end; function IsContrastEnough(AColor, ABkgndColor: Integer; DoAdjustThreshold: Boolean; Threshold: Single): Boolean; begin if DoAdjustThreshold then Threshold := GetAdjustedThreshold(ColorDistance(ABkgndColor, $000000), Threshold); Result := ColorDistance(ABkgndColor, AColor) > Threshold; end; procedure AdjustContrast(var AColor: Integer; ABkgndColor: Integer; Threshold: Single); var X, Y, Z: Single; R, G, B: Single; RR, GG, BB: Integer; I1, I2, S, Q, W: Single; DoInvert: Boolean; begin I1 := ColorDistance(AColor, $000000); I2 := ColorDistance(ABkgndColor, $000000); Threshold := GetAdjustedThreshold(I2, Threshold); if I1 > I2 then DoInvert := I2 < 442 - Threshold else DoInvert := I2 < Threshold; X := (ABkgndColor and $FF) * WeightR; Y := (ABkgndColor shr 8 and $FF) * WeightG; Z := (ABkgndColor shr 16) * WeightB; R := (AColor and $FF) * WeightR; G := (AColor shr 8 and $FF) * WeightG; B := (AColor shr 16) * WeightB; if DoInvert then begin R := 195 - R; G := 390 - G; B := 65 - B; X := 195 - X; Y := 390 - Y; Z := 65 - Z; end; S := Sqrt(Sqr(B) + Sqr(G) + Sqr(R)); if S < 0.01 then S := 0.01; Q := (R * X + G * Y + B * Z) / S; X := Q / S * R - X; Y := Q / S * G - Y; Z := Q / S * B - Z; W := Sqrt(Sqr(Threshold) - Sqr(X) - Sqr(Y) - Sqr(Z)); R := (Q - W) * R / S; G := (Q - W) * G / S; B := (Q - W) * B / S; if DoInvert then begin R := 195 - R; G := 390 - G; B := 65 - B; end; if R < 0 then R := 0 else if R > 195 then R := 195; if G < 0 then G := 0 else if G > 390 then G := 390; if B < 0 then B := 0 else if B > 65 then B := 65; RR := Trunc(R * (1 / WeightR) + 0.5); GG := Trunc(G * (1 / WeightG) + 0.5); BB := Trunc(B * (1 / WeightB) + 0.5); if RR > $FF then RR := $FF else if RR < 0 then RR := 0; if GG > $FF then GG := $FF else if GG < 0 then GG := 0; if BB > $FF then BB := $FF else if BB < 0 then BB := 0; AColor := (BB and $FF) shl 16 or (GG and $FF) shl 8 or (RR and $FF); end; procedure SetContrast(var Color: TColor; BkgndColor: TColor; Threshold: Integer); var T: Single; begin if Color < 0 then Color := GetSysColor(Color and $FF); if BkgndColor < 0 then BkgndColor := GetSysColor(BkgndColor and $FF); T := Threshold; if not IsContrastEnough(Color, BkgndColor, True, T) then AdjustContrast(Integer(Color), BkgndColor, T); end; function ResizeProportionalX(InitialValue: Integer): Integer; begin Result := InitialValue * ResX div 96; end; function ResizeProportionalY(InitialValue: Integer): Integer; begin Result := InitialValue * ResY div 96; end; procedure InitResolution; var DC: HDC; begin DC := GetDC(0); ResX := GetDeviceCaps(DC, LOGPIXELSX); ResY := GetDeviceCaps(DC, LOGPIXELSY); ReleaseDC(0, DC); end; { TCustomPngImageListEditorDlg } function TCustomPngImageListEditorDlg.ConformDimensions(Png: TPngImage): Boolean; begin //Returns whether an image conforms the specified dimensions, if available Result := ((ImageHeight = 0) and (ImageWidth = 0)) or ((ImageHeight = Png.Height) and (ImageWidth = Png.Width)); end; function TCustomPngImageListEditorDlg.FirstSelected: Integer; begin //Return the first selected image Result := 0; while not lbxImages.Selected[Result] and (Result < lbxImages.Items.Count) do Inc(Result); end; function TCustomPngImageListEditorDlg.LastSelected: Integer; begin //Return the last selected image Result := lbxImages.Items.Count - 1; while not lbxImages.Selected[Result] and (Result >= 0) do Dec(Result); end; procedure TCustomPngImageListEditorDlg.DrawBackground(Canvas: TCanvas; const ARect: TRect; ScrollPos, Index: Integer; BlendColor: TColor; IgnoreScrollPos: Boolean); var I, X, Y: Integer; PatBitmap, BkBitmap: TBitmap; Even: Boolean; begin //Draw the background of the listbox, if any if Index = 0 then begin //No background, then skip the hard part if BlendColor = clNone then Canvas.Brush.Color := clWindow else Canvas.Brush.Color := BlendColor; Canvas.FillRect(ARect); Exit; end; //Draw the background BkBitmap := TBitmap.Create; PatBitmap := TBitmap.Create; try PatBitmap.Height := 16; PatBitmap.Width := 16; with PatBitmap.Canvas do begin //First, draw the background for the pattern bitmap if BlendColor = clNone then begin Brush.Color := clWindow; FillRect(Rect(0, 0, PatBitmap.Height, PatBitmap.Width)); Brush.Color := Blend(clWindow, clBtnFace, 50); end else begin Brush.Color := Blend(clWindow, BlendColor, 50); FillRect(Rect(0, 0, PatBitmap.Height, PatBitmap.Width)); Brush.Color := BlendColor; end; //Then, draw the foreground on the pattern bitmap Pen.Color := Brush.Color; case Index of 1: begin //Checkerboard background FillRect(Rect(PatBitmap.Width div 2, 0, PatBitmap.Width, PatBitmap.Height div 2)); FillRect(Rect(0, PatBitmap.Height div 2, PatBitmap.Width div 2, PatBitmap.Height)); end; 2: begin //Diamonds background PatBitmap.Width := 10; PatBitmap.Height := 10; Polygon([Point(PatBitmap.Width div 2, 0), Point(PatBitmap.Width, PatBitmap.Height div 2), Point(PatBitmap.Width div 2, PatBitmap.Height), Point(0, PatBitmap.Height div 2)]); end; 3: begin //Slashed background Even := True; I := 2; while I < PatBitmap.Width + PatBitmap.Height do begin if I < PatBitmap.Width then begin MoveTo(I, 0); LineTo(-1, I + 1); end else begin MoveTo(PatBitmap.Width, I - PatBitmap.Width); LineTo(I - PatBitmap.Width, PatBitmap.Height); end; if Even then Inc(I, 1) else Inc(I, 3); Even := not Even; end; end; 4: begin //Backslashed background Even := True; I := 2; while I < PatBitmap.Width + PatBitmap.Height do begin if I < PatBitmap.Width then begin MoveTo(I, 0); LineTo(PatBitmap.Width, PatBitmap.Height - I); end else begin MoveTo(0, I - PatBitmap.Width - 1); LineTo(PatBitmap.Width - (I - PatBitmap.Width) + 1, PatBitmap.Height); end; if Even then Inc(I, 1) else Inc(I, 3); Even := not Even; end; end; end; end; //The actual background bitmap, its width and height are increased to compensate //for scrolling distance BkBitmap.Width := ARect.Left mod PatBitmap.Width + ARect.Right - ARect.Left; if IgnoreScrollPos then ScrollPos := 0 else ScrollPos := (ARect.Top + ScrollPos) mod PatBitmap.Height; BkBitmap.Height := ScrollPos + ARect.Bottom - ARect.Top; //Now repeat the pattern bitmap onto the background bitmap with BkBitmap.Canvas do begin Y := 0; while Y < BkBitmap.Height do begin X := 0; while X < BkBitmap.Width do begin Draw(X, Y, PatBitmap); Inc(X, PatBitmap.Width); end; Inc(Y, PatBitmap.Height); end; end; //And finally, draw the background bitmap to the canvas BitBlt(Canvas.Handle, ARect.Left, ARect.Top, ARect.Right - ARect.Left, ARect.Bottom - ARect.Top, BkBitmap.Canvas.Handle, ARect.Left mod PatBitmap.Width, ScrollPos, SRCCOPY); finally BkBitmap.Free; PatBitmap.Free; end; end; //Method for getting color values procedure TCustomPngImageListEditorDlg.GetColorProc(const S: string); begin cmbBackgroundColor.Items.Add(S); end; //Parse a background color name or code procedure TCustomPngImageListEditorDlg.ParseBackgroundColor(Sender: TObject; CanDisplayError, CanChangeText: Boolean); var S: string; I, ParsedColor: Integer; begin with cmbBackgroundColor do begin //First, see if its a known color name if IdentToColor(Text, ParsedColor) then begin ItemIndex := Items.IndexOf(Text); pnlBackgroundColor.Color := ParsedColor; end else begin S := Text; //Replace # with $ so StringToColor recognizes it if (Length(S) > 0) and (S[1] = '#') then S[1] := '$'; try //Try to convert to a real color value ParsedColor := StringToColor(S); if CanChangeText then begin //And try to convert back to an identifier (i.e. if you type in $000000, it'll become clBlack) if ColorToIdent(ParsedColor, S) then ItemIndex := Items.IndexOf(S) else Text := S; end; pnlBackgroundColor.Color := ParsedColor; except //If it fails, display a message if neccesary on EConvertError do if CanDisplayError then begin MessageBox(Self.Handle, PChar(Format(SIsNotAValidColorValue, [Text])), PChar(Self.Caption), MB_ICONERROR or MB_OK); SetFocus; end; end; end; end; //And finally, set the background color to every selected image if (Sender <> lbxImages) then for I := 0 to lbxImages.Items.Count - 1 do if lbxImages.Selected[I] then Images.Items[I].Background := pnlBackgroundColor.Color; end; procedure TCustomPngImageListEditorDlg.SelectBackgroundColor(Sender: TObject; Color: TColor); var S: string; begin //This happens after a background color has been slected from the color dialog //Try to convert a color into an identifier, or else into a hexadecimal representation if ColorToIdent(Color, S) then cmbBackgroundColor.ItemIndex := cmbBackgroundColor.Items.IndexOf(S) else cmbBackgroundColor.Text := '$' + IntToHex(dlgColor.Color, 6); ParseBackgroundColor(Sender, False, True); end; procedure TCustomPngImageListEditorDlg.btnAddClick(Sender: TObject); var Png: TPngImageCollectionItem; I, Selected, FirstSelected: Integer; begin //The Add button is pressed, let the programmer look for an image dlgOpenPicture.Options := dlgOpenPicture.Options + [ofAllowMultiSelect]; if dlgOpenPicture.Execute then begin for I := 0 to lbxImages.Items.Count - 1 do lbxImages.Selected[I] := False; FirstSelected := -1; for I := 0 to dlgOpenPicture.Files.Count - 1 do begin Png := Images.Items.Add; with Png.PngImage do begin //Load the image, but remove any gamma, so that the gamma won't be reapplied //when loading the image from the DFM LoadFromFile(dlgOpenPicture.Files[I]); if Png.PngImage.Header.ColorType in [COLOR_RGB, COLOR_RGBALPHA, COLOR_PALETTE] then Chunks.RemoveChunk(Chunks.ItemFromClass(TChunkgAMA)); end; //Does the image conform the specified dimensions, if any? if ConformAdjustDimensions(Png.PngImage, ExtractFilename(dlgOpenPicture.Files[I])) then begin //Update maximum image width if FMaxWidth < Png.PngImage.Width then FMaxWidth := Png.PngImage.Width; //Invent a name for the image, and initialize its background color if chkUseFilenames.Checked then Png.Name := ChangeFileExt(ExtractFileName(dlgOpenPicture.Files[I]), '') else Png.Name := 'PngImage' + IntToStr(Images.Items.Count - 1); // do not localize Png.Background := clWindow; //Finally, add it and select it Selected := lbxImages.Items.AddObject(Png.Name, Png); lbxImages.Selected[Selected] := True; if FirstSelected = -1 then FirstSelected := Selected; end else begin //The image does not conform the specified dimensions Images.Items.Delete(Png.Index); end; end; //Focus the first selected (added) image lbxImages.ItemIndex := FirstSelected; lbxImages.SetFocus; lbxImagesClick(nil); end; end; procedure TCustomPngImageListEditorDlg.btnClearClick(Sender: TObject); begin //Clear the listbox and the collection if (lbxImages.Items.Count > 0) and (MessageBox(Handle, PChar(SThisWillClearTheEntireImageList), PChar(Self.Caption), MB_ICONEXCLAMATION or MB_YESNO or MB_DEFBUTTON2) = IDYES) then begin lbxImages.Items.Clear; Images.Items.Clear; lbxImagesClick(nil); end; end; procedure TCustomPngImageListEditorDlg.btnDeleteClick(Sender: TObject); function GetCommaList: string; var I: Integer; S: TStringList; begin //Get a comma list of the names of the selected images in the form "name1, //name2 and name3" Result := ''; S := TStringList.Create; try for I := 0 to lbxImages.Items.Count - 1 do if lbxImages.Selected[I] then S.Add(Images.Items[I].Name); for I := 0 to S.Count - 1 do begin Result := Result + S[I]; if I < S.Count - 2 then Result := Result + ', ' else if I < S.Count - 1 then Result := Result + SAnd; end; finally S.Free; end; end; var I, NewIndex: Integer; begin with lbxImages do if (SelCount > 0) and (MessageBox(Handle, PChar(Format(SAreYouSureYouWantToDelete, [GetCommaList])), PChar(Self.Caption), MB_ICONEXCLAMATION or MB_YESNO) = IDYES) then begin //Delete every selected image from the listbox and from the collection NewIndex := -1; I := 0; while I < Items.Count do if Selected[I] then begin if NewIndex = -1 then NewIndex := I; lbxImages.Items.Delete(I); Images.Items.Delete(I); end else Inc(I); //Figure out the new selection index if NewIndex > Items.Count - 1 then NewIndex := Items.Count - 1 else if (NewIndex = -1) and (Items.Count > 0) then NewIndex := 0; Selected[NewIndex] := True; ItemIndex := NewIndex; lbxImagesClick(nil); end; end; procedure TCustomPngImageListEditorDlg.btnDownClick(Sender: TObject); var I: Integer; begin //Move the selected items one position down with lbxImages do if (SelCount > 0) and (LastSelected < Items.Count - 1) then for I := Items.Count - 1 downto 0 do if Selected[I] then begin Images.Items[I].Index := I + 1; Items.Exchange(I, I + 1); Selected[I + 1] := True; end; lbxImagesClick(nil); end; procedure TCustomPngImageListEditorDlg.btnReplaceClick(Sender: TObject); var Item: TPngImageCollectionItem; Index: Integer; Png: TPngImage; begin //The Replace button is pressed, let the programmer look for an image Index := FirstSelected; Item := Images.Items[Index]; dlgOpenPicture.FileName := Item.Name; dlgOpenPicture.Options := dlgOpenPicture.Options - [ofAllowMultiSelect]; with lbxImages do if (SelCount = 1) and dlgOpenPicture.Execute then begin Png := TPngImage.Create; try //First see if the image conforms the specified dimensions Png.LoadFromFile(dlgOpenPicture.Filename); if ConformDimensions(Png) then begin //Then remove any gamma, so that the gamma won't be reapplied when loading the //image from the DFM if Png.Header.ColorType in [COLOR_RGB, COLOR_RGBALPHA] then Png.Chunks.RemoveChunk(Png.Chunks.ItemFromClass(TChunkgAMA)); Item.PngImage := Png; //Update the maximum image width if FMaxWidth < Item.PngImage.Width then FMaxWidth := Item.PngImage.Width; //Repaint and update everything, to be sure lbxImages.Repaint; lbxImagesClick(nil); end else MessageBox(Handle, PChar(Format(SIncorrectSize, [ExtractFilename(dlgOpenPicture.Filename), ImageWidth, ImageHeight, Png.Width, Png.Height])), PChar(Caption), MB_ICONERROR or MB_OK); finally Png.Free; end; end; end; procedure TCustomPngImageListEditorDlg.btnUpClick(Sender: TObject); var I: Integer; begin //Move the selected items one position up with lbxImages do if (SelCount > 0) and (FirstSelected > 0) then for I := 0 to Items.Count - 1 do if Selected[I] then begin Images.Items[I].Index := I - 1; Items.Exchange(I, I - 1); Selected[I - 1] := True; end; lbxImagesClick(nil); end; procedure TCustomPngImageListEditorDlg.cmbBackgroundColorChange(Sender: TObject); begin //While typing, try parsing the background color, but without any error messages ParseBackgroundColor(Sender, False, False); end; procedure TCustomPngImageListEditorDlg.cmbBackgroundColorDblClick(Sender: TObject); begin //Just like in Delphi, when doubleclicking a color, the color dialog pops up dlgColor.Color := pnlBackgroundColor.Color; if dlgColor.Execute then SelectBackgroundColor(Sender, dlgColor.Color); end; procedure TCustomPngImageListEditorDlg.cmbBackgroundColorExit(Sender: TObject); begin //When leaving the background combobox, parse the color, but this with error //message, if neccesary ParseBackgroundColor(Sender, True, True); end; procedure TCustomPngImageListEditorDlg.cmbPreviewBackgroundChange(Sender: TObject); begin //Pewview background is changes, repaint all items lbxImages.Repaint; end; procedure TCustomPngImageListEditorDlg.cmbPreviewBackgroundDrawItem(Control: TWinControl; Index: Integer; ARect: TRect; State: TOwnerDrawState); var IconWidth: Integer; begin with cmbPreviewBackground do begin //Draw the background "icon" of the preview background combobox IconWidth := (ARect.Bottom - ARect.Top) * 4 div 3; DrawBackground(Canvas, Rect(ARect.Left, ARect.Top, ARect.Left + IconWidth, ARect.Bottom), 0, Index, clNone, True); Inc(ARect.Left, IconWidth); //Background color of the rest of the item if odSelected in State then Canvas.Brush.Color := clHighlight else Canvas.Brush.Color := clWindow; Canvas.FillRect(ARect); Inc(ARect.Left, 4); //And the text DrawText(Canvas.Handle, PChar(Items[Index]), -1, ARect, DT_LEFT or DT_NOPREFIX or DT_SINGLELINE or DT_VCENTER); Canvas.Brush.Color := clWindow; end; end; { TCustomPngImageListEditorDlg } function TCustomPngImageListEditorDlg.ConformAdjustDimensions(Png: TPngImage; const AFileName: string): Boolean; begin Result := ConformDimensions(Png); if not Result then begin if Images.Items.Count = 1 then begin { The image does not conform the specified dimensions, but is the first image loaded. We offer to adjust the image size of the imagelist to the size of the just loaded image. } if MessageBox(Handle, PChar(Format(SIncorrectSize + #13 + SAgustSize, [AFileName, ImageWidth, ImageHeight, Png.Width, Png.Height])), PChar(Caption), MB_ICONQUESTION or MB_YESNO) = mrYes then begin ImageWidth := Png.Width; ImageHeight := Png.Height; Result := True; end; end else begin { The image does not conform the specified dimensions } MessageBox(Handle, PChar(Format(SIncorrectSize, [AFileName, ImageWidth, ImageHeight, Png.Width, Png.Height])), PChar(Caption), MB_ICONERROR or MB_OK); end; end; end; procedure TCustomPngImageListEditorDlg.edtNameChange(Sender: TObject); begin //Update the selected image with the entered name, in realtime with lbxImages do if ItemIndex >= 0 then begin Images.Items[ItemIndex].Name := edtName.Text; Items[ItemIndex] := edtName.Text; end; end; procedure TCustomPngImageListEditorDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TCustomPngImageListEditorDlg.FormCreate(Sender: TObject); var Space8H: Integer; begin //Initialize OfficeXP colors for selection FSelectionBodyColor := Blend(clHighlight, clWindow, 30); SetContrast(FSelectionBodyColor, Blend(clWindow, clBtnFace, 165), 50); FSelectionBorderColor := clHighlight; //Initialize a value that keeps track of dragging FDraggingIndex := -1; //Get all available color names GetColorValues(GetColorProc); //Initialize the background to clWindow cmbBackgroundColor.ItemIndex := cmbBackgroundColor.Items.IndexOf('clWindow'); // do not localize cmbBackgroundColorChange(nil); //Do not specify image width and height by default (the imagelist will fill //these up, so that you cannot select an image other than these dimensions) ImageWidth := 0; ImageHeight := 0; //Resize everything to make it fit on "large fonts" setting. Note that these //operations are also needed on normal setting. Space8H := lbxImages.Top; Width := ResizeProportionalX(Width); Height := ResizeProportionalY(Height); Constraints.MinHeight := gbxProperties.Top + cmbBackgroundColor.Top + cmbBackgroundColor.Height + Space8H + Space8H + gbxImageInfo.Height + Space8H + (Height - pnlMain.Height); Constraints.MinWidth := Width; pnlButtons.Align := alBottom; pnlMain.Align := alClient; cmbPreviewBackground.ItemHeight := ResizeProportionalY(cmbPreviewBackground.ItemHeight); pnlBackgroundColor.Height := cmbBackgroundColor.Height; //Make sure the background color isn't reset when themes are enabled pnlBackgroundColor.ParentBackground := True; pnlBackgroundColor.ParentBackground := False; end; procedure TCustomPngImageListEditorDlg.FormResize(Sender: TObject); begin //There appears to be a bug that prevents a listbox from being redrawn correctly //when the form is resized lbxImages.Repaint; end; procedure TCustomPngImageListEditorDlg.FormShow(Sender: TObject); var I: Integer; begin //Initialize the maximum width of the images, to align text in the listbox FMaxWidth := 0; for I := 0 to Images.Items.Count - 1 do if Images.Items[I].PngImage.Width > FMaxWidth then FMaxWidth := Images.Items[I].PngImage.Width; //Fill the listbox with the images for I := 0 to Images.Items.Count - 1 do lbxImages.Items.AddObject(Images.Items[I].Name, Images.Items[I]); if lbxImages.Items.Count > 0 then begin lbxImages.Selected[0] := True; lbxImages.ItemIndex := 0; end; lbxImages.SetFocus; lbxImagesClick(nil); cmbPreviewBackground.ItemIndex := 0; FormResize(nil); end; procedure TCustomPngImageListEditorDlg.lbxImagesClick(Sender: TObject); function GetDimensions(Png: TPngImage): string; begin //Return the formatted dimensions of an image Result := Format('%dx%d', [Png.Width, Png.Height]); if Png.InterlaceMethod <> imNone then Result := Result + ' interlace'; end; function GetColorDepth(Png: TPngImage): string; begin //Return the color depth, including whether the image is grayscale or paletted case Png.Header.ColorType of COLOR_GRAYSCALE, COLOR_GRAYSCALEALPHA: Result := Format('%d-bits grayscale', [Png.Header.BitDepth]); COLOR_RGB, COLOR_RGBALPHA: Result := Format('%d-bits', [Png.Header.BitDepth * 3]); COLOR_PALETTE: Result := Format('%d-bits paletted', [Png.Header.BitDepth]); end; end; function GetTransparency(Png: TPngImage): string; begin //Return the formatted transparency depth, or transparency mode if Png.Header.ColorType in [COLOR_GRAYSCALEALPHA, COLOR_RGBALPHA] then Result := Format('%d-bits alpha', [Png.Header.BitDepth]) else case Png.TransparencyMode of ptmBit: Result := 'bitmask'; ptmPartial: Result := 'indexed'; else Result := 'none'; end; end; function GetCompression(Png: TPngImage): string; begin //Return the formatted compression level Result := Format('level %d', [Png.CompressionLevel]); end; function GetFiltering(Png: TPngImage): string; begin //Return the formatted filtering method case Png.Header.FilterMethod of FILTER_SUB: Result := 'sub'; FILTER_UP: Result := 'up'; FILTER_AVERAGE: Result := 'average'; FILTER_PAETH: Result := 'paeth'; else Result := 'none'; end; end; function SameBackgroundColor: Boolean; var FirstBgColor: TColor; I: Integer; First: Boolean; begin //Determine whether the background color of all selected images is the same FirstBgColor := clNone; First := True; Result := True; for I := 0 to lbxImages.Items.Count - 1 do if lbxImages.Selected[I] then if First then begin //Found the first selected and its background color FirstBgColor := Images.Items[I].Background; First := False; end else begin //If not equal to first background color, then break, continue otherwise Result := FirstBgColor = Images.Items[I].Background; if not Result then Break; end; end; const NoneSelected = '[ none ]'; MultipleSelected = '[ multiple ]'; begin with lbxImages do begin //Refresh the enabled state of the buttons and controls btnReplace.Enabled := SelCount = 1; btnDelete.Enabled := SelCount > 0; btnClear.Enabled := Items.Count > 0; btnUp.Enabled := (SelCount > 0) and (FirstSelected > 0); btnDown.Enabled := (SelCount > 0) and (LastSelected < Items.Count - 1); lblName.Enabled := SelCount = 1; edtName.Enabled := SelCount = 1; lblBackgroundColor.Enabled := SelCount > 0; cmbBackgroundColor.Enabled := SelCount > 0; case SelCount of 0: begin //None is selected, so no information to display lblDimensionsValue.Caption := NoneSelected; lblColorDepthValue.Caption := NoneSelected; lblTransparencyValue.Caption := NoneSelected; lblCompressionValue.Caption := NoneSelected; lblFilteringValue.Caption := NoneSelected; end; 1: with Images.Items[FirstSelected] do begin edtName.OnChange := nil; try //One item is selected, display its properties and information edtName.Text := Name; SelectBackgroundColor(Sender, Background); lblDimensionsValue.Caption := GetDimensions(PngImage); lblColorDepthValue.Caption := GetColorDepth(PngImage); lblTransparencyValue.Caption := GetTransparency(PngImage); lblCompressionValue.Caption := GetCompression(PngImage); lblFilteringValue.Caption := GetFiltering(PngImage); finally edtName.OnChange := edtNameChange; end; end; else begin //More than 1 is selected, so no image information can be displayed if SameBackgroundColor then SelectBackgroundColor(Sender, Images.Items[FirstSelected].Background) else SelectBackgroundColor(Sender, clNone); lblDimensionsValue.Caption := MultipleSelected; lblColorDepthValue.Caption := MultipleSelected; lblTransparencyValue.Caption := MultipleSelected; lblCompressionValue.Caption := MultipleSelected; lblFilteringValue.Caption := MultipleSelected; end; end; end; end; procedure TCustomPngImageListEditorDlg.lbxImagesDblClick(Sender: TObject); begin //Doubleclicking is the same as the Replace button if lbxImages.SelCount = 1 then btnReplaceClick(nil); end; procedure TCustomPngImageListEditorDlg.lbxImagesDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure MoveItem(Index, Delta: Integer); begin //Move a single item up or down, depending on Delta if lbxImages.Selected[Index] then begin Images.Items[Index].Index := Index + Delta; lbxImages.Items.Exchange(Index, Index + Delta); lbxImages.Selected[Index + Delta] := True; end; end; function InRange(Index: Integer): Boolean; begin //Return whether Index exists in the listbox Result := (Index >= 0) and (Index < lbxImages.Items.Count); end; var NewIndex, NewItemIndex, Delta, I: Integer; begin Accept := FDraggingIndex >= 0; if Accept then begin //Figure out to which index is dragged NewIndex := lbxImages.ItemAtPos(Point(X, Y), False); if NewIndex > lbxImages.Items.Count - 1 then NewIndex := lbxImages.Items.Count - 1; //Figure out the distance (delta) of the drag Delta := NewIndex - FDraggingIndex; //The destination index has to exist and has to be differend from where we //started the drag. On to pof that, the drag destination of the first and //last selected items have to be in range. if (NewIndex >= 0) and (NewIndex <> FDraggingIndex) and InRange(FirstSelected + Delta) and InRange(LastSelected + Delta) then begin //Calc the new focus index NewItemIndex := lbxImages.ItemIndex + Delta; //To prevent things to get messed up, moving downwards needs walking through the //images in opposite direction if Delta < 0 then for I := 0 to lbxImages.Items.Count - 1 do MoveItem(I, Delta) else for I := lbxImages.Items.Count - 1 downto 0 do MoveItem(I, Delta); //Set the new focus index and tracking value of the drag lbxImages.ItemIndex := NewItemIndex; FDraggingIndex := NewIndex; lbxImagesClick(nil); end; end; end; procedure TCustomPngImageListEditorDlg.lbxImagesDrawItem(Control: TWinControl; Index: Integer; ARect: TRect; State: TOwnerDrawState); var DrawRect: TRect; ScrollInfo: TScrollInfo; I, ScrollPos: Integer; begin //Get the scrolling distance ScrollPos := 0; ScrollInfo.cbSize := SizeOf(ScrollInfo); ScrollInfo.fMask := SIF_POS; if GetScrollInfo(lbxImages.Handle, SB_VERT, ScrollInfo) then for I := 0 to ScrollInfo.nPos - 1 do with lbxImages.ItemRect(I) do Inc(ScrollPos, Bottom - Top); //First, draw the background if odSelected in State then if lbxImages.Focused then DrawBackground(lbxImages.Canvas, ARect, ScrollPos, cmbPreviewBackground.ItemIndex, FSelectionBodyColor) else DrawBackground(lbxImages.Canvas, ARect, ScrollPos, cmbPreviewBackground.ItemIndex, Blend(FSelectionBodyColor, clWindow, 50)) else DrawBackground(lbxImages.Canvas, ARect, ScrollPos, cmbPreviewBackground.ItemIndex); with lbxImages.Canvas do begin //Then, draw a focus border, if focused Brush.Style := bsClear; if odFocused in State then begin if lbxImages.Focused then Pen.Color := FSelectionBorderColor else Pen.Color := Blend(FSelectionBorderColor, clWindow, 50); Pen.Style := psSolid; Rectangle(ARect); end; //Draw the image at the center of (ARect.Left, ARect.Top, ARect.Left + FMaxWidth, ARect.Bottom) with Images.Items[Index] do begin {$IF RTLVersion < 23 } if (ARect.Right - ARect.Left) < PngImage.Height then begin DrawRect.Left := ARect.Left + 2; DrawRect.Top := ARect.Top; DrawRect.Right := DrawRect.Left + Round(PngImage.Width * (ARect.Right - ARect.Left)/PngImage.Height); DrawRect.Bottom := ARect.Bottom; end else begin DrawRect.Left := ARect.Left + (FMaxWidth - PngImage.Width) div 2 + 2; DrawRect.Top := ARect.Top + (ARect.Bottom - ARect.Top - PngImage.Height) div 2; DrawRect.Right := DrawRect.Left + PngImage.Width; DrawRect.Bottom := DrawRect.Top + PngImage.Height; end; {$ELSE} if ARect.Height < PngImage.Height then begin DrawRect.Left := ARect.Left + 2; DrawRect.Top := ARect.Top; DrawRect.Right := DrawRect.Left + Round(PngImage.Width * ARect.Height/PngImage.Height); DrawRect.Bottom := ARect.Bottom; end else begin DrawRect.Left := ARect.Left + (FMaxWidth - PngImage.Width) div 2 + 2; DrawRect.Top := ARect.Top + (ARect.Bottom - ARect.Top - PngImage.Height) div 2; DrawRect.Right := DrawRect.Left + PngImage.Width; DrawRect.Bottom := DrawRect.Top + PngImage.Height; end; {$IFEND} PngImage.Draw(lbxImages.Canvas, DrawRect); end; //Draw the image index number and the name Font.Color := clWindowText; DrawRect := Rect(ARect.Left + FMaxWidth + 8, ARect.Top, ARect.Left + FMaxWidth + Canvas.TextWidth(IntToStr(lbxImages.Items.Count - 1)) + 8, ARect.Bottom); DrawText(Handle, PChar(IntToStr(Index)), -1, DrawRect, DT_RIGHT or DT_NOPREFIX or DT_SINGLELINE or DT_VCENTER); DrawRect.Left := DrawRect.Right; DrawRect.Right := ARect.Right; DrawText(Handle, PChar(' - ' + Images.Items[Index].Name), -1, DrawRect, DT_END_ELLIPSIS or DT_LEFT or DT_NOPREFIX or DT_SINGLELINE or DT_VCENTER); //Draw the normal focusrect, so that it'll become invisible if (odFocused in State) and lbxImages.Focused then DrawFocusRect(ARect); end; end; procedure TCustomPngImageListEditorDlg.lbxImagesEnter(Sender: TObject); begin //Just to be sure lbxImages.Repaint; end; procedure TCustomPngImageListEditorDlg.lbxImagesExit(Sender: TObject); begin //Just to be sure lbxImages.Repaint; end; procedure TCustomPngImageListEditorDlg.lbxImagesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin //I would expect this "ctrl"-navigation would work standardly, but appearantly //it doesn't, so we'll have to code it ourselves with lbxImages do if ssCtrl in Shift then begin case Key of VK_DOWN: begin if ItemIndex < Items.Count - 1 then ItemIndex := ItemIndex + 1; Key := 0; end; VK_UP: begin if ItemIndex > 0 then ItemIndex := ItemIndex - 1; Key := 0; end; VK_SPACE: begin Selected[ItemIndex] := not Selected[ItemIndex]; lbxImagesClick(nil); Key := 0; end; end; end; end; procedure TCustomPngImageListEditorDlg.lbxImagesMeasureItem(Control: TWinControl; Index: Integer; var Height: Integer); var Temp: Integer; begin //Figure out the height of an item, when editing an image collection, the height //of an image may differ Height := Images.Items[Index].PngImage.Height + 4; Temp := lbxImages.Canvas.TextHeight('0') + 4; if Temp > Height then Height := Temp; if Height > 255 then Height := 255; end; procedure TCustomPngImageListEditorDlg.lbxImagesMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin //If the mouse button is released, the tracking value of the drag needs to be //reset as well FDraggingIndex := -1; end; procedure TCustomPngImageListEditorDlg.lbxImagesStartDrag(Sender: TObject; var DragObject: TDragObject); var Pos: TPoint; begin //Figure out where this drag start is GetCursorPos(Pos); FDraggingIndex := lbxImages.ItemAtPos(lbxImages.ScreenToClient(Pos), True); if FDraggingIndex >= 0 then lbxImages.ItemIndex := FDraggingIndex; end; initialization InitResolution; end.
unit uSceneAbout; interface uses uScene, Graphics, uGraph, uResFont, uButton; type TSceneAbout = class(TSceneCustom) private FLogo: TBitmap; FIsLoad: Boolean; FGraph: TGraph; FFont: TResFont; FButton: TButton; procedure Load; public //** Конструктор. constructor Create; destructor Destroy; override; procedure Draw(); override; function MouseDown(Button: TMouseBtn; X, Y: Integer): Boolean; override; function MouseMove(X, Y: Integer): Boolean; override; function Click(Button: TMouseBtn): Boolean; override; function Keys(var Key: Word): Boolean; override; end; implementation uses Types, uSCR, uUtils, uIni, uSceneMenu, uGUIBorder, uSounds, uMain; { TAboutScene } function TSceneAbout.Click(Button: TMouseBtn): Boolean; begin Result := True; if FButton.MouseOver then begin SceneManager.SetScene(SceneMenu); Sound.PlayClick; end; end; procedure TSceneAbout.Draw; begin if not FIsLoad then Load; FButton.Draw; SCR.BG.Canvas.Draw(0, 0, FLogo); end; constructor TSceneAbout.Create; begin FIsLoad := False; FGraph := TGraph.Create(Path + 'Data\Images\Screens\'); FFont := TResFont.Create; FFont.LoadFromFile(Path + 'Data\Fonts\' + Ini.FontName); end; function TSceneAbout.Keys(var Key: Word): Boolean; begin Result := True; case Key of 13: begin SceneManager.SetScene(SceneMenu); Sound.PlayClick; end; 27: SceneManager.SetScene(SceneMenu); end; end; destructor TSceneAbout.Destroy; begin FButton.Free; FGraph.Free; FLogo.Free; FFont.Free; inherited; end; procedure TSceneAbout.Load; procedure AddLine(Y, FontSize: Integer; S: string; C: Integer = $00103C49); begin FGraph.DrawText(S, FLogo, 450, Y, FFont.FontName, FontSize, C); end; begin FIsLoad := True; FLogo := TBitmap.Create; FGraph.LoadImage('About.jpg', FLogo); GUIBorder.Make(FLogo); FLogo.Canvas.Brush.Style := bsClear; AddLine(200, 24, 'программирование'); AddLine(240, 20, 'Ткач Сергей, Фомин Влад', $0028485B); AddLine(300, 24, 'графика и дизайн'); AddLine(340, 20, 'Диров Илья', $0028485B); FButton := TButton.Create(590, 540, FLogo.Canvas, 'Назад'); FButton.Sellected := True; end; function TSceneAbout.MouseMove(X, Y: Integer): Boolean; begin Result := False; FButton.Draw; SceneManager.Draw; end; function TSceneAbout.MouseDown(Button: TMouseBtn; X, Y: Integer): Boolean; begin Result := False; FButton.MouseDown(X, Y); SceneManager.Draw; end; end.
unit GX_MacroLibraryConfig; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, GX_BaseForm; type TfmGxMacroLibraryConfig = class(TfmBaseForm) chk_AutoPrompt: TCheckBox; b_Ok: TButton; b_Cancel: TButton; private public class function Execute(var APromptForName: Boolean): Boolean; end; implementation {$R *.dfm} { TfmGxMacroLibraryConfig } class function TfmGxMacroLibraryConfig.Execute(var APromptForName: Boolean): Boolean; var frm: TfmGxMacroLibraryConfig; begin frm := TfmGxMacroLibraryConfig.Create(nil); try frm.chk_AutoPrompt.Checked := APromptForName; Result := mrOk = frm.ShowModal; if Result then APromptForName := frm.chk_AutoPrompt.Checked; finally FreeAndNil(frm); end; end; end.
unit Script.Engine; interface uses Script.Interfaces ; type TscriptEngine = class public class procedure RunScript(const aFileName: String; const aLog: IscriptLog); end;//TscriptEngine implementation uses System.SysUtils, Script.Parser, Testing.Engine, Script.Code, Script.WordsInterfaces ; class procedure TscriptEngine.RunScript(const aFileName: String; const aLog: IscriptLog); var l_Parser : TscriptParser; l_Context : TscriptCompileContext; begin TtestEngine.StartTest(aFileName); try l_Context := TscriptCompileContext.Create(aLog); try l_Parser := TscriptParser.Create(aFileName); try while not l_Parser.EOF do begin l_Parser.NextToken; if (aLog <> nil) then aLog.Log(l_Parser.TokenString) end;//while not l_Parser.EOF finally FreeAndNil(l_Parser); end;//try..finally finally FreeAndNil(l_Context); end;//try..finally finally TtestEngine.StopTest; end;//try..finally end; end.
unit wwStarMind; interface uses Types, Contnrs, wwTypes, wwMinds; type TwwNode = class (TObject) private FCostFromStart: Integer; FCostToFinish: Integer; FFinish: TPoint; FParent: TPoint; FPosition: TPoint; FStart: TPoint; function GetCost: Integer; public constructor Create(aPosition, aStart, aFinish : TPoint); reintroduce; function Clone: TwwNode; function CreateNear(aDirection: TwwDirection): TwwNode; property Cost: Integer read GetCost; property CostFromStart: Integer read FCostFromStart write FCostFromStart; property CostToFinish: Integer read FCostToFinish write FCostToFinish; property Parent: TPoint read FParent write FParent; property Position: TPoint read FPosition; end; TwwNodeList = class (TObjectList) public procedure AddNode(aNode: TwwNode); virtual; function HaveNode(aNode: TwwNode): Boolean; function NodeAt(aPoint: TPoint): TwwNode; procedure RemoveNode(aNode: TwwNode); virtual; end; TwwSortedNodeList = class (TwwNodeList) public procedure AddNode(aNode: TwwNode); override; procedure RemoveNode(aNode: TwwNode); override; end; TAStarMind = class (TwwMind) private f_Open: TwwSOrtedNodeList; f_Closed: TwwNodeList; private function CalcCost(A, B: TPoint): Integer; function FindDir(A, B: TPoint): TwwDirection; function DummyThing: TwwDirection; protected function GetCaption: string; override; function GetEnglishCaption: string; override; function Thinking: TwwDirection; override; public constructor Create; destructor Destroy; override; end; implementation Uses wwUtils, wwWorms, WormsWorld, wwClasses, Math; { ********************************** TAStarMind ********************************** } function TAStarMind.CalcCost(A, B: TPoint): Integer; begin (* if (IsFree(A) or Equal(A, Thing.Head.Position)) and IsFree(B) then Result:= CalcDistance(A, B) else Result:= High(Word); *) Result:= 1; if IsBusy(A) and not Equal(A, Thing.Head.Position) then Inc(Result, High(Word)); if IsBusy(B) then Inc(Result, High(Word)); end; constructor TAStarMind.Create; begin inherited Create; f_Open:= TwwSOrtedNodeList.Create; f_Closed:= TwwNodeList.Create; end; destructor TAStarMind.Destroy; begin f_Open.Free; f_Closed.Free; inherited; end; function TAStarMind.DummyThing: TwwDirection; var l_W: TwwWorm; NewHead: TPoint; TargetDir, NewDir: TwwDirection; LegalDirs: TwwDirections; begin l_W:= Thing as TwwWorm; TargetDir:= CalcDir(l_W.Head.Position, l_W.Target.Head.Position, l_W.Favorite); if (TargetDir = l_W.ToNeck) then begin if l_W.Favorite = ftVertical then TargetDir:= CalcDir(l_W.Head.Position, l_W.Target.Head.Position, ftHorizontal) else TargetDir:= CalcDir(l_W.Head.Position, l_W.Target.Head.Position, ftVertical) end; NewDir:= TargetDir; MovePoint(l_W.Head.Position, NewDir, NewHead); LegalDirs:= MoveDirs; if IsBusy(NewHead) then begin Exclude(LegalDirs, TargetDir); if IsMe(NewHead) then begin NewDir:= l_W.ToTail(NewHead); Exclude(LegalDirs, InvertDir(NewDir)); repeat if not CheckPoint(l_W.Head.Position, NewDir) then begin Exclude(LegalDirs, NewDir); if LegalDirs <> [] then begin NewDir:= ShiftDir(NewDir); end else begin NewDir:= dtStop; break; end; end else break until False; end else repeat if not CheckPoint(l_W.Head.Position, NewDir) then begin Exclude(LegalDirs, NewDir); if LegalDirs <> [] then begin NewDir:= ShiftDir(NewDir); end else begin NewDir:= dtStop; break; end; end else break until False; end; Result:= NewDir; end; function TAStarMind.FindDir(A, B: TPoint): TwwDirection; var l_Start, l_Current, l_NearCurrent: TwwNode; l_Skip: Boolean; i: TwwDirection; l_CostFrom: Integer; l_AllowFree: Boolean; l_Mem0, l_Mem1: Int64; procedure CreateRoad(aNode: TwwNode); var l_N: TwwNode; begin Result:= dtStop; l_N:= aNode; while not Equal(l_N.Position, A) and IsFree(l_N.Position) do begin Result:= CalcDir(l_N.Parent, l_N.Position, ftVertical); l_N:= f_Closed.NodeAt(l_N.Parent); if not CheckPoint(Thing.Head.Position, Result) then Result:= dtStop; end; end; begin Result:= dtStop; l_Start:= TwwNode.Create(A, A, B); f_Open.AddNode(l_Start); // Список владеет объектом l_Start, удалять нельзя while f_Open.Count <> 0 do begin l_Current:= TwwNode(f_Open.First).Clone; // Сделали копию объекта, потом нужно грохнуть f_Open.RemoveNode(l_Current); // Уничтожили оригинал объекта if Equal(l_Current.Position, B) then begin CreateRoad(l_Current); l_Current.Free; break; end; for i:= dtLeft to dtDown do begin l_AllowFree:= True; l_NearCurrent:= l_Current.CreateNear(i); // Создали дополнительный объект if IsFree(l_NearCurrent.Position) then begin l_CostFrom:= l_Current.CostFromStart + CalcCost(l_Current.Position, l_NearCurrent.Position); l_Skip:= (f_Open.HaveNode(l_NearCurrent) or f_Closed.HaveNode(l_NearCurrent)) and (l_NearCurrent.CostFromStart <= l_CostFrom); if not l_Skip then begin l_NearCurrent.CostFromStart:= l_CostFrom; f_Closed.RemoveNode(l_NearCurrent); // Удаляем объект, указывающий на Position if not f_Open.HaveNode(l_NearCurrent) then begin f_Open.AddNode(l_NearCurrent); // Добавили объект в список, уничтожать нельзя l_AllowFree:= False; end; // not l_Open.HaveNode(l_NearCurrent) end; // подходящий узел end; // IsFree(l_NearCurrent.Position) if l_AllowFree then l_NearCurrent.Free; // Уничтожили дополнительный объект end; // for i f_Closed.AddNode(l_Current); // добавили объект в список end; // while l_Open.Count <> 0 f_Open.Clear; f_Closed.Clear; end; function TAStarMind.GetCaption: string; begin Result:= 'Тугодум' end; function TAStarMind.GetEnglishCaption: string; begin Result:= 'Slowcoach' end; function TAStarMind.Thinking: TwwDirection; var l_W: TwwWorm; i: Integer; l_T: TwwThing; begin l_W:= Thing as TwwWorm; l_W.Target:= (Thing.World as TWormsField).NearestTarget(Thing.Head.Position); if IsBusy(l_W.Target.Head.Position) then begin l_T:= l_W.Target; for i:= 0 to Pred((Thing.World as TWormsField).TargetCount) do begin if (Thing.World as TWormsField).Targets[i] <> l_T then begin l_W.Target:= (Thing.World as TWormsField).Targets[i]; if IsFree(l_W.Target.Head.Position) then break; end end; end; Result:= FindDir(l_W.Head.Position, l_W.Target.Head.Position); if Result = dtStop then begin l_T:= l_W.Target; for i:= 0 to Pred((Thing.World as TWormsField).TargetCount) do begin if (Thing.World as TWormsField).Targets[i] <> l_T then begin l_W.Target:= (Thing.World as TWormsField).Targets[i]; Result:= FindDir(l_W.Head.Position, l_W.Target.Head.Position); if Result <> dtStop then break; end; // (Thing.World as TWormsField).Targets[i] <> l_T end; // for i if Result = dtStop then begin l_W.Target:= l_T; Result:= DummyThing; end; // Result = dtStop end; // Result = dtStop end; { *********************************** TwwNode ************************************ } constructor TwwNode.Create(aPosition, aStart, aFinish : TPoint); begin inherited Create; FStart:= aStart; FFinish:= aFinish; FPosition:= aPosition; FCostFromStart:= CalcDistance(aStart, FPosition); FCostToFinish:= CalcDistance(FPosition, aFinish); FParent:= Point(0, 0); end; function TwwNode.Clone: TwwNode; begin Result:= TwwNode.Create(FPOsition, FStart, FFinish); Result.CostFromStart:= CostFromStart; Result.CostToFinish:= CostToFinish; Result.Parent:= Parent; end; function TwwNode.CreateNear(aDirection: TwwDirection): TwwNode; var l_Pos: TPoint; begin MovePoint(FPosition, aDirection, l_Pos); Result:= TwwNode.Create(l_Pos, FStart, FFinish); Result.Parent:= FPosition; end; function TwwNode.GetCost: Integer; begin Result:= CostFromStart + CostToFinish; end; { ********************************* TwwNodeList ********************************** } procedure TwwNodeList.AddNode(aNode: TwwNode); begin Add(aNode{.Clone}); end; function TwwNodeList.HaveNode(aNode: TwwNode): Boolean; begin Result:= NodeAt(aNode.Position) <> nil; end; function TwwNodeList.NodeAt(aPoint: TPoint): TwwNode; var I: Integer; begin Result:= nil; for i:= 0 to Pred(Count) do if Equal(TwwNode(Items[i]).Position, aPoint) then begin Result:= TwwNode(Items[i]); break; end; end; procedure TwwNodeList.RemoveNode(aNode: TwwNode); var I: Integer; l_N: TwwNode; begin for i:= 0 to Pred(Count) do begin l_N:= TwwNode(Items[i]); if Equal(aNode.Position, l_N.Position) then begin Remove(l_N); //Delete(i); break; end; // Equal(aNode.Position, l_N.Position) end // for i end; function CompareCost(Item1, Item2: TObject): Integer; begin Result := CompareValue((Item1 as TwwNode).Cost, TwwNode(Item2).Cost); end; { ****************************** TwwSortedNodeList ******************************* } procedure TwwSortedNodeList.AddNode(aNode: TwwNode); begin inherited AddNode(aNode); Sort(@CompareCost); end; procedure TwwSortedNodeList.RemoveNode(aNode: TwwNode); begin inherited; Sort(@CompareCost); end; end.
unit Animations; interface uses Windows, SpriteImages; type TAnimation = class public constructor Create(Image : TFrameImage; x, y : integer); destructor Destroy; override; public procedure Tick; private fImage : TFrameImage; fPos : TPoint; fFrame : dword; fLastFrameUpdate : dword; public property Image : TFrameImage read fImage; property Pos : TPoint read fPos; property Frame : dword read fFrame; end; implementation uses Classes; constructor TAnimation.Create(Image : TFrameImage; x, y : integer); begin inherited Create; fImage := Image; fPos := Point(x, y); fLastFrameUpdate := GetTickCount; end; destructor TAnimation.Destroy; begin inherited; end; procedure TAnimation.Tick; var curtickcount : cardinal; begin curtickcount := GetTickCount; if curtickcount - fLastFrameUpdate > fImage.FrameDelay[fFrame] then begin if fFrame < pred(fImage.FrameCount) then inc(fFrame) else fFrame := 0; fLastFrameUpdate := curtickcount; end; end; end.
unit tablefrm; interface uses Classes, Forms, Buttons, SysUtils, vg_grid, vg_layouts, vg_scene, Controls, vg_controls, ImgList, vg_actions, Grids; type TfrmTableDemo = class(TForm) vgScene1: TvgScene; Root1: TvgBackground; Table1: TvgGrid; Column1: TvgColumn; CheckColumn1: TvgCheckColumn; ProgressColumn1: TvgProgressColumn; Column2: TvgColumn; PopupColumn1: TvgPopupColumn; ToolBar1: TvgToolBar; ImageColumn1: TvgImageColumn; vgImageList1: TvgImageList; procedure Table1GetValue(Sender: TObject; const Col, Row: Integer; var Value: Variant); procedure Table1SetValue(Sender: TObject; const Col, Row: Integer; const Value: Variant); procedure Table1EdititingDone(Sender: TObject; const Col, Row: Integer); private { Private declarations } public { Public declarations } Data: array of array of Variant; procedure CreateData; end; var frmTableDemo: TfrmTableDemo; implementation {$R *.dfm} { TfrmTableDemo } procedure TfrmTableDemo.Table1GetValue(Sender: TObject; const Col, Row: Integer; var Value: Variant); begin if Length(Data) = 0 then begin // Init Data arrays CreateData; end; // we not use Col - because Col return Column - but Column may realigned Value := Data[Table1.Columns[Col].Tag][Row]; end; procedure TfrmTableDemo.Table1SetValue(Sender: TObject; const Col, Row: Integer; const Value: Variant); begin // we not use Col - because Col return Column - but Column may realigned Data[Table1.Columns[Col].Tag][Row] := Value; end; procedure TfrmTableDemo.CreateData; var i: integer; begin // set table row count Table1.RowCount := 300; // set column Tag - this is real index - because Column may realign for i := 0 to Table1.ColumnCount - 1 do Table1.Columns[i].Tag := i; // create array SetLength(Data, Table1.ColumnCount); for i := 0 to High(Data) do begin SetLength(Data[i], Table1.RowCount); end; // Initialize Data // 0 Column - text for i := 0 to Table1.RowCount - 1 do Data[0][i] := 'text cell ' + IntToStr(i); // 1 Column - check for i := 0 to Table1.RowCount - 1 do Data[1][i] := random(3) = 2; // 2 Column - progress for i := 0 to Table1.RowCount - 1 do Data[2][i] := random(100); // 3 Column - text for i := 0 to Table1.RowCount - 1 do Data[3][i] := 'second text ' + IntToStr(i); // 4 Column - popup for i := 0 to Table1.RowCount - 1 do Data[4][i] := PopupColumn1.Items[random(PopupColumn1.Items.Count)]; // 5 Column - image for i := 0 to Table1.RowCount - 1 do Data[5][i] := ObjectToVariant(vgImageList1.Images[random(vgImageList1.Count)]); end; procedure TfrmTableDemo.Table1EdititingDone(Sender: TObject; const Col, Row: Integer); begin Caption := 'Cell ' + IntToStr(Col) + ':' + IntToStr(Row) + ' was changed'; end; end.
unit Unit8; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, System.LogEvents.Progress, System.LogEvents, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Samples.Spin; type TForm8 = class(TForm) Button1: TButton; SpinEdit1: TSpinEdit; Label1: TLabel; procedure Button1Click(Sender: TObject); private procedure Prog(msg: string; ATipo: TLogEventType); { Private declarations } public { Public declarations } end; var Form8: TForm8; implementation {$R *.dfm} const LSeed = 10000; procedure TForm8.Prog(msg: string; ATipo: TLogEventType); var n,x: integer; begin LogEvents.DoProgress(self, 0, ATipo, msg); n := Random(LSeed); //sleep(n); LogEvents.Sleep(n); //TThread.Sleep(n); end; procedure TForm8.Button1Click(Sender: TObject); var LProgr: IProgressEvents; i: integer; begin // inicializa a janela de progresso LogEvents.Syncronized := false; LProgr := TProgressEvents.new; LProgr.max := 1000; // opcional: marca o número máximo itens LProgr.MaxThreads := SpinEdit1.Value; // indica o número máximo de threads em paralelo LProgr.CanCancel := false; // marca se pode cancelar a operação for i := 1 to 100 do begin // loop de demonstração - simulando uma lista de processos LProgr.Text := 'Produto: ' + intToStr(i); // texto livre LProgr.add(i, 'Produto: ' + intToStr(i), // processo a executar procedure(x: integer) var n: integer; msg: string; begin msg := 'Produto: ' + intToStr(x); // processo em execução LogEvents.DoProgress(self, 0, etCreating, msg); Prog(msg, etWaiting); Prog(msg, etStarting); Prog(msg, etPreparing); Prog(msg, etLoading); Prog(msg, etCalc); Prog(msg, etWorking); Prog(msg, etSaving); Prog(msg, etEnding); Prog(msg, etFinished); end); if LProgr.Terminated then break; end; LogEvents.DoProgress(self, 0, etAllFinished, ''); // sinaliza que todas os processo foram completados. end; end.
unit DW.Macapi.Helpers; {*******************************************************} { } { Kastri } { } { Delphi Worlds Cross-Platform Library } { } { Copyright 2020-2021 Dave Nottage under MIT license } { which is located in the root folder of this library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses // RTL System.Classes, // macOS {$IF Defined(MACOS)} Macapi.CoreFoundation, {$ENDIF} {$IF Defined(MACDEV)} Macapi.Foundation, Macapi.AppKit; {$ENDIF} // iOS {$IF Defined(IOS)} iOSapi.Foundation; {$ENDIF} type TNSDictionaryHelper = record private FDictionary: NSDictionary; function GetValuePtr(const AKey: string): Pointer; public constructor Create(const ADictionary: NSDictionary); function GetValue(const AKey: string; const ADefault: Double = 0): Double; overload; function GetValue(const AKey: string; const ADefault: Integer = 0): Integer; overload; function GetValue(const AKey: string; const ADefault: string = ''): string; overload; end; TNSMutableDictionaryHelper = record private FDictionary: NSMutableDictionary; public constructor Create(const ADictionary: NSMutableDictionary); function Dictionary: NSDictionary; procedure SetValue(const AValue: Integer; const AKey: string); overload; procedure SetValue(const AValue, AKey: string); overload; end; TNSArrayHelper = record public class function FromNSObjects(const AArray: array of NSObject): NSArray; static; end; TMacHelperEx = record public // class function GetLocationManagerAuthorization: TAuthorizationType; static; // class function NSDictionaryToJSON(const ADictionary: NSDictionary): string; static; class function GetBundleValue(const AKey: string): string; static; class function GetBundleValueNS(const AKey: string): NSString; static; class function MainBundle: NSBundle; static; {$IF Defined(MACDEV)} class function SharedApplication: NSApplication; static; {$ENDIF} class function StandardUserDefaults: NSUserDefaults; static; end; /// <summary> /// Retrieves cocoa double constant /// </summary> function CocoaDoubleConst(const AFwk: string; const AConstStr: string): Double; /// <summary> /// Retrieves a number value from an NSDictionary, with optional default (otherwise zero) /// </summary> function GetDictionaryNumberValue(const ADictionary: NSDictionary; const AKey: NSString; const ADefault: Double = 0): Double; /// <summary> /// Retrieves a string value from an NSDictionary, with optional default (otherwise blank) /// </summary> function GetDictionaryStringValue(const ADictionary: NSDictionary; const AKey: NSString; const ADefault: string = ''): string; /// <summary> /// Converts GMT to local time /// </summary> function GetLocalDateTime(const ADateTime: TDateTime): TDateTime; /// <summary> /// Puts string values from an NSArray into an string array /// </summary> function NSArrayToStringArray(const AArray: NSArray): TArray<string>; /// <summary> /// Puts string values from an array into an NSArray /// </summary> function StringArrayToNSArray(const AArray: array of string; const ADequote: Boolean = False): NSArray; /// <summary> /// Puts string values from a TStrings into an NSArray /// </summary> function StringsToNSArray(const AStrings: TStrings; const ADequote: Boolean = False): NSArray; /// <summary> /// Converts a string directly into an NSString reference (ID) /// </summary> function StrToObjectID(const AStr: string): Pointer; /// <summary> /// Converts a string into an CFStringRef /// </summary> function StrToCFStringRef(const AStr: string): CFStringRef; implementation uses // RTL System.DateUtils, System.SysUtils, // macOS Macapi.ObjectiveC, Macapi.Helpers; { TNSDictionaryHelper } constructor TNSDictionaryHelper.Create(const ADictionary: NSDictionary); begin FDictionary := ADictionary; end; function TNSDictionaryHelper.GetValuePtr(const AKey: string): Pointer; begin Result := FDictionary.valueForKey(StrToNSStr(AKey)); end; function TNSDictionaryHelper.GetValue(const AKey: string; const ADefault: Double = 0): Double; var LValuePtr: Pointer; begin Result := ADefault; LValuePtr := GetValuePtr(AKey); if LValuePtr <> nil then Result := TNSNumber.Wrap(LValuePtr).doubleValue; end; function TNSDictionaryHelper.GetValue(const AKey: string; const ADefault: Integer = 0): Integer; var LValuePtr: Pointer; begin Result := ADefault; LValuePtr := GetValuePtr(AKey); if LValuePtr <> nil then Result := TNSNumber.Wrap(LValuePtr).integerValue; end; function TNSDictionaryHelper.GetValue(const AKey: string; const ADefault: string = ''): string; var LValuePtr: Pointer; begin Result := ADefault; LValuePtr := GetValuePtr(AKey); if LValuePtr <> nil then Result := NSStrToStr(TNSString.Wrap(LValuePtr)); end; { TNSMutableDictionaryHelper } constructor TNSMutableDictionaryHelper.Create(const ADictionary: NSMutableDictionary); begin FDictionary := ADictionary; end; function TNSMutableDictionaryHelper.Dictionary: NSDictionary; begin Result := TNSDictionary.Wrap(NSObjectToID(FDictionary)); end; procedure TNSMutableDictionaryHelper.SetValue(const AValue: Integer; const AKey: string); begin FDictionary.setObject(TNSNumber.OCClass.numberWithInt(AValue), NSObjectToID(StrToNSStr(AKey))); end; procedure TNSMutableDictionaryHelper.SetValue(const AValue, AKey: string); begin FDictionary.setObject(NSObjectToID(StrToNSStr(AValue)), NSObjectToID(StrToNSStr(AKey))); end; function GetDictionaryNumberValue(const ADictionary: NSDictionary; const AKey: NSString; const ADefault: Double = 0): Double; var LValuePtr: Pointer; begin Result := ADefault; LValuePtr := ADictionary.valueForKey(AKey); if LValuePtr <> nil then Result := TNSNumber.Wrap(LValuePtr).doubleValue; end; function GetDictionaryStringValue(const ADictionary: NSDictionary; const AKey: NSString; const ADefault: string = ''): string; var LValuePtr: Pointer; begin Result := ADefault; LValuePtr := ADictionary.valueForKey(AKey); if LValuePtr <> nil then Result := NSStrToStr(TNSString.Wrap(LValuePtr)); end; function CocoaDoubleConst(const AFwk: string; const AConstStr: string): Double; var LObj: Pointer; begin LObj := CocoaPointerConst(AFwk, AConstStr); if LObj <> nil then Result := Double(LObj^) else Result := 0; end; function NSArrayToStringArray(const AArray: NSArray): TArray<string>; var I: Integer; begin for I := 0 to AArray.count - 1 do Result := Result + [NSStrToStr(TNSString.Wrap(AArray.objectAtIndex(I)))]; end; function StringsToNSArray(const AStrings: TStrings; const ADequote: Boolean = False): NSArray; var LArray: array of Pointer; I: Integer; LString: string; begin SetLength(LArray, AStrings.Count); for I := 0 to AStrings.Count - 1 do begin LString := AStrings[I]; if ADequote then LString := AnsiDequotedStr(LString, '"'); LArray[I] := NSObjectToID(StrToNSStr(LString)); end; Result := TNSArray.Wrap(TNSArray.OCClass.arrayWithObjects(@LArray[0], Length(LArray))); end; function StringArrayToNSArray(const AArray: array of string; const ADequote: Boolean = False): NSArray; var LArray: array of Pointer; I: Integer; LString: string; begin SetLength(LArray, Length(AArray)); for I := 0 to Length(AArray) - 1 do begin LString := AArray[I]; if ADequote then LString := AnsiDequotedStr(LString, '"'); LArray[I] := NSObjectToID(StrToNSStr(LString)); end; Result := TNSArray.Wrap(TNSArray.OCClass.arrayWithObjects(@LArray[0], Length(LArray))); end; function StrToObjectID(const AStr: string): Pointer; begin Result := NSObjectToID(StrToNSStr(AStr)); end; function StrToCFStringRef(const AStr: string): CFStringRef; begin Result := CFStringCreateWithCharacters(kCFAllocatorDefault, PChar(AStr), Length(AStr)); end; function GetLocalDateTime(const ADateTime: TDateTime): TDateTime; begin Result := IncSecond(ADateTime, TNSTimeZone.Wrap(TNSTimeZone.OCClass.localTimeZone).secondsFromGMT); end; { TNSArrayHelper } class function TNSArrayHelper.FromNSObjects(const AArray: array of NSObject): NSArray; var LArray: array of Pointer; I: Integer; begin SetLength(LArray, Length(AArray)); for I := 0 to Length(AArray) - 1 do LArray[I] := NSObjectToID(AArray[I]); Result := TNSArray.Wrap(TNSArray.OCClass.arrayWithObjects(@LArray[0], Length(LArray))); end; { TMacHelperEx } class function TMacHelperEx.GetBundleValue(const AKey: string): string; var LValue: NSString; begin Result := ''; LValue := GetBundleValueNS(AKey); if LValue <> nil then Result := NSStrToStr(LValue); end; class function TMacHelperEx.GetBundleValueNS(const AKey: string): NSString; var LValueObject: Pointer; begin Result := nil; LValueObject := MainBundle.infoDictionary.objectForKey(StrToObjectID(AKey)); if LValueObject <> nil then Result := TNSString.Wrap(LValueObject); end; class function TMacHelperEx.MainBundle: NSBundle; begin Result := TNSBundle.Wrap(TNSBundle.OCClass.mainBundle); end; {$IF Defined(MACDEV)} class function TMacHelperEx.SharedApplication: NSApplication; begin Result := TNSApplication.Wrap(TNSApplication.OCClass.sharedApplication); end; {$ENDIF} class function TMacHelperEx.StandardUserDefaults: NSUserDefaults; begin Result := TNSUserDefaults.Wrap(TNSUserDefaults.OCClass.standardUserDefaults); end; end.
{ VOLATILE FOLLOWERS Volatile Followers Patcher by dragonjet MOD: http://www.nexusmods.com/skyrim/mods/71998/ SOURCE: https://github.com/dragonjet/skyrim-volatilefollowers Credit for more util functions: https://github.com/matortheeternal/TES5EditScripts/blob/58b52d21baab82181ec13c9a22beccb6eb50e3ac/Edit%20Scripts/mteFunctions.pas } unit vfpatcher; uses mteFunctions; uses vf_utils; uses vf_logic; var VolatileESP : IwbFile; var VF_filename : string; { INITIALIZE } function Initialize : integer; var PluginCtr : integer; begin AddMessage('----------- VOLATILE FOLLOWERS 1.1 ----------'); VF_filename := 'VolatileFollowers.esp'; //GetUserPreferences(); // Get ESP file to work with VolatileESP := MakeESPFile(VF_filename); if VolatileESP <> nil then begin // Reset groups to clear all data within the plugin if coming from existing file ResetGroup( VolatileESP, 'QUST' ); ResetGroup( VolatileESP, 'NPC_' ); // Modify of follower hiring quest that re-enables protected flag, so next time, it won't SuppressFollowerQuest( VolatileESP ); // Start looping all plugins to check for NPCs for PluginCtr := 0 to (FileCount - 1) do begin if GetFileName(FileByIndex( PluginCtr )) <> VF_filename then begin MortalizePlugin( VolatileESP, FileByIndex( PluginCtr ) ); end; end; end; end; { FINALIZE } function Finalize : nil; begin if VolatileESP <> nil then begin AddMessage('Cleaning and sorting masters...'); CleanMasters( VolatileESP ); SortMasters( VolatileESP ); end; AddMessage('------ Volatile Followers Complete ------'); end; end.
{ Bens Simple CSV Format v1.0.0 This is a very basic csv readeer and writer that I needed for a basic program //See below for features: Return RecordCount OpenCsv SaveCsv Allows saveing to other filenames. Update saves the current csv opened file. Read field values Write field values Add new records Delete recoreds and more. } {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} unit ccsv; interface uses SysUtils, Classes; type TCsv = class private lFilename: string; db: TStringList; dbOpen: boolean; fFieldCount: integer; fRecords: integer; fDelimiter: char; function Split(Source: string): TStringList; public constructor Create(Filename: string); procedure OpenCsv(); property IsOpen: boolean read dbOpen; property FieldCount: integer read fFieldCount; property RecordCount: integer read fRecords; property Delimiter: char read fDelimiter write fDelimiter; procedure SaveCsv(Filename: string); function GetFieldValue(RecIdx: integer; FieldIdx: integer): string; function GetRecord(RecIdx: integer): string; function DeleteRecord(RecIdx: integer): boolean; procedure SetFieldValue(RecIdx: integer; FieldIdx: integer; Data: string); procedure AddRecord(Data: string); function UpdateCsv(): boolean; end; implementation procedure TCsv.AddRecord(Data: string); begin //Add new record. DB.Add(Data); //Update record count. fRecords := DB.Count; end; function Tcsv.UpdateCsv(): boolean; begin Result := False; //Use this function to update the current opened csv filename. if not dbOpen then exit; //Save csv filename. DB.SaveToFile(lFilename); //Return good result; Result := True; end; function Tcsv.DeleteRecord(RecIdx: integer): boolean; begin //Check record index. if (RecIdx < 0) or (RecIdx > RecordCount) then begin Result := False; end else begin //Delete Record. DB.Delete(RecIdx); //Update record count. fRecords := DB.Count; //Return good result Result := True; end; end; function Tcsv.GetRecord(RecIdx: integer): string; begin //Check record index. if (RecIdx < 0) or (RecIdx > RecordCount) then begin Result := ''; end else begin //Return record. Result := db[RecIdx]; end; end; function TCsv.GetFieldValue(RecIdx: integer; FieldIdx: integer): string; var Fields: TStringList; begin //Check record index. if (RecIdx < 0) or (RecIdx > RecordCount) then begin Result := ''; end //Check field index is in range. else if (FieldIdx < 0) or (FieldIdx > FieldCount) then Result := '' else begin //Create stringlist object. Fields := Split(db[RecIdx]); //Return field value. Result := Fields[FieldIdx]; //Clear up. Fields.Destroy; end; end; procedure TCsv.SetFieldValue(RecIdx: integer; FieldIdx: integer; Data: string); var Fields: TStringList; sRec: string; X: integer; begin //Init sRec := ''; //Check record index. if (RecIdx < 0) or (RecIdx > RecordCount) then begin exit; end //Check field index is in range. else if (FieldIdx < 0) or (FieldIdx > FieldCount) then exit else begin //Get record. Fields := Split(db[RecIdx]); //Edit the field value. Fields[FieldIdx] := Data; //Go tho the field values. for X := 0 to Fields.Count - 1 do begin //Build new record. sRec := sRec + Fields[X] + fDelimiter; end; //Remove last comma at the of string. Delete(sRec, Length(sRec), 1); //Replace the record back. DB[RecIdx] := sRec; //Clear up. Fields.Destroy; end; end; procedure TCsv.OpenCsv(); var nSize: integer; begin //Return true or false if file was opened. dbOpen := FileExists(lFilename); if dbOpen then begin nSize := 0; DB.LoadFromFile(lFilename); //Get number of records. fRecords := DB.Count; //Check if we have any records if fRecords > 0 then begin //Store size of returned string list. nSize := Split(db[0]).Count; end; //Set records size. fFieldCount := nSize; end; end; constructor TCsv.Create(Filename: string); begin //Create db stringlist db := TStringList.Create; //Set Filename lFilename := Filename; //Set defaults dbOpen := False; fFieldCount := 0; fDelimiter := ','; end; function TCsv.Split(Source: string): TStringList; var lDB: TStringList; begin //Create the object lDB := TStringList.Create; lDB.Delimiter := fDelimiter; lDB.CommaText := '"'; lDB.DelimitedText := Source; //Return result Result := lDB; end; procedure Tcsv.SaveCsv(Filename: string); begin //Save string list to filename. DB.SaveToFile(Filename); end; end.
unit l3ProtoObjectComparable; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "L3" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/L3/l3ProtoObjectComparable.pas" // Начат: 16.02.2011 19:17 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Low Level::L3::OVP::Tl3ProtoObjectComparable // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\L3\l3Define.inc} interface uses l3ProtoObject ; type Tl3ProtoObjectComparable = class(Tl3ProtoObject) public // public methods function CompareWith(anOther: Tl3ProtoObjectComparable): Integer; virtual; abstract; end;//Tl3ProtoObjectComparable implementation end.
unit uMain; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls, Buttons,httpsend, ComCtrls, Utils, xmlread,dom, EditBtn, FileUtil, XMLPropStorage,Clipbrd; type { TfWikiHelp } TfWikiHelp = class(TForm) bSearch: TButton; bCreate: TButton; eOutputDir: TDirectoryEdit; ePageOffset: TEdit; eWikiPage: TEdit; eFoundPages: TLabel; lOutputDir: TLabel; lbFoundPages: TListBox; lPageOffset: TLabel; lWikiPage: TLabel; pbProgress: TProgressBar; Properties: TXMLPropStorage; cbLanguage: TComboBox; lLanguage: TLabel; cbAddLinkedPages: TCheckBox; procedure bCreateClick(Sender: TObject); procedure bSearchClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure cbLanguageSelect(Sender: TObject); private { private declarations } SpecialPageURL : string; ExportPageURL : string; ImageTagName : string; public { public declarations } procedure Wiki2Html(wname : string;OutputDir : string;content : string); end; var fWikiHelp: TfWikiHelp; implementation uses uAppconsts; { TfWikiHelp } procedure TfWikiHelp.bSearchClick(Sender: TObject); var http : THttpSend; ss : TStringStream; s : string; tmp: String; begin lbFoundPages.Items.Clear; ss := TStringStream.Create(''); http := THttpSend.Create; http.UserAgent := 'Mozilla/4.0 (compatible; WikiHelp)'; http.HTTPMethod('GET',eWikiPage.Text+SpecialPageURL); http.Document.SaveToStream(ss); http.Free; s := ss.DataString; s := copy(s,pos('<table style="background: inherit;" border="0" width="100%"><tr><td>',s),length(s)); s := copy(s,0,pos('</td></tr></table><div class="printfooter">',s)); if s = '' then begin Showmessage('Special Page not found !'); exit; end; ss.Free; while pos('<a href="',s) > 0 do begin s := copy(s,pos('<a href="',s)+10,length(s)); tmp := copy(s,0,pos('"',s)-1); while pos(copy(tmp,0,pos('/',tmp)-1),eWikiPage.Text) > 0 do tmp := copy(tmp,pos('/',tmp)+1,length(tmp)); if copy(tmp,0,length(ePageOffset.Text)) = ePageOffset.Text then begin lbFoundPages.Items.Add(tmp); end; s := copy(s,pos('"',s)+1,length(s)); end; end; procedure TfWikiHelp.FormCreate(Sender: TObject); var FindRec: TSearchRec; begin if not DirectoryExists(GetConfigDir(vAppname)) then ForceDirectories(GetConfigDir(vAppname)); Properties.FileName := GetConfigDir(vAppname)+'config.xml'; Properties.Restore; if Properties.StoredValue['WIKIPAGE'] <> '' then eWikiPage.Text := Properties.StoredValue['WIKIPAGE']; ePageOffset.Text := Properties.StoredValue['PAGEOFFSET']; eOutputDir.Text := Properties.StoredValue['OUTPUTDIR']; cbLanguage.Items.Clear; IF FindFirst(ExtractFileDir(Application.Exename) + DirectorySeparator + '*.xml', faAnyFile, FindRec) = 0 THEN REPEAT IF (FindRec.Name <> '.') AND (FindRec.Name <> '..') THEN cbLanguage.Items.Add(copy(FindRec.Name,0,rpos('.',FindRec.Name)-1)); UNTIL FindNext(FindRec) <> 0; FindClose(FindRec); end; procedure TfWikiHelp.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin Properties.StoredValue['WIKIPAGE'] := eWikiPage.Text; Properties.StoredValue['PAGEOFFSET'] := ePageOffset.Text; Properties.StoredValue['OUTPUTDIR'] := eOutputDir.Text; end; procedure TfWikiHelp.cbLanguageSelect(Sender: TObject); var xml: TXMLDocument; iNode: TDOMNode; begin if FileExists(ExtractFilePath(Application.Exename)+DirectorySeparator+cbLanguage.Text+'.xml') then begin xml := TXMLDocument.Create; ReadXMLFile(xml,ExtractFilePath(Application.Exename)+DirectorySeparator+cbLanguage.Text+'.xml'); iNode := xml.DocumentElement.FindNode('SpecialPageURL'); SpecialPageURL := iNode.FirstChild.NodeValue; iNode := xml.DocumentElement.FindNode('ExportPageURL'); if Assigned(iNode) then ExportPageURL := StringReplace(iNode.FirstChild.NodeValue,#10,'',[rfReplaceAll]); iNode := xml.DocumentElement.FindNode('ImageTagName'); if Assigned(iNode) then ImageTagName := iNode.FirstChild.NodeValue; xml.Free; end; end; procedure DoReplace(var InStr,OutStr : string;ReplaceTag,NewTag : string;MustbeInOneLine : Boolean = False); var NewLine: String; begin while pos(ReplaceTag,instr) > 0 do begin NewLine := copy(instr,pos(ReplaceTag,instr)+length(ReplaceTag),length(instr)); if MustBeInOneLine and ((pos(#10,NewLine) < pos(ReplaceTag,NewLine))) and (not (length(NewLine) = pos(ReplaceTag,NewLine)+length(ReplaceTag)-1)) then break; outstr := outstr+copy(instr,0,pos(ReplaceTag,instr)-1); instr := copy(instr,pos(replaceTag,instr)+length(ReplaceTag),length(instr)); outstr := outstr+'<'+NewTag+'>'+copy(instr,0,pos(ReplaceTag,instr)-1)+'</'+NewTag+'>'; instr := copy(instr,pos(ReplaceTag,instr)+length(ReplaceTag),length(instr)); end; outstr := outstr+instr; instr := outstr; outstr := ''; end; procedure TfWikiHelp.Wiki2Html(wname: string;OutputDir : string;content: string); var f : TextFile; istr : string; ostr : string; http : THttpSend; open_uls,act_uls : integer; i: LongInt; intd: Boolean; tstr: String; aWikiStart: String; linkcontent: String; begin istr := content; ForceDirectories(OutputDir); AssignFile(f,AppendPathDelim(OutputDir)+ValidateFileName(lowercase(wname))+'.html'); Rewrite(f); ostr := ''; open_uls := 0; act_uls := 0; //Remove NOTOC istr := StringReplace(istr,'__NOTOC__','',[rfReplaceAll]); //Remove TOC istr := StringReplace(istr,'__TOC__','',[rfReplaceAll]); //Remove Templates while pos('{{',istr) > 0 do begin ostr := ostr+copy(istr,0,pos('{{',istr)-1); istr := copy(istr,pos('{{',istr)+2,length(istr)); istr := copy(istr,pos('}}',istr)+2,length(istr)); end; ostr := ostr+istr; istr := ostr; ostr := ''; //Replace Lists while pos('*',istr) > 0 do begin ostr := ostr+copy(istr,0,pos('*',istr)-1); istr := copy(istr,pos('*',istr)+1,length(istr)); inc(act_uls); while istr[1] = '*' do begin inc(act_uls); istr := copy(istr,2,length(istr)); end; if open_uls < act_uls then begin for i := open_uls to act_uls-1 do ostr := ostr+'<ul>'; end else begin for i := act_uls to open_uls-1 do ostr := ostr+'</ul>'; end; open_uls := act_uls; act_uls := 0; ostr := ostr+'<li>'; if pos(#10,istr) > 0 then begin ostr := ostr+copy(istr,0,pos(#10,istr)-1); istr := copy(istr,pos(#10,istr)+1,length(istr)); end else begin ostr := ostr+istr; istr := ''; end; ostr := ostr+'</li>'; if (length(istr) > 0) and (istr[1] <> '*') then begin for i := 0 to open_uls-1 do ostr := ostr+'</ul>'; open_uls := 0; end; end; ostr := ostr+istr; istr := ostr; ostr := ''; open_uls := 0; act_uls := 0; //Replace Numerated Lists while pos('#',istr) > 0 do begin ostr := ostr+copy(istr,0,pos('#',istr)-1); istr := copy(istr,pos('#',istr)+1,length(istr)); inc(act_uls); while istr[1] = '#' do begin inc(act_uls); istr := copy(istr,2,length(istr)); end; if open_uls < act_uls then begin for i := open_uls to act_uls-1 do ostr := ostr+'<ol>'; end else begin for i := act_uls to open_uls-1 do ostr := ostr+'</ol>'; end; open_uls := act_uls; act_uls := 0; ostr := ostr+'<li>'; if pos(#10,istr) > 0 then begin ostr := ostr+copy(istr,0,pos(#10,istr)-1); istr := copy(istr,pos(#10,istr)+1,length(istr)); end else begin ostr := ostr+istr; istr := ''; end; ostr := ostr+'</li>'; if (length(istr) > 0) and (istr[1] <> '#') then begin for i := 0 to open_uls-1 do ostr := ostr+'</ol>'; open_uls := 0; end; end; ostr := ostr+istr; istr := ostr; ostr := ''; //Replace Tables while pos('{|',istr) > 0 do begin ostr := ostr+copy(istr,0,pos('{|',istr)-1); istr := copy(istr,pos('{|',istr)+2,length(istr)); //remove also content behing {| istr := copy(istr,pos(#10,istr)-1,length(istr)); tstr := copy(istr,0,pos(#10+'|}',istr)-1); istr := copy(istr,pos(#10+'|}',istr)+3,length(istr)); ostr := ostr+'<table><tr>'; tstr := StringReplace(tstr,'|-','</tr><tr>',[rfReplaceAll]); intd := False; while length(tstr) > 2 do begin if ((tstr[1] = #10) and (tstr[2] = '|')) or ((tstr[1] = #10) and (tstr[2] = '!')) then begin if inTD then ostr := ostr+'</td>' else ostr := ostr+'<td>'; inTD := not inTD; tstr := copy(tstr,3,length(tstr)); end else if ((tstr[1] = '!') and (tstr[2] = '!')) or ((tstr[1] = '|') and (tstr[2] = '|')) then begin if inTD then begin ostr := ostr+'</td><td>' end else //Schould never happen begin ostr := ostr+'<td>'; inTD := True; end; tstr := copy(tstr,3,length(tstr)); end else begin if (tstr[1] = #10) and InTD then begin ostr := ostr+'</td>'; InTD := False; end else ostr := ostr+tstr[1]; tstr := copy(tstr,2,length(tstr)); end; end; ostr := ostr+tstr+'</tr></table>'; end; ostr := ostr+istr; istr := ostr; ostr := ''; //Replace Images while pos('[['+ImageTagName+':',istr) > 0 do begin ostr := ostr+copy(istr,0,pos('[['+ImageTagName+':',istr)-1); istr := copy(istr,pos('[['+ImageTagName+':',istr)+length(ImageTagname)+3,length(istr)); if (pos('|',istr) > 0) and (pos('|',istr) < pos(']]',istr)) then begin http := THttpSend.Create; http.HTTPMethod('GET','/images/'+copy(istr,0,pos('|',istr)-1)); http.Document.SaveToFile(AppendPathDelim(OutputDir)+ValidateFileName(lowercase(copy(istr,0,pos('|',istr)-1)))); http.Free; ostr := ostr+'<img src="'+ValidateFileName(lowercase(copy(istr,0,pos('|',istr)-1)))+'" alt="'; istr := copy(istr,0,pos('|',istr)+1); ostr := ostr+copy(istr,0,pos(']]',istr)-1)+'"></img>'; istr := copy(istr,pos(']]',istr)+2,length(istr)); end else begin aWikiStart := eWikiPage.Text; if pos('index.php',aWikiStart) > 0 then aWikiStart := copy(aWikiStart,0,pos('index.php',aWikiStart)-1); http := THttpSend.Create; http.HTTPMethod('GET',aWikiStart+'/images/'+copy(istr,0,pos(']]',istr)-1)); http.Document.SaveToFile(AppendPathDelim(OutputDir)+ValidateFileName(lowercase(copy(istr,0,pos(']]',istr)-1)))); http.Free; ostr := ostr+'<img src="'+ValidateFileName(lowercase(copy(istr,0,pos(']]',istr)-1)))+'" alt="'+copy(istr,0,pos(']]',istr)-1)+'"></img>'; istr := copy(istr,pos(']]',istr)+2,length(istr)); end; end; ostr := ostr+istr; istr := ostr; ostr := ''; //Replace Links while pos('[[',istr) > 0 do begin ostr := ostr+copy(istr,0,pos('[[',istr)-1); istr := copy(istr,pos('[[',istr)+2,length(istr)); if (pos('|',istr) > 0) and (pos('|',istr) < pos(']]',istr)) then begin linkcontent := copy(istr,0,pos('|',istr)-1); if (cbAddLinkedPages.Checked and (lbFoundPages.Items.IndexOf(linkcontent) = -1)) then begin lbFoundPages.Items.Add(linkcontent); pbProgress.Max := pbProgress.Max+1; end; if (lbFoundPages.Items.IndexOf(linkcontent) > -1) or (FileExists(AppendPathDelim(OutputDir)+ValidateFileName(lowercase(linkcontent)+'.html'))) then begin ostr := ostr+'<a href="'+ValidateFileName(linkcontent)+'.html">'; istr := copy(istr,pos('|',istr)+1,length(istr)); ostr := ostr+copy(istr,0,pos(']]',istr)-1)+'</a>'; istr := copy(istr,pos(']]',istr)+2,length(istr)); end else begin istr := copy(istr,pos('|',istr)+1,length(istr)); ostr := ostr+copy(istr,0,pos(']]',istr)-1); istr := copy(istr,pos(']]',istr)+2,length(istr)); end; end else begin linkcontent := copy(istr,0,pos(']]',istr)-1); if (cbAddLinkedPages.Checked and (lbFoundPages.Items.IndexOf(linkcontent) = -1)) then begin lbFoundPages.Items.Add(linkcontent); pbProgress.Max := pbProgress.Max+1; end; if lbFoundPages.Items.IndexOf(linkcontent) > -1 then begin ostr := ostr+'<a href="'+ValidateFileName(linkcontent)+'.html">'+copy(istr,0,pos(']]',istr)-1)+'</a>'; istr := copy(istr,pos(']]',istr)+2,length(istr)); end else begin ostr := ostr+copy(istr,0,pos(']]',istr)-1); istr := copy(istr,pos(']]',istr)+2,length(istr)); end; end; end; ostr := ostr+istr; istr := ostr; ostr := ''; //Replace extern Links while pos('[http://',lowercase(istr)) > 0 do begin ostr := ostr+copy(istr,0,pos('[http://',lowercase(istr))-1); istr := copy(istr,pos('[http://',lowercase(istr)),length(istr)); if (pos(' ',istr) > 0) and (pos(' ',istr) < pos(']',lowercase(istr))) then begin ostr := ostr+'<a href="'+StringReplace(copy(istr,2,pos(' ',istr)-2),'http://./','',[rfReplaceAll])+'" target="_BLANK">'; istr := copy(istr,pos(' ',istr)+1,length(istr)); ostr := ostr+copy(istr,0,pos(']',lowercase(istr))-1)+'</a>'; istr := copy(istr,pos(']',lowercase(istr))+1,length(istr)); end else begin ostr := ostr+'<a href="'+StringReplace(copy(istr,2,pos(']',lowercase(istr))-2),'http://./','',[rfReplaceAll])+'" target="_BLANK">'+StringReplace(copy(istr,2,pos(']',lowercase(istr))-2),'http://./','',[rfReplaceAll])+'</a>'; istr := copy(istr,pos(']',lowercase(istr))+1,length(istr)); end; end; ostr := ostr+istr; istr := ostr; ostr := ''; //Replace Bold Text while pos('''''''',istr) > 0 do begin ostr := ostr+copy(istr,0,pos('''''''',istr)-1); istr := copy(istr,pos('''''''',istr)+3,length(istr)); ostr := ostr+'<b>'+copy(istr,0,pos('''''''',istr)-1)+'</b>'; istr := copy(istr,pos('''''''',istr)+3,length(istr)); end; ostr := ostr+istr; istr := ostr; ostr := ''; //Replace Italic Text while pos('''''',istr) > 0 do begin ostr := ostr+copy(istr,0,pos('''''',istr)-1); istr := copy(istr,pos('''''',istr)+2,length(istr)); ostr := ostr+'<i>'+copy(istr,0,pos('''''',istr)-1)+'</i>'; istr := copy(istr,pos('''''',istr)+2,length(istr)); end; ostr := ostr+istr; istr := ostr; ostr := ''; //Replace Header Level 5 DoReplace(istr,ostr,'=====','h6',True); //Replace Header Level 4 DoReplace(istr,ostr,'====','h5',True); //Replace Header Level 3 DoReplace(istr,ostr,'===','h4',True); //Replace Header Level 2 DoReplace(istr,ostr,'==','h3',True); //Replace Header Level 1 // DoReplace(istr,ostr,'=','h2',True); //Too many problems at time TODO: check if we are in an html tag bevore replace //Process unformated stuff while pos(#10+' ',istr) > 0 do begin //Replace Line breaks in text bevore pre ostr := ostr+StringReplace(StringReplace(copy(istr,0,pos(#10+' ',istr)-1),#10#10,'<br><br>',[rfReplaceAll]),#10,'',[rfReplaceAll]); istr := copy(istr,pos(#10+' ',istr)+2,length(istr)); ostr := ostr+'<pre>'; while (pos(#10+' ',istr) > 0) do begin ostr := ostr+copy(istr,0,pos(#10,istr)); istr := copy(istr,pos(#10,istr)+1,length(istr)); if (length(istr) > 0) and (istr[1] <> ' ') then break else istr := copy(istr,2,length(istr)); end; ostr := ostr+'</pre>'; end; ostr := ostr+StringReplace(StringReplace(istr,#10#10,'<br><br>',[rfReplaceAll]),#10,'',[rfReplaceAll]); //Remove <br> after <h*> ostr := StringReplace(ostr,'</h2><br><br>','</h2>',[rfReplaceAll]); ostr := StringReplace(ostr,'</h3><br><br>','</h3>',[rfReplaceAll]); ostr := StringReplace(ostr,'</h4><br><br>','</h4>',[rfReplaceAll]); ostr := StringReplace(ostr,'</h5><br><br>','</h5>',[rfReplaceAll]); ostr := StringReplace(ostr,'</h6><br><br>','</h6>',[rfReplaceAll]); ostr := StringReplace(ostr,'</h2><br>','</h2>',[rfReplaceAll]); ostr := StringReplace(ostr,'</h3><br>','</h3>',[rfReplaceAll]); ostr := StringReplace(ostr,'</h4><br>','</h4>',[rfReplaceAll]); ostr := StringReplace(ostr,'</h5><br>','</h5>',[rfReplaceAll]); ostr := StringReplace(ostr,'</h6><br>','</h6>',[rfReplaceAll]); write(f,'<html><head><title>'+wname+'</title></head><body><font face="arial,verdana">'+ostr+'</font></body></html>'); CloseFile(f); end; procedure TfWikiHelp.bCreateClick(Sender: TObject); var http : THttpSend; xml : TXMLDocument; i: Integer; iNode: TDOMNode; a: Integer; aWikiStart : string; begin bCreate.Enabled := false; Screen.Cursor := crHourglass; pbProgress.Max := lbFoundPages.Items.Count; pbProgress.Position := 0; while lbFoundPages.Items.Count > 0 do begin aWikiStart := eWikiPage.Text; if pos('index.php',aWikiStart) > 0 then aWikiStart := copy(aWikiStart,0,pos('index.php',aWikiStart)-1); http := THttpSend.Create; http.HTTPMethod('POST',aWikiStart+Format(ExportPageURL,[HTTPEncode(lbFoundPages.Items[0])])); if http.ResultCode = 200 then begin xml := TXMLDocument.Create; try ReadXMLFile(xml,http.Document); iNode := xml.DocumentElement.FindNode('page'); if Assigned(iNode) then iNode := iNode.FindNode('revision'); if Assigned(iNode) then iNode := iNode.FindNode('text'); if Assigned(iNode) then begin Wiki2Html(lbFoundPages.Items[0],eOutputDir.Text,iNode.FirstChild.NodeValue); end else Showmessage('Page: '+lbFoundPages.Items[0]+' not found !'); xml.Free; except on e : Exception do Showmessage('Error Processing :'+lbFoundPages.Items[0]+':'+e.Message); end; end else Showmessage('Page: '+lbFoundPages.Items[0]+' not found !'); http.Free; pbProgress.Position := i+1; lbFoundPages.Items.Delete(0); Application.Processmessages; end; Screen.Cursor := crDefault; bCreate.Enabled := True; end; initialization {$I umain.lrs} 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.18 12/10/04 1:13:34 PM RLebeau FormatDateTime() fixes. Was using 'mm' instead of 'nn' for minutes. Rev 1.17 10/26/2004 9:36:26 PM JPMugaas Updated ref. Rev 1.16 10/26/2004 9:19:14 PM JPMugaas Fixed references. Rev 1.15 10/1/2004 6:17:12 AM JPMugaas Removed some dead code. Rev 1.14 6/27/2004 1:45:36 AM JPMugaas Can now optionally support LastAccessTime like Smartftp's FTP Server could. I also made the MLST listing object and parser support this as well. Rev 1.13 6/11/2004 9:34:44 AM DSiders Added "Do not Localize" comments. Rev 1.12 4/19/2004 5:06:02 PM JPMugaas Class rework Kudzu wanted. Rev 1.11 2004.02.03 5:45:34 PM czhower Name changes Rev 1.10 24/01/2004 19:18:48 CCostelloe Cleaned up warnings Rev 1.9 1/4/2004 12:09:54 AM BGooijen changed System.Delete to IdDelete Rev 1.8 11/26/2003 6:23:44 PM JPMugaas Quite a number of fixes for recursive dirs and a few other things that slipped my mind. Rev 1.7 10/19/2003 2:04:02 PM DSiders Added localization comments. Rev 1.6 3/11/2003 07:36:00 PM JPMugaas Now reports permission denied in subdirs when doing recursive listts in Unix export. Rev 1.5 3/9/2003 12:01:26 PM JPMugaas Now can report errors in recursive lists. Permissions work better. Rev 1.4 3/3/2003 07:18:34 PM JPMugaas Now honors the FreeBSD -T flag and parses list output from a program using it. Minor changes to the File System component. Rev 1.3 2/26/2003 08:57:10 PM JPMugaas Bug fix. The owner and group should be left-justified. Rev 1.2 2/24/2003 07:24:00 AM JPMugaas Now honors more Unix switches just like the old code and now work with the NLIST command when emulating Unix. -A switch support added. Switches are now in constants. Rev 1.1 2/23/2003 06:19:42 AM JPMugaas Now uses Classes instead of classes. Rev 1.0 2/21/2003 06:51:46 PM JPMugaas FTP Directory list output object for the FTP server. } unit IdFTPListOutput; interface {$i IdCompilerDefines.inc} uses Classes, IdFTPList; type // we can't use the standard FTP MLSD option types in the FTP Server // because we support some minimal things that the user can't set. // We have the manditory items to make it harder for the user to mess up. TIdFTPFactOutput = (ItemType, Modify, Size, Perm, Unique, UnixMODE, UnixOwner, UnixGroup, CreateTime, LastAccessTime, WinAttribs,WinDriveType,WinDriveLabel); TIdFTPFactOutputs = set of TIdFTPFactOutput; TIdDirOutputFormat = (doUnix, doWin32, doEPLF); TIdFTPListOutputItem = class(TIdFTPListItem) protected FLinkCount: Integer; FGroupName: string; FOwnerName : String; FLinkedItemName : string; FNumberBlocks : Integer; FInode : Integer; FLastAccessDate: TDateTime; FLastAccessDateGMT: TDateTime; FCreationDate: TDateTime; FCreationDateGMT : TDateTime; //Unique ID for an item to prevent yourself from downloading something twice FUniqueID : String; //MLIST things FMLISTPermissions : String; FUnixGroupPermissions: string; FUnixOwnerPermissions: string; FUnixOtherPermissions: string; FUnixinode : Integer; FWinAttribs : Cardinal; //an error has been reported in the DIR listing itself for an item FDirError : Boolean; FWinDriveType : Integer; FWinDriveLabel : String; public constructor Create(AOwner: TCollection); override; property NumberBlocks : Integer read FNumberBlocks write FNumberBlocks; property Inode : Integer read FInode write FInode; //Last Access time values are for MLSD data output and can be returned by the MLST command property LastAccessDate: TDateTime read FLastAccessDate write FLastAccessDate; property LastAccessDateGMT : TDateTime read FLastAccessDateGMT write FLastAccessDateGMT; //Creation time values are for MLSD data output and can be returned by the MLST command property CreationDate: TDateTime read FCreationDate write FCreationDate; property CreationDateGMT : TDateTime read FCreationDateGMT write FCreationDateGMT; // If this is not blank, you can use this as a unique identifier for an item to prevent // yourself from downloading the same item twice (which is not easy to see with some // some FTP sites where symbolic links or similar things are used. //Valid only with EPLF and MLST property UniqueID : string read FUniqueID write FUniqueID; //Creation time values are for MLSD data output and can be returned by the //the MLSD parser in some cases property ModifiedDateGMT; //Windows NT File Attributes (just like what is reported by RaidenFTPD //BlackMoon FTP Server, and Serv-U //On the server side, you deal with it as a number right from the Win32 FindFirst, //FindNext functions. Easy property WinAttribs : Cardinal read FWinAttribs write FWinAttribs; property WinDriveType : Integer read FWinDriveType write FWinDriveType; property WinDriveLabel : String read FWinDriveLabel write FWinDriveLabel; //MLIST Permissions property MLISTPermissions : string read FMLISTPermissions write FMLISTPermissions; property UnixOwnerPermissions: string read FUnixOwnerPermissions write FUnixOwnerPermissions; property UnixGroupPermissions: string read FUnixGroupPermissions write FUnixGroupPermissions; property UnixOtherPermissions: string read FUnixOtherPermissions write FUnixOtherPermissions; property LinkCount: Integer read FLinkCount write FLinkCount; property OwnerName: string read FOwnerName write FOwnerName; property GroupName: string read FGroupName write FGroupName; property LinkedItemName : string read FLinkedItemName write FLinkedItemName; property DirError : Boolean read FDirError write FDirError; end; TIdFTPListOutput = class(TCollection) protected FSwitches : String; FOutput : String; FDirFormat : TIdDirOutputFormat; FExportTotalLine : Boolean; function GetLocalModTime(AItem : TIdFTPListOutputItem) : TDateTime; virtual; function HasSwitch(const ASwitch: String): Boolean; function UnixItem(AItem : TIdFTPListOutputItem) : String; virtual; function Win32Item(AItem : TIdFTPListOutputItem) : String; virtual; function EPLFItem(AItem : TIdFTPListOutputItem) : String; virtual; function NListItem(AItem : TIdFTPListOutputItem) : String; virtual; function MListItem(AItem : TIdFTPListOutputItem; AMLstOpts : TIdFTPFactOutputs) : String; virtual; procedure InternelOutputDir(AOutput : TStrings; ADetails : Boolean = True); virtual; function UnixINodeOutput(AItem : TIdFTPListOutputItem) : String; function UnixBlocksOutput(AItem : TIdFTPListOutputItem) : String; function UnixGetOutputOwner(AItem : TIdFTPListOutputItem) : String; function UnixGetOutputGroup(AItem : TIdFTPListOutputItem) : String; function UnixGetOutputOwnerPerms(AItem : TIdFTPListOutputItem) : String; function UnixGetOutputGroupPerms(AItem : TIdFTPListOutputItem) : String; function UnixGetOutputOtherPerms(AItem : TIdFTPListOutputItem) : String; function GetItems(AIndex: Integer): TIdFTPListOutputItem; procedure SetItems(AIndex: Integer; const AValue: TIdFTPListOutputItem); public function Add: TIdFTPListOutputItem; constructor Create; reintroduce; function IndexOf(AItem: TIdFTPListOutputItem): Integer; property Items[AIndex: Integer]: TIdFTPListOutputItem read GetItems write SetItems; default; procedure LISTOutputDir(AOutput : TStrings); virtual; procedure MLISTOutputDir(AOutput : TStrings; AMLstOpts : TIdFTPFactOutputs); virtual; procedure NLISTOutputDir(AOutput : TStrings); virtual; property DirFormat : TIdDirOutputFormat read FDirFormat write FDirFormat; property Switches : String read FSwitches write FSwitches; property Output : String read FOutput write FOutput; property ExportTotalLine : Boolean read FExportTotalLine write FExportTotalLine; end; const DEF_FILE_OWN_PERM = 'rw-'; {do not localize} DEF_FILE_GRP_PERM = DEF_FILE_OWN_PERM; DEF_FILE_OTHER_PERM = 'r--'; {do not localize} DEF_DIR_OWN_PERM = 'rwx'; {do not localize} DEF_DIR_GRP_PERM = DEF_DIR_OWN_PERM; DEF_DIR_OTHER_PERM = 'r-x'; {do not localize} DEF_OWNER = 'root'; {do not localize} {NLIST and LIST switches - based on /bin/ls } { Note that the standard Unix form started simply by Unix FTP deamons piping output from the /bin/ls program for both the NLIST and LIST FTP commands. The standard /bin/ls program has several standard switches that allow the output to be customized. For our output, we wish to emulate this behavior. Microsoft IIS even honors a subset of these switches dealing sort order and recursive listings. It does not honor some sort-by-switches although we honor those in Win32 (hey, we did MS one better, not that it says much though. } const {format switches - used by Unix mode only} SWITCH_COLS_ACCROSS = 'x'; SWITCH_COLS_DOWN = 'C'; SWITCH_ONE_COL = '1'; SWITCH_ONE_DIR = 'f'; SWITCH_COMMA_STREAM = 'm'; SWITCH_LONG_FORM = 'l'; {recursive for both Win32 and Unix forms} SWITCH_RECURSIVE = 'R'; {sort switches - used both by Win32 and Unix forms} SWITCH_SORT_REVERSE = 'r'; SWITCH_SORTBY_MTIME = 't'; SWITCH_SORTBY_CTIME = 'u'; SWITCH_SORTBY_EXT = 'X'; SWITCH_SORTBY_SIZE = 'S'; {Output switches for Unix mode only} SWITCH_CLASSIFY = 'F'; // { -F Put aslash (/) aftereach filename if the file is a directory, an asterisk (*) if the file is executable, an equal sign(=) if the file is an AF_UNIX address family socket, andan ampersand (@) if the file is asymbolic link.Unless the -H option isalso used, symbolic links are followed to see ifthey might be adirectory; see above. From: http://www.mcsr.olemiss.edu/cgi-bin/man-cgi?ls+1 } SWITCH_SLASHDIR = 'p'; SWITCH_QUOTEDNAME = 'Q'; SWITCH_PRINT_BLOCKS = 's'; SWITCH_PRINT_INODE = 'i'; SWITCH_SHOW_ALLPERIOD = 'a'; //show all entries even ones with a pariod starting the filename/hidden //note that anything starting with a period is shown except for the .. and . entries for security reasons SWITCH_HIDE_DIRPOINT = 'A'; //hide the "." and ".." entries SWITCH_BOTH_TIME_YEAR = 'T'; //This is used by FTP Voyager with a Serv-U FTP Server to both //a time and year in the FTP list. Note that this does conflict with a ls -T flag used to specify a column size //on Linux but in FreeBSD, the -T flag is also honored. implementation uses //facilitate inlining only. IdException, {$IFDEF DOTNET} {$IFDEF USE_INLINE} System.IO, {$ENDIF} {$ENDIF} {$IFDEF USE_VCL_POSIX} Posix.SysTime, {$ENDIF} IdContainers, IdGlobal, IdFTPCommon, IdGlobalProtocols, IdStrings, SysUtils; type TDirEntry = class(TObject) protected FPathName : String; FDirListItem : TIdFTPListOutputItem; FSubDirs : TIdObjectList; FFileList : TIdBubbleSortStringList; public constructor Create(const APathName : String; ADirListItem : TIdFTPListOutputItem); destructor Destroy; override; // procedure Sort(ACompare: TIdSortCompare;const Recurse : Boolean = True); procedure SortAscendFName; procedure SortDescendFName; procedure SortAscendMTime; procedure SortDescendMTime; procedure SortAscendSize; procedure SortDescendSize; procedure SortAscendFNameExt; procedure SortDescendFNameExt; function AddSubDir(const APathName : String; ADirEnt : TIdFTPListOutputItem) : Boolean; function AddFileName(const APathName : String; ADirEnt : TIdFTPListOutputItem) : Boolean; property SubDirs : TIdObjectList read FSubDirs; property FileList : TIdBubbleSortStringList read FFileList; property PathName : String read FPathName; property DirListItem : TIdFTPListOutputItem read FDirListItem; end; function RawSortAscFName(AItem1, AItem2: TIdFTPListItem; const ASubDirs : Boolean = True): Integer; var { > 0 (positive) Item1 is less than Item2 = 0 Item1 is equal to Item2 < 0 (negative) Item1 is greater than Item2 } LTmpPath1, LTmpPath2 : String; LPath1Dot, LPath2Dot : Boolean; begin LTmpPath1 := IndyGetFileName(AItem1.FileName); LTmpPath2 := IndyGetFileName(AItem2.FileName); //periods are always greater then letters in dir lists LPath1Dot := TextStartsWith(LTmpPath1, '.'); LPath2Dot := TextStartsWith(LTmpPath2, '.'); if LPath1Dot and LPath2Dot then begin if (LTmpPath1 = CUR_DIR) and (LTmpPath2 = PARENT_DIR) then begin Result := 1; Exit; end; if (LTmpPath2 = CUR_DIR) and (LTmpPath1 = PARENT_DIR) then begin Result := -1; Exit; end; if (LTmpPath2 = CUR_DIR) and (LTmpPath1 = CUR_DIR) then begin Result := 0; Exit; end; if (LTmpPath2 = PARENT_DIR) and (LTmpPath1 = PARENT_DIR) then begin Result := 0; Exit; end; end; if LPath2Dot and (not LPath1Dot) then begin Result := -1; Exit; end; if LPath1Dot and (not LPath2Dot) then begin Result := 1; Exit; end; Result := -IndyCompareStr(LTmpPath1, LTmpPath2); end; function RawSortDescFName(AItem1, AItem2: TIdFTPListItem): Integer; begin Result := -RawSortAscFName(AItem1, AItem2); end; function RawSortAscFNameExt(AItem1, AItem2: TIdFTPListItem; const ASubDirs : Boolean = True): Integer; var { > 0 (positive) Item1 is less than Item2 = 0 Item1 is equal to Item2 < 0 (negative) Item1 is greater than Item2 } LTmpPath1, LTmpPath2 : String; begin LTmpPath1 := ExtractFileExt(AItem1.FileName); LTmpPath2 := ExtractFileExt(AItem2.FileName); Result := -IndyCompareStr(LTmpPath1, LTmpPath2); if Result = 0 then begin Result := RawSortAscFName(AItem1, AItem2); end; end; function RawSortDescFNameExt(AItem1, AItem2: TIdFTPListItem): Integer; begin Result := -RawSortAscFNameExt(AItem1, AItem2, False); end; function RawSortAscMTime(AItem1, AItem2: TIdFTPListItem): Integer; begin { > 0 (positive) Item1 is less than Item2 0 Item1 is equal to Item2 < 0 (negative) Item1 is greater than Item2 } if AItem1.ModifiedDate < AItem2.ModifiedDate then begin Result := -1; end else if AItem1.ModifiedDate > AItem2.ModifiedDate then begin Result := 1; end else begin Result := RawSortAscFName(AItem1, AItem2); end; end; function RawSortDescMTime(AItem1, AItem2: TIdFTPListItem): Integer; begin Result := -RawSortAscMTime(AItem1, AItem2); end; function RawSortAscSize(AItem1, AItem2: TIdFTPListItem; const ASubDirs : Boolean = True): Integer; var LSize1, LSize2 : Int64; { > 0 (positive) Item1 is less than Item2 = 0 Item1 is equal to Item2 < 0 (negative) Item1 is greater than Item2 } begin LSize1 := AItem1.Size; LSize2 := AItem2.Size; if TIdFTPListOutput(AItem1.Collection).DirFormat = doUnix then begin if AItem1.ItemType = ditDirectory then begin LSize1 := UNIX_DIR_SIZE; end; if AItem2.ItemType = ditDirectory then begin LSize2 := UNIX_DIR_SIZE; end; end; if LSize1 < LSize2 then begin Result := -1; end else if LSize1 > LSize2 then begin Result := 1; end else begin Result := RawSortAscFName (AItem1, AItem2); end; end; function RawSortDescSize(AItem1, AItem2: TIdFTPListItem): Integer; begin Result := -RawSortAscSize(AItem1, AItem2, False); end; {DirEntry objects} function DESortAscFName(AItem1, AItem2: TDirEntry): Integer; begin Result := -IndyCompareStr(AItem1.PathName, AItem2.PathName); end; function DESortAscMTime(AItem1, AItem2: TDirEntry): Integer; var L1, L2 : TIdFTPListItem; { > 0 (positive) Item1 is less than Item2 = 0 Item1 is equal to Item2 < 0 (negative) Item1 is greater than Item2 } begin L1 := AItem1.DirListItem; L2 := AItem2.DirListItem; if L1.ModifiedDate > L2.ModifiedDate then begin Result := -1; end else if L1.ModifiedDate < L2.ModifiedDate then begin Result := 1; end else begin Result := DESortAscFName(AItem1, AItem2); end; end; function DESortDescMTime(AItem1, AItem2: TDirEntry): Integer; begin Result := -DESortAscMTime(AItem1, AItem2); end; function DESortDescFName(AItem1, AItem2: TDirEntry): Integer; begin Result := -DESortAscFName(AItem1, AItem2); end; {stringlist objects} function StrSortAscMTime(List: TStringList; Index1, Index2: Integer): Integer; begin Result := RawSortAscMTime( TIdFTPListItem(List.Objects[Index1]), TIdFTPListItem(List.Objects[Index2])); end; function StrSortDescMTime(List: TStringList; Index1, Index2: Integer): Integer; begin Result := RawSortDescMTime( TIdFTPListItem(List.Objects[Index1]), TIdFTPListItem(List.Objects[Index2])); end; function StrSortAscSize(List: TStringList; Index1, Index2: Integer): Integer; begin Result := RawSortAscSize( TIdFTPListItem(List.Objects[Index1]), TIdFTPListItem(List.Objects[Index2])); end; function StrSortDescSize(List: TStringList; Index1, Index2: Integer): Integer; begin Result := RawSortDescSize( TIdFTPListItem(List.Objects[Index1]), TIdFTPListItem(List.Objects[Index2])); end; function StrSortAscFName(List: TStringList; Index1, Index2: Integer): Integer; begin Result := RawSortAscFName( TIdFTPListItem(List.Objects[Index1]), TIdFTPListItem(List.Objects[Index2])); end; function StrSortDescFName(List: TStringList; Index1, Index2: Integer): Integer; begin Result := RawSortDescFName( TIdFTPListItem(List.Objects[Index1]), TIdFTPListItem(List.Objects[Index2])); end; function StrSortAscFNameExt(List: TStringList; Index1, Index2: Integer): Integer; begin Result := RawSortAscFNameExt( TIdFTPListItem(List.Objects[Index1]), TIdFTPListItem(List.Objects[Index2])); end; function StrSortDescFNameExt(List: TStringList; Index1, Index2: Integer): Integer; begin Result := RawSortDescFNameExt( TIdFTPListItem(List.Objects[Index1]), TIdFTPListItem(List.Objects[Index2])); end; { TIdFTPListOutput } function TIdFTPListOutput.Add: TIdFTPListOutputItem; begin Result := TIdFTPListOutputItem(inherited Add); end; constructor TIdFTPListOutput.Create; begin inherited Create(TIdFTPListOutputItem); FDirFormat := doUnix; end; function TIdFTPListOutput.EPLFItem(AItem: TIdFTPListOutputItem): String; var LFileName : String; begin LFileName := IndyGetFileName(AItem.FileName); if AItem.ModifiedDateGMT > EPLF_BASE_DATE then begin Result := '+m' + GMTDateTimeToEPLFDate(AItem.ModifiedDateGMT); end else if AItem.ModifiedDate > EPLF_BASE_DATE then begin Result := '+m'+LocalDateTimeToEPLFDate(AItem.ModifiedDate); end else begin Result := ''; end; if AItem.ItemType = ditFile then begin Result := Result + ',r'; end else begin Result := Result + ',/'; end; Result := Result + ',s' + IntToStr(AItem.Size); Result := Result + #9 + LFileName; end; function TIdFTPListOutput.GetItems(AIndex: Integer): TIdFTPListOutputItem; begin Result := TIdFTPListOutputItem(inherited GetItem(AIndex)); end; function TIdFTPListOutput.GetLocalModTime(AItem: TIdFTPListOutputItem): TDateTime; begin if AItem.ModifiedDateGMT <> 0 then begin Result := AItem.ModifiedDateGMT - TimeZoneBias; end else begin Result := AItem.ModifiedDate; end; end; function TIdFTPListOutput.HasSwitch(const ASwitch: String): Boolean; begin Result := IndyPos(ASwitch, Switches) > 0; end; function TIdFTPListOutput.IndexOf(AItem: TIdFTPListOutputItem): Integer; var i : Integer; begin Result := -1; for i := 0 to Count - 1 do begin if AItem = Items[i] then begin Result := i; Exit; end; end; end; procedure TIdFTPListOutput.InternelOutputDir(AOutput: TStrings; ADetails: Boolean); type TIdDirOutputType = (doColsAccross, doColsDown, doOneCol, doOnlyDirs, doComma, doLong); var i : Integer; //note we use this for sorting pathes with recursive dirs LRootPath : TDirEntry; LShowNavSym : BOolean; function DetermineOp : TIdDirOutputType; //we do things this way because the last switch in a mutually exclusive set //always takes precidence over the others. var LStopScan : Boolean; li : Integer; begin if ADetails then begin Result := doLong; end else begin Result := doOneCol; end; if DirFormat <> doUnix then begin Exit; end; LStopScan := False; for li := Length(Switches) downto 1 do begin case Switches[li] of SWITCH_COLS_ACCROSS : begin Result := doColsAccross; LStopScan := True; end; SWITCH_COLS_DOWN : begin Result := doColsDown; LStopScan := True; end; SWITCH_ONE_COL : begin Result := doOneCol; LStopScan := True; end; SWITCH_ONE_DIR : begin Result := doOnlyDirs; LStopScan := True; end; SWITCH_COMMA_STREAM : begin Result := doComma; LStopScan := True; end; SWITCH_LONG_FORM : begin Result := doLong; LStopScan := True; end; end; if LStopScan then begin Break; end; end; end; procedure PrintSubDirHeader(ARoot, ACurDir : TDirEntry; ALOutput : TStrings; const Recurse : Boolean = False); var LUnixPrependPath : Boolean; begin LUnixPrependPath := HasSwitch(SWITCH_SORT_REVERSE) or HasSwitch(SWITCH_SORTBY_MTIME) or (DetermineOp <> doLong); if (ACurDir <> ARoot) or LUnixPrependPath then begin //we don't want an empty line to start the list if ACurDir <> ARoot then begin ALOutput.Add(''); end; if DirFormat = doWin32 then begin ALOutput.Add(MS_DOS_CURDIR + UnixPathToDOSPath(ACurDir.PathName) + ':'); end else if LUnixPrependPath then begin if ACurDir = ARoot then begin ALOutput.Add(CUR_DIR + ':'); end else begin ALOutput.Add(UNIX_CURDIR + DOSPathToUnixPath(ACurDir.PathName) + ':'); end; end else begin ALOutput.Add(DOSPathToUnixPath(ACurDir.PathName) + ':'); end; end; end; procedure ProcessOnePathCol(ARoot, ACurDir : TDirEntry; ALOutput : TStrings; const Recurse : Boolean = False); var li : Integer; LCurItem : TIdFTPListOutputItem; begin if Recurse and Assigned(ACurDir.SubDirs) then begin if Recurse then begin PrintSubDirHeader(ARoot, ACurDir, ALOutput, Recurse); end; end; for li := 0 to ACurDir.FileList.Count-1 do begin ALOutput.Add(NListItem(TIdFTPListOutputItem(ACurDir.FileList.Objects[li]))); end; if Recurse and Assigned(ACurDir.SubDirs) then begin for li := 0 to ACurDir.SubDirs.Count-1 do begin LCurItem := TDirEntry(ACurDir.SubDirs[li]).DirListItem; if LCurItem.DirError then begin if li = 0 then begin ALOutput.Add(''); end; ALOutput.Add(IndyFormat('/bin/ls: %s: Permission denied', [LCurItem.FileName])); {do not localize} end else begin ProcessOnePathCol(ARoot, TDirEntry(ACurDir.SubDirs[li]), ALOutput, Recurse); end; end; end; end; function CalcMaxLen(ARoot, ACurDir : TDirEntry; ALOutput : TStrings; const Recurse : Boolean = False) : Integer; var LEntryMaxLen : Integer; li : Integer; begin Result := 0; for li := 0 to ACurDir.FileList.Count-1 do begin LEntryMaxLen := Length(NListItem(TIdFTPListOutputItem(ACurDir.FileList.Objects[li]))); if LEntryMaxLen > Result then begin Result := LEntryMaxLen; end; end; if Recurse and Assigned(ACurDir.SubDirs) then begin for li := 0 to ACurDir.SubDirs.Count-1 do begin LEntryMaxLen := CalcMaxLen(ARoot, TDirEntry(ACurDir.SubDirs[li]), ALOutput, Recurse); if LEntryMaxLen > Result then begin Result := LEntryMaxLen; end; end; end; end; procedure ProcessPathAccross(ARoot, ACurDir : TDirEntry; ALOutput : TStrings; const Recurse : Boolean = False); var li, j : Integer; LTmp : String; LMaxLen : Integer; LCols : Integer; LCurItem : TIdFTPListOutputItem; begin if ACurDir.FileList.Count = 0 then begin Exit; end; //Note that we will assume a console width of 80 and we don't want something to wrap //causing a blank line LMaxLen := CalcMaxLen(ARoot, ACurDir, ALOutput, Recurse); //if more than 39, we probably are going to exceed the width of the screen, //just treat as one column if LMaxLen > 39 then begin ProcessOnePathCol(ARoot, ACurDir, ALOutput, Recurse); Exit; end; if Recurse and Assigned(ACurDir.SubDirs) then begin if Recurse then begin PrintSubDirHeader(ARoot, ACurDir, ALOutput, Recurse); end; end; LCols := 79 div (LMaxLen + 2);//2 spaces between columns j := 0; repeat LTmp := ''; for li := 0 to LCols -1 do begin LTmp := LTmp + PadString(NListItem(TIdFTPListOutputItem(ACurDir.FileList.Objects[j])), LMaxLen, ' ') + ' '; Inc(j); if j = ACurDir.FileList.Count then begin Break; end; end; ALOutput.Add(TrimRight(LTmp)); until j = ACurDir.FileList.Count; if Recurse and Assigned(ACurDir.SubDirs) then begin for li := 0 to ACurDir.SubDirs.Count-1 do begin LCurItem := TDirEntry(ACurDir.SubDirs[li]).DirListItem; if LCurItem.DirError then begin if li = 0 then begin ALOutput.Add(''); end; ALOutput.Add(IndyFormat('/bin/ls: %s: Permission denied', [LCurItem.FileName])); {do not localize} end else begin ProcessPathAccross(ARoot, TDirEntry(ACurDir.SubDirs[li]), ALOutput, Recurse); end; end; end; end; procedure ProcessPathDown(ARoot, ACurDir : TDirEntry; ALOutput : TStrings; const Recurse : Boolean = False); var li, j : Integer; LTmp : String; LMaxLen : Integer; LCols : Integer; LLines : Integer; // LFrm : String; LCurItem : TIdFTPListOutputItem; begin if ACurDir.FileList.Count = 0 then begin Exit; end; //Note that we will assume a console width of 80 and we don't want something to wrap //causing a blank line LMaxLen := CalcMaxLen(ARoot, ACurDir, ALOutput, Recurse); //if more than 39, we probably are going to exceed the width of the screen, //just treat as one column if LMaxLen > 39 then begin ProcessOnePathCol(ARoot, ACurDir, ALOutput, Recurse); Exit; end; if Recurse and Assigned(ACurDir.SubDirs) then begin if Recurse then begin PrintSubDirHeader(ARoot, ACurDir, ALOutput, Recurse); end; end; LCols := 79 div (LMaxLen + 2);//2 spaces between columns LLines := ACurDir.FileList.COunt div LCols; //LFrm := '%' + IntToStr(LMaxLen+2) + 's'; if (ACurDir.FileList.COunt mod LCols) > 0 then begin Inc(LLines); end; for li := 1 to LLines do begin j := 0; LTmp := ''; repeat if ((li-1)+(LLInes*j)) < ACurDir.FileList.Count then begin LTmp := LTmp + PadString(NListItem(TIdFTPListOutputItem(ACurDir.FileList.Objects[(li-1)+(LLInes*j)])), LMaxLen, ' ') + ' '; end; Inc(j); until (j > LCols); ALOutput.Add(TrimRight(LTmp)); end; if Recurse and Assigned(ACurDir.SubDirs) then begin for li := 0 to ACurDir.SubDirs.Count -1 do begin LCurItem := TDirEntry(ACurDir.SubDirs[li]).DirListItem; if LCurItem.DirError then begin if li = 0 then begin ALOutput.Add(''); end; ALOutput.Add(IndyFormat('/bin/ls: %s: Permission denied', [LCurItem.FileName])); {do not localize} end else begin ProcessPathAccross(ARoot, TDirEntry(ACurDir.SubDirs[li]), ALOutput, Recurse); end; end; end; end; procedure ProcessPathComma(ARoot, ACurDir : TDirEntry; ALOutput : TStrings; const Recurse : Boolean = False); var li : Integer; LTmp : String; LCurItem : TIdFTPListOutputItem; begin if Recurse then begin PrintSubDirHeader(ARoot, ACurDir, ALOutput, Recurse); end; LTmp := ''; for li := 0 to ACurDir.FileList.Count -1 do begin LTmp := LTmp + NListItem(TIdFTPListOutputItem(ACurDir.FileList.Objects[li])) + ', '; end; IdDelete(LTmp, Length(LTmp)-1, 2); ALOutput.Text := ALOutput.Text + IndyWrapText(LTmp, EOL + ' ', LWS + ',' , 79); //79 good maxlen for text only terminals if Recurse and Assigned(ACurDir.SubDirs) then begin for li := 0 to ACurDir.SubDirs.Count -1 do begin LCurItem := TDirEntry(ACurDir.SubDirs[li]).DirListItem; if LCurItem.DirError then begin if li = 0 then begin ALOutput.Add(''); end; ALOutput.Add(IndyFormat('/bin/ls: %s: Permission denied', [LCurItem.FileName])); {do not localize} end else begin ProcessPathComma(ARoot, TDirEntry(ACurDir.SubDirs[li]), ALOutput, Recurse); end; end; end; end; procedure ProcessPathLong(ARoot, ACurDir : TDirEntry; ALOutput : TStrings; const Recurse : Boolean = False); var li : Integer; LBlockCount : Integer; LCurItem : TIdFTPListOutputItem; begin if Recurse then begin PrintSubDirHeader(ARoot, ACurDir, ALOutput, Recurse); end; if (DirFormat = doUnix) and ExportTotalLine then begin LBlockCount := 0; for li := 0 to ACurDir.FileList.Count-1 do begin LBlockCount := LBlockCount + TIdFTPListOutputItem(ACurDir.FileList.Objects[li]).NumberBlocks; end; ALOutput.Add(IndyFormat('total %d', [LBlockCount])); {Do not translate} end; for li := 0 to ACurDir.FileList.Count-1 do begin LCurItem := TIdFTPListOutputItem(ACurDir.FileList.Objects[li]); case DirFormat of doEPLF : ALOutput.Add(EPLFItem(LCurItem)); doWin32 : ALOutput.Add(Win32Item(LCurItem)); else ALOutput.Add(UnixItem(LCurItem)); end; end; if Recurse and Assigned(ACurDir.SubDirs) then begin for li := 0 to ACurDir.SubDirs.Count-1 do begin LCurItem := TDirEntry(ACurDir.SubDirs[li]).DirListItem; if LCurItem.DirError then begin if DirFormat = doUnix then begin if li = 0 then begin ALOutput.Add(''); end; ALOutput.Add(IndyFormat('/bin/ls: %s: Permission denied', [LCurItem.FileName])); {do not localize} end; end; ProcessPathLong(ARoot, TDirEntry(ACurDir.SubDirs[li]), ALOutput, Recurse); end; end; end; procedure DoUnixfParam(ARoot : TDirEntry; ALOutput : TStrings); var li : Integer; LIt : TIdFTPListItem; begin for li := 0 to ARoot.FileList.Count -1 do begin LIt := TIdFTPListItem(ARoot.FileList.Objects[li]); if LIt.ItemType = ditDirectory then begin ALOutput.Add(IndyGetFileName(LIt.FileName)); end; end; end; begin LShowNavSym := (DirFormat = doUnix) and HasSwitch(SWITCH_SHOW_ALLPERIOD); if LShowNavSym then begin LShowNavSym := not HasSwitch(SWITCH_HIDE_DIRPOINT); end; LRootPath := TDirEntry.Create('', nil); try for i := 0 to Count-1 do begin if Items[i].ItemType in [ditDirectory, ditSymbolicLinkDir] then begin if not IsNavPath(StripInitPathDelim(IndyGetFileName(Items[i].FileName))) then begin LRootPath.AddSubDir(StripInitPathDelim(Items[i].FileName), Items[i]); end else begin //if it's a "." or "..", we show it only in Unix mode and only with eht -a switch if LShowNavSym then begin LRootPath.AddFileName(StripInitPathDelim(Items[i].FileName), Items[i]); end; end; end; end; //add the file names for i := 0 to Count-1 do begin if Items[i].ItemType in [ditFile, ditSymbolicLink] then begin if IsNavPath(StripInitPathDelim(IndyGetFileName(Items[i].FileName))) then begin if LShowNavSym then begin LRootPath.AddFileName(StripInitPathDelim(Items[i].FileName), Items[i]); end; end else begin LRootPath.AddFileName(StripInitPathDelim(Items[i].FileName), Items[i]); end; end; end; //Note that Indy does not support a Last Access time in some file systems //so we use the u parameter to mean the same as the t parameter if HasSwitch(SWITCH_SORT_REVERSE) then begin if HasSwitch(SWITCH_SORTBY_MTIME) or HasSwitch(SWITCH_SORTBY_CTIME) then begin LRootPath.SortDescendMTime; end else if HasSwitch(SWITCH_SORTBY_EXT) then begin LRootPath.SortDescendFNameExt; end else if HasSwitch(SWITCH_SORTBY_SIZE) then begin LRootPath.SortDescendSize; end else begin LRootPath.SortDescendFName; end; end else if HasSwitch(SWITCH_SORTBY_MTIME) or HasSwitch(SWITCH_SORTBY_CTIME) then begin LRootPath.SortAscendMTime; end else if HasSwitch(SWITCH_SORTBY_EXT) then begin LRootPath.SortAscendFNameExt; end else if HasSwitch(SWITCH_SORTBY_SIZE) then begin LRootPath.SortAscendSize; end else begin LRootPath.SortAscendFName; end; //select the operation // do the selected output operation case DetermineOp of doColsAccross : ProcessPathAccross(LRootPath, LRootPath, AOutput, HasSwitch(SWITCH_RECURSIVE)); doColsDown : ProcessPathDown(LRootPath, LRootPath, AOutput, HasSwitch(SWITCH_RECURSIVE)); doOneCol : ProcessOnePathCol(LRootPath, LRootPath, AOutput, HasSwitch(SWITCH_RECURSIVE)); doOnlyDirs : DoUnixfParam(LRootPath, AOutput); doComma : ProcessPathComma(LRootPath, LRootPath, AOutput, HasSwitch(SWITCH_RECURSIVE)); else ProcessPathLong(LRootPath, LRootPath, AOutput, HasSwitch(SWITCH_RECURSIVE)); end; finally FreeAndNil(LRootPath); end; end; procedure TIdFTPListOutput.LISTOutputDir(AOutput: TStrings); begin InternelOutputDir(AOutput, True); end; function TIdFTPListOutput.MListItem(AItem: TIdFTPListOutputItem; AMLstOpts: TIdFTPFactOutputs): String; begin Result := ''; if AMLstOpts = [] then begin Result := AItem.FileName; Exit; end; if (Size in AMLstOpts) and AItem.SizeAvail then begin Result := 'size=' + IntToStr(AItem.Size) + ';'; {do not localize} end; if ItemType in AMLstOpts then begin Result := Result + 'type='; {do not localize} case AItem.ItemType of ditFile : begin Result := Result + 'file;'; {do not localize} end; ditDirectory : begin if AItem.FileName = '..' then begin {do not localize} Result := Result + 'pdir;'; {do not localize} end else if AItem.FileName = '.' then begin Result := Result + 'cdir;'; {do not localize} end else begin Result := Result + 'dir;'; {do not localize} end; end; ditSymbolicLink : begin Result := Result + 'OS.unix=slink:' + AItem.FileName + ';'; {do not localize} end; end; end; if Perm in AMLstOpts then begin Result := Result + 'perm=' + AItem.MLISTPermissions + ';'; {do not localize} end; if (winDriveType in AMLstOpts) and (AItem.WinDriveType<>-1) then begin Result := Result + 'win32.dt='+IntToStr(AItem.WinDriveType )+';'; end; if CreateTime in AMLstOpts then begin if AItem.CreationDateGMT <> 0 then begin Result := Result + 'create='+ FTPGMTDateTimeToMLS(AItem.CreationDateGMT) + ';'; {do not localize} end else if AItem.CreationDate <> 0 then begin Result := Result + 'create='+ FTPLocalDateTimeToMLS(AItem.CreationDate) + ';'; {do not localize} end; end; if (Modify in AMLstOpts) and AItem.ModifiedAvail then begin if AItem.ModifiedDateGMT <> 0 then begin Result := Result + 'modify='+ FTPGMTDateTimeToMLS(AItem.ModifiedDateGMT) + ';'; {do not localize} end else if AItem.ModifiedDate <> 0 then begin Result := Result + 'modify='+ FTPLocalDateTimeToMLS(AItem.ModifiedDate) + ';'; {do not localize} end; end; if UnixMODE in AMLstOpts then begin Result := Result + 'UNIX.mode='+ IndyFormat('%.4d', [PermsToChmodNo(UnixGetOutputOwnerPerms(AItem), UnixGetOutputGroupPerms(AItem), UnixGetOutputOtherPerms(AItem) )] ) + ';'; {do not localize} end; if UnixOwner in AMLstOpts then begin Result := Result + 'UNIX.owner=' + UnixGetOutputOwner(AItem) + ';'; {do not localize} end; if UnixGroup in AMLstOpts then begin Result := Result + 'UNIX.group=' + UnixGetOutputGroup(AItem) + ';'; {do not localize} end; if (Unique in AMLstOpts) and (AItem.UniqueID <> '') then begin Result := Result + 'unique=' + AItem.UniqueID + ';'; {do not localize} end; if LastAccessTime in AMLstOpts then begin if AItem.ModifiedDateGMT <> 0 then begin Result := Result + 'windows.lastaccesstime=' + FTPGMTDateTimeToMLS(AItem.ModifiedDateGMT) + ';'; {do not localize} end else if AItem.ModifiedDate <> 0 then begin Result := Result + 'windows.lastaccesstime=' + FTPLocalDateTimeToMLS(AItem.ModifiedDate) + ';'; {do not localize} end; end; if WinAttribs in AMLstOpts then begin Result := Result + 'win32.ea=0x' + IntToHex(AItem.WinAttribs, 8) + ';'; {do not localize} end; if (AItem.WinDriveType > -1) and (WinDriveType in AMLstOpts) then begin Result := Result + 'Win32.dt='+IntToStr( AItem.WinDriveType ) + ';'; end; if (AItem.WinDriveLabel <> '') and (WinDriveLabel in AMLstOpts) then begin Result := Result + 'Win32.dl='+AItem.WinDriveLabel; end; Result := Result + ' ' + AItem.FileName; end; procedure TIdFTPListOutput.MLISTOutputDir(AOutput : TStrings; AMLstOpts: TIdFTPFactOutputs); var i : Integer; begin AOutput.Clear; for i := 0 to Count-1 do begin AOutput.Add(MListItem(Items[i], AMLstOpts)); end; end; function TIdFTPListOutput.NListItem(AItem: TIdFTPListOutputItem): String; begin Result := IndyGetFileName(AItem.FileName); if DirFormat = doUnix then begin if HasSwitch(SWITCH_QUOTEDNAME) then begin Result := '"' + Result + '"'; end; if HasSwitch(SWITCH_CLASSIFY) or HasSwitch(SWITCH_SLASHDIR) then begin case AItem.ItemType of ditDirectory : Result := Result + PATH_SUBDIR_SEP_UNIX; ditSymbolicLink, ditSymbolicLinkDir : Result := Result + '@'; else begin if IsUnixExec(AItem.UnixOwnerPermissions, AItem.UnixGroupPermissions , AItem.UnixOtherPermissions) then begin Result := Result + '*'; end; end; end; end; Result := UnixinodeOutput(AItem)+ UnixBlocksOutput(AItem) + Result; end; end; procedure TIdFTPListOutput.NLISTOutputDir(AOutput: TStrings); begin InternelOutputDir(AOutput, False); end; procedure TIdFTPListOutput.SetItems(AIndex: Integer; const AValue: TIdFTPListOutputItem); begin inherited Items[AIndex] := AValue; end; function TIdFTPListOutput.UnixBlocksOutput(AItem: TIdFTPListOutputItem): String; begin if HasSwitch(SWITCH_PRINT_BLOCKS) then begin Result := IndyFormat('%4d ', [AItem.NumberBlocks]); end else begin Result := ''; end; end; function TIdFTPListOutput.UnixGetOutputGroup(AItem: TIdFTPListOutputItem): String; begin if AItem.GroupName = '' then begin Result := UnixGetOutputOwner(AItem); end else begin Result := AItem.GroupName; end; end; function TIdFTPListOutput.UnixGetOutputGroupPerms(AItem: TIdFTPListOutputItem): String; begin if AItem.UnixOtherPermissions = '' then begin if AItem.ItemType in [ditSymbolicLink, ditSymbolicLinkDir] then begin Result := DEF_DIR_GRP_PERM; end else begin Result := DEF_FILE_GRP_PERM; end; end else begin Result := AItem.UnixOtherPermissions; end; end; function TIdFTPListOutput.UnixGetOutputOtherPerms(AItem: TIdFTPListOutputItem): String; begin if AItem.UnixOtherPermissions = '' then begin if AItem.ItemType in [ditSymbolicLink, ditSymbolicLinkDir] then begin Result := DEF_DIR_OTHER_PERM; end else begin Result := DEF_FILE_OTHER_PERM; end; end else begin Result := AItem.UnixOtherPermissions; end; end; function TIdFTPListOutput.UnixGetOutputOwner(AItem: TIdFTPListOutputItem): String; begin if AItem.OwnerName = '' then begin Result := DEF_OWNER; end else begin Result := AItem.OwnerName; end; end; function TIdFTPListOutput.UnixGetOutputOwnerPerms(AItem: TIdFTPListOutputItem): String; begin if AItem.UnixOwnerPermissions = '' then begin if AItem.ItemType in [ditSymbolicLink, ditSymbolicLinkDir] then begin Result := DEF_DIR_OWN_PERM; end else begin Result := DEF_FILE_OWN_PERM; end; end else begin Result := AItem.UnixOwnerPermissions; end; end; function TIdFTPListOutput.UnixINodeOutput(AItem: TIdFTPListOutputItem): String; var LInode : String; begin Result := ''; if HasSwitch(SWITCH_PRINT_INODE) then begin LInode := IntToStr(Abs(AItem.Inode)); //should be no more than 10 digits LInode := Copy(LInode, 1, 10); Result := Result + IndyFormat('%10s ', [LInode]); end; end; function TIdFTPListOutput.UnixItem(AItem: TIdFTPListOutputItem): String; var LSize, LTime: string; l, month: Word; LLinkNum : Integer; LFileName : String; LFormat : String; LMTime : TDateTime; begin LFileName := IndyGetFileName(AItem.FileName); Result := UnixINodeOutput(AItem) + UnixBlocksOutput(AItem); case AItem.ItemType of ditDirectory: begin AItem.Size := UNIX_DIR_SIZE; LSize := 'd'; {Do not Localize} end; ditSymbolicLink: begin LSize := 'l'; {Do not Localize} end; else begin LSize := '-'; {Do not Localize} end; end; if AItem.LinkCount = 0 then begin LLinkNum := 1; end else begin LLinkNum := AItem.LinkCount; end; LFormat := '%3:3s%4:3s%5:3s %6:3d '; {Do not localize} //g - surpress owner //lrwxrwxrwx 1 other 7 Nov 16 2001 bin -> usr/bin //where it would normally print //lrwxrwxrwx 1 root other 7 Nov 16 2001 bin -> usr/bin if not HasSwitch('g') then begin LFormat := LFormat + '%1:-8s '; {Do not localize} end; //o - surpress group //lrwxrwxrwx 1 root 7 Nov 16 2001 bin -> usr/bin //where it would normally print //lrwxrwxrwx 1 root other 7 Nov 16 2001 bin -> usr/bin if not HasSwitch('o') then begin LFormat := LFormat + '%2:-8s '; {Do not localize} end; LFormat := LFormat + '%0:8d'; {Do not localize} LSize := LSize + IndyFormat(LFormat, [AItem.Size, UnixGetOutputOwner(AItem), UnixGetOutputGroup(AItem), UnixGetOutputOwnerPerms(AItem), UnixGetOutputGroupPerms(AItem), UnixGetOutputOtherPerms(AItem), LLinkNum]); LMTime := GetLocalModTime(AItem); DecodeDate(LMTime, l, month, l); LTime := MonthNames[month] + FormatDateTime(' dd', LMTime); {Do not Localize} if HasSwitch(SWITCH_BOTH_TIME_YEAR) then begin LTime := LTime + FormatDateTime(' hh:nn:ss yyyy', LMTime); {Do not Localize} end else if IsIn6MonthWindow(LMTime) then begin {Do not Localize} LTime := LTime + FormatDateTime(' hh:nn', LMTime); {Do not Localize} end else begin LTime := LTime + FormatDateTime(' yyyy', LMTime); {Do not Localize} end; // A.Neillans, 20 Apr 2002, Fixed glitch, extra space in front of names. // Result := LSize + ' ' + LTime + ' ' + FileName; {Do not Localize} Result := Result + LSize + ' ' + LTime + ' '; if HasSwitch(SWITCH_QUOTEDNAME) then begin Result := Result + '"' + LFileName + '"'; {Do not Localize} end else begin Result := Result + LFileName; end; if AItem.ItemType in [ditSymbolicLink, ditSymbolicLinkDir] then begin if HasSwitch(SWITCH_QUOTEDNAME) then begin Result := Result + UNIX_LINKTO_SYM + '"' + AItem.LinkedItemName + '"'; {Do not Localize} end else begin Result := Result + UNIX_LINKTO_SYM + AItem.LinkedItemName; end; end; if ((IndyPos(SWITCH_CLASSIFY,Switches)>0) or (IndyPos(SWITCH_SLASHDIR,Switches)>0)) and {Do not translate} (AItem.ItemType in [ditDirectory, ditSymbolicLinkDir]) then begin Result := Result + PATH_SUBDIR_SEP_UNIX; end; if HasSwitch(SWITCH_CLASSIFY) and (AItem.ItemType = ditFile) and IsUnixExec(UnixGetOutputOwnerPerms(AItem), UnixGetOutputGroupPerms(AItem), UnixGetOutputOtherPerms(AItem)) then begin //star is placed at the end of a file name //like this: //-r-xr-xr-x 1 0 1 17440 Aug 8 2000 ls* Result := Result + '*'; end; end; function TIdFTPListOutput.Win32Item(AItem: TIdFTPListOutputItem): String; var LSize, LFileName : String; begin LFileName := IndyGetFileName(AItem.FileName); if AItem.ItemType = ditDirectory then begin LSize := ' <DIR>' + StringOfChar(' ', 9); {Do not Localize} end else begin LSize := StringOfChar(' ', 20 - Length(IntToStr(AItem.Size))) + IntToStr(AItem.Size); {Do not Localize} end; Result := FormatDateTime('mm-dd-yy hh:nnAM/PM', GetLocalModTime(AItem)) + ' ' + LSize + ' ' + LFileName; {Do not Localize} end; { TDirEntry } function TDirEntry.AddFileName(const APathName: String; ADirEnt: TIdFTPListOutputItem) : Boolean; var i : Integer; LParentPart : String; LDirEnt : TDirEntry; begin Result := False; LParentPart := StripInitPathDelim(IndyGetFilePath(APathName)); if LParentPart = PathName then begin if FFileList.IndexOf(APathName) = -1 then begin FFileList.AddObject(APathName, ADirEnt); end; Result := True; Exit; end; if Assigned(SubDirs) then begin for i := 0 to SubDirs.Count-1 do begin LDirEnt := TDirEntry(SubDirs[i]); LParentPart := StripInitPathDelim(IndyGetFilePath(LDirEnt.FDirListItem.FileName)); if TextStartsWith(APathName, LParentPart) then begin if TDirEntry(SubDirs[i]).AddFileName(APathName, ADirEnt) then begin Result := True; Break; end; end; end; end; end; function TDirEntry.AddSubDir(const APathName: String; ADirEnt: TIdFTPListOutputItem) : Boolean; var LDirEnt : TDirEntry; i : Integer; LParentPart : String; begin Result := False; LParentPart := StripInitPathDelim(IndyGetFilePath(APathName)); if LParentPart = PathName then begin if not Assigned(FSubDirs) then begin FSubDirs := TIdObjectList.Create; end; LParentPart := StripInitPathDelim(IndyGetFilePath(APathName)); LParentPart := IndyGetFileName(LParentPart); LDirEnt := TDirEntry.Create(APathName, ADirEnt); try FSubDirs.Add(LDirEnt); except LDirEnt.Free; raise; end; AddFileName(APathName, ADirEnt); Result := True; Exit; end; if Assigned(SubDirs) then begin for i := 0 to SubDirs.Count-1 do begin LDirEnt := TDirEntry(SubDirs[i]); LParentPart := StripInitPathDelim(IndyGetFilePath(LDirEnt.FDirListItem.FileName)); if TextStartsWith(APathName, LParentPart) then begin if LDirEnt.AddSubDir(APathName, ADirEnt) then begin Result := True; Break; end; end; end; end; end; constructor TDirEntry.Create(const APathName : String; ADirListItem : TIdFTPListOutputItem); begin inherited Create; FPathName := APathName; FFileList := TIdBubbleSortStringList.Create; FDirListItem := ADirListItem; //create that only when necessary; FSubDirs := TIdObjectList.Create; end; destructor TDirEntry.Destroy; begin FreeAndNil(FFileList); FreeAndNil(FSubDirs); inherited Destroy; end; procedure TDirEntry.SortAscendFName; var i : Integer; begin if Assigned(FFileList) then begin FFileList.BubbleSort(StrSortAscFName); end; if Assigned(FSubDirs) then begin FSubDirs.BubbleSort(TIdSortCompare(@DESortAscFName)); for i := 0 to FSubDirs.Count-1 do begin TDirEntry(FSubDirs[i]).SortAscendFName; end; end; end; procedure TDirEntry.SortAscendMTime; var i : Integer; begin if Assigned(FFileList) then begin FFileList.BubbleSort(StrSortAscMTime); end; if Assigned(FSubDirs) then begin FSubDirs.BubbleSort(TIdSortCompare(@DESortAscMTime)); for i := 0 to FSubDirs.Count-1 do begin TDirEntry(FSubDirs[i]).SortAscendMTime; end; end; end; procedure TDirEntry.SortDescendMTime; var i : Integer; begin if Assigned(FFileList) then begin FFileList.BubbleSort(StrSortDescMTime); end; if Assigned(FSubDirs) then begin FSubDirs.BubbleSort(TIdSortCompare(@DESortDescMTime)); for i := 0 to FSubDirs.Count -1 do begin TDirEntry(FSubDirs[i]).SortDescendMTime; end; end; end; procedure TDirEntry.SortDescendFName; var i : Integer; begin if Assigned(FSubDirs) then begin FSubDirs.BubbleSort(TIdSortCompare(@DESortDescFName)); for i := 0 to FSubDirs.Count-1 do begin TDirEntry(FSubDirs[i]).SortDescendFName; end; end; if Assigned(FFileList) then begin FFileList.BubbleSort(StrSortDescFName); end; end; procedure TDirEntry.SortAscendFNameExt; var i : Integer; begin if Assigned(FFileList) then begin FFileList.BubbleSort(StrSortAscFNameExt); end; if Assigned(FSubDirs) then begin FSubDirs.BubbleSort(TIdSortCompare(@DESortAscFName)); for i := 0 to FSubDirs.Count-1 do begin TDirEntry(FSubDirs[i]).SortAscendFNameExt; end; end; end; procedure TDirEntry.SortDescendFNameExt; var i : Integer; begin if Assigned(FFileList) then begin FFileList.BubbleSort(StrSortDescFNameExt); end; if Assigned(FSubDirs) then begin FSubDirs.BubbleSort(TIdSortCompare(@DESortAscFName)); for i := 0 to FSubDirs.Count-1 do begin TDirEntry(FSubDirs[i]).SortDescendFNameExt; end; end; end; procedure TDirEntry.SortAscendSize; var i : Integer; begin if Assigned(FFileList) then begin FFileList.BubbleSort(StrSortAscSize); end; if Assigned(FSubDirs) then begin FSubDirs.BubbleSort(TIdSortCompare(@DESortAscMTime)); for i := 0 to FSubDirs.Count-1 do begin TDirEntry(FSubDirs[i]).SortAscendSize; end; end; end; procedure TDirEntry.SortDescendSize; var i : Integer; begin if Assigned(FFileList) then begin FFileList.BubbleSort(StrSortDescSize); end; if Assigned(FSubDirs) then begin FSubDirs.BubbleSort(TIdSortCompare(@DESortDescFName)); for i := 0 to FSubDirs.Count-1 do begin TDirEntry(FSubDirs[i]).SortDescendSize; end; end; end; { TIdFTPListOutputItem } constructor TIdFTPListOutputItem.Create(AOwner: TCollection); begin inherited Create(AOwner); //indicate that this fact is not applicable FWinDriveType := -1; end; end.
program ultiboimgconv; {$mode objfpc}{$H+} { Raspberry Pi 3 Application } { Add your program code below, add additional units to the "uses" section if } { required and create new units by selecting File, New Unit from the menu. } { } { To compile your program select Run, Compile (or Run, Build) from the menu. } {_$define UseFile} uses RaspberryPi3, GlobalConfig, GlobalConst, GlobalTypes, Platform, Threads, Console, SysUtils, UltiboUtils, {Include Ultibo utils for some command line manipulation} HTTP, {Include HTTP and WebStatus so we can see from a web browser what is happening} WebStatus, Classes, Ultibo, FPImage, FPWriteXPM, FPWritePNG, FPWriteBMP, FPReadXPM, FPReadPNG, FPReadBMP, fpreadjpeg, fpwritejpeg, fpreadtga, fpwritetga, fpreadpnm, fpwritepnm, uTFTP, Winsock2, { needed to use ultibo-tftp } { needed for telnet } Shell, ShellFilesystem, ShellUpdate, RemoteShell, { needed for telnet } Logging, Syscalls {Include the Syscalls unit to provide C library support} { Add additional units here }; var img : TFPMemoryImage; reader : TFPCustomImageReader; Writer : TFPCustomimageWriter; ReadFile, WriteFile, WriteOptions : string; INPUTFILETYPE,OUTPUTFILETYPE: String; INPUTFILE,OUTPUTFILE: String; WindowHandle:TWindowHandle; MyPLoggingDevice : ^TLoggingDevice; HTTPListener:THTTPListener; { needed to use ultibo-tftp } TCP : TWinsock2TCPClient; IPAddress : string; function WaitForIPComplete : string; var TCP : TWinsock2TCPClient; begin TCP := TWinsock2TCPClient.Create; Result := TCP.LocalAddress; if (Result = '') or (Result = '0.0.0.0') or (Result = '255.255.255.255') then begin while (Result = '') or (Result = '0.0.0.0') or (Result = '255.255.255.255') do begin sleep (1500); Result := TCP.LocalAddress; end; end; TCP.Free; end; procedure Msg (Sender : TObject; s : string); begin ConsoleWindowWriteLn (WindowHandle, s); end; procedure WaitForSDDrive; begin while not DirectoryExists ('C:\') do sleep (500); end; procedure Init; var t : char; begin if paramcount = 4 then begin T := upcase (paramstr(1)[1]); if T = 'X' then Reader := TFPReaderXPM.Create else if T = 'B' then Reader := TFPReaderBMP.Create else if T = 'J' then Reader := TFPReaderJPEG.Create else if T = 'P' then Reader := TFPReaderPNG.Create else if T = 'T' then Reader := TFPReaderTarga.Create else if T = 'N' then Reader := TFPReaderPNM.Create else begin Writeln('Unknown file format : ',T); //Halt(1); end; ReadFile := paramstr(2); WriteOptions := paramstr(3); WriteFile := paramstr(4); end else begin Reader := nil; ReadFile := paramstr(1); WriteOptions := paramstr(2); WriteFile := paramstr(3); end; WriteOptions := uppercase (writeoptions); T := WriteOptions[1]; if T = 'X' then Writer := TFPWriterXPM.Create else if T = 'B' then begin Writer := TFPWriterBMP.Create; TFPWriterBMP(Writer).BitsPerPixel:=32; end else if T = 'J' then Writer := TFPWriterJPEG.Create else if T = 'P' then Writer := TFPWriterPNG.Create else if T = 'T' then Writer := TFPWriterTARGA.Create else if T = 'N' then Writer := TFPWriterPNM.Create else begin Writeln('Unknown file format : ',T); //Halt(1); end; img := TFPMemoryImage.Create(0,0); img.UsePalette:=false; end; procedure ReadImage; {$ifndef UseFile}var str : TStream;{$endif} begin if assigned (reader) then img.LoadFromFile (ReadFile, Reader) else {$ifdef UseFile} img.LoadFromFile (ReadFile); {$else} if fileexists (ReadFile) then begin str := TFileStream.create (ReadFile,fmOpenRead); try img.loadFromStream (str); finally str.Free; end; end else writeln ('File ',readfile,' doesn''t exists!'); {$endif} end; procedure WriteImage; var t : string; begin t := WriteOptions; writeln (' WriteImage, options=',t); if (t[1] = 'P') then with (Writer as TFPWriterPNG) do begin Grayscale := pos ('G', t) > 0; Indexed := pos ('I', t) > 0; WordSized := pos('W', t) > 0; UseAlpha := pos ('A', t) > 0; writeln ('Grayscale ',Grayscale, ' - Indexed ',Indexed, ' - WordSized ',WordSized,' - UseAlpha ',UseAlpha); end else if (t[1] = 'X') then begin if length(t) > 1 then with (Writer as TFPWriterXPM) do begin ColorCharSize := ord(t[2]) - ord('0'); end; end; writeln ('Options checked, now writing...'); img.SaveToFile (WriteFile, Writer); end; procedure Clean; begin Reader.Free; Writer.Free; Img.Free; end; begin { Add your program code here } {Create a console window as usual} WindowHandle:=ConsoleWindowCreate(ConsoleDeviceGetDefault,CONSOLE_POSITION_FULL,True); ConsoleWindowWriteLn(WindowHandle,'Starting FPImage Imgconv'); // Prompt for file type {ConsoleWindowWrite(WindowHandle,'Enter Input file type (X for XPM, P for PNG, B for BMP, J for JPEG, T for TGA): '); ConsoleWindowReadLn(WindowHandle,INPUTFILEType); ConsoleWindowWrite(WindowHandle,'Enter Output file type (X for XPM, P for PNG, B for BMP, J for JPEG, T for TGA): '); ConsoleWindowReadLn(WindowHandle,OUTPUTFILEType); ConsoleWindowWrite(WindowHandle,'Enter Input file '); ConsoleWindowReadLn(WindowHandle,INPUTFILE); ConsoleWindowWrite(WindowHandle,'Enter Output file '); ConsoleWindowReadLn(WindowHandle,OUTPUTFILE); ConsoleWindowWriteln(WindowHandle, INPUTFILEType+' '+INPUTFILE); ConsoleWindowWriteln(WindowHandle, OUTPUTFILEType+' '+OUTPUTFILE);} {Wait a couple of seconds for C:\ drive to be ready} ConsoleWindowWriteLn(WindowHandle,'Waiting for drive C:\'); while not DirectoryExists('C:\') do begin {Sleep for a second} Sleep(1000); end; // wait for IP address and SD Card to be initialised. WaitForSDDrive; IPAddress := WaitForIPComplete; {Wait a few seconds for all initialization (like filesystem and network) to be done} Sleep(5000); ConsoleWindowWriteLn(WindowHandle,'C:\ drive is ready'); ConsoleWindowWriteLn(WindowHandle,''); ConsoleWindowWriteLn (WindowHandle, 'Local Address ' + IPAddress); SetOnMsg (@Msg); {Create and start the HTTP Listener for our web status page} {HTTPListener:=THTTPListener.Create; HTTPListener.Active:=True; {Register the web status page, the "Thread List" page will allow us to see what is happening in the example} WebStatusRegister(HTTPListener,'','',True);} ConsoleWindowWriteLn(WindowHandle,'Completed setting up WebStatus & IP'); HTTPListener:=THTTPListener.Create; HTTPListener.Active:=True; {Register the web status page, the "Thread List" page will allow us to see what is happening in the example} WebStatusRegister(HTTPListener,'','',True); ConsoleWindowWriteLn(WindowHandle,'Initing'); Reader := TFPReaderPNG.create; ConsoleWindowWriteLn(WindowHandle,'Reader bmp'); Writer := TFPWriterBMP.Create; ConsoleWindowWriteLn(WindowHandle,'Writer png'); ReadFile := 'lena640480.png'; WriteFile := 'lena640480.bmp'; WriteOptions := 'B'; img := TFPMemoryImage.Create(0,0); img.UsePalette:=false; ConsoleWindowWriteLn(WindowHandle,' img create & UsePalette false'); ConsoleWindowWriteLn(WindowHandle,'Calling ReadImage ReadFile '+ReadFile); if assigned (reader) then ConsoleWindowWriteLn(WindowHandle,'reader is assigned') else ConsoleWindowWriteLn(WindowHandle,'reader is not assigned'); ReadImage; ConsoleWindowWriteLn(WindowHandle,'Calling WriteImage WriteFile '+WriteFile +' ' + WriteOptions); WriteImage; Clean; {Halt the main thread here} ThreadHalt(0); end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpIX9ECPoint; {$I ..\Include\CryptoLib.inc} interface uses ClpCryptoLibTypes, ClpIProxiedInterface, ClpIECInterface; type IX9ECPoint = interface(IAsn1Encodable) ['{B91190B8-A56A-4231-9687-24E4BB1397C7}'] function GetPointEncoding(): TCryptoLibByteArray; function GetIsPointCompressed: Boolean; function GetPoint: IECPoint; property Point: IECPoint read GetPoint; property IsPointCompressed: Boolean read GetIsPointCompressed; end; implementation end.
{ lzRichEdit Copyright (C) 2010 Elson Junio elsonjunio@yahoo.com.br This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit Win32WSRichBoxFactory; {$mode objfpc}{$H+} interface uses RichBox, Win32WSRichBox, WSLCLClasses; function RegisterCustomRichBox: Boolean; implementation function RegisterCustomRichBox: Boolean; alias : 'WSRegisterCustomRichBox'; begin Result := True; RegisterWSComponent(TCustomRichBox, TWin32WSCustomRichBox); end; end.
unit mp_types; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TStat = record attempts,tAttempts,status,loses:integer; ms: double; end; { TPingItem } TPingItem = class(TCollectionItem) public //stored IP: string; Name: string; Melody: string; PlaySound: integer; CheckTimeout: integer; AlarmTimeout: integer; AsHost: boolean; //not stored CurrentStat: TStat; constructor Create(Col: TCollection); override; destructor Destroy; override; end; { TPingItemList } TPingItemList = class(TCollection) function GetItems(Index: Integer): TPingItem; public function AddItem: TPingItem; constructor Create; property Items[Index: Integer]: TPingItem read GetItems; default; end; { TNetworkItem } TNetworkItem = class(TCollectionItem) public Name: string; PCList: TPingItemList; constructor Create(Col: TCollection); override; destructor Destroy; override; end; TNetwork = class(TCollection) function GetItems(Index: Integer): TNetworkItem; public function AddItem: TNetworkItem; constructor Create; property Items[Index: Integer]: TNetworkItem read GetItems; default; end; implementation function TNetwork.GetItems(Index: Integer): TNetworkItem; begin Result := TNetworkItem(inherited Items[Index]); end; function TNetwork.AddItem: TNetworkItem; begin Result := TNetworkItem(inherited Add()); end; constructor TNetwork.Create; begin inherited Create(TNetworkItem); end; { TNetworkItem } constructor TNetworkItem.Create(Col: TCollection); begin inherited Create(Col); PCList:=TPingItemList.Create; end; destructor TNetworkItem.Destroy; begin inherited Destroy; end; constructor TPingItem.Create(Col: TCollection); begin inherited Create(Col); end; destructor TPingItem.Destroy; begin inherited Destroy; end; { TPingItemList } function TPingItemList.GetItems(Index: Integer): TPingItem; begin Result := TPingItem(inherited Items[Index]); end; function TPingItemList.AddItem: TPingItem; begin Result := TPingItem(inherited Add()); end; constructor TPingItemList.Create; begin inherited Create(TPingItem); end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpMiscObjectIdentifiers; {$I ..\..\Include\CryptoLib.inc} interface uses ClpDerObjectIdentifier, ClpIDerObjectIdentifier; type TMiscObjectIdentifiers = class abstract(TObject) strict private class var FIsBooted: Boolean; Fblake2, Fid_blake2b160, Fid_blake2b256, Fid_blake2b384, Fid_blake2b512, Fid_blake2s128, Fid_blake2s160, Fid_blake2s224, Fid_blake2s256 : IDerObjectIdentifier; class function Getblake2: IDerObjectIdentifier; static; inline; class function Getid_blake2b160: IDerObjectIdentifier; static; inline; class function Getid_blake2b256: IDerObjectIdentifier; static; inline; class function Getid_blake2b384: IDerObjectIdentifier; static; inline; class function Getid_blake2b512: IDerObjectIdentifier; static; inline; class function Getid_blake2s128: IDerObjectIdentifier; static; inline; class function Getid_blake2s160: IDerObjectIdentifier; static; inline; class function Getid_blake2s224: IDerObjectIdentifier; static; inline; class function Getid_blake2s256: IDerObjectIdentifier; static; inline; class constructor MiscObjectIdentifiers(); public class property blake2: IDerObjectIdentifier read Getblake2; class property id_blake2b160: IDerObjectIdentifier read Getid_blake2b160; class property id_blake2b256: IDerObjectIdentifier read Getid_blake2b256; class property id_blake2b384: IDerObjectIdentifier read Getid_blake2b384; class property id_blake2b512: IDerObjectIdentifier read Getid_blake2b512; class property id_blake2s128: IDerObjectIdentifier read Getid_blake2s128; class property id_blake2s160: IDerObjectIdentifier read Getid_blake2s160; class property id_blake2s224: IDerObjectIdentifier read Getid_blake2s224; class property id_blake2s256: IDerObjectIdentifier read Getid_blake2s256; class procedure Boot(); static; end; implementation { TMiscObjectIdentifiers } class function TMiscObjectIdentifiers.Getblake2: IDerObjectIdentifier; begin result := Fblake2; end; class function TMiscObjectIdentifiers.Getid_blake2b160: IDerObjectIdentifier; begin result := Fid_blake2b160; end; class function TMiscObjectIdentifiers.Getid_blake2b256: IDerObjectIdentifier; begin result := Fid_blake2b256; end; class function TMiscObjectIdentifiers.Getid_blake2b384: IDerObjectIdentifier; begin result := Fid_blake2b384; end; class function TMiscObjectIdentifiers.Getid_blake2b512: IDerObjectIdentifier; begin result := Fid_blake2b512; end; class function TMiscObjectIdentifiers.Getid_blake2s128: IDerObjectIdentifier; begin result := Fid_blake2s128; end; class function TMiscObjectIdentifiers.Getid_blake2s160: IDerObjectIdentifier; begin result := Fid_blake2s160; end; class function TMiscObjectIdentifiers.Getid_blake2s224: IDerObjectIdentifier; begin result := Fid_blake2s224; end; class function TMiscObjectIdentifiers.Getid_blake2s256: IDerObjectIdentifier; begin result := Fid_blake2s256; end; class procedure TMiscObjectIdentifiers.Boot; begin if not FIsBooted then begin // // Blake2b and Blake2s // Fblake2 := TDerObjectIdentifier.Create('1.3.6.1.4.1.1722.12.2'); Fid_blake2b160 := blake2.Branch('1.5'); Fid_blake2b256 := blake2.Branch('1.8'); Fid_blake2b384 := blake2.Branch('1.12'); Fid_blake2b512 := blake2.Branch('1.16'); Fid_blake2s128 := blake2.Branch('2.4'); Fid_blake2s160 := blake2.Branch('2.5'); Fid_blake2s224 := blake2.Branch('2.7'); Fid_blake2s256 := blake2.Branch('2.8'); FIsBooted := True; end; end; class constructor TMiscObjectIdentifiers.MiscObjectIdentifiers; begin TMiscObjectIdentifiers.Boot; end; end.
unit uSettingsForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, LazUTF8, IDEWindowIntf, Forms, Controls, Graphics, Dialogs, IniPropStorage, ValEdit, StdCtrls, XMLPropStorage; type { TsettingsForm } TsettingsForm = class(TForm) Button1: TButton; edFilemanagerCmd: TEdit; edCommanderCmd: TEdit; edEditorCmd: TEdit; edTerminalCmd: TEdit; edFilemanagerParams: TEdit; edCommanderParams: TEdit; edEditorParams: TEdit; edAnnexCmd: TEdit; edTerminalParams: TEdit; edAnnexParams: TEdit; IniPropStorageCmd: TIniPropStorage; lblFilemanager: TLabel; lblCommander: TLabel; lblEditor: TLabel; lblTerminal: TLabel; lblAnnex: TLabel; procedure Button1Click(Sender: TObject); Procedure FormActivate(Sender: TObject); private function getAnnexCmd: string; function getAnnexParams: string; function getFilemanagerParams: string; function getCommanderCmd: string; function getCommanderParams: string; function getEditorCmd: string; function getEditorParams: string; function getFilemanagerCmd: string; function getTerminalCmd: string; function getTerminalParams: string; procedure LoadSettings; procedure SaveSettings; { private declarations } public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; // properties for config values property FilemanagerCmd: string read getFilemanagerCmd; property FilemanagerParams: string read getFilemanagerParams; property CommanderCmd: string read getCommanderCmd; property CommanderParams: string read getCommanderParams; property EditorCmd: string read getEditorCmd; property EditorParams: string read getEditorParams; property TerminalCmd: string read getTerminalCmd; property TerminalParams: string read getTerminalParams; property AnnexCmd: string read getAnnexCmd; property AnnexParams: string read getAnnexParams; end; var settingsForm: TsettingsForm; implementation {$R *.lfm} { TsettingsForm } function TsettingsForm.getFilemanagerCmd: string; begin Result := IniPropStorageCmd.StoredValue['FilemanagerCmd']; end; procedure TsettingsForm.Button1Click(Sender: TObject); begin SaveSettings; Close; end; Procedure TsettingsForm.FormActivate(Sender: TObject); Begin LoadSettings; end; function TsettingsForm.getAnnexCmd: string; begin Result := IniPropStorageCmd.StoredValue['AnnexCmd']; end; function TsettingsForm.getAnnexParams: string; begin Result := IniPropStorageCmd.StoredValue['AnnexParams']; end; function TsettingsForm.getFilemanagerParams: string; begin Result := IniPropStorageCmd.StoredValue['FilemanagerParams']; end; function TsettingsForm.getCommanderCmd: string; begin Result := IniPropStorageCmd.StoredValue['CommanderCmd']; end; function TsettingsForm.getCommanderParams: string; begin Result := IniPropStorageCmd.StoredValue['CommanderParams']; end; function TsettingsForm.getEditorCmd: string; begin Result := IniPropStorageCmd.StoredValue['EditorCmd']; end; function TsettingsForm.getEditorParams: string; begin Result := IniPropStorageCmd.StoredValue['EditorParams']; end; function TsettingsForm.getTerminalCmd: string; begin Result := IniPropStorageCmd.StoredValue['TerminalCmd']; end; function TsettingsForm.getTerminalParams: string; begin Result := IniPropStorageCmd.StoredValue['TerminalParams']; end; procedure TsettingsForm.LoadSettings; begin edFilemanagerCmd.Text := FilemanagerCmd; edFilemanagerParams.Text := FilemanagerParams; edCommanderCmd.Text := CommanderCmd; edCommanderParams.Text := CommanderParams; edEditorCmd.Text := EditorCmd; edEditorParams.Text := EditorParams; edTerminalCmd.Text := TerminalCmd; edTerminalParams.Text := TerminalParams; edAnnexCmd.Text := AnnexCmd; edAnnexParams.Text := AnnexParams; end; procedure TsettingsForm.SaveSettings; begin IniPropStorageCmd.StoredValue['FilemanagerCmd'] := edFilemanagerCmd.Text; IniPropStorageCmd.StoredValue['FilemanagerParams'] := edFilemanagerParams.Text; IniPropStorageCmd.StoredValue['CommanderCmd'] := edCommanderCmd.Text; IniPropStorageCmd.StoredValue['CommanderParams'] := edCommanderParams.Text; IniPropStorageCmd.StoredValue['EditorCmd'] := edEditorCmd.Text; IniPropStorageCmd.StoredValue['EditorParams'] := edEditorParams.Text; IniPropStorageCmd.StoredValue['TerminalCmd'] := edTerminalCmd.Text; IniPropStorageCmd.StoredValue['TerminalParams'] := edTerminalParams.Text; IniPropStorageCmd.StoredValue['AnnexCmd'] := edAnnexCmd.Text; IniPropStorageCmd.StoredValue['AnnexParams'] := edAnnexParams.Text; IniPropStorageCmd.Save; end; constructor TsettingsForm.Create(TheOwner: TComponent); begin inherited Create(TheOwner); IniPropStorageCmd.Active := False; IniPropStorageCmd.IniFileName := GetEnvironmentVariableUTF8('HOME') + '/.mloc.ini'; IniPropStorageCmd.Active := True; end; destructor TsettingsForm.Destroy; begin IniPropStorageCmd.Save; inherited Destroy; end; end.
Program locate; {$mode objfpc}{$H+} Uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, uMainDataModule, uTools, CustApp { you can add units after this }; Type { locate } { TLocate } TLocate = Class(TCustomApplication) private FAnnexOpen: String; Procedure writeStdResult; Procedure writeIceMenuResult; protected Procedure DoRun; override; Public Constructor Create(TheOwner: TComponent); override; Destructor Destroy; override; Procedure WriteHelp; virtual; End; { TLocate } Procedure TLocate.writeStdResult; Begin DM.SQLQueryResult.First; while not DM.SQLQueryResult.EOF do begin WriteLn(DM.getPath); DM.SQLQueryResult.Next; End; End; Procedure TLocate.writeIceMenuResult; Var lAnnex: String; Begin DM.SQLQueryResult.First; while not DM.SQLQueryResult.EOF do begin lAnnex := ''; if DM.isAnnex and (FAnnexOpen <> '') then lAnnex := FAnnexOpen; WriteLn('prog "' + DM.getItemName + '" "' + DM.getIcon + '" ' + lAnnex + ' ' + DM.getCommand + ' "' + DM.getPath + '"'); DM.SQLQueryResult.Next; End; End; Procedure TLocate.DoRun; Var ErrorMsg, lTag, lSearch, lPath: String; lNormalize, lIceMenu: Boolean; Begin // quick check parameters //ErrorMsg := CheckOptions('h', 'help'); //If ErrorMsg <> '' Then Begin // ShowException(Exception.Create(ErrorMsg)); // Terminate; // Exit; //End; // // parse parameters If HasOption('h', 'help') Then Begin WriteHelp; Terminate; Exit; End; { main program } if HasOption('l', 'localdb') then DM.DBPath := GetOptionValue('l', 'localdb') else DM.DBPath := IncludeTrailingPathDelimiter(GetUserDir) + '.mlocate.db'; lNormalize := HasOption('n', 'normalize'); if HasOption('t', 'tag') then lTag := GetOptionValue('t', 'tag'); if HasOption('p', 'path') then lPath := GetOptionValue('p', 'path'); if HasOption('a', 'annex') then FAnnexOpen := GetOptionValue('a', 'annex'); if HasOption('s', 'search') then lSearch := GetOptionValue('s', 'search'); if lSearch <> '' then if lNormalize then begin lSearch := NormalizeTerm(lSearch); lSearch := StringReplace(lSearch, ' ', '* ', [rfReplaceAll, rfIgnoreCase]); lSearch := Trim(lSearch + '*'); end; lIceMenu := HasOption('m', 'icemenu'); DM.DBSearch(lSearch, lPath, lTag); if lIceMenu then writeIceMenuResult else writeStdResult; // stop program loop Terminate; End; Constructor TLocate.Create(TheOwner: TComponent); Begin Inherited Create(TheOwner); StopOnException := True; End; Destructor TLocate.Destroy; Begin Inherited Destroy; End; Procedure TLocate.WriteHelp; Begin { add your help code here } writeln('Usage: ', ExeName); writeln(' -h --help show this help'); writeln(' -l --localdb path to database file, default: $HOME/.mlocate.db'); writeln(' -n --normalize normalize query pattern'); writeln(' -t --tag tag'); writeln(' -p --path=X paths for search'); writeln(' -s --search=X pattern for search'); writeln(' -m --menu format output as dynamic menu for icewm'); End; Var Application: TLocate; Begin Application := TLocate.Create(Nil); DM := TDM.Create(Application); Application.Run; Application.Free; End.
{******************************************************************************} { } { Delphi FB4D Library } { Copyright (c) 2018-2022 Christoph Schneider } { Schneider Infosystems AG, Switzerland } { https://github.com/SchneiderInfosystems/FB4D } { } {******************************************************************************} { } { 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 FB4D.FireStore.Listener; interface uses System.Types, System.Classes, System.SysUtils, System.Generics.Collections, System.NetConsts, System.Net.HttpClient, System.Net.URLClient, System.NetEncoding, System.SyncObjs, FB4D.Interfaces, FB4D.Helpers; type TTargetKind = (tkDocument, tkQuery); TTarget = record TargetID: cardinal; OnChangedDoc: TOnChangedDocument; OnDeletedDoc: TOnDeletedDocument; TargetKind: TTargetKind; // tkDocument: DocumentPath: string; // tkQuery: QueryJSON: string; end; TTargets = TList<TTarget>; TFSListenerThread = class(TThread) private const cWaitTimeBeforeReconnect = 2000; // 2 sec cTimeoutConnectionLost = 61000; // 1 minute 1sec cDefTimeOutInMS = 500; private type TInitMode = (Refetch, NewSIDRequest, NewListener); private fDatabase: string; fAuth: IFirebaseAuthentication; // For ListenForValueEvents fLastTokenRefreshCount: cardinal; fSID, fGSessionID: string; fRequestID: string; fClient: THTTPClient; fAsyncResult: IAsyncResult; fGetFinishedEvent: TEvent; fStream: TMemoryStream; fReadPos: Int64; fMsgSize: integer; fOnStopListening: TOnStopListenEvent; fOnListenError: TOnRequestError; fOnAuthRevoked: TOnAuthRevokedEvent; fOnConnectionStateChange: TOnConnectionStateChange; fDoNotSynchronizeEvents: boolean; fLastKeepAliveMsg: TDateTime; fLastReceivedMsg: TDateTime; fConnected: boolean; fRequireTokenRenew: boolean; fCloseRequest: boolean; fStopWaiting: boolean; fPartialResp: string; fLastTelegramNo: integer; fResumeToken: string; fTargets: TTargets; function GetTargetIndById(TargetID: cardinal): integer; function SearchForTarget(TargetKind: TTargetKind; const DocumentPath, QueryJSON: string; OnChangedDoc: TOnChangedDocument; OnDeletedDoc: TOnDeletedDocument; out TargetID: cardinal): boolean; function GetRequestData: string; procedure InitListen(Mode: TInitMode = Refetch); function RequestSIDInThread: boolean; function SearchNextMsg: string; procedure Parser; procedure Interprete(const Telegram: string); procedure ReportErrorInThread(const ErrMsg: string); procedure OnRecData(const Sender: TObject; ContentLength, ReadCount: Int64; var Abort: Boolean); procedure OnEndListenerGet(const ASyncResult: IAsyncResult); procedure OnEndThread(Sender: TObject); protected procedure Execute; override; public constructor Create(const ProjectID, DatabaseID: string; Auth: IFirebaseAuthentication); destructor Destroy; override; procedure RegisterEvents(OnStopListening: TOnStopListenEvent; OnError: TOnRequestError; OnAuthRevoked: TOnAuthRevokedEvent; OnConnectionStateChange: TOnConnectionStateChange; DoNotSynchronizeEvents: boolean); procedure StopListener(TimeOutInMS: integer = cDefTimeOutInMS); procedure StopNotStarted; function IsRunning: boolean; function SubscribeDocument(DocumentPath: TRequestResourceParam; OnChangedDoc: TOnChangedDocument; OnDeletedDoc: TOnDeletedDocument): cardinal; function SubscribeQuery(Query: IStructuredQuery; DocumentPath: TRequestResourceParam; OnChangedDoc: TOnChangedDocument; OnDeletedDoc: TOnDeletedDocument): cardinal; procedure Unsubscribe(TargetID: cardinal); function CloneTargets: TTargets; procedure RestoreClonedTargets(Targets: TTargets); property LastReceivedMsg: TDateTime read fLastReceivedMsg; end; implementation uses System.JSON, System.StrUtils, REST.Types, FB4D.Document, FB4D.Response, FB4D.Request; {$IFDEF DEBUG} {$DEFINE ParserLog} {.$DEFINE ParserLogDetails} {$ENDIF} const cBaseURL = 'https://firestore.googleapis.com/google.firestore.v1.Firestore'; cResourceParams: TRequestResourceParam = ['Listen', 'channel']; cVER = '8'; cCVER = '22'; cHttpHeaders = 'X-Goog-Api-Client:gl-js/ file(8.2.3'#13#10'Content-Type:text/plain'; resourcestring rsEvtListenerFailed = 'Event listener failed: %s'; rsEvtStartFailed = 'Event listener start failed: %s'; rsEvtParserFailed = 'Exception in listener: '; rsParserFailed = 'Exception in event parser: '; rsInterpreteFailed = 'Exception in event interpreter: '; rsUnknownStatus = 'Unknown status msg %d: %s'; rsUnexpectedExcept = 'Unexpected exception: '; rsUnexpectedThreadEnd = 'Listener unexpected stopped'; { TListenerThread } constructor TFSListenerThread.Create(const ProjectID, DatabaseID: string; Auth: IFirebaseAuthentication); var EventName: string; begin inherited Create(true); Assert(assigned(Auth), 'Authentication not initalized'); fAuth := Auth; fDatabase := 'projects/' + ProjectID + '/databases/' + DatabaseID; fTargets := TTargets.Create; {$IFDEF MSWINDOWS} EventName := 'FB4DFSListenerGetFini'; {$ELSE} EventName := ''; {$ENDIF} fGetFinishedEvent := TEvent.Create(nil, false, false, EventName); OnTerminate := OnEndThread; FreeOnTerminate := false; {$IFNDEF LINUX64} NameThreadForDebugging('FB4D.FSListenerThread', ThreadID); {$ENDIF} end; destructor TFSListenerThread.Destroy; begin fAsyncResult := nil; FreeAndNil(fGetFinishedEvent); FreeAndNil(fTargets); FreeAndNil(fStream); inherited; end; function TFSListenerThread.SubscribeDocument( DocumentPath: TRequestResourceParam; OnChangedDoc: TOnChangedDocument; OnDeletedDoc: TOnDeletedDocument): cardinal; var Target: TTarget; Path: string; begin if IsRunning then raise EFirestoreListener.Create( 'SubscribeDocument must not be called for started Listener'); Path := TFirebaseHelpers.EncodeResourceParams(DocumentPath); if not SearchForTarget(tkDocument, Path, '', OnChangedDoc, OnDeletedDoc, result) then begin Target.TargetID := (fTargets.Count + 1) * 2; Target.TargetKind := TTargetKind.tkDocument; Target.DocumentPath := Path; Target.QueryJSON := ''; Target.OnChangedDoc := OnChangedDoc; Target.OnDeletedDoc := OnDeletedDoc; fTargets.Add(Target); result := Target.TargetID; end; end; function TFSListenerThread.SubscribeQuery(Query: IStructuredQuery; DocumentPath: TRequestResourceParam; OnChangedDoc: TOnChangedDocument; OnDeletedDoc: TOnDeletedDocument): cardinal; var Target: TTarget; JSONobj: TJSONObject; begin if IsRunning then raise EFirestoreListener.Create( 'SubscribeQuery must not be called for started Listener'); JSONobj := Query.AsJSON; JSONobj.AddPair('parent', fDatabase + '/documents' + TFirebaseHelpers.EncodeResourceParams(DocumentPath)); if not SearchForTarget(tkQuery, '', JSONobj.ToJSON, OnChangedDoc, OnDeletedDoc, result) then begin Target.TargetID := (fTargets.Count + 1) * 2; Target.TargetKind := TTargetKind.tkQuery; Target.QueryJSON := JSONobj.ToJSON; Target.DocumentPath := ''; Target.OnChangedDoc := OnChangedDoc; Target.OnDeletedDoc := OnDeletedDoc; fTargets.Add(Target); result := Target.TargetID; end; end; procedure TFSListenerThread.Unsubscribe(TargetID: cardinal); var c: integer; begin if IsRunning then raise EFirestoreListener.Create( 'Unsubscribe must not be called for started Listener'); c := GetTargetIndById(TargetID); if c >= 0 then fTargets.Delete(c); end; function TFSListenerThread.GetTargetIndById(TargetID: cardinal): integer; var c: integer; begin for c := 0 to fTargets.Count - 1 do if fTargets[c].TargetID = TargetID then exit(c); result := -1; end; function TFSListenerThread.SearchForTarget(TargetKind: TTargetKind; const DocumentPath, QueryJSON: string; OnChangedDoc: TOnChangedDocument; OnDeletedDoc: TOnDeletedDocument; out TargetID: cardinal): boolean; var Target: TTarget; begin result := false; for Target in fTargets do if (Target.TargetKind = TargetKind) and (Target.DocumentPath = DocumentPath) and (Target.QueryJSON = QueryJSON) and (@Target.OnChangedDoc = @OnChangedDoc) and (@Target.OnDeletedDoc = @OnDeletedDoc) then begin TargetID := Target.TargetID; exit(true); end; end; function TFSListenerThread.CloneTargets: TTargets; var Target: TTarget; begin result := TTargets.Create; for Target in fTargets do result.Add(Target); end; procedure TFSListenerThread.RestoreClonedTargets(Targets: TTargets); var Target: TTarget; begin Assert(fTargets.Count = 0, 'RestoreClonedTargets expects empty target list'); Assert(assigned(Targets), 'RestoreClonedTargets missing targets argument'); for Target in Targets do fTargets.Add(Target); Targets.Free; // Free the cloned targets end; function TFSListenerThread.GetRequestData: string; const // Count=1 // ofs=0 // req0___data__={"database":"projects/<ProjectID>/databases/(default)", // "addTarget":{"documents":{"documents":["projects/<ProjectID>/databases/(default)/documents/<DBPath>"]}, // "targetId":2}} cResumeToken = ',"resumeToken":"%s"'; cDocumentTemplate = '{"database":"%0:s",' + '"addTarget":{' + '"documents":' + '{"documents":["%0:s/documents%1:s"]},' + '"targetId":%2:d%3:s}}'; cQueryTemplate = '{"database":"%0:s",' + '"addTarget":{' + '"query":%1:s,' + '"targetId":%2:d%3:s}}'; cHead = 'count=%d&ofs=0'; cTarget= '&req%d___data__=%s'; var Target: TTarget; ind: cardinal; JSON: string; begin ind := 0; result := Format(cHead, [fTargets.Count]); for Target in fTargets do begin if fResumeToken.IsEmpty then JSON := '' else JSON := Format(cResumeToken, [fResumeToken]); case Target.TargetKind of tkDocument: begin JSON := Format(cDocumentTemplate, [fDatabase, Target.DocumentPath, Target.TargetID, JSON]); {$IFDEF ParserLogDetails} TFirebaseHelpers.Log('FSListenerThread.GetRequestData Doc: ' + JSON); {$ENDIF} end; tkQuery: begin JSON := Format(cQueryTemplate, [fDatabase, Target.QueryJSON, Target.TargetID, JSON]); {$IFDEF ParserLogDetails} TFirebaseHelpers.Log('FSListenerThread.GetRequestData Query: ' + JSON); {$ENDIF} end; end; result := result + Format(cTarget, [ind, TNetEncoding.URL.Encode(JSON)]); inc(ind); end; end; procedure TFSListenerThread.Interprete(const Telegram: string); procedure HandleTargetChanged(ChangedObj: TJsonObject); var targetChangeType, msg: string; cause: TJsonObject; begin {$IFDEF ParserLog} TFirebaseHelpers.Log('FSListenerThread.Interprete.HandleTargetChanged: ' + ChangedObj.ToString); {$ENDIF} if ChangedObj.TryGetValue('resumeToken', fResumeToken) then begin {$IFDEF ParserLogDetails} TFirebaseHelpers.Log('FSListenerThread.Interprete Token: ' + fResumeToken); {$ENDIF} end else if ChangedObj.TryGetValue('targetChangeType', targetChangeType) and SameText(targetChangeType, 'REMOVE') and ChangedObj.TryGetValue('cause', cause) and cause.TryGetValue('message', msg) then ReportErrorInThread(msg); end; procedure HandleDocChanged(DocChangedObj: TJsonObject); var DocObj: TJsonObject; TargetIds: TJsonArray; c, ind: integer; Doc: IFirestoreDocument; begin DocObj := DocChangedObj.GetValue('document') as TJsonObject; TargetIds := DocChangedObj.GetValue('targetIds') as TJsonArray; Doc := TFirestoreDocument.CreateFromJSONObj(DocObj); try for c := 0 to TargetIds.Count - 1 do begin ind := GetTargetIndById(TargetIds.Items[c].AsType<integer>); if (ind >= 0) and assigned(fTargets[ind].OnChangedDoc) then begin if fDoNotSynchronizeEvents then fTargets[ind].OnChangedDoc(Doc) else TThread.Synchronize(nil, procedure begin fTargets[ind].OnChangedDoc(Doc); end); end; end; finally Doc := nil; end; end; function HandleDocDeleted(DocDeletedObj: TJsonObject): boolean; var DocPath: string; TargetIds: TJsonArray; TimeStamp: TDateTime; c, ind: integer; begin result := false; DocPath := DocDeletedObj.GetValue<string>('document'); TimeStamp := DocDeletedObj.GetValue<TDateTime>('readTime'); TargetIds := DocDeletedObj.GetValue('removedTargetIds') as TJsonArray; for c := 0 to TargetIds.Count - 1 do begin ind := GetTargetIndById(TargetIds.Items[c].AsType<integer>); if (ind >= 0) and assigned(fTargets[ind].OnDeletedDoc) then if fDoNotSynchronizeEvents then fTargets[ind].OnDeletedDoc(DocPath, TimeStamp) else TThread.Queue(nil, procedure begin fTargets[ind].OnDeletedDoc(DocPath, TimeStamp); end); end; end; procedure HandleErrorStatus(ErrObj: TJsonObject); var ErrCode: integer; begin ErrCode := (ErrObj.GetValue('code') as TJSONNumber).AsInt; case ErrCode of 401: // Missing or invalid authentication fRequireTokenRenew := true; else ReportErrorInThread(Format(rsUnknownStatus, [ErrCode, Telegram])); end; end; const cKeepAlive = '"noop"'; cClose = '"close"'; cDocChange = 'documentChange'; cDocDelete = 'documentDelete'; cDocRemove = 'documentRemove'; cTargetChange = 'targetChange'; cFilter = 'filter'; cStatusMessage = '__sm__'; var Obj: TJsonObject; ObjName: string; StatusArr, StatusArr2: TJSONArray; c, d: integer; begin try {$IFDEF ParserLog} TFirebaseHelpers.LogFmt('FSListenerThread.Interprete Telegram[%d] %s', [fLastTelegramNo, Telegram]); {$ENDIF} if Telegram = cKeepAlive then fLastKeepAliveMsg := now else if Telegram = cClose then fCloseRequest := true else if Telegram.StartsWith('{') and Telegram.EndsWith('}') then begin Obj := TJSONObject.ParseJSONValue(Telegram) as TJSONObject; try ObjName := Obj.Pairs[0].JsonString.Value; if ObjName = cTargetChange then HandleTargetChanged(Obj.Pairs[0].JsonValue as TJsonObject) else if ObjName = cFilter then // Filter(Obj.Pairs[0].JsonValue as TJsonObject) else if ObjName = cDocChange then HandleDocChanged(Obj.Pairs[0].JsonValue as TJsonObject) else if (ObjName = cDocDelete) or (ObjName = cDocRemove) then HandleDocDeleted(Obj.Pairs[0].JsonValue as TJsonObject) else if ObjName = cStatusMessage then begin StatusArr := (Obj.Pairs[0].JsonValue as TJsonObject). GetValue('status') as TJSONArray; for c := 0 to StatusArr.Count - 1 do begin StatusArr2 := StatusArr.Items[c] as TJSONArray; for d := 0 to StatusArr2.Count - 1 do HandleErrorStatus( StatusArr2.Items[c].GetValue<TJsonObject>('error')); end; end else raise EFirestoreListener.Create('Unknown JSON telegram: ' + Telegram); finally Obj.Free; end; end else raise EFirestoreListener.Create('Unknown telegram: ' + Telegram); except on e: exception do ReportErrorInThread(rsInterpreteFailed + e.Message); end; end; function TFSListenerThread.IsRunning: boolean; begin result := Started and not Finished; end; function TFSListenerThread.SearchNextMsg: string; function GetNextLine(const Line: string; out NextResp: string): string; const cLineFeed = #10; var p: integer; begin p := Pos(cLineFeed, Line); if p > 1 then begin result := copy(Line, 1, p - 1); NextResp := copy(Line, p + 1); end else result := ''; end; var NextResp: string; begin fMsgSize := StrToIntDef(GetNextLine(fPartialResp, NextResp), -1); if (fMsgSize >= 0) and (NextResp.Length >= fMsgSize) then begin result := copy(NextResp, 1, fMsgSize); fPartialResp := copy(NextResp, fMsgSize + 1); {$IFDEF ParserLog} if not fPartialResp.IsEmpty then TFirebaseHelpers.Log('FSListenerThread.Rest line after SearchNextMsg: ' + fPartialResp); {$ENDIF} end else result := ''; end; procedure TFSListenerThread.Parser; procedure ParseNextMsg(const msg: string); function FindTelegramStart(var Line: string): integer; var p: integer; begin // Telegram start with '[' + MsgNo.ToString+ ',[' if not Line.StartsWith('[') then raise EFirestoreListener.Create('Invalid telegram start: ' + Line); p := 2; while (p < Line.Length) and (Line[p] <> ',') do inc(p); if Copy(Line, p, 2) = ',[' then begin result := StrToIntDef(copy(Line, 2, p - 2), -1); Line := Copy(Line, p + 2); end else if Copy(Line, p, 2) = ',{' then begin result := StrToIntDef(copy(Line, 2, p - 2), -1); Line := Copy(Line, p + 1); // Take { into telegram end else raise EFirestoreListener.Create('Invalid telegram received: ' + Line); end; function FindNextTelegram(var Line: string): string; var p, BracketLevel, BraceLevel: integer; InString, EndFlag: boolean; begin Assert(Line.Length > 2, 'Too short telegram: ' + Line); BracketLevel := 0; BraceLevel := 0; InString := false; if Line[1] = '[' then BracketLevel := 1 else if Line[1] = '{' then BraceLevel := 1 else if Line[1] = '"' then InString := true else raise EFirestoreListener.Create('Invalid telegram start char: ' + Line); EndFlag := false; p := 2; result := Line[1]; while p < Line.Length do begin if (Line[p] = '"') and (Line[p - 1] <> '\') then begin InString := not InString; if (Line[1] = '"') and not InString then EndFlag := true; end else if not InString then begin if Line[p] = '{' then inc(BraceLevel) else if Line[p] = '}' then begin dec(BraceLevel); if (BraceLevel = 0) and (Line[1] = '{') then EndFlag := true; end else if Line[p] = '[' then inc(BracketLevel) else if Line[p] = ']' then begin dec(BracketLevel); if (BracketLevel = 0) and (Line[1] = '[') then EndFlag := true; end; end; if InString or (Line[p] <> #10) then result := result + Line[p]; inc(p); if EndFlag then begin if Line[p] = #10 then Line := Copy(Line, p + 1) else Line := Copy(Line, p); exit; end; end; raise EFirestoreListener.Create('Invalid telegram end received: ' + Line); end; var msgNo: integer; Line, Telegram: string; begin {$IFDEF ParserLogDetails} TFirebaseHelpers.Log('FSListenerThread.Parser: ' + msg); {$ENDIF} if not(msg.StartsWith('[') and msg.EndsWith(']')) then raise EFirestoreListener.Create('Invalid packet received: ' + msg); Line := copy(msg, 2, msg.Length - 2); repeat MsgNo := FindTelegramStart(Line); if MsgNo > fLastTelegramNo then begin fLastTelegramNo := MsgNo; Interprete(FindNextTelegram(Line)); end else begin Telegram := FindNextTelegram(Line); {$IFDEF ParserLog} TFirebaseHelpers.Log('FSListenerThread.Parser Ignore obsolete ' + 'telegram ' + MsgNo.ToString + ': ' + Telegram); {$ENDIF} end; if not Line.EndsWith(']]') then raise EFirestoreListener.Create('Invalid telegram end received: ' + Line); if (Line.length > 4) and (Line[3] = ',') then Line := Copy(Line, 4) else Line := Copy(Line, 3); until Line.IsEmpty; end; var msg: string; begin if TFirebaseHelpers.AppIsTerminated then exit; try repeat msg := SearchNextMsg; if not msg.IsEmpty then ParseNextMsg(msg); until msg.IsEmpty; except on e: exception do ReportErrorInThread(rsParserFailed + e.Message); end; end; procedure TFSListenerThread.ReportErrorInThread(const ErrMsg: string); begin if assigned(fOnListenError) and not TFirebaseHelpers.AppIsTerminated then if fDoNotSynchronizeEvents then fOnListenError(fRequestID, ErrMsg) else TThread.Queue(nil, procedure begin fOnListenError(fRequestID, ErrMsg); end) else TFirebaseHelpers.Log('FSListenerThread.ReportErrorInThread ' + ErrMsg); end; procedure TFSListenerThread.InitListen(Mode: TInitMode); begin fReadPos := 0; fLastKeepAliveMsg := 0; fRequireTokenRenew := false; fCloseRequest := false; fStopWaiting := false; fMsgSize := -1; fPartialResp := ''; if Mode >= NewSIDRequest then begin fLastTelegramNo := 0; fSID := ''; fGSessionID := ''; fConnected := false; if Mode >= NewListener then begin fResumeToken := ''; fLastReceivedMsg := 0; end; end; end; function TFSListenerThread.RequestSIDInThread: boolean; function FetchSIDFromResponse(Response: IFirebaseResponse): boolean; // 51 // [[0,["c","XrzGTQGX9ETvyCg6j6Rjyg","",8,12,30000]]] const cBeginPattern = '[[0,['; cEndPattern = ']]]'#10; var RespElement: TStringDynArray; Resp: string; begin fPartialResp := Response.ContentAsString; Resp := SearchNextMsg; fPartialResp := ''; if not Resp.StartsWith(cBeginPattern) then raise EFirestoreListener.Create('Invalid SID response start: ' + Resp); if not Resp.EndsWith(cEndPattern) then raise EFirestoreListener.Create('Invalid SID response end: ' + Resp); Resp := copy(Resp, cBeginPattern.Length + 1, Resp.Length - cBeginPattern.Length - cEndPattern.Length); RespElement := SplitString(Resp, ','); if length(RespElement) < 2 then raise EFirestoreListener.Create('Invalid SID response array size: ' + Resp); fSID := RespElement[1]; if (fSID.Length < 24) or not(fSID.StartsWith('"') and fSID.EndsWith('"')) then raise EFirestoreListener.Create('Invalid SID ' + fSID + ' response : ' + Resp); fSID := copy(fSID, 2, fSID.Length - 2); fGSessionID := Response.HeaderValue('x-http-session-id'); {$IFDEF ParserLog} TFirebaseHelpers.Log('FSListenerThread.RequestSIDInThread ' + fSID + ', ' + fGSessionID); {$ENDIF} result := true; end; var Request: IFirebaseRequest; DataStr: TStringStream; QueryParams: TQueryParams; Response: IFirebaseResponse; begin result := false; InitListen(NewSIDRequest); try Request := TFirebaseRequest.Create(cBaseURL, fRequestID, fAuth); DataStr := TStringStream.Create(GetRequestData); QueryParams := TQueryParams.Create; try QueryParams.Add('database', [fDatabase]); QueryParams.Add('VER', [cVER]); QueryParams.Add('RID', ['0']); QueryParams.Add('CVER', [cCVER]); QueryParams.Add('X-HTTP-Session-Id', ['gsessionid']); QueryParams.Add('$httpHeaders', [cHttpHeaders]); Response := Request.SendRequestSynchronous(cResourceParams, rmPost, DataStr, TRESTContentType.ctTEXT_PLAIN, QueryParams, tmBearer); if Response.StatusOk then begin fLastTokenRefreshCount := fAuth.GetTokenRefreshCount; result := FetchSIDFromResponse(Response); end else ReportErrorInThread(Format(rsEvtStartFailed, [Response.StatusText])); finally QueryParams.Free; DataStr.Free; end; except on e: exception do if fConnected then ReportErrorInThread(Format(rsEvtStartFailed, [e.Message])); end; end; procedure TFSListenerThread.Execute; var URL: string; QueryParams: TQueryParams; WasTokenRefreshed: boolean; WaitRes: TWaitResult; LastWait: TDateTime; begin if fStopWaiting then exit; // for StopNotStarted InitListen(NewListener); QueryParams := TQueryParams.Create; try while not CheckTerminated and not fStopWaiting do begin if assigned(fAuth) then WasTokenRefreshed := fAuth.GetTokenRefreshCount > fLastTokenRefreshCount else WasTokenRefreshed := false; if fSID.IsEmpty or fGSessionID.IsEmpty or WasTokenRefreshed or fCloseRequest then begin if not RequestSIDInThread then fCloseRequest := true // Probably not connected with server else if not fConnected then begin fConnected := true; if assigned(fOnConnectionStateChange) then if fDoNotSynchronizeEvents then fOnConnectionStateChange(true) else TThread.Queue(nil, procedure begin fOnConnectionStateChange(true); end); end; end else InitListen; if fSID.IsEmpty or fGSessionID.IsEmpty then begin {$IFDEF ParserLog} TFirebaseHelpers.Log('FSListenerThread delay before reconnect'); {$ENDIF} Sleep(cWaitTimeBeforeReconnect); end else begin fStream := TMemoryStream.Create; fClient := THTTPClient.Create; try try fClient.HandleRedirects := true; fClient.Accept := '*/*'; fClient.OnReceiveData := OnRecData; QueryParams.Clear; QueryParams.Add('database', [fDatabase]); QueryParams.Add('gsessionid', [fGSessionID]); QueryParams.Add('VER', [cVER]); QueryParams.Add('RID', ['rpc']); QueryParams.Add('SID', [fSID]); QueryParams.Add('AID', [fLastTelegramNo.ToString]); QueryParams.Add('TYPE', ['xmlhttp']); URL := cBaseURL + TFirebaseHelpers.EncodeResourceParams(cResourceParams) + TFirebaseHelpers.EncodeQueryParams(QueryParams); {$IFDEF ParserLog} TFirebaseHelpers.Log('FSListenerThread Get: [' + fLastTelegramNo.ToString + '] ' + URL); {$ENDIF} if not fCloseRequest then begin fAsyncResult := fClient.BeginGet(OnEndListenerGet, URL, fStream); repeat LastWait := now; WaitRes := fGetFinishedEvent.WaitFor(cTimeoutConnectionLost); if (WaitRes = wrTimeout) and (fLastReceivedMsg < LastWait) then begin fCloseRequest := true; fAsyncResult.Cancel; {$IFDEF ParserLog} TFirebaseHelpers.Log('FSListenerThread timeout: ' + TimeToStr(now - fLastReceivedMsg)); {$ENDIF} end; until (WaitRes = wrSignaled) or fCloseRequest or CheckTerminated; end; if fCloseRequest and not (fStopWaiting or fRequireTokenRenew) then begin if assigned(fOnConnectionStateChange) and fConnected then if fDoNotSynchronizeEvents then fOnConnectionStateChange(false) else TThread.Queue(nil, procedure begin fOnConnectionStateChange(false); end); fConnected := false; if fLastReceivedMsg < now - cTimeoutConnectionLost then begin {$IFDEF ParserLog} TFirebaseHelpers.Log('FSListenerThread wait before reconnect'); {$ENDIF} Sleep(cWaitTimeBeforeReconnect); end; end else if not fConnected then begin fConnected := true; if assigned(fOnConnectionStateChange) then if fDoNotSynchronizeEvents then fOnConnectionStateChange(true) else TThread.Queue(nil, procedure begin fOnConnectionStateChange(true); end); end; except on e: exception do begin ReportErrorInThread(Format(rsEvtListenerFailed, ['InnerException=' + e.Message])); // retry end; end; if fRequireTokenRenew then begin if assigned(fAuth) and fAuth.CheckAndRefreshTokenSynchronous then begin {$IFDEF ParserLog} TFirebaseHelpers.Log( 'FSListenerThread RequireTokenRenew: sucess at ' + TimeToStr(now)); {$ENDIF} fRequireTokenRenew := false; end else begin {$IFDEF ParserLog} TFirebaseHelpers.Log( 'FSListenerThread RequireTokenRenew: failed at ' + TimeToStr(now)); {$ENDIF} end; if assigned(fOnAuthRevoked) and not TFirebaseHelpers.AppIsTerminated then if fDoNotSynchronizeEvents then fOnAuthRevoked(not fRequireTokenRenew) else TThread.Queue(nil, procedure begin fOnAuthRevoked(not fRequireTokenRenew); end); end; finally FreeAndNil(fClient); end; end; end; except on e: exception do ReportErrorInThread(Format(rsEvtListenerFailed, [e.Message])); end; {$IFDEF ParserLog} TFirebaseHelpers.Log('FSListenerThread exit thread'); {$ENDIF} FreeAndNil(QueryParams); end; procedure TFSListenerThread.RegisterEvents(OnStopListening: TOnStopListenEvent; OnError: TOnRequestError; OnAuthRevoked: TOnAuthRevokedEvent; OnConnectionStateChange: TOnConnectionStateChange; DoNotSynchronizeEvents: boolean); begin if IsRunning then raise EFirestoreListener.Create( 'RegisterEvents must not be called for started Listener'); InitListen(NewListener); fRequestID := 'FSListener for ' + fTargets.Count.ToString + ' target(s)'; fOnStopListening := OnStopListening; fOnListenError := OnError; fOnAuthRevoked := OnAuthRevoked; fOnConnectionStateChange := OnConnectionStateChange; fDoNotSynchronizeEvents := DoNotSynchronizeEvents; end; procedure TFSListenerThread.OnEndListenerGet(const ASyncResult: IAsyncResult); var Resp: IHTTPResponse; begin if TFirebaseHelpers.AppIsTerminated then exit; try if not assigned(fClient) then begin {$IFDEF ParserLog} TFirebaseHelpers.Log('FSListenerThread.OnEndListenerGet: aborted HTTP'); {$ENDIF} end else if not ASyncResult.GetIsCancelled then begin try Resp := fClient.EndAsyncHTTP(ASyncResult); if not fCloseRequest and (Resp.StatusCode < 200) or (Resp.StatusCode >= 300) then begin ReportErrorInThread(Resp.StatusText); fCloseRequest := true; {$IFDEF ParserLogDetails} TFirebaseHelpers.Log('FSListenerThread.OnEndListenerGet Response: ' + Resp.ContentAsString); {$ENDIF} end else {$IFDEF ParserLog} TFirebaseHelpers.Log('FSListenerThread.OnEndListenerGet ' + Resp.StatusCode.ToString + ': ' + Resp.StatusText); {$ENDIF} finally Resp := nil; end; end else begin {$IFDEF ParserLog} TFirebaseHelpers.Log('FSListenerThread.OnEndListenerGet: canceled'); {$ENDIF} end; FreeAndNil(fStream); if assigned(fGetFinishedEvent) then fGetFinishedEvent.SetEvent except on e: ENetException do begin fCloseRequest := true; {$IFDEF ParserLog} TFirebaseHelpers.Log( 'FSListenerThread.OnEndListenerGet Disconnected by Server:' + e.Message); {$ENDIF} FreeAndNil(fStream); fGetFinishedEvent.SetEvent; end; on e: exception do TFirebaseHelpers.Log('FSListenerThread.OnEndListenerGet Exception ' + e.Message); end; end; procedure TFSListenerThread.OnEndThread(Sender: TObject); begin if TFirebaseHelpers.AppIsTerminated then exit; if assigned(fOnStopListening) then TThread.ForceQueue(nil, procedure begin fOnStopListening(Sender); end); if not fStopWaiting and assigned(fOnListenError) then fOnListenError(fRequestID, rsUnexpectedThreadEnd); end; procedure TFSListenerThread.StopListener(TimeOutInMS: integer); var Timeout: integer; begin if not fStopWaiting then begin {$IFDEF ParserLog} TFirebaseHelpers.Log('FSListenerThread.StopListener stop'); {$ENDIF} fStopWaiting := true; if not assigned(fClient) then raise EFirestoreListener.Create('Missing Client in StopListener') else if not assigned(fAsyncResult) then raise EFirestoreListener.Create('Missing AsyncResult in StopListener') else fAsyncResult.Cancel; end; Timeout := TimeOutInMS; while not Finished and (Timeout > 0) do begin if Timeout < TimeOutInMS div 2 then begin {$IFDEF ParserLog} TFirebaseHelpers.Log('FSListenerThread.StopListener emergency stop'); {$ENDIF} if assigned(fAsyncResult) then fAsyncResult.Cancel; if assigned(fGetFinishedEvent) then fGetFinishedEvent.SetEvent; end; TFirebaseHelpers.SleepAndMessageLoop(5); dec(Timeout, 5); end; if not Finished then begin {$IFDEF ParserLog} TFirebaseHelpers.Log('FSListenerThread.StopListener not stopped!'); {$ENDIF} end; end; procedure TFSListenerThread.StopNotStarted; begin fStopWaiting := true; if not Suspended then begin {$IFDEF ParserLog} TFirebaseHelpers.Log('FSListenerThread.StopNotStarted'); {$ENDIF} if assigned(fAsyncResult) then fAsyncResult.Cancel; if assigned(fGetFinishedEvent) then fGetFinishedEvent.SetEvent; Start; WaitFor; end; end; procedure TFSListenerThread.OnRecData(const Sender: TObject; ContentLength, ReadCount: Int64; var Abort: Boolean); var ss: TStringStream; ErrMsg: string; Retry: integer; StreamReadFailed: boolean; len: Int64; begin if TFirebaseHelpers.AppIsTerminated then exit; try fLastReceivedMsg := Now; len := ReadCount - fReadPos; if fStopWaiting then Abort := true else if assigned(fStream) and ((fReadPos >= 0) and (len >= 0)) and ((fMsgSize = -1) or (fPartialResp.Length + len >= fMsgSize)) then begin ss := TStringStream.Create('', TEncoding.UTF8); try Retry := 2; StreamReadFailed := false; repeat fStream.Position := fReadPos; try ss.CopyFrom(fStream, len); StreamReadFailed := false; except on e: EReadError do if Retry > 0 then begin StreamReadFailed := true; dec(Retry); end else Raise; end; until not StreamReadFailed; try fPartialResp := fPartialResp + ss.DataString; fReadPos := ReadCount; except on e: EEncodingError do if (fMsgSize = -1) and fPartialResp.IsEmpty then // ignore Unicode decoding errors for the first received packet else raise; end; if not fPartialResp.IsEmpty then Parser; finally ss.Free; end; end; except on e: Exception do begin ErrMsg := e.Message; if not TFirebaseHelpers.AppIsTerminated then if assigned(fOnListenError) then if fDoNotSynchronizeEvents then fOnListenError(fRequestID, rsEvtParserFailed + ErrMsg) else TThread.Queue(nil, procedure begin fOnListenError(fRequestID, rsEvtParserFailed + ErrMsg); end) else TFirebaseHelpers.Log('FSListenerThread.OnRecData ' + ErrMsg); end; end; end; end.
unit TTSSemTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSSemRecord = record PUserName: String[10]; PSemNum: Integer; End; TTTSSemBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSSemRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSSem = (TTSSemByUserName, TTSSemBySemNum); TTTSSemTable = class( TDBISAMTableAU ) private FDFUserName: TStringField; FDFSemNum: TIntegerField; procedure SetPUserName(const Value: String); function GetPUserName:String; procedure SetPSemNum(const Value: Integer); function GetPSemNum:Integer; procedure SetEnumIndex(Value: TEITTSSem); function GetEnumIndex: TEITTSSem; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSSemRecord; procedure StoreDataBuffer(ABuffer:TTTSSemRecord); property DFUserName: TStringField read FDFUserName; property DFSemNum: TIntegerField read FDFSemNum; property PUserName: String read GetPUserName write SetPUserName; property PSemNum: Integer read GetPSemNum write SetPSemNum; published property Active write SetActive; property EnumIndex: TEITTSSem read GetEnumIndex write SetEnumIndex; end; { TTTSSemTable } procedure Register; implementation procedure TTTSSemTable.CreateFields; begin FDFUserName := CreateField( 'UserName' ) as TStringField; FDFSemNum := CreateField( 'SemNum' ) as TIntegerField; end; { TTTSSemTable.CreateFields } procedure TTTSSemTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSSemTable.SetActive } procedure TTTSSemTable.SetPUserName(const Value: String); begin DFUserName.Value := Value; end; function TTTSSemTable.GetPUserName:String; begin result := DFUserName.Value; end; procedure TTTSSemTable.SetPSemNum(const Value: Integer); begin DFSemNum.Value := Value; end; function TTTSSemTable.GetPSemNum:Integer; begin result := DFSemNum.Value; end; procedure TTTSSemTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin //VG 260717: RecId added as a primary key, because otherwise DBISAM ads one automatically, which causes the VerifyStructure to fail Add('RecId, AutoInc, 0, N'); Add('UserName, String, 10, N'); Add('SemNum, Integer, 0, N'); end; end; procedure TTTSSemTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, RecId, Y, Y, N, N'); Add('ByUserName, UserName, N, N, N, N'); Add('BySemNum, SemNum, N, N, N, N'); end; end; procedure TTTSSemTable.SetEnumIndex(Value: TEITTSSem); begin case Value of TTSSemByUserName: IndexName := 'ByUserName'; TTSSemBySemNum : IndexName := 'BySemNum'; end; end; function TTTSSemTable.GetDataBuffer:TTTSSemRecord; var buf: TTTSSemRecord; begin fillchar(buf, sizeof(buf), 0); buf.PUserName := DFUserName.Value; buf.PSemNum := DFSemNum.Value; result := buf; end; procedure TTTSSemTable.StoreDataBuffer(ABuffer:TTTSSemRecord); begin DFUserName.Value := ABuffer.PUserName; DFSemNum.Value := ABuffer.PSemNum; end; function TTTSSemTable.GetEnumIndex: TEITTSSem; var iname : string; begin result := TTSSemByUserName; iname := uppercase(indexname); if iname = '' then result := TTSSemByUserName; if iname = 'BYUSERNAME' then result := TTSSemByUserName; if iname = 'BYSEMNUM' then result := TTSSemBySemNum; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSSemTable, TTTSSemBuffer ] ); end; { Register } function TTTSSemBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..2] of string = ('USERNAME','SEMNUM'); var x : integer; begin s := uppercase(s); x := 1; while (x <= 2) and (flist[x] <> s) do inc(x); if x <= 2 then result := x else result := 0; end; function TTTSSemBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftInteger; end; end; function TTTSSemBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PUserName; 2: result := @Data.PSemNum; end; end; end.
unit FindUnit.FormMessage; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Types, TransparentCanvas, ExtCtrls; type TfrmMessage = class(TForm) tmrClose: TTimer; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure tmrCloseTimer(Sender: TObject); private procedure PrintOnCanvas; protected class var CurTop: integer; FTexto: string; procedure CreateParams(var Params: TCreateParams); override; function GetPosition: TRect; function GetTextWidth: tagSIZE; procedure SetPosition; public procedure ShowMessage(const Text: string); class procedure ShowInfoToUser(const Text: string); end; implementation uses FindUnit.DelphiVlcWrapper, Log4Pascal; const MARGIN_PADING = 5; COORNER_MARGIN = 10; {$R *.dfm} { TfrmMessage } procedure TfrmMessage.Button1Click(Sender: TObject); begin PrintOnCanvas; end; procedure TfrmMessage.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.ExStyle := WS_EX_TRANSPARENT or WS_EX_TOPMOST or WS_EX_NOACTIVATE; end; procedure TfrmMessage.SetPosition; var OpenRect: TRect; TextSize: tagSIZE; begin OpenRect := GetPosition; TextSize := GetTextWidth; Top := OpenRect.Top + CurTop; CurTop := CurTop + 30; if OpenRect.Left <> OpenRect.Right then begin Width := TextSize.cx + COORNER_MARGIN * 2 + MARGIN_PADING; Left := OpenRect.Right - Width - COORNER_MARGIN * 2; Top := Top + COORNER_MARGIN; end else Left := OpenRect.Left; BringToFront; end; class procedure TfrmMessage.ShowInfoToUser(const Text: string); var MsgForm: TfrmMessage; begin MsgForm := TfrmMessage.Create(nil); MsgForm.ShowMessage(Text); end; procedure TfrmMessage.ShowMessage(const Text: string); begin FTexto := Text; SetPosition; ShowWindow(Handle, SW_SHOWNOACTIVATE); Visible := True; PrintOnCanvas; tmrClose.Enabled := True; end; procedure TfrmMessage.tmrCloseTimer(Sender: TObject); begin Close; end; procedure TfrmMessage.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; CurTop := CurTop - 30; end; procedure TfrmMessage.FormCreate(Sender: TObject); begin Brush.Style := bsClear; BorderStyle := bsNone; end; function TfrmMessage.GetPosition: TRect; begin Result := TDelphiVLCWrapper.GetEditorRect; end; function TfrmMessage.GetTextWidth: tagSIZE; var GlassCanvas: TTransparentCanvas; begin GlassCanvas := TTransparentCanvas.Create(ClientWidth, ClientHeight); try GlassCanvas.Font.Name := 'Courier New'; GlassCanvas.Font.Size := -13; GlassCanvas.Font.Color := $000146A5; Result := GlassCanvas.TextExtent(FTexto); finally GlassCanvas.Free; end; end; procedure TfrmMessage.PrintOnCanvas; var TextSize: tagSIZE; GlassCanvas: TTransparentCanvas; begin try GlassCanvas := TTransparentCanvas.Create(ClientWidth, ClientHeight); try GlassCanvas.Font.Name := 'Courier New'; GlassCanvas.Font.Size := -13; GlassCanvas.Font.Color := $000146A5; TextSize := GlassCanvas.TextExtent(FTexto); GlassCanvas.Pen.Width := 1; GlassCanvas.Pen.Color := $004080FF; GlassCanvas.Brush.Color := $00CCE6FF; GlassCanvas.Rectangle(COORNER_MARGIN, 0, TextSize.cx + COORNER_MARGIN + MARGIN_PADING + MARGIN_PADING, 30, 240); GlassCanvas.GlowTextOutBackColor(COORNER_MARGIN + MARGIN_PADING, MARGIN_PADING, 0, FTexto, clBlack, taLeftJustify, 10, 255); GlassCanvas.DrawToGlass(0, 0, Canvas.Handle); finally GlassCanvas.Free; end; except on e: exception do Logger.Error('TfrmMessage.PrintOnCanvas: %s', [E.Message]); end; end; end.
{*******************************************************} { Проект: Repository } { Модуль: uInterfaceListExt.pas } { Описание: Дополненная реализация списка интерфейсов } { Copyright (C) 2015 Боборыкин В.В. (bpost@yandex.ru) } { } { Распространяется по лицензии GPLv3 } {*******************************************************} unit uInterfaceListExt; interface uses SysUtils, Classes; type TSelectFunc = function(AItem: IInterface; AContext: array of const): Boolean; IInterfaceListExt = interface(IInterfaceList) ['{211349E9-E61B-40F8-9C1A-51F88A2EEF4E}'] function Clone: IInterfaceListExt; stdcall; function Select(ASelector: TSelectFunc; AContext: array of const): IInterfaceListExt; stdcall; overload; end; function CreateInterfaceListExt: IInterfaceListExt; implementation { ****************************** TInterfaceListExt ******************************* } type TInterfaceListExt = class(TInterfaceList, IInterfaceListExt) private public function Select(ASelector: TSelectFunc; AContext: array of const): IInterfaceListExt; overload; stdcall; function Clone: IInterfaceListExt; stdcall; end; function SelectAll(AItem: IInterface; Acontext: array of const): Boolean; begin Result := True; end; function TInterfaceListExt.Clone: IInterfaceListExt; begin Result := Select(SelectAll, []); end; function TInterfaceListExt.Select(ASelector: TSelectFunc; AContext: array of const): IInterfaceListExt; var I: Integer; begin Result := CreateInterfaceListExt; if Assigned(ASelector) then begin Lock; try for I := 0 to Count-1 do if ASelector(Items[I], AContext) then Result.Add(Items[I]); finally Unlock; end; end; end; function CreateInterfaceListExt: IInterfaceListExt; begin Result := TInterfaceListExt.Create; end; end.
unit Interval; interface uses System.Classes, System.SysUtils, Patterns.Observable; type TInterval = class(TObservable) private FMinValue: Integer; FMaxValue: Integer; FLength: Integer; procedure calculateLength; procedure calculateMaxValue; protected procedure SetMinValue(Value: Integer); procedure SetMaxValue(Value: Integer); procedure SetLength(Value: Integer); public property MinValue: Integer read FMinValue write SetMinValue; property MaxValue: Integer read FMaxValue write SetMaxValue; property Length: Integer read FLength write SetLength; end; implementation { TInterval } procedure TInterval.SetMinValue(Value: Integer); begin if Value <> FMinValue then begin FMinValue := Value; calculateMaxValue(); setChanged; notifyObservers; end; end; procedure TInterval.SetMaxValue(Value: Integer); begin if Value <> FMaxValue then begin FMaxValue := Value; calculateLength(); setChanged; notifyObservers; end; end; procedure TInterval.SetLength(Value: Integer); begin if Value <> FLength then begin FLength := Value; calculateMaxValue; setChanged; notifyObservers; end; end; procedure TInterval.calculateMaxValue; begin FMaxValue := MinValue + Length; end; procedure TInterval.calculateLength; begin FLength := MaxValue - MinValue; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.24 10/26/2004 10:39:54 PM JPMugaas Updated refs. Rev 1.23 10/4/2004 3:16:44 PM BGooijen Added constructor Rev 1.22 8/3/2004 11:49:56 AM JPMugaas Fix for issue where 2.0.0 was always being set even if it should not have been set. Rev 1.21 7/27/2004 7:18:20 PM JPMugaas Fixed the TIdReplySMTP object as per Bas's suggestion. He told me that we were overriding the wrong object. I also fixed the Assign so it will work properly. Rev 1.20 7/24/04 1:04:48 PM RLebeau Bug fix for TIdReplySMTP.AssignTo(). The logic was backwards Rev 1.19 5/31/04 12:47:02 PM RLebeau Bug fixes for TIdSMTPEnhancedCode.AssignTo() and TIdReplySMTP.AssignTo() Rev 1.18 5/18/04 2:39:52 PM RLebeau Changed TIdRepliesSMTP constructor back to using 'override' Rev 1.17 5/18/04 11:21:54 AM RLebeau Changed TIdRepliesSMTP constructor to use 'reintroduce' instead Rev 1.16 5/16/04 5:27:32 PM RLebeau Added TIdRepliesSMTP class Rev 1.15 2004.02.03 5:45:44 PM czhower Name changes Rev 1.14 2004.01.29 12:07:54 AM czhower .Net constructor problem fix. Rev 1.13 2004.01.23 10:09:54 PM czhower REmoved unneded check because of CharIsInSet functinoalty. Also was a short circuit which is not permitted. Rev 1.12 1/22/2004 4:23:02 PM JPMugaas Undid a set change that didn't work. Rev 1.11 1/22/2004 4:51:40 PM SPerry fixed set problems Rev 1.10 1/3/2004 8:05:54 PM JPMugaas Bug fix: Sometimes, replies will appear twice due to the way functionality was enherited. Rev 1.9 2003.10.18 9:42:14 PM czhower Boatload of bug fixes to command handlers. Rev 1.8 10/17/2003 12:58:54 AM DSiders Added localization comments. Rev 1.7 2003.09.20 10:38:42 AM czhower Bug fix to allow clearing code field (Return to default value) Rev 1.6 6/5/2003 04:54:24 AM JPMugaas Reworkings and minor changes for new Reply exception framework. Rev 1.5 5/30/2003 8:46:28 PM BGooijen Rev 1.4 5/26/2003 12:22:08 PM JPMugaas Rev 1.3 5/25/2003 03:45:16 AM JPMugaas Rev 1.2 5/25/2003 02:46:16 AM JPMugaas Rev 1.1 5/23/2003 04:52:30 AM JPMugaas Work started on TIdDirectSMTP to support enhanced error codes. Rev 1.0 5/22/2003 05:24:52 PM JPMugaas RFC 2034 descendant of TIdRFCReply for IdSMTP. This also includes some extended error code constants. } unit IdReplySMTP; interface {$i IdCompilerDefines.inc} uses Classes, IdException, IdReply, IdReplyRFC; const ValidClassChars = '245'; ValidClassVals = [2,4,5]; CLASS_DEF = 2; AVAIL_DEF = False; NODETAILS = 0; PARTSEP = '.'; type TIdSMTPEnhancedCode = class(TPersistent) protected FStatusClass : Cardinal; FSubject : Cardinal; FDetails : Cardinal; FAvailable : Boolean; procedure AssignTo(ADest: TPersistent); override; function IsValidReplyCode(const AText : String) : Boolean; function GetReplyAsStr : String; procedure SetReplyAsStr(const AText : String); procedure SetStatusClass(const AValue: Cardinal); procedure SetAvailable(const AValue: Boolean); public constructor Create; published property StatusClass : Cardinal read FStatusClass write SetStatusClass default CLASS_DEF; property Subject : Cardinal read FSubject write FSubject default NODETAILS; property Details : Cardinal read FDetails write FDetails default NODETAILS; property Available : Boolean read FAvailable write SetAvailable default AVAIL_DEF; property ReplyAsStr : String read GetReplyAsStr write SetReplyAsStr; end; TIdReplySMTP = class(TIdReplyRFC) protected FEnhancedCode : TIdSMTPEnhancedCode; procedure AssignTo(ADest: TPersistent); override; procedure SetEnhancedCode(AValue : TIdSMTPEnhancedCode); function GetFormattedReply: TStrings; override; procedure SetFormattedReply(const AValue: TStrings); override; public constructor Create(ACollection: TCollection); overload; override; constructor CreateWithReplyTexts(ACollection: TCollection; AReplyTexts: TIdReplies); overload; override; destructor Destroy; override; procedure RaiseReplyError; override; procedure SetEnhReply(const ANumericCode : Integer; const AEnhReply, AText : String); published property EnhancedCode : TIdSMTPEnhancedCode read FEnhancedCode write SetEnhancedCode; end; TIdRepliesSMTP = class(TIdRepliesRFC) public constructor Create(AOwner: TPersistent); override; end; //note that this is here so we don't have to put this unit in an implementaiton clause //and both TIdSMTP and TIdDirectSMTP share this. EIdSMTPReplyError = class(EIdReplyRFCError) protected FEnhancedCode : TIdSMTPEnhancedCode; public constructor CreateError(const AErrCode: Integer; AEnhanced : TIdSMTPEnhancedCode; const AReplyMessage: string); reintroduce; destructor Destroy; override; property EnhancedCode : TIdSMTPEnhancedCode read FEnhancedCode; end; type EIdSMTPReply = class(EIdException); EIdSMTPReplyInvalidReplyString = class(EIdSMTPReply); EIdSMTPReplyInvalidClass = class(EIdSMTPReply); //suggested extended replies const //{ From RFC 3463 Enhanced Mail System Status Codes Id_EHR_USE_STARTTLS = '5.7.0'; //required by RFC 2487 {do not localize} //X.0.0 Other undefined Status Id_EHR_GENERIC_OK = '2.0.0'; {do not localize} Id_EHR_GENERIC_TRANS = '4.0.0'; {do not localize} Id_EHR_GENERIC_PERM = '5.0.0'; {do not localize} //X.1.0 Other address status Id_EHR_MSG_OTH_OK = '2.1.0'; {do not localize} Id_EHR_MSG_OTH_TRANS = '4.1.0'; {do not localize} Id_EHR_MSG_OTH_PERM = '5.1.0'; {do not localize} //X.1.1 Bad destination mailbox address Id_EHR_MSG_BAD_DEST = '5.1.1'; {do not localize} //X.1.2 Bad destination system address Id_EHR_MSG_BAD_DEST_SYST = '5.1.2'; {do not localize} //X.1.3 Bad destination mailbox address syntax Id_EHR_MSG_BAD_DEST_SYNTAX = '5.1.3'; {do not localize} //X.1.4 Destination mailbox address ambiguous Id_EHR_MSG_AMBIG_DEST = '5.1.4'; {do not localize} //X.1.5 Destination address valid Id_EHR_MSG_VALID_DEST = '2.1.5'; {do not localize} //X.1.6 Destination mailbox has moved, No forwarding address Id_EHR_MSG_DEST_MOVED_NOFORWARD = '2.1.6'; {do not localize} //X.1.7 Bad senderís mailbox address syntax Id_EHR_MSG_SENDER_BOX_SYNTAX = '5.1.7'; {do not localize} //X.1.8 Bad senderís system address Id_EHR_MSG_BAD_SENDER_ADDR = '5.1.8'; {do not localize} //X.2.0 Other or undefined mailbox status Id_EHR_MB_OTHER_STATUS_OK = '2.2.0'; {do not localize} Id_EHR_MB_OTHER_STATUS_TRANS = '4.2.0'; {do not localize} Id_EHR_MB_OTHER_STATUS_PERM = '5.2.0'; {do not localize} //X.2.1 Mailbox disabled, not accepting messages Id_EHR_MB_DISABLED_TEMP = '4.2.1'; {do not localize} Id_EHR_MB_DISABLED_PERM = '5.2.1'; {do not localize} //X.2.2 Mailbox full - user can probably delete some messages to make more room Id_EHR_MB_FULL = '4.2.2'; {do not localize} //X.2.3 Message length exceeds administrative limit - probably can not be fixed by a user deleting messages Id_EHR_MB_MSG_LEN_LIMIT = '5.2.3'; {do not localize} //X.2.4 Mailing list expansion problem Id_EHR_MB_ML_EXPAN_TEMP = '4.2.4'; {do not localize} Id_EHR_MB_ML_EXPAN_PERM = '5.2.4'; {do not localize} //X.3.0 Other or undefined mail system status Id_EHR_MD_OTHER_OK = '2.3.0'; {do not localize} Id_EHR_MD_OTHER_TRANS = '4.3.0'; {do not localize} Id_EHR_MD_OTHER_PERM = '5.3.0'; {do not localize} //X.3.1 Mail system full Id_EHR_MD_MAIL_SYSTEM_FULL = '4.3.1'; {do not localize} //X.3.2 System not accepting network messages Id_EHR_MD_NOT_EXCEPTING_TRANS = '4.3.2'; {do not localize} Id_EHR_MD_NOT_EXCEPTING_PERM = '5.3.2'; {do not localize} //X.3.3 System not capable of selected features Id_EHR_MD_NOT_CAPABLE_FEAT_TRANS = '4.3.3'; {do not localize} Id_EHR_MD_NOT_CAPABLE_FEAT_PERM = '5.3.3'; {do not localize} //X.3.4 Message too big for system Id_EHR_MD_TOO_BIG = '5.3.4'; {do not localize} //X.3.5 System incorrectly configured Id_EHR_MD_INCORRECT_CONFIG_TRANS = '4.3.5'; {do not localize} Id_EHR_MD_INCORRECT_CONFIG_PERM = '5.3.5'; {do not localize} //X.4.0 Other or undefined network or routing status Id_EHR_NR_OTHER_OK = '2.4.0'; {do not localize} Id_EHR_NR_OTHER_TRANS = '4.4.0'; {do not localize} Id_EHR_NR_OTHER_PERM = '5.4.0'; {do not localize} //X.4.1 No answer from host Id_EHR_NR_NO_ANSWER = '4.4.1'; {do not localize} //X.4.2 Bad connection Id_EHR_NR_BAD_CONNECTION = '4.4.2'; {do not localize} //X.4.3 Directory server failure Id_EHR_NR_DIR_SVR_FAILURE = '4.4.3'; {do not localize} //X.4.4 Unable to route Id_EHR_NR_UNABLE_TO_ROUTE_TRANS = '4.4.4'; {do not localize} Id_EHR_NR_UNABLE_TO_ROUTE_PERM = '5.4.4'; {do not localize} //X.4.5 Mail system congestion Id_EHR_NR_SYSTEM_CONGESTION = '4.4.5'; {do not localize} //X.4.6 Routing loop detected Id_EHR_NR_LOOP_DETECTED = '4.4.6'; {do not localize} //X.4.7 Delivery time expired Id_EHR_NR_DELIVERY_EXPIRED_TEMP = '4.4.7'; {do not localize} Id_EHR_NR_DELIVERY_EXPIRED_PERM = '5.4.7'; {do not localize} //X.5.0 Other or undefined protocol status Id_EHR_PR_OTHER_OK = '2.5.0'; {do not localize} Id_EHR_PR_OTHER_TEMP = '4.5.0'; {do not localize} Id_EHR_PR_OTHER_PERM = '5.5.0'; {do not localize} //X.5.1 Invalid command Id_EHR_PR_INVALID_CMD = '5.5.1'; {do not localize} //X.5.2 Syntax error Id_EHR_PR_SYNTAX_ERR = '5.5.2'; {do not localize} //X.5.3 Too many recipients - note that this is given if segmentation isn't possible Id_EHR_PR_TOO_MANY_RECIPIENTS_TEMP = '4.5.3'; {do not localize} Id_EHR_PR_TOO_MANY_RECIPIENTS_PERM = '5.5.3'; {do not localize} //X.5.4 Invalid command arguments Id_EHR_PR_INVALID_CMD_ARGS = '5.5.4'; {do not localize} //X.5.5 Wrong protocol version Id_EHR_PR_WRONG_VER_TRANS = '4.5.5'; {do not localize} Id_EHR_PR_WRONG_VER_PERM = '5.5.5'; {do not localize} //X.6.0 Other or undefined media error Id_EHR_MED_OTHER_OK = '2.6.0'; {do not localize} Id_EHR_MED_OTHER_TRANS = '4.6.0'; {do not localize} Id_EHR_MED_OTHER_PERM = '5.6.0'; {do not localize} //X.6.1 Media not supported Id_EHR_MED_NOT_SUPPORTED = '5.6.1'; {do not localize} //6.2 Conversion required and prohibited Id_EHR_MED_CONV_REQUIRED_PROHIB_TRANS = '4.6.2'; {do not localize} Id_EHR_MED_CONV_REQUIRED_PROHIB_PERM = '5.6.2'; {do not localize} //X.6.3 Conversion required but not supported Id_EHR_MED_CONV_REQUIRED_NOT_SUP_TRANS = '4.6.3'; {do not localize} Id_EHR_MED_CONV_REQUIRED_NOT_SUP_PERM = '5.6.3'; {do not localize} //X.6.4 Conversion with loss performed Id_EHR_MED_CONV_LOSS_WARNING = '2.6.4'; {do not localize} Id_EHR_MED_CONV_LOSS_ERROR = '5.6.4'; {do not localize} //X.6.5 Conversion Failed Id_EHR_MED_CONV_FAILED_TRANS = '4.6.5'; {do not localize} Id_EHR_MED_CONV_FAILED_PERM = '5.6.5'; {do not localize} //X.7.0 Other or undefined security status Id_EHR_SEC_OTHER_OK = '2.7.0'; {do not localize} Id_EHR_SEC_OTHER_TRANS = '4.7.0'; {do not localize} Id_EHR_SEC_OTHER_PERM = '5.7.0'; {do not localize} //X.7.1 Delivery not authorized, message refused Id_EHR_SEC_DEL_NOT_AUTH = '5.7.1'; {do not localize} //X.7.2 Mailing list expansion prohibited Id_EHR_SEC_EXP_NOT_AUTH = '5.7.2'; {do not localize} //X.7.3 Security conversion required but not possible Id_EHR_SEC_CONV_REQ_NOT_POSSIBLE = '5.7.3'; {do not localize} //X.7.4 Security features not supported Id_EHR_SEC_NOT_SUPPORTED = '5.7.4'; {do not localize} //X.7.5 Cryptographic failure Id_EHR_SEC_CRYPT_FAILURE_TRANS = '4.7.5'; {do not localize} Id_EHR_SEC_CRYPT_FAILURE_PERM = '5.7.5'; {do not localize} //X.7.6 Cryptographic algorithm not supported Id_EHR_SEC_CRYPT_ALG_NOT_SUP_TRANS = '4.7.6'; {do not localize} Id_EHR_SEC_CRYPT_ALG_NOT_SUP_PERM = '5.7.6'; {do not localize} //X.7.7 Message integrity failure Id_EHR_SEC_INTEGRETIY_FAILED_WARN = '2.7.7'; {do not localize} Id_EHR_SEC_INTEGRETIY_FAILED_TRANS = '4.7.7'; {do not localize} implementation uses IdGlobal, IdGlobalProtocols, IdResourceStringsProtocols, SysUtils; { TIdSMTPEnhancedCode } procedure TIdSMTPEnhancedCode.AssignTo(ADest: TPersistent); var LE : TIdSMTPEnhancedCode; begin if ADest is TIdSMTPEnhancedCode then begin LE := TIdSMTPEnhancedCode(ADest); LE.StatusClass := FStatusClass; LE.Subject := FSubject; LE.Details := FDetails; LE.Available := FAvailable; end else begin inherited AssignTo(ADest); end; end; constructor TIdSMTPEnhancedCode.Create; begin inherited Create; FStatusClass := CLASS_DEF; FSubject := NODETAILS; FDetails := NODETAILS; FAvailable := AVAIL_DEF; end; function TIdSMTPEnhancedCode.GetReplyAsStr: String; begin Result := ''; if Available then begin Result := Copy(IntToStr(FStatusClass),1,1)+PARTSEP+ Copy(IntToStr(FSubject),1,3)+PARTSEP+ Copy(IntToStr(FDetails),1,3); end; end; function TIdSMTPEnhancedCode.IsValidReplyCode(const AText: String): Boolean; var LTmp, LBuf, LValidPart : String; begin Result := (Trim(AText) = ''); if not Result then begin LTmp := AText; LBuf := Fetch(LTmp); //class LValidPart := Fetch(LBuf,PARTSEP); if CharIsInSet(LValidPart, 1, ValidClassChars) then begin //subject LValidPart := Fetch(LBuf,PARTSEP); if (LValidPart<>'') and IsNumeric(LValidPart) then begin //details Result := (LBuf<>'') and IsNumeric(LBuf); end; end; end; end; procedure TIdSMTPEnhancedCode.SetAvailable(const AValue: Boolean); begin if FAvailable <> AValue then begin FAvailable := AValue; if AValue then begin FStatusClass := CLASS_DEF; FSubject := NODETAILS; FDetails := NODETAILS; end; end; end; procedure TIdSMTPEnhancedCode.SetReplyAsStr(const AText: String); var LTmp, LBuf: string; LValidPart: string; begin if not IsValidReplyCode(AText) then begin EIdSMTPReplyInvalidReplyString.Toss(RSSMTPReplyInvalidReplyStr); end; LTmp := AText; LBuf := Fetch(LTmp); if LBuf <> '' then begin //class LValidPart := Fetch(LBuf, PARTSEP); FStatusClass := IndyStrToInt(LValidPart, 0); //subject LValidPart := Fetch(LBuf, PARTSEP); FSubject := IndyStrToInt(LValidPart,0); //details FDetails := IndyStrToInt(LBuf,0); FAvailable := True; end else begin FAvailable := False; end; end; procedure TIdSMTPEnhancedCode.SetStatusClass(const AValue: Cardinal); begin if not (AValue in ValidClassVals) then begin EIdSMTPReplyInvalidClass.Toss(RSSMTPReplyInvalidClass); end; FStatusClass := AValue; end; { TIdReplySMTP } procedure TIdReplySMTP.AssignTo(ADest: TPersistent); var LS : TIdReplySMTP; begin if ADest is TIdReplySMTP then begin LS := TIdReplySMTP(ADest); //set code first as it possibly clears the reply LS.Code := Code; LS.EnhancedCode := EnhancedCode; LS.Text.Assign(Text); end else begin inherited AssignTo(ADest); end; end; constructor TIdReplySMTP.Create(ACollection: TCollection); begin inherited Create(ACollection); FEnhancedCode := TIdSMTPEnhancedCode.Create; end; constructor TIdReplySMTP.CreateWithReplyTexts(ACollection: TCollection; AReplyTexts: TIdReplies); begin inherited CreateWithReplyTexts(ACollection, AReplyTexts); FEnhancedCode := TIdSMTPEnhancedCode.Create; end; destructor TIdReplySMTP.Destroy; begin FreeAndNil(FEnhancedCode); inherited; end; function TIdReplySMTP.GetFormattedReply: TStrings; var i: Integer; LCode: String; begin Result := GetFormattedReplyStrings; { JP here read from Items and format according to the reply, in this case RFC and put it into FFormattedReply } if NumericCode > 0 then begin LCode := IntToStr(NumericCode); if FText.Count > 0 then begin for i := 0 to FText.Count - 1 do begin if i < FText.Count - 1 then begin if EnhancedCode.Available then begin Result.Add(LCode + '-' + EnhancedCode.ReplyAsStr + ' ' + FText[i]); end else begin Result.Add(LCode + '-' + FText[i]); end; end else begin if EnhancedCode.Available then begin Result.Add(LCode + ' ' + EnhancedCode.ReplyAsStr + ' ' + FText[i]); end else begin Result.Add(LCode + ' ' + FText[i]); end; end; end; end else begin if EnhancedCode.Available then begin Result.Add(LCode + ' ' + EnhancedCode.ReplyAsStr); end else begin Result.Add(LCode); end; end; end else if FText.Count > 0 then begin Result.AddStrings(FText); end; end; procedure TIdReplySMTP.RaiseReplyError; begin raise EIdSMTPReplyError.CreateError(NumericCode, FEnhancedCode, Text.Text); end; procedure TIdReplySMTP.SetEnhancedCode(AValue: TIdSMTPEnhancedCode); begin FEnhancedCode.Assign(AValue); end; procedure TIdReplySMTP.SetEnhReply(const ANumericCode: Integer; const AEnhReply, AText: String); begin inherited SetReply(ANumericCode, AText); FEnhancedCode.ReplyAsStr := AEnhReply; end; procedure TIdReplySMTP.SetFormattedReply(const AValue: TStrings); { in here just parse and put in items, no need to store after parse } var i: Integer; s: string; begin Clear; if AValue.Count > 0 then begin // Get 4 chars - for POP3 s := Trim(Copy(AValue[0], 1, 4)); if Length(s) = 4 then begin if s[4] = '-' then begin SetLength(s, 3); end; end; Code := s; for i := 0 to AValue.Count - 1 do begin s := Copy(AValue[i], 5, MaxInt); if FEnhancedCode.IsValidReplyCode(s) then begin FEnhancedCode.ReplyAsStr := Fetch(s); end; Text.Add(s); end; end; end; { TIdRepliesSMTP } constructor TIdRepliesSMTP.Create(AOwner: TPersistent); begin inherited Create(AOwner, TIdReplySMTP); end; { EIdSMTPReplyError } constructor EIdSMTPReplyError.CreateError(const AErrCode: Integer; AEnhanced: TIdSMTPEnhancedCode; const AReplyMessage: string); begin inherited CreateError(AErrCode,AReplyMessage); FEnhancedCode := TIdSMTPEnhancedCode.Create; FEnhancedCode.Assign(AEnhanced); end; destructor EIdSMTPReplyError.Destroy; begin FreeAndNil(FEnhancedCode); inherited Destroy; end; end.
unit Unbound.Game.WorldFeatures; interface uses Pengine.IntMaths, Pengine.Vector, Pengine.Noise, Pengine.ICollections, Pengine.Interfaces, Pengine.Random, Unbound.Game, Unbound.Game.Serialization; type TNoise2 = class(TInterfaceBase, IGradientSource2, ISerializable) private FPerlinNoise: TPerlinNoise2; FSeed: Integer; FFactor: TVector2; FOffset: TVector2; FBias: Single; function GetValue(APos: TVector2): Single; // IGradientSource2 function GetGradient(APos: TIntVector2): TVector2; function GetBounds: TIntBounds2; public constructor Create; destructor Destroy; override; function Copy: TNoise2; property PerlinNoise: TPerlinNoise2 read FPerlinNoise; property Seed: Integer read FSeed; property Factor: TVector2 read FFactor; property Offset: TVector2 read FOffset; property Bias: Single read FBias; property Values[APos: TVector2]: Single read GetValue; default; // IGradientSource2 property Gradients[APos: TIntVector2]: TVector2 read GetGradient; property Bounds: TIntBounds2 read GetBounds; function HasBounds: Boolean; // ISerializable procedure Serialize(ASerializer: TSerializer); end; TNoise2Editable = class(TNoise2) public procedure SetSeed(ASeed: Integer); procedure SetFactor(AFactor: TVector2); procedure SetOffset(AOffset: TVector2); procedure SetBias(ABias: Single); end; TMaterialPool = class(TInterfaceBase, ISerializable) public type TEntry = class(TInterfaceBase, ISerializable) private FMaterial: TTerrainMaterial; FWeight: Single; public function Copy: TEntry; property Material: TTerrainMaterial read FMaterial; property Weight: Single read FWeight; // ISerializable procedure Serialize(ASerialize: TSerializer); end; TEntryEditable = class(TEntry) public procedure SetMaterial(AMaterial: TTerrainMaterial); procedure SetWeight(AWeight: Single); end; private FSeed: Integer; FEntries: ISortedObjectList<TEntry>; FTotalWeight: Single; procedure UpdateTotalWeight; function GetEntries: IReadonlyList<TEntry>; function GetMaterial(APos: TIntVector3): TTerrainMaterial; public constructor Create; function Copy: TMaterialPool; property Seed: Integer read FSeed; property Entries: IReadonlyList<TEntry> read GetEntries; property TotalWeight: Single read FTotalWeight; property Materials[APos: TIntVector3]: TTerrainMaterial read GetMaterial; default; // ISerializable procedure Serialize(ASerialize: TSerializer); end; TMaterialPoolEditable = class(TMaterialPool) end; TWorldFeatureTerrain = class(TWorldFeature) protected procedure CalculateBlock(ATerrain: TTerrain; const AChunkPos: TIntVector3); virtual; abstract; public procedure Apply(AChunk: TChunk); override; end; TWorldFeatureHeightmap = class(TWorldFeatureTerrain) private FNoises: IObjectList<TNoise2>; function GetNoises: IReadonlyList<TNoise2>; protected procedure Assign(AFrom: TWorldFeature); override; procedure CalculateBlock(ATerrain: TTerrain; const AChunkPos: TIntVector3); override; public constructor Create; override; class function GetName: string; override; property Noises: IReadonlyList<TNoise2> read GetNoises; procedure Serialize(ASerializer: TSerializer); override; end; TWorldFeatureHeightmapEditable = class(TWorldFeatureHeightmap) public procedure AddNoise(ANoise: TNoise2); procedure RemoveNoise(ANoise: TNoise2); end; TWorldFeatureNoise = class(TWorldFeatureTerrain) protected procedure CalculateBlock(ATerrain: TTerrain; const AChunkPos: TIntVector3); override; public class function GetName: string; override; end; TWorldFeatureStructure = class(TWorldFeatureTerrain) protected procedure CalculateBlock(ATerrain: TTerrain; const AChunkPos: TIntVector3); override; public class function GetName: string; override; end; const WorldFeatureClasses: array [0 .. 2] of TWorldFeatureClass = ( TWorldFeatureHeightmap, TWorldFeatureNoise, TWorldFeatureStructure ); implementation { TNoise2 } function TNoise2.GetValue(APos: TVector2): Single; begin Result := FPerlinNoise[APos]; end; function TNoise2.GetGradient(APos: TIntVector2): TVector2; var Rand: TRandom; begin Rand := TRandom.FromSeed((Int64(TDefault.Hash(APos)) shl 32) or Seed); Result.Create(Rand.NextSingle, Rand.NextSingle); end; function TNoise2.GetBounds: TIntBounds2; begin Result := IBounds2(0); end; constructor TNoise2.Create; begin FPerlinNoise := TPerlinNoise2.Create; FPerlinNoise.GradientSource := Self; FFactor := 1; end; destructor TNoise2.Destroy; begin FPerlinNoise.Free; inherited; end; function TNoise2.Copy: TNoise2; begin Result := TNoise2.Create; Result.FSeed := Seed; Result.FFactor := Factor; Result.FOffset := Offset; Result.FBias := Bias; end; function TNoise2.HasBounds: Boolean; begin Result := False; end; procedure TNoise2.Serialize(ASerializer: TSerializer); begin ASerializer.Define('Seed', FSeed); ASerializer.Define('Factor', FFactor); ASerializer.Define('Offset', FOffset); ASerializer.Define('Bias', FBias); end; { TNoise2Editable } procedure TNoise2Editable.SetSeed(ASeed: Integer); begin FSeed := ASeed; end; procedure TNoise2Editable.SetFactor(AFactor: TVector2); begin FFactor := AFactor; end; procedure TNoise2Editable.SetOffset(AOffset: TVector2); begin FOffset := AOffset; end; procedure TNoise2Editable.SetBias(ABias: Single); begin FBias := ABias; end; { TMaterialPool.TEntry } function TMaterialPool.TEntry.Copy: TEntry; begin Result := TEntry.Create; Result.FMaterial := Material; Result.FWeight := Weight; end; procedure TMaterialPool.TEntry.Serialize(ASerialize: TSerializer); begin // TODO: Only reference via name, maybe add something for that into TSerializer directly // ASerialize.Define('Material', FMaterial); ASerialize.Define('Weight', FWeight); end; { TMaterialPool.TEntryEditable } procedure TMaterialPool.TEntryEditable.SetMaterial(AMaterial: TTerrainMaterial); begin FMaterial := AMaterial; end; procedure TMaterialPool.TEntryEditable.SetWeight(AWeight: Single); begin FWeight := AWeight; end; { TMaterialPool } function TMaterialPool.Copy: TMaterialPool; var Entry: TEntry; begin Result := TMaterialPool.Create; Result.FSeed := Seed; for Entry in Entries do Result.FEntries.Add(Entry.Copy); end; constructor TMaterialPool.Create; begin FEntries := TSortedObjectList<TEntry>.Create; FEntries.Compare := function(A, B: TEntry): Boolean begin Result := A.Weight > B.Weight; end; end; function TMaterialPool.GetEntries: IReadonlyList<TEntry>; begin Result := FEntries.ReadonlyList; end; function TMaterialPool.GetMaterial(APos: TIntVector3): TTerrainMaterial; var Value: Single; Entry: TEntry; begin Value := TRandom.FromSeed((Int64(TDefault.Hash(APos)) shl 32) or Cardinal(Seed)).NextSingle * FTotalWeight; for Entry in Entries do begin Value := Value - Entry.Weight; if Value < 0 then Exit(Entry.Material); end; Exit(Entries.Last.Material); end; procedure TMaterialPool.Serialize(ASerialize: TSerializer); begin ASerialize.Define('Seed', FSeed); ASerialize.Define<TEntry>('Entries', FEntries); if ASerialize.Mode = smUnserialize then UpdateTotalWeight; end; procedure TMaterialPool.UpdateTotalWeight; var Entry: TEntry; begin FTotalWeight := 0; for Entry in Entries do FTotalWeight := FTotalWeight + Entry.Weight; end; { TWorldFeatureTerrain } procedure TWorldFeatureTerrain.Apply(AChunk: TChunk); var X, Y, Z, SX, SY, SZ: Integer; Terrain: TTerrain; begin // Use nested loop for better performance SX := AChunk.Size.X; SY := AChunk.Size.Y; SZ := AChunk.Size.Z; Terrain := AChunk.Terrain; for X := 0 to SX do for Y := 0 to SY do for Z := 0 to SZ do CalculateBlock(Terrain, IVec3(X, Y, Z)); end; { TWorldFeatureHeightmap } procedure TWorldFeatureHeightmap.Assign(AFrom: TWorldFeature); var Typed: TWorldFeatureHeightmap; Noise: TNoise2; begin Typed := AFrom as TWorldFeatureHeightmap; for Noise in Typed.Noises do FNoises.Add(Noise.Copy); end; procedure TWorldFeatureHeightmap.CalculateBlock(ATerrain: TTerrain; const AChunkPos: TIntVector3); begin end; constructor TWorldFeatureHeightmap.Create; begin inherited; FNoises := TObjectList<TNoise2>.Create; end; class function TWorldFeatureHeightmap.GetName: string; begin Result := 'Heightmap'; end; function TWorldFeatureHeightmap.GetNoises: IReadonlyList<TNoise2>; begin Result := FNoises.ReadonlyList; end; procedure TWorldFeatureHeightmap.Serialize(ASerializer: TSerializer); begin inherited; ASerializer.Define<TNoise2>('Noises', FNoises); end; { TWorldFeatureHeightmapEditable } procedure TWorldFeatureHeightmapEditable.AddNoise(ANoise: TNoise2); begin FNoises.Add(ANoise.Copy); end; procedure TWorldFeatureHeightmapEditable.RemoveNoise(ANoise: TNoise2); begin FNoises.Remove(ANoise) end; { TWorldFeatureNoise } procedure TWorldFeatureNoise.CalculateBlock(ATerrain: TTerrain; const AChunkPos: TIntVector3); begin end; class function TWorldFeatureNoise.GetName: string; begin Result := 'Noise'; end; { TWorldFeatureStructure } procedure TWorldFeatureStructure.CalculateBlock(ATerrain: TTerrain; const AChunkPos: TIntVector3); begin end; class function TWorldFeatureStructure.GetName: string; begin Result := 'Structure'; end; end.
unit clLacres; interface uses clConexao; type TLacre = Class(TObject) private function getBase: Integer; function getNumero: String; function getStatus: Integer; procedure setBse(const Value: Integer); procedure setNumero(const Value: String); procedure setStatus(const Value: Integer); function getManutencao: TDateTime; function getUsuario: String; procedure setManutencao(const Value: TDateTime); procedure setUsuario(const Value: String); constructor Create; destructor Destroy; protected _base: Integer; _numero: String; _status: Integer; _usuario: String; _manutencao: TDateTime; _conexao: TConexao; public property Base: Integer read getBase write setBse; property Numero: String read getNumero write setNumero; property Status: Integer read getStatus write setStatus; property Usuario: String read getUsuario write setUsuario; property Manutencao: TDateTime read getManutencao write setManutencao; function Validar(): Boolean; function JaExiste(id: String): Boolean; function Delete(filtro: String): Boolean; function getObject(id, filtro: String): Boolean; function Insert(): Boolean; function Update(): Boolean; function getObjects(): Boolean; function getField(campo, coluna: String): String; end; const TABLENAME = 'TBLACRES'; implementation { TLacre } uses SysUtils, Dialogs, udm, clUtil, ZDataset, ZAbstractRODataset, DB, Math; constructor TLacre.Create; begin _conexao := TConexao.Create; if (not _conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0); end; end; destructor TLacre.Destroy; begin _conexao.Free; end; procedure TLacre.setBse(const Value: Integer); begin _base := Value; end; procedure TLacre.setManutencao(const Value: TDateTime); begin _manutencao := Value; end; procedure TLacre.setNumero(const Value: String); begin _numero := Value; end; procedure TLacre.setStatus(const Value: Integer); begin _status := Value; end; procedure TLacre.setUsuario(const Value: String); begin _usuario := Value; end; function TLacre.Validar(): Boolean; begin Result := False; if Self.Base = 0 then begin MessageDlg('Informe o código da Base', mtWarning, [mbOK], 0); Exit end; if TUtil.Empty(Self.Numero) then begin MessageDlg('Informe o número do Lacre!', mtWarning, [mbNo], 0); Exit; end; Result := True; end; function TLacre.JaExiste(id: String): Boolean; begin try Result := False; if TUtil.Empty(id) then begin Exit; end; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); SQL.Add(' WHERE NUM_LACRE = :NUMERO '); SQL.Add('AND COD_BASE = :BASE '); ParamByName('NUMERO').AsString := id; ParamByName('BASE').AsInteger := Self.Base; dm.ZConn.PingServer; Open; if not IsEmpty then begin Result := True; end; Close; SQL.Clear; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TLacre.Delete(filtro: String): Boolean; begin try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Add('DELETE FROM ' + TABLENAME); if filtro = 'BASE' then begin SQL.Add(' WHERE COD_BASE = :BASE'); ParamByName('BASE').AsInteger := Self.Base; end else if filtro = 'NUMERO' then begin SQL.Add(' WHERE COD_BASE = :BASE'); SQL.Add(' AND NUM_LACRE = :NUMERO'); ParamByName('BASE').AsInteger := Self.Base; ParamByName('NUMERO').AsString := Self.Numero; end; dm.ZConn.PingServer; ExecSQL; Close; SQL.Clear; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TLacre.getObject(id, filtro: String): Boolean; begin try Result := False; if TUtil.Empty(id) then begin Exit; end; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); if filtro = 'BASE' then begin SQL.Add(' WHERE COD_BASE = :BASE'); ParamByName('BASE').AsInteger := StrToInt(id); end else if filtro = 'NUMERO' then begin SQL.Add(' WHERE COD_BASE = :BASE'); SQL.Add(' AND NUM_LACRE = :NUMERO'); ParamByName('BASE').AsInteger := Self.Base; ParamByName('NUMERO').AsString := id; end else if filtro = 'LACRE' then begin SQL.Add(' WHERE COD_BASE IN (:BASE)'); SQL.Add(' AND NUM_LACRE = :NUMERO'); ParamByName('BASE').AsString := id; ParamByName('NUMERO').AsString := Self.Numero; end; dm.ZConn.PingServer; Open; if (not IsEmpty) then begin First; Self.Base := FieldByName('COD_BASE').AsInteger; Self.Numero := FieldByName('NUM_LACRE').AsString; Self.Status := FieldByName('COD_STATUS').AsInteger; Self.Usuario := FieldByName('NOM_USUARIO').AsString; Self.Manutencao := FieldByName('DAT_MANUTENCAO').AsDateTime; Result := True; end else begin Close; SQL.Clear; end; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TLacre.Insert(): Boolean; begin Try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'INSERT INTO ' + TABLENAME + '(' + 'COD_BASE, ' + 'NUM_LACRE, ' + 'COD_STATUS, ' + 'NOM_USUARIO, ' + 'DAT_MANUTENCAO) ' + 'VALUES (' + ':BASE, ' + ':NUMERO, ' + ':STATUS, ' + ':USUARIO, ' + ':MANUTENCAO) '; ParamByName('BASE').AsInteger := Self.Base; ParamByName('NUMERO').AsString := Self.Numero; ParamByName('STATUS').AsInteger := Self.Status; ParamByName('USUARIO').AsString := Self.Usuario; ParamByName('MANUTENCAO').AsDateTime := Self.Manutencao; dm.ZConn.PingServer; ExecSQL; Close; SQL.Clear; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TLacre.Update(): Boolean; begin try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'COD_STATUS = :STATUS, ' + 'NOM_USUARIO = :USUARIO, ' + 'DAT_MANUTENCAO = :MANUTENCAO ' + 'WHERE ' + 'COD_BASE = :BASE AND ' + 'NUM_LACRE = :NUMERO'; ParamByName('BASE').AsInteger := Self.Base; ParamByName('NUMERO').AsString := Self.Numero; ParamByName('STATUS').AsInteger := Self.Status; ParamByName('USUARIO').AsString := Self.Usuario; ParamByName('MANUTENCAO').AsDateTime := Self.Manutencao; dm.ZConn.PingServer; ExecSQL; Close; SQL.Clear; Result := True; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TLacre.getObjects(): Boolean; begin try Result := False; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); dm.ZConn.PingServer; Open; if not IsEmpty then begin Result := True; end; Close; SQL.Clear; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TLacre.getField(campo, coluna: String): String; begin try Result := ''; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Text := 'SELECT ' + campo + ' FROM ' + TABLENAME; if coluna = 'BASE' then begin SQL.Add(' WHERE COD_BASE = :BASE'); ParamByName('BASE').AsInteger := Self.Base; end else if coluna = 'NUMERO' then begin SQL.Add(' WHERE COD_BASE = :BASE'); SQL.Add(' AND NUM_LACRE = :NUMERO'); ParamByName('BASE').AsInteger := Self.Base; ParamByName('NUMERO').AsString := Self.Numero; end; dm.ZConn.PingServer; Open; if (not IsEmpty) then begin First; Result := FieldByName(campo).AsString; end; Close; SQL.Clear; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TLacre.getManutencao: TDateTime; begin Result := _manutencao; end; function TLacre.getBase: Integer; begin Result := _base; end; function TLacre.getStatus: Integer; begin Result := _status; end; function TLacre.getUsuario: String; begin Result := _usuario; end; function TLacre.getNumero: String; begin Result := _numero; end; end.
unit OfficeLike_Result_Controls; {* Результат диалога } // Модуль: "w:\common\components\gui\Garant\VCM\UserInteraction\OfficeLike_Result_Controls.pas" // Стереотип: "VCMControls" // Элемент модели: "Result" MUID: (4A8AD3C70195) {$Include w:\common\components\gui\sdoDefine.inc} interface {$If NOT Defined(NoVCM)} uses l3IntfUses , vcmExternalInterfaces ; const en_Result = 'Result'; en_capResult = 'Результат диалога'; op_Cancel = 'Cancel'; op_capCancel = 'Отмена'; op_Ok = 'Ok'; op_capOk = 'OK'; var opcode_Result_Cancel: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Result_Ok: TvcmOPID = (rEnID : -1; rOpID : -1); var st_user_Result_Ok_Search: TvcmOperationStateIndex = (rID : -1); {* Результат диалога -> OK <-> Искать } var st_user_Result_Ok_Print: TvcmOperationStateIndex = (rID : -1); {* Результат диалога -> OK <-> Печать } var st_user_Result_Ok_AttributesSelect: TvcmOperationStateIndex = (rID : -1); {* Результат диалога -> OK <-> Подтвердить выбор элементов } var st_user_Result_Ok_ConsultationMark: TvcmOperationStateIndex = (rID : -1); {* Результат диалога -> OK <-> Оценить } var st_user_Result_Ok_Analize: TvcmOperationStateIndex = (rID : -1); {* Результат диалога -> OK <-> Построить } var st_user_Result_Cancel_Close: TvcmOperationStateIndex = (rID : -1); {* Результат диалога -> Отмена <-> Закрыть } {$IfEnd} // NOT Defined(NoVCM) implementation {$If NOT Defined(NoVCM)} uses l3ImplUses , vcmOperationsForRegister , vcmOperationStatesForRegister ; initialization with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Result, op_Cancel, en_capResult, op_capCancel, False, False, opcode_Result_Cancel)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Result, op_Cancel, en_capResult, op_capCancel, False, False, opcode_Result_Cancel)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Result, op_Ok, en_capResult, op_capOk, False, False, opcode_Result_Ok)) do begin with AddState(TvcmOperationStateForRegister_C('Search', st_user_Result_Ok_Search))^ do begin rCaption := 'Искать'; rHint := 'Провести поиск по выбранным параметрам'; end; with AddState(TvcmOperationStateForRegister_C('Print', st_user_Result_Ok_Print))^ do begin rCaption := 'Печать'; rImageIndex := 3; end; with AddState(TvcmOperationStateForRegister_C('AttributesSelect', st_user_Result_Ok_AttributesSelect))^ do begin rCaption := 'Подтвердить выбор элементов'; end; with AddState(TvcmOperationStateForRegister_C('ConsultationMark', st_user_Result_Ok_ConsultationMark))^ do begin rCaption := 'Оценить'; end; with AddState(TvcmOperationStateForRegister_C('Analize', st_user_Result_Ok_Analize))^ do begin rCaption := 'Построить'; end; end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Result, op_Ok, en_capResult, op_capOk, False, False, opcode_Result_Ok)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Result, op_Cancel, en_capResult, op_capCancel, False, False, opcode_Result_Cancel)) do begin with AddState(TvcmOperationStateForRegister_C('Close', st_user_Result_Cancel_Close))^ do begin rCaption := 'Закрыть'; end; end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Result, op_Cancel, en_capResult, op_capCancel, False, False, opcode_Result_Cancel)) do begin end; {$IfEnd} // NOT Defined(NoVCM) end.
unit CleanArch_EmbrConf.Infra.Repository.Memory; interface uses CleanArch_EmbrConf.Core.Entity.Interfaces, System.JSON, CleanArch_EmbrConf.Core.Entity.Impl.ParkingLot, CleanArch_EmbrConf.Adapter.Impl.ParkingLotAdapter, CleanArch_EmbrConf.Core.Repository.Interfaces; type TParkingLotRepositoryMemory = class(TInterfacedObject, iParkingLotRepository) private public constructor Create; destructor Destroy; override; class function New: iParkingLotRepository; function getParkingLot(Code : String) : iParkingLot; function getParkingLotJSON(Code : String) : TJSONArray; function saveParkedCar(Value : iParkedCar) : iParkingLotRepository; end; implementation constructor TParkingLotRepositoryMemory.Create; begin end; destructor TParkingLotRepositoryMemory.Destroy; begin inherited; end; function TParkingLotRepositoryMemory.getParkingLot(Code: String): iParkingLot; var lParkingLot, lParkingLotData : iParkingLot; begin lParkingLotData := TParkingLot.New .Code('shopping') .Capacity(5) .OpenHour(8) .CloseHour(22); lParkingLot := TParkingLotAdapter.New .Code(lParkingLotData.Code) .Capacity(lParkingLotData.Capacity) .OpenHour(lParkingLotData.OpenHour) .CloseHour(lParkingLotData.CloseHour) .ParkingLot; Result := lParkingLot; end; function TParkingLotRepositoryMemory.getParkingLotJSON( Code: String): TJSONArray; begin end; class function TParkingLotRepositoryMemory.New: iParkingLotRepository; begin Result := Self.Create; end; function TParkingLotRepositoryMemory.saveParkedCar(Value: iParkedCar) : iParkingLotRepository; begin end; end.
unit UTriangle; interface uses UFigure, URectangle, SysUtils, Graphics, ExtCtrls, Windows; type TTriangle = class(TRectangle) private FThirdPoint: TPoint; public constructor Create(APoint: TPoint; AColor:TColor; ASecondPoint:TPoint; AThirdPoint:TPoint); function Area:real; override; procedure Draw(Image: TImage); override; property ThirdPoint:TPoint read FThirdPoint write FThirdPoint; end; implementation constructor TTriangle.Create(APoint: TPoint; AColor:TColor; ASecondPoint:TPoint; AThirdPoint:TPoint); begin inherited Create(APoint, AColor, ASecondPoint); FThirdPoint:= AThirdPoint; end; function TTriangle.Area:real; begin Result:= 0.5 * abs((SecondPoint.X - Point.X) * (ThirdPoint.Y - Point.Y) - (ThirdPoint.X - Point.X) * (SecondPoint.Y - Point.Y)); end; procedure TTriangle.Draw(Image: TImage); var Points: array of TPoint; begin SetLength(Points, 3); with Image.Canvas do begin SetLength(Points, 3); Points[0] := Point; Points[1] := SecondPoint; Points[2] := ThirdPoint; Pen.Width := 1; Pen.Color := Color; Brush.Color := Color; Polygon(Points); end; end; end.
unit clServicos; interface uses clConexao; type TServicos = Class(TObject) private function getCodigo: Integer; procedure setCodigo(const Value: Integer); function getDescricao: String; procedure setDescricao(const Value: String); function getAgregacao: String; procedure setAgregacao(const Value: String); function getValor: Double; procedure setValor(const Value: Double); constructor Create; destructor Destroy; function getValorAgregado: Double; procedure setValorAgregado(const Value: Double); protected _codigo: Integer; _descricao: String; _agregacao: String; _valor: Double; _valoragregado: Double; _conexao: TConexao; public property Codigo: Integer read getCodigo write setCodigo; property Descricao: String read getDescricao write setDescricao; property Agregacao: String read getAgregacao write setAgregacao; property Valor: Double read getValor write setValor; property ValorAgregado: Double read getValorAgregado write setValorAgregado; function Validar(): Boolean; function Delete(filtro: String): Boolean; function getObject(id, filtro: String): Boolean; function Insert(): Boolean; function Update(): Boolean; function getObjects(): Boolean; function getField(campo, coluna: String): String; procedure MaxCod; end; const TABLENAME = 'TBSERVICOS'; implementation { TServicos } uses SysUtils, Dialogs, udm, clUtil, ZDataset, ZAbstractRODataset, DB, Math; constructor TServicos.Create; begin _conexao := TConexao.Create; if (not _conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conex„o ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0); end; end; destructor TServicos.Destroy; begin _conexao.Free; end; function TServicos.getAgregacao: String; begin Result := _agregacao; end; function TServicos.getCodigo: Integer; begin Result := _codigo; end; function TServicos.getDescricao: String; begin Result := _descricao; end; function TServicos.Validar(): Boolean; begin Result := False; if TUtil.Empty(Self.Descricao) then begin MessageDlg('Informe o nome do cliente!', mtWarning, [mbNo], 0); Exit; end; Result := True; end; procedure TServicos.MaxCod; begin try with dm.QryGetObject do begin Close; SQL.Clear; SQL.Text := 'SELECT MAX(COD_SERVICO) AS CODIGO FROM ' + TABLENAME; dm.ZConn.PingServer; Open; if not(IsEmpty) then First; end; Self.Codigo := (dm.QryGetObject.FieldByName('CODIGO').AsInteger) + 1; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TServicos.Delete(filtro: String): Boolean; begin try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Add('DELETE FROM ' + TABLENAME); if filtro = 'CODIGO' then begin SQL.Add('WHERE COD_SERVICO = :CODIGO'); ParamByName('CODIGO').AsInteger := Self.Codigo; end; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TServicos.getObject(id, filtro: String): Boolean; begin Try Result := False; if TUtil.Empty(id) then Exit; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); if filtro = 'CODIGO' then begin SQL.Add(' WHERE COD_SERVICO = :CODIGO'); ParamByName('CODIGO').AsInteger := StrToInt(id); end else if filtro = 'DESCRICAO' then begin SQL.Add(' WHERE DES_SERVICO = :DESCRICAO'); ParamByName('DESCRICAO').AsString := id; end; dm.ZConn.PingServer; Open; if not IsEmpty then First; end; if dm.QryGetObject.RecordCount > 0 then begin dm.QryGetObject.First; Self.Codigo := dm.QryGetObject.FieldByName('COD_SERVICO').AsInteger; Self.Descricao := dm.QryGetObject.FieldByName('DES_SERVICO').AsString; Self.Agregacao := dm.QryGetObject.FieldByName('DOM_AGREGACAO').AsString; Self.Valor := dm.QryGetObject.FieldByName('VAL_SERVICO').AsFloat; Self.ValorAgregado := dm.QryGetObject.FieldByName('VAL_AGREGADO').AsFloat; Result := True; end else begin dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TServicos.Insert(): Boolean; begin Try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'INSERT INTO ' + TABLENAME + '(' + 'COD_SERVICO, ' + 'DES_SERVICO, ' + 'DOM_AGREGACAO, ' + 'VAL_SERVICO, VAL_AGREGADO) ' + 'VALUES (' + ':CODIGO, ' + ':DESCRICAO, ' + ':AGREGACAO, ' + ':VALOR, :VALAGREGADO)'; MaxCod; ParamByName('CODIGO').AsInteger := Self.Codigo; ParamByName('DESCRICAO').AsString := Self.Descricao; ParamByName('AGREGACAO').AsString := Self.Agregacao; ParamByName('VALOR').AsFloat := Self.Valor; ParamByName('VALAGREGADO').AsFloat := Self.ValorAgregado; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; MessageDlg('Os dados foram salvos com sucesso!', mtInformation, [mbOK], 0); Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TServicos.Update(): Boolean; begin try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'DES_SERVICO = :DESCRICAO, ' + 'DOM_AGREGACAO = :AGREGACAO, ' + 'VAL_SERVICO = :VALOR, VAL_AGREGADO = :VALAGREGADO ' + 'WHERE ' + 'COD_SERVICO = :CODIGO'; ParamByName('CODIGO').AsInteger := Self.Codigo; ParamByName('DESCRICAO').AsString := Self.Descricao; ParamByName('AGREGACAO').AsString := Self.Agregacao; ParamByName('VALOR').AsFloat := Self.Valor; ParamByName('VALAGREGADO').AsFloat := Self.ValorAgregado; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; MessageDlg('Os dados foram alterado com sucesso!', mtInformation, [mbOK], 0); Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TServicos.getObjects(): Boolean; begin try Result := False; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); dm.ZConn.PingServer; Open; if not IsEmpty then First; end; if dm.QryGetObject.RecordCount > 0 then Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TServicos.getValor: Double; begin Result := _valor; end; function TServicos.getValorAgregado: Double; begin Result := _valoragregado; end; function TServicos.getField(campo, coluna: String): String; begin Try Result := ''; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Text := 'SELECT ' + campo + ' FROM ' + TABLENAME; if coluna = 'CODIGO' then begin SQL.Add(' WHERE COD_SERVICO = :CODIGO '); ParamByName('CODIGO').AsInteger := Self.Codigo; end else if coluna = 'NOME' then begin SQL.Add(' WHERE DES_SERVICO = :DESCRICAO '); ParamByName('DESCRICAO').AsString := Self.Descricao; end; dm.ZConn.PingServer; Open; if not IsEmpty then First; end; if dm.QryGetObject.RecordCount > 0 then Result := dm.QryGetObject.FieldByName(campo).AsString; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; procedure TServicos.setAgregacao(const Value: String); begin _agregacao := Value; end; procedure TServicos.setCodigo(const Value: Integer); begin _codigo := Value; end; procedure TServicos.setDescricao(const Value: String); begin _descricao := Value; end; procedure TServicos.setValor(const Value: Double); begin _valor := Value; end; procedure TServicos.setValorAgregado(const Value: Double); begin _valoragregado := valUE; end; end.
{$mode objfpc}{$H+} { Implements the game logic, independent from mobile / standalone. } unit Game; interface uses CastleWindow; var Window: TCastleWindowCustom; implementation uses SysUtils, CastleFilesUtils, CastleKeysMouse, CastleTimeUtils, CastleControls, CastleImages, CastleGLImages, CastleVectors, CastleMessages, CastleColors; type { Entity in a world, like a player or enemy or rocket. } TEntity = object Position: TVector2Single; Alive: boolean; Image: TGLImage; DieTime: TFloatTime; DieAnimation: TGLVideo2D; function Collides(const E: TEntity): boolean; function Width: Integer; function Height: Integer; end; function TEntity.Collides(const E: TEntity): boolean; begin Result := Alive and E.Alive and { note: use "div 3", not "div 2" below, to collide only when things are really close, not when merely their bounding boxes collide. } (Abs(Position[0] - E.Position[0]) < (Width + E.Width ) div 3) and (Abs(Position[1] - E.Position[1]) < (Height + E.Height) div 3); end; function TEntity.Width: Integer; begin Result := Image.Width; end; function TEntity.Height: Integer; begin Result := Image.Height; end; var Map, PlayerImage, Enemy, Rocket: TGLImage; MapMask: TGrayscaleImage; Player: TEntity; Enemies: array [0..50] of TEntity; Rockets: array [0..40] of TEntity; EnemiesDestroyed: Cardinal; CurrentTime: TFloatTime; Explosion: TGLVideo2D; procedure Restart; var I: Integer; begin Player.Alive := true; Player.Image := PlayerImage; Player.Position := Vector2Single(Map.Width / 2 - 100, Player.Height); for I := 0 to High(Enemies) do begin Enemies[I].Alive := true; Enemies[I].Image := Enemy; Enemies[I].DieAnimation := Explosion; Enemies[I].Position := Vector2Single( Map.Width div 4 + Random * Map.Width / 2, Random * Map.Height * 3 ); end; for I := 0 to High(Rockets) do begin Rockets[I].Alive := false; Rockets[I].Image := Rocket; end; EnemiesDestroyed := 0; CurrentTime := 0; end; { One-time initialization of resources. } procedure ApplicationInitialize; begin Map := TGLImage.Create(ApplicationData('map.png')); MapMask := LoadImage(ApplicationData('map_mask.png'), [TGrayscaleImage]) as TGrayscaleImage; PlayerImage := TGLImage.Create(ApplicationData('SpaceShipSmall.png')); Enemy := TGLImage.Create(ApplicationData('ship6c.png')); Rocket := TGLImage.Create(ApplicationData('cohete_off.png')); //Explosion := TGLVideo2D.Create(ApplicationData('explosion_320x240/explosion_1@counter(4).png'), false); Explosion := TGLVideo2D.Create(ApplicationData('explosion_320x240_frameskip2/explosion_1@counter(4).png'), false); Restart; end; { Window.OnRender callback. } procedure WindowRender(Container: TUIContainer); function ShiftY: Single; begin Result := -Player.Position[1] + 1.5 * Player.Height; end; procedure DrawEntity(const E: TEntity); begin if E.Alive then E.Image.Draw( Round(E.Position[0] - E.Width div 2), Round(E.Position[1] - E.Height div 2 + ShiftY) ) else if (E.DieAnimation <> nil) and (E.DieTime <> 0) and (CurrentTime < E.DieTime + E.DieAnimation.Duration) then E.DieAnimation.GLImageFromTime(CurrentTime - E.DieTime).Draw( Round(E.Position[0] - E.DieAnimation.Width div 2), Round(E.Position[1] - E.DieAnimation.Height div 2 + ShiftY) ); end; var I: Integer; S: string; const { how soon to disappear the rocket, to make Rockets[] slots available, and to avoid killing enemies far away. Equal to Window.Width and Map.Width now, although does not have to. } RocketDisappearDistance = 1024; begin // TODO: couple of times render map for I := 0 to 3 do // TODO: unoptimal, only 2 draws should be needed Map.Draw(0, Round(ShiftY + Map.Height * I)); DrawEntity(Player); for I := 0 to High(Enemies) do DrawEntity(Enemies[I]); for I := 0 to High(Rockets) do begin if Rockets[I].Alive and (Rockets[I].Position[1] > Player.Position[1] + RocketDisappearDistance) then Rockets[I].Alive := false; DrawEntity(Rockets[I]); end; S := Format('Survided: %fs', [CurrentTime]); UIFont.Print(10, Container.Height - 10 - UIFont.RowHeight, LightGreen, S); S := Format('Destroyed: %d', [EnemiesDestroyed]); UIFont.Print( Container.Width - 10 - UIFont.TextWidth(S), Container.Height - 10 - UIFont.RowHeight, Yellow, S); end; { Window.OnUpdate callback. } procedure WindowUpdate(Container: TUIContainer); function PlayerCrashedWithWall(const X, Y: Single): boolean; const { For collisions of "player vs wall", we check points around player middle, but not too far around, to not detect collisions too soon. Set this to 1.0 to exactly check player bbox corners, set to something smaller to give more chance to avoid collisions. } PlayerMargin = 0.5; var MapX, MapY: Integer; begin MapX := Round(Player.Position[0] + X * PlayerMargin * Player.Width / 2); MapY := Round(Player.Position[1] + Y * PlayerMargin * Player.Height / 2); { is mask black } Result := MapMask.PixelPtr(MapX mod Map.Width, MapY mod Map.Height)^ = 0; if Result then begin MessageOk(Window, 'Crash!'); Restart; end; end; const { speeds, in map pixels per second } MoveSidewaysSpeed = 300; MoveForwardSpeed = 500; RocketSpeed = 2000; var SecondsPassed: Single; I, J: Integer; begin SecondsPassed := Window.Fps.UpdateSecondsPassed; CurrentTime += SecondsPassed; { move player } Player.Position += Vector2Single(0, SecondsPassed * MoveForwardSpeed); if Window.Pressed[K_Right] then Player.Position += Vector2Single(SecondsPassed * MoveSidewaysSpeed, 0); if Window.Pressed[K_Left] then Player.Position -= Vector2Single(SecondsPassed * MoveSidewaysSpeed, 0); { collisions enemies vs player } for I := 0 to High(Enemies) do if Player.Collides(Enemies[I]) then begin MessageOk(Window, 'Crash with enemy!'); Restart; Exit; end; { collisions rockets vs enemies, move rockets } for I := 0 to High(Rockets) do if Rockets[I].Alive then begin for J := 0 to High(Enemies) do if Enemies[J].Collides(Rockets[I]) then begin Enemies[J].Alive := false; Enemies[J].DieTime := CurrentTime; Rockets[I].Alive := false; Inc(EnemiesDestroyed); Break; end; Rockets[I].Position += Vector2Single(0, SecondsPassed * RocketSpeed); end; { collisions player vs wall } if PlayerCrashedWithWall( 0, 0) then Exit; if PlayerCrashedWithWall(-1, -1) then Exit; if PlayerCrashedWithWall(-1, 1) then Exit; if PlayerCrashedWithWall( 1, 1) then Exit; if PlayerCrashedWithWall( 1, -1) then Exit; { we constantly change Player.Position, to just redraw constantly } Window.Invalidate; end; procedure WindowPress(Container: TUIContainer; const Event: TInputPressRelease); var I: Integer; begin if Event.IsKey(K_Space) then begin for I := 0 to High(Rockets) do { fire first available rocket } if not Rockets[I].Alive then begin Rockets[I].Alive := true; Rockets[I].Position := Player.Position; Break; end; end; if Event.IsKey(K_F5) then Window.SaveScreen(FileNameAutoInc(ApplicationName + '_screen_%d.png')); end; function MyGetApplicationName: string; begin Result := 'fly_over_river'; end; initialization { This sets SysUtils.ApplicationName. It is useful to make sure it is correct (as early as possible) as our log routines use it. } OnGetApplicationName := @MyGetApplicationName; { initialize Application callbacks } Application.OnInitialize := @ApplicationInitialize; { create Window and initialize Window callbacks } Window := TCastleWindowCustom.Create(Application); Application.MainWindow := Window; { for now, just hardcode the size to match map width, looks best } Window.Width := 1024; Window.Height := 1024; Window.ResizeAllowed := raNotAllowed; Window.OnRender := @WindowRender; Window.OnUpdate := @WindowUpdate; Window.OnPress := @WindowPress; finalization FreeAndNil(Map); FreeAndNil(MapMask); FreeAndNil(PlayerImage); FreeAndNil(Enemy); FreeAndNil(Rocket); FreeAndNil(Explosion); end.
unit fmBarChart; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, TeEngine, Series, TeeProcs, Chart, uEventAgg, uEvents, uModel; type TfrmBarChart = class(TForm) Chart1: TChart; Series1: TBarSeries; pnlFooter: TPanel; btnClose: TButton; CheckBox1: TCheckBox; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure CheckBox1Click(Sender: TObject); private FCurrent: TReportCard; procedure UpdateChart(const aPublisher: TObject; const anEvent: TEventClass); end; var frmBarChart: TfrmBarChart; implementation uses dmController; {$R *.dfm} { TfrmBarChart } procedure TfrmBarChart.btnCloseClick(Sender: TObject); begin Close; end; procedure TfrmBarChart.CheckBox1Click(Sender: TObject); begin EA.Unsubscribe(UpdateChart); if CheckBox1.Checked then EA.Subscribe(UpdateChart, TReportCardEvent) else EA.Subscribe(UpdateChart, TReportCardChange); end; procedure TfrmBarChart.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TfrmBarChart.FormCreate(Sender: TObject); begin FCurrent := nil; UpdateChart(dtmController.Current, TReportCardNav); EA.Subscribe(UpdateChart, TReportCardEvent); end; procedure TfrmBarChart.FormDestroy(Sender: TObject); begin EA.Unsubscribe(UpdateChart); end; procedure TfrmBarChart.UpdateChart(const aPublisher: TObject; const anEvent: TEventClass); begin // If it's a navigational event, make this object the 'Current' object. if anEvent.InheritsFrom(TReportCardNav) then FCurrent := TReportCard(aPublisher); if aPublisher = FCurrent then begin Chart1.Title.Caption := FCurrent.Name; Series1.Clear; Series1.Add(FCurrent.ScoreA, 'A', clRed); Series1.Add(FCurrent.ScoreB, 'B', clBlue); Series1.Add(FCurrent.ScoreC, 'C', clGreen); end; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons; type TfrmFahrenheit_na_Grade = class(TForm) bmbReset: TBitBtn; bmbClose: TBitBtn; btnBereken: TButton; lblFahrenheit: TLabel; lblAfvoer: TLabel; edtFahrenheit: TEdit; procedure btnBerekenClick(Sender: TObject); procedure bmbResetClick(Sender: TObject); procedure FormActivate(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmFahrenheit_na_Grade: TfrmFahrenheit_na_Grade; implementation {$R *.dfm} procedure TfrmFahrenheit_na_Grade.btnBerekenClick(Sender: TObject); var// variables sAfvoer : string; rFahrenheit,rCelsius : real; begin rFahrenheit := StrToFloat(edtFahrenheit.Text);// Hoeveel Fahrenheit in gesluitel is rCelsius := (rFahrenheit - 32) * 5/9;// Hoeveel grade celxius dit is //sAfvoer := FloatToStr (rFahrenheit) + ' grade Fahrenheit is ' + FloatToStr (rCelsius, ffFixed, 5, 1) + ' grade Celsius.'; sAfvoer := FloatToStr (rFahrenheit) + ' grade Fahrenheit is ' + FloatToStr (rCelsius) + ' grade Celsius.';// Die verwerking se afvoer lblAfvoer.Caption := sAfvoer;// Vertoon afvoer end; procedure TfrmFahrenheit_na_Grade.bmbResetClick(Sender: TObject); var sBlank : string; begin sBlank := ' '; edtFahrenheit.Text := sBlank; lblAfvoer.Caption := sBlank; edtFahrenheit.SetFocus; end; procedure TfrmFahrenheit_na_Grade.FormActivate(Sender: TObject); begin edtFahrenheit.SetFocus; end; end.
unit GX_Debug; {$I GX_CondDefine.inc} {$IFDEF GX_DEBUGLOG} interface uses SysUtils; procedure GxAddToDebugLog(const Msg: string); procedure GxAddExceptionToLog(const E: Exception; const Msg: string); implementation uses Classes, Windows, // This requires the JCL 1.11: http://delphi-jedi.org/CODELIBJCL // And a detailed map file (see the linker options in the IDE) JclDebug, JclHookExcept; var DebugData: TStringList = nil; DebugFile: string = ''; procedure LoadDebugFile; var Buf: array[0..MAX_PATH + 1] of Char; begin if DebugData = nil then begin DebugData := TStringList.Create; SetString(DebugFile, Buf, GetModuleFileName(HInstance, Buf, SizeOf(Buf))); DebugFile := DebugFile + '.debuglog'; if FileExists(DebugFile) then DebugData.LoadFromFile(DebugFile); end; end; procedure GxExceptionNotify(ExceptObj: TObject; ExceptAddr: Pointer; OSException: Boolean); begin try LoadDebugFile; if ExceptObj is Exception then begin DebugData.Add(Format('Exception %s "%s" at: %s', [ExceptObj.ClassName, Exception(ExceptObj).Message, DateTimeToStr(Now)])); end else DebugData.Add('Exception at: ' + DateTimeToStr(Now)); if JclLastExceptStackList <> nil then JclLastExceptStackList.AddToStrings(DebugData); DebugData.Add(''); DebugData.SaveToFile(DebugFile); except // Swallow exceptions end; end; // Do we need a more performance conscious way to save the log // without waiting until we unload. Keep the file open for append? // A method that supports multiple clients writing to the log file? // As-is it allows us to debug some machine hangs, though procedure GxAddToDebugLog(const Msg: string); begin try LoadDebugFile; DebugData.Text := DebugData.Text + Msg; DebugData.SaveToFile(DebugFile); except // Swallow exceptions end; end; procedure GxAddExceptionToLog(const E: Exception; const Msg: string); begin try LoadDebugFile; DebugData.Add(Msg +': '+ E.ClassName +': '+ E.Message); if JclLastExceptStackList <> nil then JclLastExceptStackList.AddToStrings(DebugData); DebugData.SaveToFile(DebugFile); except // Swallow exceptions end; end; initialization JclStartExceptionTracking; JclAddExceptNotifier(GxExceptionNotify); finalization JclStopExceptionTracking; {$ELSE not GX_DEBUGLOG} interface implementation {$ENDIF not GX_DEBUGLOG} end.
unit Main9_1; (************************************************************************ Copyright (C) 2009, 2010 by Russell J. Peters, Roger Aelbrecht, Eric W. Engler and Chris Vleghert. This file is part of TZipMaster Version 1.9. TZipMaster is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. TZipMaster is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with TZipMaster. If not, see <http://www.gnu.org/licenses/>. contact: problems@delphizip.org (include ZipMaster in the subject). updates: http://www.delphizip.org DelphiZip maillist subscribe at http://www.freelists.org/list/delphizip ************************************************************************) interface uses Windows, Messages, SysUtils, {Variants,} Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TForm1 = class(TForm) Memo1: TMemo; Panel1: TPanel; Button1: TButton; Button2: TButton; procedure FormCreate(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } fzip: TThread; public { Public declarations } property ZipThread: TThread read fzip write fzip; end; var Form1: TForm1; implementation Uses ZThrd; {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin fzip := nil; end; procedure TForm1.Button2Click(Sender: TObject); begin if assigned(fzip) then fzip.Terminate else Memo1.Lines.Add('**** Not Running ****'); end; procedure TForm1.Button1Click(Sender: TObject); var sl: TStringList; begin if not assigned(fzip) then begin sl := TStringList.Create; try sl.Add('*.pas'); sl.Add('*.dfm'); sl.Add('*.bpr'); fzip := TZipThread.Create('test.zip',sl,Memo1,false); finally sl.Free; end; end; end; end.
Class Jabatan index() try select all data from table jabatan show to view catch get exception create() try show view add data catch get exception store() try get Kode Jabatan get Nama Jabatan get Jumlah Pegawai if Kode Jabatan are exists show alert "Data dengan Kode Jabatan tidak boleh sama" else save record to table jabatan index() with alert "Data berhasil disimpan" catch get exception edit(id) try get id check Kode Jabatan from table jabatan if data found show to view else show alert "Data tidak ditemukan" catch get exception update(id) try get Kode Jabatan get Nama Jabatan get Jumlah Pegawai if Kode Jabatan are same with another data in table jabatan show alert "Ditemukan data dengan Kode Jabatan yang sama" else update record to database with alert index() with alert "Data berhasil diubah" catch get exception delete(id) try get id check Kode Jabatan from table jabatan if data found delete data from table jabatan index() with alert "Data berhasil dihapus" else show alert "Data tidak ditemukan" catch get exception
inherited dmCtasBancarias: TdmCtasBancarias OldCreateOrder = True inherited qryManutencao: TIBCQuery SQLInsert.Strings = ( 'INSERT INTO STWCPGTCTA' ' (BANCO, AGENCIA, CONTA, NOME_AGENCIA, NOME_CONTA, ENDERECO, CT' + 'A_CONTABIL, BAIRRO, CIDADE, ESTADO, CEP, TELEFONE, CONTATO, NR_C' + 'EDENTE, ULT_BLOQUETO, ULT_REMESSA, ULT_CHEQUE, ULT_ENTRADA, CART' + 'EIRA, TP_ESCRITURAL, TX_BANCARIA, LIMITE_CREDITO, DT_ALTERACAO, ' + 'OPERADOR)' 'VALUES' ' (:BANCO, :AGENCIA, :CONTA, :NOME_AGENCIA, :NOME_CONTA, :ENDERE' + 'CO, :CTA_CONTABIL, :BAIRRO, :CIDADE, :ESTADO, :CEP, :TELEFONE, :' + 'CONTATO, :NR_CEDENTE, :ULT_BLOQUETO, :ULT_REMESSA, :ULT_CHEQUE, ' + ':ULT_ENTRADA, :CARTEIRA, :TP_ESCRITURAL, :TX_BANCARIA, :LIMITE_C' + 'REDITO, :DT_ALTERACAO, :OPERADOR)') SQLDelete.Strings = ( 'DELETE FROM STWCPGTCTA' 'WHERE' ' BANCO = :Old_BANCO AND AGENCIA = :Old_AGENCIA AND CONTA = :Old' + '_CONTA') SQLUpdate.Strings = ( 'UPDATE STWCPGTCTA' 'SET' ' BANCO = :BANCO, AGENCIA = :AGENCIA, CONTA = :CONTA, NOME_AGENC' + 'IA = :NOME_AGENCIA, NOME_CONTA = :NOME_CONTA, ENDERECO = :ENDERE' + 'CO, CTA_CONTABIL = :CTA_CONTABIL, BAIRRO = :BAIRRO, CIDADE = :CI' + 'DADE, ESTADO = :ESTADO, CEP = :CEP, TELEFONE = :TELEFONE, CONTAT' + 'O = :CONTATO, NR_CEDENTE = :NR_CEDENTE, ULT_BLOQUETO = :ULT_BLOQ' + 'UETO, ULT_REMESSA = :ULT_REMESSA, ULT_CHEQUE = :ULT_CHEQUE, ULT_' + 'ENTRADA = :ULT_ENTRADA, CARTEIRA = :CARTEIRA, TP_ESCRITURAL = :T' + 'P_ESCRITURAL, TX_BANCARIA = :TX_BANCARIA, LIMITE_CREDITO = :LIMI' + 'TE_CREDITO, DT_ALTERACAO = :DT_ALTERACAO, OPERADOR = :OPERADOR' 'WHERE' ' BANCO = :Old_BANCO AND AGENCIA = :Old_AGENCIA AND CONTA = :Old' + '_CONTA') SQLRefresh.Strings = ( 'SELECT BANCO, AGENCIA, CONTA, NOME_AGENCIA, NOME_CONTA, ENDERECO' + ', CTA_CONTABIL, BAIRRO, CIDADE, ESTADO, CEP, TELEFONE, CONTATO, ' + 'NR_CEDENTE, ULT_BLOQUETO, ULT_REMESSA, ULT_CHEQUE, ULT_ENTRADA, ' + 'CARTEIRA, TP_ESCRITURAL, TX_BANCARIA, LIMITE_CREDITO, DT_ALTERAC' + 'AO, OPERADOR FROM STWCPGTCTA' 'WHERE' ' BANCO = :Old_BANCO AND AGENCIA = :Old_AGENCIA AND CONTA = :Old' + '_CONTA') SQLLock.Strings = ( 'SELECT NULL FROM STWCPGTCTA' 'WHERE' 'BANCO = :Old_BANCO AND AGENCIA = :Old_AGENCIA AND CONTA = :Old_C' + 'ONTA' 'FOR UPDATE WITH LOCK') SQL.Strings = ( 'SELECT' ' CTA.BANCO,' ' CTA.AGENCIA,' ' CTA.CONTA,' ' CTA.NOME_AGENCIA,' ' CTA.NOME_CONTA,' ' CTA.ENDERECO,' ' CTA.CTA_CONTABIL,' ' CTA.BAIRRO,' ' CTA.CIDADE,' ' CTA.ESTADO,' ' CTA.CEP,' ' CTA.TELEFONE,' ' CTA.CONTATO,' ' CTA.NR_CEDENTE,' ' CTA.ULT_BLOQUETO,' ' CTA.ULT_REMESSA,' ' CTA.ULT_CHEQUE,' ' CTA.ULT_ENTRADA,' ' CTA.CARTEIRA,' ' CTA.TP_ESCRITURAL,' ' CTA.TX_BANCARIA,' ' CTA.LIMITE_CREDITO,' ' CTA.DT_ALTERACAO,' ' CTA.OPERADOR,' ' BCO.NOME_BCO' 'FROM STWCPGTCTA CTA' 'LEFT JOIN STWFATTBCO BCO ON BCO.COD_BCO = CTA.BANCO') object qryManutencaoBANCO: TStringField FieldName = 'BANCO' Required = True Size = 3 end object qryManutencaoAGENCIA: TStringField FieldName = 'AGENCIA' Required = True Size = 10 end object qryManutencaoCONTA: TStringField FieldName = 'CONTA' Required = True Size = 10 end object qryManutencaoNOME_AGENCIA: TStringField FieldName = 'NOME_AGENCIA' Size = 40 end object qryManutencaoNOME_CONTA: TStringField FieldName = 'NOME_CONTA' Size = 40 end object qryManutencaoENDERECO: TStringField FieldName = 'ENDERECO' Size = 40 end object qryManutencaoCTA_CONTABIL: TStringField FieldName = 'CTA_CONTABIL' Size = 30 end object qryManutencaoBAIRRO: TStringField FieldName = 'BAIRRO' Size = 15 end object qryManutencaoCIDADE: TStringField FieldName = 'CIDADE' Size = 30 end object qryManutencaoESTADO: TStringField FieldName = 'ESTADO' Size = 2 end object qryManutencaoCEP: TStringField FieldName = 'CEP' Size = 9 end object qryManutencaoTELEFONE: TStringField FieldName = 'TELEFONE' Size = 15 end object qryManutencaoCONTATO: TStringField FieldName = 'CONTATO' Size = 30 end object qryManutencaoNR_CEDENTE: TStringField FieldName = 'NR_CEDENTE' end object qryManutencaoULT_BLOQUETO: TFloatField FieldName = 'ULT_BLOQUETO' end object qryManutencaoULT_REMESSA: TFloatField FieldName = 'ULT_REMESSA' end object qryManutencaoULT_CHEQUE: TFloatField FieldName = 'ULT_CHEQUE' end object qryManutencaoULT_ENTRADA: TFloatField FieldName = 'ULT_ENTRADA' end object qryManutencaoCARTEIRA: TStringField FieldName = 'CARTEIRA' Size = 3 end object qryManutencaoTP_ESCRITURAL: TStringField FieldName = 'TP_ESCRITURAL' Size = 1 end object qryManutencaoTX_BANCARIA: TFloatField FieldName = 'TX_BANCARIA' end object qryManutencaoLIMITE_CREDITO: TFloatField FieldName = 'LIMITE_CREDITO' end object qryManutencaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryManutencaoOPERADOR: TStringField FieldName = 'OPERADOR' end object qryManutencaoNOME_BCO: TStringField FieldName = 'NOME_BCO' ReadOnly = True Size = 40 end end inherited qryLocalizacao: TIBCQuery SQL.Strings = ( 'SELECT' ' CTA.BANCO,' ' CTA.AGENCIA,' ' CTA.CONTA,' ' CTA.NOME_AGENCIA,' ' CTA.NOME_CONTA,' ' CTA.ENDERECO,' ' CTA.CTA_CONTABIL,' ' CTA.BAIRRO,' ' CTA.CIDADE,' ' CTA.ESTADO,' ' CTA.CEP,' ' CTA.TELEFONE,' ' CTA.CONTATO,' ' CTA.NR_CEDENTE,' ' CTA.ULT_BLOQUETO,' ' CTA.ULT_REMESSA,' ' CTA.ULT_CHEQUE,' ' CTA.ULT_ENTRADA,' ' CTA.CARTEIRA,' ' CTA.TP_ESCRITURAL,' ' CTA.TX_BANCARIA,' ' CTA.LIMITE_CREDITO,' ' CTA.DT_ALTERACAO,' ' CTA.OPERADOR,' ' BCO.NOME_BCO' 'FROM STWCPGTCTA CTA' 'LEFT JOIN STWFATTBCO BCO ON BCO.COD_BCO = CTA.BANCO') object qryLocalizacaoBANCO: TStringField FieldName = 'BANCO' Required = True Size = 3 end object qryLocalizacaoAGENCIA: TStringField FieldName = 'AGENCIA' Required = True Size = 10 end object qryLocalizacaoCONTA: TStringField FieldName = 'CONTA' Required = True Size = 10 end object qryLocalizacaoNOME_AGENCIA: TStringField FieldName = 'NOME_AGENCIA' Size = 40 end object qryLocalizacaoNOME_CONTA: TStringField FieldName = 'NOME_CONTA' Size = 40 end object qryLocalizacaoENDERECO: TStringField FieldName = 'ENDERECO' Size = 40 end object qryLocalizacaoCTA_CONTABIL: TStringField FieldName = 'CTA_CONTABIL' Size = 30 end object qryLocalizacaoBAIRRO: TStringField FieldName = 'BAIRRO' Size = 15 end object qryLocalizacaoCIDADE: TStringField FieldName = 'CIDADE' Size = 30 end object qryLocalizacaoESTADO: TStringField FieldName = 'ESTADO' Size = 2 end object qryLocalizacaoCEP: TStringField FieldName = 'CEP' Size = 9 end object qryLocalizacaoTELEFONE: TStringField FieldName = 'TELEFONE' Size = 15 end object qryLocalizacaoCONTATO: TStringField FieldName = 'CONTATO' Size = 30 end object qryLocalizacaoNR_CEDENTE: TStringField FieldName = 'NR_CEDENTE' end object qryLocalizacaoULT_BLOQUETO: TFloatField FieldName = 'ULT_BLOQUETO' end object qryLocalizacaoULT_REMESSA: TFloatField FieldName = 'ULT_REMESSA' end object qryLocalizacaoULT_CHEQUE: TFloatField FieldName = 'ULT_CHEQUE' end object qryLocalizacaoULT_ENTRADA: TFloatField FieldName = 'ULT_ENTRADA' end object qryLocalizacaoCARTEIRA: TStringField FieldName = 'CARTEIRA' Size = 3 end object qryLocalizacaoTP_ESCRITURAL: TStringField FieldName = 'TP_ESCRITURAL' Size = 1 end object qryLocalizacaoTX_BANCARIA: TFloatField FieldName = 'TX_BANCARIA' end object qryLocalizacaoLIMITE_CREDITO: TFloatField FieldName = 'LIMITE_CREDITO' end object qryLocalizacaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryLocalizacaoOPERADOR: TStringField FieldName = 'OPERADOR' end object qryLocalizacaoNOME_BCO: TStringField FieldName = 'NOME_BCO' ReadOnly = True Size = 40 end end end
unit InfoESOANOTSTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoESOANOTSRecord = record PEntId: String[8]; PModCount: Integer; End; TInfoESOANOTSClass2 = class public PEntId: String[8]; PModCount: Integer; End; // function CtoRInfoESOANOTS(AClass:TInfoESOANOTSClass):TInfoESOANOTSRecord; // procedure RtoCInfoESOANOTS(ARecord:TInfoESOANOTSRecord;AClass:TInfoESOANOTSClass); TInfoESOANOTSBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoESOANOTSRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoESOANOTS = (InfoESOANOTSPrimaryKey); TInfoESOANOTSTable = class( TDBISAMTableAU ) private FDFEntId: TStringField; FDFModCount: TIntegerField; FDFNotes: TBlobField; procedure SetPEntId(const Value: String); function GetPEntId:String; procedure SetPModCount(const Value: Integer); function GetPModCount:Integer; procedure SetEnumIndex(Value: TEIInfoESOANOTS); function GetEnumIndex: TEIInfoESOANOTS; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoESOANOTSRecord; procedure StoreDataBuffer(ABuffer:TInfoESOANOTSRecord); property DFEntId: TStringField read FDFEntId; property DFModCount: TIntegerField read FDFModCount; property DFNotes: TBlobField read FDFNotes; property PEntId: String read GetPEntId write SetPEntId; property PModCount: Integer read GetPModCount write SetPModCount; published property Active write SetActive; property EnumIndex: TEIInfoESOANOTS read GetEnumIndex write SetEnumIndex; end; { TInfoESOANOTSTable } TInfoESOANOTSQuery = class( TDBISAMQueryAU ) private FDFEntId: TStringField; FDFModCount: TIntegerField; FDFNotes: TBlobField; procedure SetPEntId(const Value: String); function GetPEntId:String; procedure SetPModCount(const Value: Integer); function GetPModCount:Integer; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; public function GetDataBuffer:TInfoESOANOTSRecord; procedure StoreDataBuffer(ABuffer:TInfoESOANOTSRecord); property DFEntId: TStringField read FDFEntId; property DFModCount: TIntegerField read FDFModCount; property DFNotes: TBlobField read FDFNotes; property PEntId: String read GetPEntId write SetPEntId; property PModCount: Integer read GetPModCount write SetPModCount; published property Active write SetActive; end; { TInfoESOANOTSTable } procedure Register; implementation procedure TInfoESOANOTSTable.CreateFields; begin FDFEntId := CreateField( 'EntId' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TIntegerField; FDFNotes := CreateField( 'Notes' ) as TBlobField; end; { TInfoESOANOTSTable.CreateFields } procedure TInfoESOANOTSTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoESOANOTSTable.SetActive } procedure TInfoESOANOTSTable.SetPEntId(const Value: String); begin DFEntId.Value := Value; end; function TInfoESOANOTSTable.GetPEntId:String; begin result := DFEntId.Value; end; procedure TInfoESOANOTSTable.SetPModCount(const Value: Integer); begin DFModCount.Value := Value; end; function TInfoESOANOTSTable.GetPModCount:Integer; begin result := DFModCount.Value; end; procedure TInfoESOANOTSTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('EntId, String, 8, N'); Add('ModCount, Integer, 0, N'); Add('Notes, Memo, 0, N'); end; end; procedure TInfoESOANOTSTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, EntId, Y, Y, N, N'); end; end; procedure TInfoESOANOTSTable.SetEnumIndex(Value: TEIInfoESOANOTS); begin case Value of InfoESOANOTSPrimaryKey : IndexName := ''; end; end; function TInfoESOANOTSTable.GetDataBuffer:TInfoESOANOTSRecord; var buf: TInfoESOANOTSRecord; begin fillchar(buf, sizeof(buf), 0); buf.PEntId := DFEntId.Value; buf.PModCount := DFModCount.Value; result := buf; end; procedure TInfoESOANOTSTable.StoreDataBuffer(ABuffer:TInfoESOANOTSRecord); begin DFEntId.Value := ABuffer.PEntId; DFModCount.Value := ABuffer.PModCount; end; function TInfoESOANOTSTable.GetEnumIndex: TEIInfoESOANOTS; var iname : string; begin result := InfoESOANOTSPrimaryKey; iname := uppercase(indexname); if iname = '' then result := InfoESOANOTSPrimaryKey; end; procedure TInfoESOANOTSQuery.CreateFields; begin FDFEntId := CreateField( 'EntId' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TIntegerField; FDFNotes := CreateField( 'Notes' ) as TBlobField; end; { TInfoESOANOTSQuery.CreateFields } procedure TInfoESOANOTSQuery.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoESOANOTSQuery.SetActive } procedure TInfoESOANOTSQuery.SetPEntId(const Value: String); begin DFEntId.Value := Value; end; function TInfoESOANOTSQuery.GetPEntId:String; begin result := DFEntId.Value; end; procedure TInfoESOANOTSQuery.SetPModCount(const Value: Integer); begin DFModCount.Value := Value; end; function TInfoESOANOTSQuery.GetPModCount:Integer; begin result := DFModCount.Value; end; function TInfoESOANOTSQuery.GetDataBuffer:TInfoESOANOTSRecord; var buf: TInfoESOANOTSRecord; begin fillchar(buf, sizeof(buf), 0); buf.PEntId := DFEntId.Value; buf.PModCount := DFModCount.Value; result := buf; end; procedure TInfoESOANOTSQuery.StoreDataBuffer(ABuffer:TInfoESOANOTSRecord); begin DFEntId.Value := ABuffer.PEntId; DFModCount.Value := ABuffer.PModCount; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoESOANOTSTable, TInfoESOANOTSQuery, TInfoESOANOTSBuffer ] ); end; { Register } function TInfoESOANOTSBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..2] of string = ('ENTID','MODCOUNT' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 2) and (flist[x] <> s) do inc(x); if x <= 2 then result := x else result := 0; end; function TInfoESOANOTSBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftInteger; end; end; function TInfoESOANOTSBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PEntId; 2 : result := @Data.PModCount; end; end; end.
unit task_2; interface { Дерево, базовый Класс} type TTree=class private fLeft: TTree; fRight: TTree; fParent: TTree; fValue: Variant; fItems: TArray<TTree>; fRightCout: Integer; fLeftCout: Integer; function get_right: TTree; function get_left: TTree; function get_parent: TTree; function get_value: Variant; // делае узел головным function make_me_head: TTree; // Сравнение двух деревьев(по значению) function compare(another_tree: TTree): Integer; // Ищем вершину дерева(полезно, если данное дерево не является вершиной) function get_tree_head: TTree; function _build_json(rec_lvl: Integer): String; function _get_tree_value_or_null(_tree: TTree; rec_lvl: Integer): String; function get_right_cout: Integer; function get_left_cout: Integer; procedure set_value(new_value: Variant); procedure set_right(new_right: TTree); procedure set_left(new_left: TTree); procedure set_right_cout(new_cout: Integer); procedure set_left_cout(new_cout: Integer); property RightCout: Integer read get_right_cout write set_right_cout; property LeftCout: Integer read get_left_cout write set_left_cout; procedure update_child_cout; public property Value: Variant read get_value write set_value; property Right: TTree read get_right write set_right; property Left: TTree read get_left write set_left; property Parent: TTree read get_parent; // Дерево без предков и дочерних узлов constructor __init__(my_value: Variant); overload; // Создаем с предком constructor __init__(my_value: Variant; my_parent: TTree); overload; // Создаем с предком и дочерним constructor __init__(my_value: Variant; my_parent: TTree; my_child: TTree); overload; // Создаем с предком и дочерними constructor __init__(my_value: Variant; my_parent: TTree; my_child_1: TTree; my_child_2: TTree); overload; // Добавление нового узла, через значение procedure add(new_tree_value: Variant); overload; // Добавление нового узла(дерева) procedure add(new_tree: TTree); overload; // балансировка дерева function balance: TTree; // Конвертирование дерева в отсортированный массив function AsArray: TArray<Variant>; // Наивысшее значение структуры function Max: Variant; // Наименьшее значение function Low: Variant; // Наивысший Элемент структуры function Max_Node: TTree; // Наименьший Элемент структуры function Low_Node: TTree; // Возвращаем значение ввиде строки function ToString: String; // Генерируем JSON строку function build_json: String; // Проверка элемента на вхождение function entry_check(val: Variant): Boolean; // Поиск function find(val: Variant): TTree; end; function repeat_str(str: String; loop: Integer): String; implementation uses System.Generics.Collections, SysUtils, System.TypInfo, System.Generics.Defaults; const NL: String = ^M + ^J; TAB: String = chr(9); NLTAB: String = ^M + ^J + chr(9); { TTree } { Конструкторы } constructor TTree.__init__(my_value: Variant; my_parent, my_child: TTree); begin self.Value := my_value; self.fParent := my_parent; self.add(my_child); end; constructor TTree.__init__(my_value: Variant; my_parent, my_child_1, my_child_2: TTree); begin self.Value := my_value; self.fParent := my_parent; self.add(my_child_1); self.add(my_child_2); end; constructor TTree.__init__(my_value: Variant); begin self.Value := my_value; end; constructor TTree.__init__(my_value: Variant; my_parent: TTree); begin self.Value := my_value; self.fParent := my_parent; end; { Процедуры } procedure TTree.add(new_tree_value: Variant); var new_tree: TTree; begin new_tree := TTree.__init__(new_tree_value, self); self.add(new_tree); end; procedure TTree.add(new_tree: TTree); begin if self.Value <> new_tree.Value then begin if self.Value > new_tree.Value then self.Left := new_tree; if self.Value < new_tree.Value then self.Right := new_tree; SetLength(self.fItems , Length(self.fItems )+1); self.fItems[High(self.fItems)] := new_tree; end; new_tree.fRightCout := self.fRightCout + self.fLeftCout; end; procedure TTree.set_left(new_left: TTree); begin self.LeftCout := self.LeftCout + 1; if self.Left <> nil then begin self.Left.add(new_left); end else begin self.update_child_cout(); self.fLeft := new_left; self.fLeft.fParent := self; end; end; procedure TTree.set_left_cout(new_cout: Integer); begin self.fLeftCout := new_cout; end; procedure TTree.update_child_cout; var item: TTree; begin for item in self.fItems do item.RightCout := item.RightCout+1; end; procedure TTree.set_right(new_right: TTree); var item: TTree; begin self.RightCout := self.RightCout+1; if self.Right <> nil then begin self.fRight.add(new_right); end else begin self.update_child_cout(); self.fRight := new_right; self.fRight.fParent := self; end; end; procedure TTree.set_right_cout(new_cout: Integer); begin self.fRightCout := new_cout; end; procedure TTree.set_value(new_value: Variant); begin self.fValue := new_value; end; function TTree.ToString: String; begin result := Format('%s', [self.fValue]); end; { Функции } function TTree.Compare(another_tree: TTree): Integer; var LComparer: IComparer<Variant>; begin LComparer := TComparer<Variant>.Default; result := LComparer.Compare(self.Value, another_tree.Value); end; function TTree.entry_check(val: Variant): Boolean; var head: TTree; var item: TTree; begin head := self.get_tree_head; result := false; for item in head.fItems do begin if item.Value = val then begin result := true; break; end; end; end; function TTree.find(val: Variant): TTree; var item: TTree; var head: TTree; begin head := self.get_tree_head; for item in head.fItems do begin if item.Value = val then begin result := item; break; end; end; end; function TTree.get_left: TTree; begin result := self.fLeft; end; function TTree.get_left_cout: Integer; begin result := self.fLeftCout; end; function TTree.get_parent: TTree; begin result := self.fParent; end; function TTree.get_right: TTree; begin result := Self.fRight; end; function TTree.get_right_cout: Integer; begin result := self.fRightCout; end; function TTree.get_tree_head: TTree; var next: TTree; begin next := self; while next.Parent <> nil do next := next.Parent; result := next; end; function TTree.get_value: Variant; begin result := self.fValue; end; function TTree.Low: Variant; begin result := self.Low_Node.Value; end; function TTree.Low_Node: TTree; var next: TTree; begin next := self; while next.Left <> nil do next := next.Left; result := next; end; function TTree.make_me_head: TTree; var old_head: TTree; i: Integer; new_tree: TTree; begin new_tree := TTree.__init__(self.Value); old_head := self.get_tree_head; new_tree.add(old_head.Value); for i:=0 to Length(old_head.fItems)-1 do new_tree.add(old_head.fItems[i].Value); result := new_tree; end; function TTree.Max: Variant; begin result := self.Max_Node.Value; end; function TTree.Max_Node: TTree; var next: TTree; begin next := self; while next.Right <> nil do next := next.Right; result := next; end; function TTree.AsArray: TArray<Variant>; var q: Integer; i: Integer; temp: TTree; begin SetLength(result, Length(self.fItems)); for q:=0 to Length(self.fItems)-1 do begin for i := 0 to Length(self.fItems)-1 do begin if self.fItems[i].Value > self.fItems[q].Value then begin result[i] := self.fItems[q].Value; result[q] := self.fItems[i].Value; end; end; end; end; function TTree.balance: TTree; var best: TTree; item: TTree; best_index: Integer; now_index: Integer; begin best := self; best_index := best.RightCout-best.LeftCout; for item in self.fItems do begin now_index := item.RightCout-item.LeftCout; if best_index < 0 then best_index :=best_index*-1; if now_index < 0 then now_index :=now_index*-1; if best_index > now_index then begin best := item; best_index := best.RightCout-best.LeftCout; end; end; result := best.make_me_head; end; function TTree.build_json: String; begin result := self._build_json(0); end; function TTree._get_tree_value_or_null(_tree: TTree; rec_lvl: Integer): String; begin if _tree <> nil then begin result := _tree._build_json(rec_lvl); end else begin result := 'null'; end; end; function TTree._build_json(rec_lvl: Integer): String; var tb: String; begin tb := repeat_str(TAB, rec_lvl); result := '{' + NL + tb + '"Value": "' + self.ToString +'", '; result := result + NL + tb + '"Right": '; result := result + self._get_tree_value_or_null(self.fRight, rec_lvl+1); result := result + NL + tb + '"Left": '; result := result + self._get_tree_value_or_null(self.fLeft, rec_lvl+1) + NL + tb + '}'; if rec_lvl <> 0 then result := result + ','; end; function repeat_str(str: String; loop: Integer): String; var I: Integer; begin for I := 0 to loop do result := result + str; end; end.
{ MIT License Copyright (c) 2017 Marcos Douglas B. Santos Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. } unit James.IO.Tests; {$include james.inc} interface uses Classes, SysUtils, fpcunit, testregistry, James.IO.Clss; type TFileTest = class(TTestCase) published procedure Path; procedure Name; procedure Stream; end; TFileMergedTest = class(TTestCase) published //procedure end; implementation { TFileTest } procedure TFileTest.Path; begin AssertEquals('c:\path\', TFile.New('c:\path\filename.txt').Path); end; procedure TFileTest.Name; begin AssertEquals('filename.txt', TFile.New('c:\path\filename.txt').Name); end; procedure TFileTest.Stream; const TXT = 'ABCC~#'; FILE_NAME = 'file.txt'; var M: TMemoryStream; begin M := TMemoryStream.Create; try M.WriteBuffer(TXT[1], Length(TXT) * SizeOf(Char)); M.SaveToFile(FILE_NAME); AssertEquals(TXT, TFile.New(FILE_NAME).Stream.AsString); finally DeleteFile(FILE_NAME); M.Free; end; end; initialization RegisterTest('Files', TFileTest); end.
unit Project.Interfaces; interface type iEndereco<T> = interface; iEndereco<T> = interface function Rua ( aValue : String ) : iEndereco<T>; overload; function Rua : String; overload; function Numero ( aValue : Integer ) : iEndereco<T>; overload; function Numero : Integer; overload; function &End : T; end; iPessoaFisica = interface ['{BA97123F-5B75-466B-8F3C-D2DA3FDE9267}'] function Endereco : iEndereco<iPessoaFisica>; function CPF ( aValue : String ) : iPessoaFisica; overload; function CPF : String; overload; end; iPessoaJuridica = interface ['{3D0D4CB3-BCAE-4205-8F92-F2E01143454A}'] function Endereco : iEndereco<iPessoaJuridica>; function CNPJ ( aValue : String ) : iPessoaJuridica; overload; function CNPJ : String; overload; end; implementation end.
unit udmResposta; interface uses Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS, uMatVars; type TdmResposta = class(TdmPadrao) qryManutencaoIDRESP: TIntegerField; qryManutencaoFILIAL: TStringField; qryManutencaoDATA: TDateTimeField; qryManutencaoIDPGTA: TIntegerField; qryManutencaoDETRESPOSTA: TStringField; qryManutencaoOPERADOR: TStringField; qryManutencaoDT_ALTERACAO: TDateTimeField; qryLocalizacaoIDRESP: TIntegerField; qryLocalizacaoFILIAL: TStringField; qryLocalizacaoDATA: TDateTimeField; qryLocalizacaoIDPGTA: TIntegerField; qryLocalizacaoDETRESPOSTA: TStringField; qryLocalizacaoOPERADOR: TStringField; qryLocalizacaoDT_ALTERACAO: TDateTimeField; qryManutencaoDESCRICAO: TStringField; qryLocalizacaoDESCRICAO: TStringField; protected procedure MontaSQLBusca(DataSet: TDataSet = nil); override; procedure MontaSQLRefresh; override; private FFilial: string; FData: TDateTime; public function InicializarResposta: Boolean; property Filial: string read FFilial write FFilial; property Data: TDateTime read FData write FData; end; const SQL_DEFAULT = 'SELECT ' + ' IDRESP, ' + ' FILIAL, ' + ' DATA, ' + ' IDPGTA, ' + ' PERGUNTA.DESCRICAO, ' + ' DETRESPOSTA, ' + ' OPERADOR, ' + ' DT_ALTERACAO ' + 'FROM RESPOSTA ' + 'LEFT JOIN PERGUNTA ON PERGUNTA.IDPGTA = RESPOSTA.IDPGTA'; var dmResposta: TdmResposta; implementation uses udmVariaveis, udmPrincipal; {$R *.dfm} function TdmResposta.InicializarResposta: Boolean; var sData: string; begin sData := FormatDateTime('yyyy-mm-dd', FData); if not Localizar then begin try with qryManipulacao do begin Close; SQL.Clear; SQL.Add('INSERT INTO RESPOSTA'); SQL.Add('SELECT'); SQL.Add(' GEN_ID(gen_resposta, 1), '); SQL.Add(' ' + QuotedStr(FFilial) + ', '); SQL.Add(' ' + QuotedStr(sData) + ', '); SQL.Add(' IDPGTA, '); SQL.Add(' '''', '); SQL.Add(' ' + QuotedStr(sSnh_NmUsuario) + ', '); SQL.Add(' CURRENT_TIMESTAMP '); SQL.Add('FROM PERGUNTA '); SQL.Add('WHERE NOT EXISTS (SELECT * FROM RESPOSTA OP WHERE OP.IDPGTA = PERGUNTA.IDPGTA'); SQL.Add(' AND OP.DATA = ' + QuotedStr(sData) ); SQL.Add(' AND OP.FILIAL = ' + QuotedStr(FFilial) + ')'); SQL.Add(' AND ((' + QuotedStr(sData) + ' >= PERGUNTA.DT_PERGUNTA)'); SQL.Add(' AND (' + QuotedStr(sData) + ' < PERGUNTA.DT_VALIDADE))'); ExecSQL; end; dmPrincipal.ConexaoBanco.Commit; except on E:Exception do begin // dmPrincipal.ConexaoBanco.Rollback; MessageDlg('Erro no processamento das respostas: ' + E.Message, mtWarning, [mbOk], 0); end; end; end; Localizar(qryManutencao); end; procedure TdmResposta.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE FILIAL = ' + QuotedStr(FFilial)); SQL.Add(' AND DATA = ' + QuotedStr(FormatDateTime('yyyy-mm-dd', FData))); end; end; procedure TdmResposta.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add(SQL_DEFAULT); end; end; end.
unit uMVCAuthorization; interface uses System.SysUtils, System.Classes, Forms, ufmMain, uUtils, uRemoteDM, uTypes, Data.DB, FIBDataSet, pFIBDataSet, PaxCompiler, PaxRunner, PaxProgram, PaxEval, PAXCOMP_CONSTANTS, IMPORT_COMMON, Generics.Collections, System.Variants, uDMConfig; type TMVCAuthorization = class(TDataModule) ConstituentDataSource: TDataSource; RepresentativesDataSource: TDataSource; Notary: TpFIBDataSet; NotaryDataSource: TDataSource; published Authorization: TpFIBDataSet; Constituent: TpFIBDataSet; Representatives: TpFIBDataSet; AuthorizationDataSource: TDataSource; PaxCompiler: TPaxCompiler; PaxPascalLanguage: TPaxPascalLanguage; PaxProgram: TPaxProgram; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); function LogToMain(AMsg: string): boolean; function getRepresentatives: TpFIBDataSet; private FInterpretersCollection: TObjectDictionary<cardinal, TMemoryStream>; procedure ReportProgress(const CurrentTag: string; Total: Word; Current: Word); public function setID(AID: string): boolean; function buildReport(AInputFileName: string; AOutputFileName: string): boolean; function GetCustomTagValue(const Tag: AnsiString; var Value: string): boolean; function GetCustomTagValue1(const Tag: AnsiString; var Value: String): boolean; function GetCustomTagValue2(const Tag: AnsiString; var Value: String): boolean; function initProgram(AProgram: TPaxProgram): boolean; function prepareScript: boolean; procedure EditReport; function resultFromProgram(const APaxProgram: TPaxProgram): variant; end; var MVCAuthorization: TMVCAuthorization; implementation uses ShaCrcUnit, uDbFreeReporter, uFreeReporter, uStrUtils, DateUtils, Globals; {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TMVCAuthorization } function TMVCAuthorization.buildReport(AInputFileName: string; AOutputFileName: string): boolean; var Reporter: TDbFreeReporter; begin prepareScript; Reporter := TDbFreeReporter.Create; Reporter.OnGetCustomTagValue := GetCustomTagValue; Reporter.OnProgress := ReportProgress; Reporter.AddDataSet(Authorization); Reporter.AddDataSet(Constituent); Reporter.AddDataSet(Representatives); Reporter.AddDataSet(Notary); TfmMain(Application.MainForm).ShowStatusProgressBar; Reporter.CreateReport(AInputFileName, AOutputFileName); TfmMain(Application.MainForm).HideStatusProgressBar; Reporter.Free; end; procedure TMVCAuthorization.DataModuleCreate(Sender: TObject); begin // PaxEval := TPaxEval.Create(nil); FInterpretersCollection := TObjectDictionary<cardinal, TMemoryStream>.Create([doOwnsValues]); end; procedure TMVCAuthorization.DataModuleDestroy(Sender: TObject); var CRC32: Cardinal; ProgramInterpreterState: TMemoryStream; begin Constituent.Close; Representatives.Close; Notary.Close; Authorization.Close; // if Assigned(PaxEval) then PaxEval.Free; for CRC32 in FInterpretersCollection.Keys do begin FInterpretersCollection.TryGetValue(CRC32, ProgramInterpreterState); ProgramInterpreterState.Free; end; FInterpretersCollection.Free; end; procedure TMVCAuthorization.EditReport; begin end; function TMVCAuthorization.GetCustomTagValue1(const Tag: AnsiString; var Value: String): boolean; var I: Integer; CRC32: Cardinal; ProgramInterpreterState: TMemoryStream; ProgramInterpreter: TPaxProgram; begin Value := ''; CRC32 := ShaCrcRefresh($FFFFFFFF, @Tag[1], Length(Tag)); Log(Format('CRC32=%.8x',[not CRC32])); ProgramInterpreter := TPaxProgram.Create(Self); if FInterpretersCollection.TryGetValue(CRC32, ProgramInterpreterState) then begin ProgramInterpreterState.Position := 0; ProgramInterpreter.LoadFromStream(ProgramInterpreterState); Log('Loaded from cache'); end else begin prepareScript; if PaxCompiler.CompileExpression(Tag, ProgramInterpreter, PaxPascalLanguage.LanguageName) then begin ProgramInterpreterState := TMemoryStream.Create; ProgramInterpreter.SaveToStream(ProgramInterpreterState); ProgramInterpreterState.Position := 0; FInterpretersCollection.Add(CRC32, ProgramInterpreterState); Log('Compiled and saved'); end; end; try ProgramInterpreter.Run; Value := String(ProgramInterpreter.ResultPtr^); except Value := '[!ERROR: (' + Tag + ')]'; for I:=0 to PaxCompiler.ErrorCount -1 do begin Log('[!] Program error:' + PaxCompiler.ErrorMessage[I]); Value := Value + PaxCompiler.ErrorMessage[I]; end; end; ProgramInterpreter.Free; Log('[i]: '+Tag+'='+Value); Result := True; end; function TMVCAuthorization.initProgram(AProgram: TPaxProgram): boolean; begin // AProgram.RegisterClassType(0, TMVCAuthorization); // AProgram.RegisterClassType(0, TpFIBDataSet); // AProgram.RegisterClassType(0, TField); { AProgram.SetAddress(); PaxCompiler.RegisterHeader(0, 'function GetUnitCase(const AValue: Integer; const AUnit1, AUnit2, AUnit3: String): String;', @uStrUtils.GetUnitCase); PaxCompiler.RegisterHeader(0, 'function YearsBetween(const ANow, AThen: TDateTime): Integer;', @DateUtils.YearsBetween); PaxCompiler.RegisterHeader(0, 'function Month_Case_Nominative(ADate: TDateTime): string;', @uStrUtils.Month_Case_Nominative); PaxCompiler.RegisterHeader(0, 'function Month_Case_Genitive(ADate: TDateTime): string;', @uStrUtils.Month_Case_Genitive); PaxCompiler.RegisterHeader(0, 'function ExtraSpell(Number:extended; Param: string): string;', @uStrUtils.ExtraSpell); PaxCompiler.RegisterHeader(0, 'procedure Log(AText: string);', @ufmMain.Log); PaxCompiler.RegisterHeader(datasetHandle, 'function FieldByName(const FieldName: string): TField;', @TpFIBDataSet.FieldByName); PaxCompiler.RegisterVariable(0, 'DataModule: TMVCAuthorization', @Self); RepresentativesHandle := PaxCompiler.RegisterVariable(0, 'Representatives', datasetHandle, @Representatives); RepresentativesHandle := PaxCompiler.RegisterVariable(0, 'Authorization', datasetHandle, @Authorization); RepresentativesHandle := PaxCompiler.RegisterVariable(0, 'Constituent', datasetHandle, @Constituent);} end; function TMVCAuthorization.GetCustomTagValue2(const Tag: AnsiString; var Value: String): boolean; var I: Integer; CRC32: Cardinal; ProgramInterpreterState: TMemoryStream; ProgramInterpreter: TPaxProgram; PaxEval: TPaxEval; begin Value := ''; Log('[d] request tag: ' + Tag); CRC32 := ShaCrcRefresh($FFFFFFFF, @Tag[1], Length(Tag)); Log(Format('CRC32=%.8x',[not CRC32])); ProgramInterpreterState := TMemoryStream.Create; if FInterpretersCollection.TryGetValue(CRC32, ProgramInterpreterState) then begin Log(IntToStr(ProgramInterpreterState.Size)); ProgramInterpreterState.Position := 0; PaxProgram.LoadFromStream(ProgramInterpreterState); initProgram(PaxProgram); PaxProgram.Run; Log('Loaded from cache'); end else begin // prepareScript; PaxEval := TPaxEval.Create(nil); PaxEval.RegisterCompiler(PaxCompiler, PaxProgram); PaxEval.CompileExpression(Tag); // if PaxCompiler.CompileExpression(Tag, PaxProgram, PaxPascalLanguage.LanguageName) then if PaxEval.ErrorCount = 0 then begin if Assigned(ProgramInterpreterState) then ProgramInterpreterState.Free; ProgramInterpreterState := TMemoryStream.Create; PaxProgram.SaveToStream(ProgramInterpreterState); ProgramInterpreterState.Position := 0; // FInterpretersCollection.Add(CRC32, ProgramInterpreterState); Log('Compiled and saved'); end else begin for I:=0 to PaxCompiler.ErrorCount -1 do begin Log('[!] Precompile error:' + PaxCompiler.ErrorMessage[I]); Value := Value + PaxCompiler.ErrorMessage[I]; end; end; end; // PaxEval.CompileExpression(Tag); try PaxEval.Run; Value := PaxEval.ResultAsString; except Value := '[!ERROR: (' + Tag + ')]'; for I:=0 to PaxCompiler.ErrorCount -1 do begin Log('[!] Program error:' + PaxCompiler.ErrorMessage[I]); Value := Value + PaxCompiler.ErrorMessage[I]; end; for I:=0 to PaxEval.ErrorCount -1 do begin Log('[!] Program eval error:' + PaxEval.ErrorMessage[I]); Value := Value + PaxEval.ErrorMessage[I]; end; end; PaxEval.Reset; PaxEval.Free; Log('[i] interpreted as: '+Tag+'='+Value); Result := True; end; function TMVCAuthorization.GetCustomTagValue(const Tag: AnsiString; var Value: String): boolean; var I: Integer; CRC32: Cardinal; ProgramInterpreterState: TMemoryStream; ProgramInterpreter: TPaxProgram; PaxEval: TPaxEval; begin Value := ''; Log('[d] request tag: ' + Tag); CRC32 := ShaCrcRefresh($FFFFFFFF, @Tag[1], Length(Tag)); Log(Format('CRC32=%.8x',[not CRC32])); ProgramInterpreterState := TMemoryStream.Create; if FInterpretersCollection.TryGetValue(CRC32, ProgramInterpreterState) then begin Log(IntToStr(ProgramInterpreterState.Size)); PaxProgram.LoadFromStream(ProgramInterpreterState); //initProgram(PaxProgram); //PaxProgram.Run; Log('Loaded from cache'); end else begin PaxCompiler.ResetCompilation; if PaxCompiler.CompileExpression(Tag, PaxProgram, PaxPascalLanguage.LanguageName) then begin ProgramInterpreterState := TMemoryStream.Create; PaxProgram.SaveToStream(ProgramInterpreterState); ProgramInterpreterState.Position := 0; // FInterpretersCollection.Add(CRC32, ProgramInterpreterState); Log('Compiled and saved'); end else begin for I:=0 to PaxCompiler.ErrorCount -1 do begin Log('[!] Precompile error:' + PaxCompiler.ErrorMessage[I]); Value := Value + PaxCompiler.ErrorMessage[I]; end; end; end; // PaxEval.CompileExpression(Tag); try PaxProgram.Run; Value := VarToStr(resultFromProgram(PaxProgram)); except Value := '[!ERROR: (' + Tag + ')]' + Value; end; Log('[i] interpreted as: '+Tag+'='+Value); Result := True; end; function TMVCAuthorization.LogToMain(AMsg: string): boolean; begin Log(AMsg); end; function TMVCAuthorization.prepareScript: boolean; var I: Integer; funcPointer: Pointer; funcHandle: Integer; mainHandle: Integer; datasetHandle: Integer; fieldHandle: Integer; RepresentativesHandle: Integer; res: Variant; begin PaxCompiler.Reset; // PaxPascalLanguage.SetCallConv(__ccCDECL); // PaxPascalLanguage.SetCallConv(__ccSTDCALL); // PaxPascalLanguage.SetCallConv(__ccREGISTER); // PaxPascalLanguage.SetCallConv(__ccCDECL); // PaxPascalLanguage.SetCallConv(__ccPASCAL); // PaxPascalLanguage.SetCallConv(__ccSAFECALL); // PaxPascalLanguage.SetCallConv(__ccMSFASTCALL); PaxCompiler.RegisterLanguage(PaxPascalLanguage); // PaxCompiler.AddModule('main', PaxPascalLanguage.LanguageName); // mainHandle := PaxCompiler.RegisterClassType(0, TMVCAuthorization); datasetHandle := PaxCompiler.RegisterClassType(0, TpFIBDataSet); fieldHandle := PaxCompiler.RegisterClassType(0, TField); PaxCompiler.RegisterHeader(0, 'function GetUnitCase(const AValue: Integer; const AUnit1, AUnit2, AUnit3: String): String;', @uStrUtils.GetUnitCase); PaxCompiler.RegisterHeader(0, 'function YearsBetween(const ANow, AThen: TDateTime): Integer;', @DateUtils.YearsBetween); PaxCompiler.RegisterHeader(0, 'function Month_Case_Nominative(ADate: TDateTime): string;', @uStrUtils.Month_Case_Nominative); PaxCompiler.RegisterHeader(0, 'function Month_Case_Genitive(ADate: TDateTime): string;', @uStrUtils.Month_Case_Genitive); PaxCompiler.RegisterHeader(0, 'function ExtraSpell(Number:extended; Param: string): string;', @uStrUtils.ExtraSpell); PaxCompiler.RegisterHeader(0, 'procedure Log(AText: string);', @ufmMain.Log); PaxCompiler.RegisterHeader(datasetHandle, 'function FieldByName(const FieldName: string): TField;', @TpFIBDataSet.FieldByName); PaxCompiler.RegisterHeader(0, 'function DatePart(ADate: TDateTime; APart: Char): Word;', @Globals.DatePart); PaxCompiler.RegisterHeader(0, 'function DatePartStr(ADate: TDateTime; APart: Char): String;', @Globals.DatePartStr); PaxCompiler.RegisterHeader(0, 'function FieldByName(ADataSet: TpFIBDataSet; AFieldName: string): string;', @Globals.FieldByName); PaxCompiler.RegisterHeader(0, 'function DSisEOF(ADataSet: TpFIBDataSet): Boolean;', @Globals.DSisEOF); PaxCompiler.RegisterHeader(0, 'function DSisBOF(ADataSet: TpFIBDataSet): Boolean;', @Globals.DSisBOF); PaxCompiler.RegisterHeader(0, 'function DSIsEmpty(ADataSet: TpFIBDataSet): Boolean;', @Globals.DSIsEmpty); PaxCompiler.RegisterHeader(0, 'function DSRecCount(ADataSet: TpFIBDataSet): Integer;', @Globals.DSRecCount); PaxCompiler.RegisterHeader(0, 'function DSRecNo(ADataSet: TpFIBDataSet): Integer;', @Globals.DSRecNo); PaxCompiler.RegisterHeader(0, 'function ifFalse(AValue: Boolean; AResultString: string): string;', @Globals.ifFalse); PaxCompiler.RegisterHeader(0, 'function ifTrue(AValue: Boolean; AResultString: string): string;', @Globals.ifTrue); PaxCompiler.RegisterHeader(0, 'function ifSingle(ACheckValue: integer; AResultString: string): string;', @Globals.ifSingle); PaxCompiler.RegisterHeader(0, 'function ifNone(ACheckValue: integer; AResultString: string): string;', @Globals.ifNone); PaxCompiler.RegisterHeader(0, 'function ifMore(ACheckValue: integer; AResultString: string): string;', @Globals.ifMore); PaxCompiler.RegisterHeader(0, 'function ifAny(ACheckValue: integer; AResultString: string): string;', @Globals.ifAny); PaxCompiler.RegisterHeader(0, 'function ifFieldEq(ADataSet: TpFIBDataSet; AFieldName: string; AValue: string; AResultString: string): string;', @Globals.ifFieldEq); PaxCompiler.RegisterHeader(0, 'function Count(ADataSet: TpFIBDataSet): Integer;', @Globals.Count); // PaxCompiler.RegisterVariable(0, 'DataModule: TMVCAuthorization', @Self); RepresentativesHandle := PaxCompiler.RegisterVariable(0, 'Representatives', datasetHandle, @Representatives); RepresentativesHandle := PaxCompiler.RegisterVariable(0, 'Authorization', datasetHandle, @Authorization); RepresentativesHandle := PaxCompiler.RegisterVariable(0, 'Constituent', datasetHandle, @Constituent); RepresentativesHandle := PaxCompiler.RegisterVariable(0, 'Notary', datasetHandle, @Notary); { // PaxCompiler.AddCodeFromFile('main', TFmMain(Application.MainForm).CurrentDir + 'lib/' + 'Globals.pas'); if PaxCompiler.Compile(PaxProgram) then begin // PaxProgram.Run; // PaxEval.RegisterCompiler(PaxCompiler, PaxProgram); end else for I:=0 to PaxCompiler.ErrorCount -1 do ufmMain.Log(PaxCompiler.ErrorMessage[I]); } end; procedure TMVCAuthorization.ReportProgress(const CurrentTag: string; Total, Current: Word); begin TfmMain(Application.MainForm).SetStatusProgressBarPosition(Total div 2, Current); end; function TMVCAuthorization.resultFromProgram(const APaxProgram: TPaxProgram): variant; var TypeId: Integer; ResultId: Integer; Address: Pointer; StackFrameNumber: Integer; begin ResultId := APaxProgram.GetProgPtr.GetRootProg.GlobalSym.ResultId; StackFrameNumber := 0; if APaxProgram.GetProgPtr.GetRootProg.GetCallStackCount > 0 then StackFrameNumber := APaxProgram.GetProgPtr.GetRootProg.GetCallStackCount - 1; TypeId := APaxProgram.GetProgPtr.GetRootProg.GlobalSym[ResultId].TypeId; Address := APaxProgram.GetProgPtr.GetRootProg.GlobalSym.GetFinalAddress(APaxProgram.GetProgPtr.GetRootProg, StackFrameNumber, ResultId); Result := APaxProgram.GetProgPtr.GetRootProg.GlobalSym.GetVariantVal(Address, TypeId); end; function TMVCAuthorization.getRepresentatives: TpFIBDataSet; begin Result := Representatives; end; function TMVCAuthorization.setID(AID: string): boolean; begin Authorization.Close; Authorization.ParamByName('ID').AsString := AID; Authorization.Open; Constituent.Open; Representatives.Open; Notary.Open; Notary.FetchAll; Authorization.FetchAll; Constituent.FetchAll; Representatives.FetchAll; end; end.
unit DSoundUtils; interface uses Windows, mmSystem, SysUtils, DirectSound; type EDSound = class(Exception); procedure FillPCMFormat(const aSampligRate, aBits, aChannels : integer; out aFormat : TWaveFormatEx); function CreateHelperDSound : IDirectSound; procedure DSoundCheck(aResult : hResult); function PercentToBufferVolume(aPercent : integer) : integer; function BufferVolumeToPercent(aVolume : integer) : integer; implementation uses Forms, Math, D3Math; procedure FillPCMFormat(const aSampligRate, aBits, aChannels : integer; out aFormat : TWaveFormatEx); begin aFormat.wFormatTag := WAVE_FORMAT_PCM; aFormat.nChannels := aChannels; aFormat.nSamplesPerSec := aSampligRate; aFormat.wBitsPerSample := aBits; aFormat.nBlockAlign := aFormat.wBitsPerSample div 8 * aFormat.nChannels; aFormat.nAvgBytesPerSec := aFormat.nSamplesPerSec * aFormat.nBlockAlign; end; function CreateHelperDSound : IDirectSound; var Desc : TDSBUFFERDESC; Primary : IDirectSoundBuffer; Format : TWaveFormatEx; begin DSoundCheck(DirectSoundCreate(nil, Result, nil)); try DSoundCheck(Result.SetCooperativeLevel(Application.Handle, DSSCL_PRIORITY)); fillchar(Desc, sizeof(Desc), 0); Desc.dwSize := sizeof(Desc); Desc.dwFlags := DSBCAPS_PRIMARYBUFFER; DSoundCheck(Result.CreateSoundBuffer(Desc, Primary, nil)); try FillPCMFormat(22050, 16, 2, Format); Primary.SetFormat(Format); finally Primary := nil; end; except Result := nil; raise; end; end; procedure DSoundCheck(aResult : hResult); begin if Failed(aResult) then raise EDSound.Create(DSErrorString(aResult)); end; function PercentToBufferVolume(aPercent : integer) : integer; begin if aPercent > 0 then Result := -round(100 * (40 - 20 * log10(aPercent))) else Result := -10000; end; function BufferVolumeToPercent(aVolume : integer) : integer; begin Result := round(power(10, 2 + aVolume / 2000)); Result := min(max(Result, 0), 100); end; end.
program controlRepeat; var x, y : integer; begin x := 0; y := 50; writeln('value of x before repeat-statement:', x); writeln('value of y before repeat-statement:', y); repeat x := x + 1; y := y + 100; until x >= 10; writeln('value of x after repeat-statement:', x); writeln('value of y after repeat-statement:', y); end.
unit TTSGUARTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSGUARRecord = record PLenderNum: String[4]; PLoanNum: String[20]; PCifNum: String[20]; PModCount: Integer; PCifY: String[1]; PCifN: String[1]; End; TTTSGUARBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSGUARRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSGUAR = (TTSGUARPrimaryKey, TTSGUARbyCif); TTTSGUARTable = class( TDBISAMTableAU ) private FDFLenderNum: TStringField; FDFLoanNum: TStringField; FDFCifNum: TStringField; FDFModCount: TIntegerField; FDFCifY: TStringField; FDFCifN: TStringField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPLoanNum(const Value: String); function GetPLoanNum:String; procedure SetPCifNum(const Value: String); function GetPCifNum:String; procedure SetPModCount(const Value: Integer); function GetPModCount:Integer; procedure SetPCifY(const Value: String); function GetPCifY:String; procedure SetPCifN(const Value: String); function GetPCifN:String; procedure SetEnumIndex(Value: TEITTSGUAR); function GetEnumIndex: TEITTSGUAR; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSGUARRecord; procedure StoreDataBuffer(ABuffer:TTTSGUARRecord); property DFLenderNum: TStringField read FDFLenderNum; property DFLoanNum: TStringField read FDFLoanNum; property DFCifNum: TStringField read FDFCifNum; property DFModCount: TIntegerField read FDFModCount; property DFCifY: TStringField read FDFCifY; property DFCifN: TStringField read FDFCifN; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PLoanNum: String read GetPLoanNum write SetPLoanNum; property PCifNum: String read GetPCifNum write SetPCifNum; property PModCount: Integer read GetPModCount write SetPModCount; property PCifY: String read GetPCifY write SetPCifY; property PCifN: String read GetPCifN write SetPCifN; published property Active write SetActive; property EnumIndex: TEITTSGUAR read GetEnumIndex write SetEnumIndex; end; { TTTSGUARTable } procedure Register; implementation procedure TTTSGUARTable.CreateFields; begin FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFLoanNum := CreateField( 'LoanNum' ) as TStringField; FDFCifNum := CreateField( 'CifNum' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TIntegerField; FDFCifY := CreateField( 'CifY' ) as TStringField; FDFCifN := CreateField( 'CifN' ) as TStringField; end; { TTTSGUARTable.CreateFields } procedure TTTSGUARTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSGUARTable.SetActive } procedure TTTSGUARTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSGUARTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSGUARTable.SetPLoanNum(const Value: String); begin DFLoanNum.Value := Value; end; function TTTSGUARTable.GetPLoanNum:String; begin result := DFLoanNum.Value; end; procedure TTTSGUARTable.SetPCifNum(const Value: String); begin DFCifNum.Value := Value; end; function TTTSGUARTable.GetPCifNum:String; begin result := DFCifNum.Value; end; procedure TTTSGUARTable.SetPModCount(const Value: Integer); begin DFModCount.Value := Value; end; function TTTSGUARTable.GetPModCount:Integer; begin result := DFModCount.Value; end; procedure TTTSGUARTable.SetPCifY(const Value: String); begin DFCifY.Value := Value; end; function TTTSGUARTable.GetPCifY:String; begin result := DFCifY.Value; end; procedure TTTSGUARTable.SetPCifN(const Value: String); begin DFCifN.Value := Value; end; function TTTSGUARTable.GetPCifN:String; begin result := DFCifN.Value; end; procedure TTTSGUARTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNum, String, 4, N'); Add('LoanNum, String, 20, N'); Add('CifNum, String, 20, N'); Add('ModCount, Integer, 0, N'); Add('CifY, String, 1, N'); Add('CifN, String, 1, N'); end; end; procedure TTTSGUARTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNum;LoanNum;CifNum, Y, Y, N, N'); Add('byCif, LenderNum;CifNum;LoanNum, N, N, Y, N'); end; end; procedure TTTSGUARTable.SetEnumIndex(Value: TEITTSGUAR); begin case Value of TTSGUARPrimaryKey : IndexName := ''; TTSGUARbyCif : IndexName := 'byCif'; end; end; function TTTSGUARTable.GetDataBuffer:TTTSGUARRecord; var buf: TTTSGUARRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNum := DFLenderNum.Value; buf.PLoanNum := DFLoanNum.Value; buf.PCifNum := DFCifNum.Value; buf.PModCount := DFModCount.Value; buf.PCifY := DFCifY.Value; buf.PCifN := DFCifN.Value; result := buf; end; procedure TTTSGUARTable.StoreDataBuffer(ABuffer:TTTSGUARRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFLoanNum.Value := ABuffer.PLoanNum; DFCifNum.Value := ABuffer.PCifNum; DFModCount.Value := ABuffer.PModCount; DFCifY.Value := ABuffer.PCifY; DFCifN.Value := ABuffer.PCifN; end; function TTTSGUARTable.GetEnumIndex: TEITTSGUAR; var iname : string; begin result := TTSGUARPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSGUARPrimaryKey; if iname = 'BYCIF' then result := TTSGUARbyCif; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSGUARTable, TTTSGUARBuffer ] ); end; { Register } function TTTSGUARBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..6] of string = ('LENDERNUM','LOANNUM','CIFNUM','MODCOUNT','CIFY','CIFN' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 6) and (flist[x] <> s) do inc(x); if x <= 6 then result := x else result := 0; end; function TTTSGUARBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftInteger; 5 : result := ftString; 6 : result := ftString; end; end; function TTTSGUARBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNum; 2 : result := @Data.PLoanNum; 3 : result := @Data.PCifNum; 4 : result := @Data.PModCount; 5 : result := @Data.PCifY; 6 : result := @Data.PCifN; end; end; end.
unit AsymSoftKeys; interface type T2x2Matrix = array[0..1,0..1] of single; TSoftKeyType = (skt64, skt128, skt256); procedure GenPair(var M, IM : T2x2Matrix; res : integer); function MultPair(A, B : T2x2Matrix) : T2x2Matrix; function GenSoftAsymKeys(var pubKey, privKey : string; kType : TSoftKeyType) : boolean; implementation uses SysUtils; procedure GenPair(var M, IM : T2x2Matrix; res : integer); var det : integer; a, b, c, d : integer; begin repeat a := random(res); // a b := random(res); // b c := random(res); // c d := random(res); // d det := a*d - c*b; until {(det = 8) or (det = 16) or (det = 32) or} (det = 64); M [0, 0] := a; M [0, 1] := b; M [1, 0] := c; M [1, 1] := d; IM[0, 0] := d/det; IM[0, 1] := -b/det; IM[1, 0] := -c/det; IM[1, 1] := a/det; end; function MultPair(A, B : T2x2Matrix) : T2x2Matrix; begin result[0, 0] := A[0, 0]*B[0, 0] + A[0, 1]*B[1, 0]; result[0, 1] := A[0, 0]*B[0, 1] + A[0, 1]*B[1, 1]; result[1, 0] := A[1, 0]*B[0, 0] + A[1, 1]*B[1, 0]; result[1, 1] := A[1, 0]*B[0, 1] + A[1, 1]*B[1, 1]; end; function T2x2MatrixToStr(M : T2x2Matrix) : string; begin result := FloatToStr(M[0, 0]) + ',' + FloatToStr(M[0, 1]) + ',' + FloatToStr(M[1, 0]) + ',' + FloatToStr(M[1, 1]); end; function sktLength(kType : TSoftKeyType) : integer; begin case kType of skt64 : result := 4; skt128 : result := 8; skt256 : result := 16; else result := 16; end; end; function GenSoftAsymKeys(var pubKey, privKey : string; kType : TSoftKeyType) : boolean; var len, i : integer; A, B : T2x2Matrix; begin pubKey := ''; privKey := ''; len := sktLength(kType); GenPair(A, B, 64); pubKey := T2x2MatrixToStr(A); privKey := T2x2MatrixToStr(B); for i := 2 to len do begin GenPair(A, B, 64); pubKey := pubKey + ',' + T2x2MatrixToStr(A); privKey := privKey + ',' + T2x2MatrixToStr(B); end; result := true; end; end.
{ *************************************************************************** } { } { } { Copyright (C) Amarildo Lacerda } { } { https://github.com/amarildolacerda } { } { } { *************************************************************************** } { } { 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 Plugin.Forms; interface uses WinApi.windows, {$IFDEF FMX} FMX.Forms, FMX.Controls, {$ELSE} VCL.Forms, VCL.Controls, {$ENDIF} System.classes, System.SysUtils, Plugin.Service, Plugin.Interf; type TPluginExecuteService = class(TPluginService, IPluginExecute) protected FSubTypeID: Int64; FParams: String; FConnectionString: string; FFilial: integer; FAppUser: string; private FOnNotify: TNotifyEvent; procedure SetSubTypeID(const Value: Int64); procedure SetOnNotify(const Value: TNotifyEvent); protected destructor Destroy; override; procedure SetForm(const Value: TForm); virtual; function GetForm(AParent: THandle): TForm; virtual; function GetCaption: string; virtual; function GetSubTypeID: Int64; virtual; procedure DoNotify; { function GetHandle:THandle; procedure SetHandle(AHandle:THandle); } procedure Connection(const AConnectionString: string); virtual; procedure User(const AFilial: integer; const AAppUser: string); virtual; procedure Sync(const AJson: string); virtual; procedure Execute(const AModal: boolean); virtual; procedure SetParams(AJsonParams: String); function GetAuthor: string; virtual; function GetName: string; virtual; function GetVersion: string; virtual; function GetDescription: string; virtual; public property SubTypeID: Int64 read GetSubTypeID write SetSubTypeID; property Usuario: string read FAppUser; property Filial: integer read FFilial; property ConnectionString: string read FConnectionString; property Params: string read FParams; property OnNotify: TNotifyEvent read FOnNotify write SetOnNotify; end; {$IFDEF FMX} TFormClass = class of TForm; {$ENDIF} TPluginFormService = class(TPluginExecuteService) protected FCaption: string; FFormClass: TFormClass; procedure Init; virtual; public constructor Create(AFormClass: TFormClass; ACaption: String); virtual; destructor Destroy; override; function GetCaption: string; override; procedure Execute(const AModal: boolean); override; procedure Embedded(const AParent: THandle); override; {$IFNDEF DLL} function EmbeddedControl(const FParent: TWinControl): boolean; overload; override; {$ENDIF} procedure DoStart; override; end; procedure Register; implementation uses System.classes.Helper, System.Rtti; procedure Register; begin // RegisterComponents('Store',[TPluginFormService]); end; procedure TPluginExecuteService.Connection(const AConnectionString: string); begin FConnectionString := AConnectionString; if not assigned(FForm) then exit; if Supports(FForm, IPluginExecuteConnection) then (FForm as IPluginExecuteConnection).Connection(AConnectionString) else begin // DO NOT CHANGE NAMES FForm.ContextProperties['ConnectionString'] := AConnectionString; end; DoNotify; end; destructor TPluginExecuteService.Destroy; begin if FOwned then FreeAndNil(FForm); inherited; end; procedure TPluginExecuteService.DoNotify; begin if assigned(FOnNotify) then FOnNotify(self); end; procedure TPluginExecuteService.Execute(const AModal: boolean); begin if not assigned(FForm) then exit; if AModal then try FForm.ShowModal finally FForm.Release end else FForm.Show; end; function TPluginExecuteService.GetAuthor: string; begin result := 'Storeware'; end; function TPluginExecuteService.GetCaption: string; begin if assigned(FForm) then result := FForm.Caption else result := ''; end; function TPluginExecuteService.GetDescription: string; begin result := 'Plugin'; end; function TPluginExecuteService.GetForm(AParent: THandle): TForm; begin result := FForm; if AParent > 0 then begin {$IFDEF FMX} {$ELSE} WinApi.windows.SetParent(FForm.Handle, AParent); {$ENDIF} end; end; { function TPluginExecuteService.GetHandle: THandle; begin result := FHandle; end; } function TPluginExecuteService.GetName: string; begin result := 'Storeware'; end; function TPluginExecuteService.GetVersion: string; begin result := '01.00'; end; function TPluginExecuteService.GetSubTypeID: Int64; begin result := FSubTypeID; end; procedure TPluginExecuteService.SetForm(const Value: TForm); begin FOwned := false; if assigned(FForm) then FreeAndNil(FForm); FForm := Value; Connection(FConnectionString); User(FFilial, FAppUser); end; procedure TPluginExecuteService.SetOnNotify(const Value: TNotifyEvent); begin FOnNotify := Value; end; procedure TPluginExecuteService.SetParams(AJsonParams: String); begin FParams := AJsonParams; DoNotify; end; procedure TPluginExecuteService.SetSubTypeID(const Value: Int64); begin FSubTypeID := Value; end; { procedure TPluginExecuteService.SetHandle(AHandle: THandle); begin FHandle := AHandle; end; } procedure TPluginExecuteService.Sync(const AJson: string); begin if not assigned(FForm) then exit; if Supports(FForm, IPluginExecuteSync) then (FForm as IPluginExecuteSync).Sync(AJson) else if Supports(FForm, IPluginExecuteConnection) then (FForm as IPluginExecuteConnection).Sync(AJson) else begin FForm.ContextInvokeMethod('Sync', [AJson]); end; DoNotify; end; procedure TPluginExecuteService.User(const AFilial: integer; const AAppUser: string); begin FFilial := AFilial; FAppUser := AAppUser; if not assigned(FForm) then exit; if Supports(FForm, IPluginExecuteConnection) then (FForm as IPluginExecuteConnection).User(AFilial, AAppUser) else begin FForm.ContextProperties['Filial'] := AFilial; FForm.ContextProperties['Usuario'] := AAppUser; end; DoNotify; end; { TPluginFormService } constructor TPluginFormService.Create(AFormClass: TFormClass; ACaption: String); begin inherited Create; FFormClass := AFormClass; FCaption := ACaption; end; destructor TPluginFormService.Destroy; begin FCaption := ''; FFormClass := nil; inherited; end; procedure TPluginFormService.DoStart; begin inherited; end; procedure TPluginFormService.Embedded(const AParent: THandle); begin Init; inherited; end; {$IFNDEF DLL} function TPluginFormService.EmbeddedControl(const FParent: TWinControl) : boolean; begin Init; result := inherited; end; {$ENDIF} procedure TPluginFormService.Execute(const AModal: boolean); begin Init; inherited; end; function TPluginFormService.GetCaption: string; begin if FCaption <> '' then result := FCaption else result := inherited GetCaption; end; procedure TPluginFormService.Init; begin if not assigned(FForm) then begin // FreeAndNil(FForm); SetForm(FFormClass.Create(TPluginService.OwnedComponents)); end; FForm.Caption := FCaption; FOwned := true; end; end.
unit uProspectEmailVO; interface uses System.Generics.Collections; type TProspectEmailVO = class private FEmail: string; FIdProspect: Integer; FDescricao: string; FId: Integer; procedure SetDescricao(const Value: string); procedure SetEmail(const Value: string); procedure SetId(const Value: Integer); procedure SetIdProspect(const Value: Integer); public property Id: Integer read FId write SetId; property IdProspect: Integer read FIdProspect write SetIdProspect; property Email: string read FEmail write SetEmail; property Descricao: string read FDescricao write SetDescricao; end; TListaProspectEmail = TObjectList<TProspectEmailVO>; implementation { TProspectEmailVO } procedure TProspectEmailVO.SetDescricao(const Value: string); begin FDescricao := Value; end; procedure TProspectEmailVO.SetEmail(const Value: string); begin FEmail := Value; end; procedure TProspectEmailVO.SetId(const Value: Integer); begin FId := Value; end; procedure TProspectEmailVO.SetIdProspect(const Value: Integer); begin FIdProspect := Value; end; end.
unit main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, frame.pianoroll, midi.output, Vcl.StdCtrls; type TMainForm = class(TForm) PianoRollFrame: TPianoRollFrame; DevicesBtn: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure DevicesBtnClick(Sender: TObject); private { Private declarations } _selectedOutputDevice: integer; _sequencer: TMIDIOutput; public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.dfm} uses midi.configuration, midi.output.form; procedure TMainForm.DevicesBtnClick(Sender: TObject); var i, n: integer; name: string; config: TMIDIConfiguration; deviceList: TStringList; dlg: TOutputMIDIDevicesForm; begin deviceList := TStringList.Create; config := TMIDIConfiguration.Create; dlg := TOutputMIDIDevicesForm.Create(self); try n := config.NumberOutputDevices; for i := 0 to n - 1 do begin name := config.GetOutputDeviceName(i); deviceList.Add(name); end; dlg.Init(deviceList, _selectedOutputDevice); if dlg.ShowModal = mrOK then _selectedOutputDevice := dlg.Selected; finally dlg.Free; deviceList.Free; config.Free; end; end; procedure TMainForm.FormCreate(Sender: TObject); begin _selectedOutputDevice := -1; _sequencer := TMIDIOutput.Create; _sequencer.SetTempo(120); end; procedure TMainForm.FormDestroy(Sender: TObject); begin _sequencer.Free; end; end.
unit MColorText; interface uses Windows, Graphics; procedure DrawPCodeText(canvas:TCanvas; rect : TRect; text:string); implementation uses SysUtils; {*************************************************************** §+B = fett (B steht für Bold) §-B = fett aus §+I = kursiv (I steht für Italic) §-I = kursiv aus §+U = unterstreichen (U steht für Underline) §-U = unterstreichen aus §TCxxxxxxxx = Text Farbe setzen xxxxxxxx ist die Farbe hexadezimal §BCxxxxxxxx = Hintergrund Farbe setzen ****************************************************************} procedure DrawPCodeText(canvas:TCanvas; rect : TRect; text:string); const ESCAPE_CHAR = '§'; procedure OutputText(const s:string); var tlen : Integer; begin Canvas.TextOut(Rect.Left, Rect.Top, s); //Teilstring in das Canvas schreiben tlen := Canvas.TextWidth(s); //Länge des Teilstrings bzw. Platzbedarf im Canvas ermitteln Inc(Rect.Left, tlen); //Zum linken X-Wert der Canvas addieren (für den nächsten Teilstring) end; function ExtractColor(const s : string):TColor; begin Result := StrToInt('$'+s); end; var i, dlen : Integer; tmp : string; begin while text <> '' do begin i := Pos(ESCAPE_CHAR, text); if i <> 0 then begin OutputText(Copy(text, 1, i-1)); Delete(text, 1, i); // ausgegeb. Text + Escapezeichen löschen dlen := 0; tmp := Copy(text,1, 2); if tmp = '+B' then begin canvas.Font.Style := canvas.Font.Style + [fsBold]; dlen := 2; end else if tmp = '-B' then begin canvas.Font.Style := canvas.Font.Style - [fsBold]; dlen := 2; end else if tmp = '+I' then begin canvas.Font.Style := canvas.Font.Style + [fsItalic]; dlen := 2; end else if tmp = '-I' then begin canvas.Font.Style := canvas.Font.Style - [fsItalic]; dlen := 2; // bei kursivem Text braucht man etwas Abstand zum folgenden Text Inc(rect.Left, 3); end else if tmp = '+U' then begin canvas.Font.Style := canvas.Font.Style + [fsUnderline]; dlen := 2; end else if tmp = '-U' then begin canvas.Font.Style := canvas.Font.Style - [fsUnderline]; dlen := 2; end else if tmp = 'TC' then // Text Color begin canvas.Font.Color := ExtractColor(Copy(text,3,8)); dlen := 10; end else if tmp = 'BC' then // Background Color begin canvas.Brush.Color := ExtractColor(Copy(text,3,8)); dlen := 10; end else if tmp[1]=ESCAPE_CHAR then begin OutputText(ESCAPE_CHAR); dlen := 1; end; if dlen > 0 then Delete(text, 1, dlen); end else begin OutputText(text); text := ''; end; end; end; end.
{ Copyright (c) 2017 Pascal Riekenberg LazProfiler: Core unit See the file COPYING.modifiedLGPL.txt, included in this distribution, for details about 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. **********************************************************************} unit LazProfilerCore; {$mode objfpc}{$H+} interface uses Classes, EpikTimer, Generics.Collections, Generics.Defaults, DOM, SysUtils; type TIntegerList = specialize TList<Integer>; { TLPBaseType } TLPBaseType = class private protected fExpanded: Boolean; function XMLNodeName: String; virtual; abstract; procedure SaveXMLNode(pDoc: TXMLDocument; pNode: TDOMElement); virtual; procedure LoadXMLNode(pNode: TDOMNode); virtual; procedure InternalCreateFormXML(pNode: TDOMNode); virtual; abstract; public constructor CreateFromXML(pNode: TDOMNode); property Expanded: Boolean read fExpanded write fExpanded; procedure SaveXML(pDoc: TXMLDocument; pNode: TDOMNode); end; { TLPPasPackage } TLPPasPackage = class(TLPBaseType) private procedure SetPackageName(pPackageName: String); protected fPackageName: String; fPackageNameUp: String; fIsProject: Boolean; fUnitOutputDirectory: String; function XMLNodeName: String; override; procedure SaveXMLNode(pDoc: TXMLDocument; pNode: TDOMElement); override; procedure LoadXMLNode(pNode: TDOMNode); override; procedure InternalCreateFormXML(pNode: TDOMNode); override; public constructor Create(pPackageName: String); property PackageName: String read fPackageName write SetPackageName; property PackageNameUp: String read fPackageNameUp; property PackageIsProject: Boolean read fIsProject; property UnitOutputDirectory: String read fUnitOutputDirectory write fUnitOutputDirectory; end; { TLPPasPackageList } TLPPasPackageList = class(specialize TObjectList<TLPPasPackage>) private protected public function IndexOf(pPackageName: String): SizeInt; overload; procedure SaveToStringList(pList: TStringList); procedure LoadFromStringList(pList: TStringList; pVersion: Integer); procedure SaveXML(pDoc: TXMLDocument); procedure LoadXML(pDoc: TXMLDocument); end; { TLPPasUnit } TLPPasUnit = class(TLPPasPackage) private procedure SetFileName(pFileName: string); procedure SetUnitName(pUnitName: String); protected fUnitName, fFileName, fUnitNameUp, fFileNameUp: String; fPasPackage: TLPPasPackage; function XMLNodeName: String; override; procedure SaveXMLNode(pDoc: TXMLDocument; pNode: TDOMElement); override; procedure InternalCreateFormXML(pNode: TDOMNode); override; public constructor Create(pUnitName, pFileName, pPackageName: String); property PasPackage: TLPPasPackage read fPasPackage write fPasPackage; property UnitName: String read fUnitName write SetUnitName; property FileName: string read fFileName write SetFileName; property UnitNameUp: String read fUnitNameUp; property FileNameUp: String read fFileNameUp; end; { TLPPasUnitList } TLPPasUnitList = class(specialize TObjectList<TLPPasUnit>) private protected public function IndexOf(pUnitName, pFileName, pPackageName: String): SizeInt; overload; procedure SaveToStringList(pList: TStringList); procedure SaveXML(pDoc: TXMLDocument); procedure LoadFromStringList(pList: TStringList; pVersion: Integer); procedure LoadXML(pDoc: TXMLDocument); end; { TLPPasClass } TLPPasClass = class(TLPPasUnit) private procedure SetNameOfClass(pNameOfClass: String); protected fNameOfClass, fNameOfClassUp: String; fPasUnit: TLPPasUnit; function XMLNodeName: String; override; procedure SaveXMLNode(pDoc: TXMLDocument; pNode: TDOMElement); override; procedure InternalCreateFormXML(pNode: TDOMNode); override; public constructor Create(pNameOfClass, pUnitName, pFileName, pPackageName: String); property PasUnit: TLPPasUnit read fPasUnit write fPasUnit; property NameOfClass: String read fNameOfClass write SetNameOfClass; property NameOfClassUp: String read fNameOfClassUp; end; { TLPPasClassList } TLPPasClassList = class(specialize TObjectList<TLPPasClass>) private protected public function IndexOf(pNameOfClass, pUnitName, pFileName, pPackageName: String): SizeInt; overload; procedure SaveToStringList(pList: TStringList); procedure SaveXML(pDoc: TXMLDocument); procedure LoadFromStringList(pList: TStringList; pVersion: Integer); procedure LoadXML(pDoc: TXMLDocument); end; { TLPProc } TLPPasProcList = class; { TLPPasProc } TLPPasProc = class(TLPPasClass) private fName, fNameUp: String; fRow: Integer; fNet, fGross, fAvgNet, fAvgGross: QWord; fCount: Integer; fKind: Integer; fPerNet, fPerGross: LongWord; fCalls, fCalledBy: TLPPasProcList; fCallsCount, fCalledByCount: TIntegerList; fInstrument: Boolean; fPasClass: TLPPasClass; fCountStr, fSumNetStr, fSumGrossStr, fAvgNetStr, fAvgGrossStr, fPerNetStr, fPerGrossStr: String; procedure SetFileName(pFileName: String); procedure SetName(pName: String); protected function XMLNodeName: String; override; procedure SaveXMLNode(pDoc: TXMLDocument; pNode: TDOMElement); override; procedure LoadXMLNode(pNode: TDOMNode); override; procedure InternalCreateFormXML(pNode: TDOMNode); override; public constructor Create(pName: String; pKind: Integer; pNameOfClass, pUnitName, pFileName, pPackageName: String; pRow: Integer); destructor Destroy; override; procedure Init; procedure Calls(pProc: TLPPasProc); procedure CalledBy(pProc: TLPPasProc); procedure SetSums(pNetSum, pGrossSum: QWord); property Name: String read fName write SetName; property Row: Integer read fRow write fRow; property Count: Integer read fCount write fCount; property Kind: Integer read fKind write fKind; property Net: QWord read fNet write fNet; property Gross: QWord read fGross write fGross; property AvgNet: QWord read fAvgNet; property AvgGross: QWord read fAvgGross; property Instrument: Boolean read fInstrument write fInstrument; property NameUp: string read fNameUp; property PerNet: LongWord read fPerNet; property PerGross: LongWord read fPerGross; property PasClass: TLPPasClass read fPasClass write fPasClass; property CountStr: String read fCountStr; property SumNetStr: String read fSumNetStr; property SumGrossStr: String read fSumGrossStr; property AvgNetStr: String read fAvgNetStr; property AvgGrossStr: String read fAvgGrossStr; property PerNetStr: String read fPerNetStr; property PerGrossStr: String read fPerGrossStr; end; PLPPasProc = ^TLPPasProc; { TLPPasProcList } TLPPasProcList = class(specialize TObjectList<TLPPasProc>) private fCallCount: Integer; public constructor Create(pOwnsObjects: Boolean = True); overload; procedure Init; procedure Convert(pTicks: ticktype); function IndexOf(pName, pNameOfClass, pUnitName, pFileName, pPackageName: String): SizeInt; overload; procedure SaveToStringList(pList: TStringList); procedure SaveXML(pDoc: TXMLDocument); procedure LoadFromStringList(pList: TStringList; pVersion: Integer); procedure LoadXML(pDoc: TXMLDocument); property CallCount: Integer read fCallCount write fCallCount; end; { TLPStackFrame } TLPStackFrame = class; TLPStackFrameList = specialize TObjectList<TLPStackFrame>; TLPStackFrame = class private fPasProc: TLPPasProc; fChildList: TLPStackFrameList; fParent: TLPStackFrame; fRunning: Boolean; fTicksInit, fTicksStart, fTicksEnd, fTicksExit, fNet, fGross, fOverhead, fOff: TickType; protected public procedure Calc; procedure CleanupChilds; constructor Create(pProc: TLPPasProc; pParent: TLPStackFrame); destructor Destroy; override; end; { TCustomLazProfiler } TCustomLazProfiler = class protected fPackageList: TLPPasPackageList; fUnitList: TLPPasUnitList; fClassList: TLPPasClassList; fProcList: TLPPasProcList; fActive: Boolean; fAutoStart: Boolean; fNeedsRebuild: Boolean; fSortColumn: Integer; fSortDirection: Integer; fSettingsVersion: Integer; procedure SaveConfig(pDoc: TXMLDocument); procedure LoadConfig(pDoc: TXMLDocument); procedure SaveToFile(pFileName: String); procedure SaveXML(pFileName: String); function LoadFromFile(pFileName: String): Boolean; function LoadXML(pFileName: String): Boolean; procedure SetDefaults; public constructor Create; destructor Destroy; override; property ProcList: TLPPasProcList read fProcList; property SortColumn: Integer read fSortColumn write fSortColumn; property SortDirection: Integer read fSortDirection write fSortDirection; end; { TLazProfiler } TLazProfiler = class(TCustomLazProfiler) private fMasterProc: TLPPasProc; fName: String; fTimer: TEpikTimer; fTicks: TickType; fThreads: TList; fCurStackFrame: array of TLPStackFrame; fRunning: Boolean; fPauseCount: array of Integer; fPauseStartTicks, fOffTicks: array of TickType; fLoaded: Boolean; Ticks: function: Ticktype of object; fLock: TRTLCriticalSection; function HWTicks: Ticktype; function SysTicks: Ticktype; function ThreadIndex(pThread: TThreadID): Integer; procedure Lock; procedure UnLock; protected public procedure EnterProfiling(pProcID: Integer); procedure ExitProfiling(pProcID: Integer); procedure StartProfiling; procedure PauseProfiling; procedure ContinueProfiling; procedure StopProfiling; constructor Create(pProgramm: String); destructor Destroy; override; end; function IntToTime(pVal: Int64): String; const cBackupExtension = '.lazprofiler_backup'; cCoreFileName = 'LazProfilerCore.pas'; cRunTimeFileName = 'LazProfilerRunTime.pas'; cTimerFileName = 'EpikTimer.pas'; cSettingExtension = '.lazprofiler_setting'; cSettingVersion = 3; { XML node strings } cXMLLazProfiler = 'lazprofiler'; cXMLConfig = 'config'; cXMLPackages = 'packages'; cXMLPackage = 'package'; cXMLUnits = 'units'; cXMLUnit = 'unit'; cXMLClasses = 'classes'; cXMLClass = 'class'; cXMLProcs = 'procs'; cXMLProc = 'proc'; cXMLRuns = 'runs'; cXMLRun = 'run'; cXMLTimings = 'timings'; cXMLTiming = 'timing'; cXMLUsings = 'usings'; cXMLUsing = 'using'; cXMLCalls = 'calls'; cXMLCalledBy = 'calledby'; { XML attribute strings } cXMLConfig_AutoStart = 'autostart'; cXMLConfig_NeedsRebuild = 'needsrebuild'; cXMLConfig_Version = 'version'; cXMLConfig_SortColumn = 'sortcolumn'; cXMLConfig_SortDirection = 'sortdirection'; cXMLConfig_Active = 'active'; { ProfilerWindow Result TreeView } cColumnCount = 11; cNameCol = 0; cClassCol = 1; cUnitCol = 2; cPackageCol = 3; cCountCol = 4; cPerNetCol = 5; cSumNetCol = 6; cPerGrossCol = 7; cSumGrossCol = 8; cAvgNetCol = 9; cAvgGrossCol = 10; implementation uses LazFileUtils, LazUTF8, strutils, XMLRead, XMLWrite; function IntToTime(pVal: Int64): String; var lVal: Extended; begin if pVal > 1000000000 then begin lVal := pVal / 1000000000.0; Result := FormatFloat('##0.000 s', lVal); end else if pVal > 1000000 then begin lVal := pVal / 1000000.0; Result := FormatFloat('##0.000 ms', lVal); end else begin lVal := pVal / 1000.0; Result := FormatFloat('##0.000 μs', lVal); end; end; { TLPBaseType } procedure TLPBaseType.SaveXMLNode(pDoc: TXMLDocument; pNode: TDOMElement); begin pNode.SetAttribute('expanded', BoolToStr(Expanded, True)); end; procedure TLPBaseType.LoadXMLNode(pNode: TDOMNode); var lExpandedAttr: TDOMNode; begin lExpandedAttr := pNode.Attributes.GetNamedItem('expanded'); if Assigned(lExpandedAttr) then fExpanded := StrToBool(lExpandedAttr.NodeValue); end; constructor TLPBaseType.CreateFromXML(pNode: TDOMNode); begin InternalCreateFormXML(pNode); LoadXMLNode(pNode); end; procedure TLPBaseType.SaveXML(pDoc: TXMLDocument; pNode: TDOMNode); var lNode: TDOMElement; begin lNode := pDoc.CreateElement(XMLNodeName); SaveXMLNode(pDoc, lNode); pNode.AppendChild(lNode); end; { TLPPasPackage } procedure TLPPasPackage.SetPackageName(pPackageName: String); begin if fPackageName = pPackageName then Exit; fPackageName := pPackageName; fPackageNameUp := UpperCase(pPackageName); end; function TLPPasPackage.XMLNodeName: String; begin Result := cXMLPackage; end; procedure TLPPasPackage.SaveXMLNode(pDoc: TXMLDocument; pNode: TDOMElement); begin inherited SaveXMLNode(pDoc, pNode); pNode.SetAttribute('packagename', fPackageName); pNode.SetAttribute('unitoutputdirectory', fPackageName); end; procedure TLPPasPackage.LoadXMLNode(pNode: TDOMNode); var lUnitOutputDirectoryAttr: TDOMNode; begin inherited LoadXMLNode(pNode); lUnitOutputDirectoryAttr := pNode.Attributes.GetNamedItem('unitoutputdirectory'); if Assigned(lUnitOutputDirectoryAttr) then fUnitOutputDirectory := lUnitOutputDirectoryAttr.NodeValue; end; procedure TLPPasPackage.InternalCreateFormXML(pNode: TDOMNode); var lPackageName: DOMString; lPackageNameAttr: TDOMNode; begin; lPackageNameAttr := pNode.Attributes.GetNamedItem('packagename'); if Assigned(lPackageNameAttr) then lPackageName := lPackageNameAttr.NodeValue; Create(lPackageName); end; constructor TLPPasPackage.Create(pPackageName: String); begin fIsProject := pPackageName = '?'; fPackageName := pPackageName; fPackageNameUp := UpperCase(fPackageName); end; { TLPPasPackageList } function TLPPasPackageList.IndexOf(pPackageName: String): SizeInt; var i: Integer; lPasPackage: TLPPasPackage; begin pPackageName := UpperCase(pPackageName); for i := 0 to Count - 1 do begin lPasPackage := Items[i]; if (lPasPackage.PackageNameUp = pPackageName) then Exit(i); end; Result := -1; end; procedure TLPPasPackageList.SaveToStringList(pList: TStringList); begin end; procedure TLPPasPackageList.LoadFromStringList(pList: TStringList; pVersion: Integer); begin end; procedure TLPPasPackageList.SaveXML(pDoc: TXMLDocument); var lNode: TDOMElement; i: Integer; begin lNode := pDoc.CreateElement(cXMLPackages); pDoc.DocumentElement.Appendchild(lNode); for i := 0 to Count - 1 do Items[i].SaveXML(pDoc, lNode); end; procedure TLPPasPackageList.LoadXML(pDoc: TXMLDocument); var lNodes, lNode: TDOMNode; i: Integer; begin Clear; lNodes := pDoc.DocumentElement.FindNode(cXMLPackages); if Assigned(lNodes) then with lNodes.ChildNodes do begin for i := 0 to Count - 1 do begin lNode := Item[i]; Add(TLPPasPackage.CreateFromXML(lNode)); end; end; end; { TLPPasUnitList } function TLPPasUnitList.IndexOf(pUnitName, pFileName, pPackageName: String): SizeInt; var i: Integer; lPasUnit: TLPPasUnit; begin pUnitName := UpperCase(pUnitName); pFileName := UpperCase(pFileName); for i := 0 to Count - 1 do begin lPasUnit := Items[i]; if (lPasUnit.UnitNameUp = pUnitName) and (lPasUnit.FileNameUp = pFileName) then Exit(i); end; Result := -1; end; procedure TLPPasUnitList.SaveToStringList(pList: TStringList); var lLine: TStringList; i: Integer; begin lLine := TStringList.Create; try lLine.Delimiter := ';'; lLine.StrictDelimiter := True; for i := 0 to Count - 1 do begin lLine.Clear; lLine.Add(Items[i].UnitName); lLine.Add(Items[i].FileName); lLine.Add(BoolToStr(Items[i].Expanded, True)); pList.Add(lLine.DelimitedText); end; finally lLine.Free; end; end; procedure TLPPasUnitList.SaveXML(pDoc: TXMLDocument); var lNode: TDOMElement; i: Integer; begin lNode := pDoc.CreateElement(cXMLUnits); pDoc.DocumentElement.Appendchild(lNode); for i := 0 to Count - 1 do Items[i].SaveXML(pDoc, lNode); end; procedure TLPPasUnitList.LoadFromStringList(pList: TStringList; pVersion: Integer); var lLine: TStringList; i: Integer; begin lLine := TStringList.Create; try lLine.Delimiter := ';'; lLine.StrictDelimiter := True; if pList.Count = 0 then exit; for i := 0 to pList.Count - 1 do begin lLine.DelimitedText := pList[i]; if lLine.Count >= 3 then begin Add(TLPPasUnit.Create(lLine[0], lLine[1], '?')); Last.Expanded := StrToBool(lLine[2]); end; end; finally lLine.Free; end; end; procedure TLPPasUnitList.LoadXML(pDoc: TXMLDocument); var lNodes, lNode: TDOMNode; i: Integer; begin Clear; lNodes := pDoc.DocumentElement.FindNode(cXMLUnits); if Assigned(lNodes) then with lNodes.ChildNodes do begin for i := 0 to Count - 1 do begin lNode := Item[i]; Add(TLPPasUnit.CreateFromXML(lNode)); end; end; end; { TLPPasClassList } function TLPPasClassList.IndexOf(pNameOfClass, pUnitName, pFileName, pPackageName: String): SizeInt; var i: Integer; lPasClass: TLPPasClass; begin pNameOfClass := UpperCase(pNameOfClass); pUnitName := UpperCase(pUnitName); pFileName := UpperCase(pFileName); for i := 0 to Count - 1 do begin lPasClass := Items[i]; if (lPasClass.fNameOfClassUp = pNameOfClass) and (lPasClass.fUnitNameUp = pUnitName) and (lPasClass.fFileNameUp = pFileName) then Exit(i); end; Result := -1; end; procedure TLPPasClassList.SaveToStringList(pList: TStringList); var lLine: TStringList; i: Integer; begin lLine := TStringList.Create; try lLine.Delimiter := ';'; lLine.StrictDelimiter := True; for i := 0 to Count - 1 do begin lLine.Clear; lLine.Add(Items[i].NameOfClass); lLine.Add(Items[i].UnitName); lLine.Add(Items[i].FileName); lLine.Add(BoolToStr(Items[i].Expanded, True)); pList.Add(lLine.DelimitedText); end; finally lLine.Free; end; end; procedure TLPPasClassList.SaveXML(pDoc: TXMLDocument); var lNode: TDOMElement; i: Integer; begin lNode := pDoc.CreateElement(cXMLClasses); pDoc.DocumentElement.Appendchild(lNode); for i := 0 to Count - 1 do Items[i].SaveXML(pDoc, lNode); end; procedure TLPPasClassList.LoadFromStringList(pList: TStringList; pVersion: Integer); var lLine: TStringList; i: Integer; begin lLine := TStringList.Create; try lLine.Delimiter := ';'; lLine.StrictDelimiter := True; if pList.Count = 0 then exit; for i := 0 to pList.Count - 1 do begin lLine.DelimitedText := pList[i]; if lLine.Count >= 4 then begin Add(TLPPasClass.Create(lLine[0], lLine[1], lLine[2], '?')); Last.Expanded := StrToBool(lLine[3]); end; end; finally lLine.Free; end; end; procedure TLPPasClassList.LoadXML(pDoc: TXMLDocument); var lNodes, lNode: TDOMNode; i: Integer; begin Clear; lNodes := pDoc.DocumentElement.FindNode(cXMLClasses); if Assigned(lNodes) then with lNodes.ChildNodes do begin for i := 0 to Count - 1 do begin lNode := Item[i]; Add(TLPPasClass.CreateFromXML(lNode)); end; end; end; { TLPPasClass } procedure TLPPasClass.SetNameOfClass(pNameOfClass: String); begin if fNameOfClass = pNameOfClass then Exit; fNameOfClass := pNameOfClass; fNameOfClassUp := UpperCase(pNameOfClass); end; function TLPPasClass.XMLNodeName: String; begin Result := cXMLClass; end; procedure TLPPasClass.SaveXMLNode(pDoc: TXMLDocument; pNode: TDOMElement); begin inherited SaveXMLNode(pDoc, pNode); pNode.SetAttribute('nameofclass', fNameOfClass); end; procedure TLPPasClass.InternalCreateFormXML(pNode: TDOMNode); var lPackageName, lFileName, lUnitName, lNameOfClass: DOMString; lUnitNameAttr, lFileNameAttr, lPackageNameAttr, lNameOfClassAttr: TDOMNode; begin; lNameOfClassAttr := pNode.Attributes.GetNamedItem('nameofclass'); if Assigned(lNameOfClassAttr) then lNameOfClass := lNameOfClassAttr.NodeValue; lUnitNameAttr := pNode.Attributes.GetNamedItem('unitname'); if Assigned(lUnitNameAttr) then lUnitName := lUnitNameAttr.NodeValue; lFileNameAttr := pNode.Attributes.GetNamedItem('filename'); if Assigned(lFileNameAttr) then lFileName := lFileNameAttr.NodeValue; lPackageNameAttr := pNode.Attributes.GetNamedItem('packagename'); if Assigned(lPackageNameAttr) then lPackageName := lPackageNameAttr.NodeValue; Create(lNameOfClass, lUnitName, lFileName, lPackageName); end; constructor TLPPasClass.Create(pNameOfClass, pUnitName, pFileName, pPackageName: String); begin inherited Create(pUnitName, pFileName, pPackageName); fNameOfClass := pNameOfClass; fNameOfClassUp := UpperCase(pNameOfClass); end; { TLPPasUnit } procedure TLPPasUnit.SetFileName(pFileName: string); begin if fFileName = pFileName then Exit; fFileName := pFileName; fFileNameUp := UpperCase(pFileName); end; procedure TLPPasUnit.SetUnitName(pUnitName: String); begin if fUnitName = pUnitName then Exit; fUnitName := pUnitName; fUnitNameUp := UpperCase(pUnitName); end; function TLPPasUnit.XMLNodeName: String; begin Result := cXMLUnit; end; procedure TLPPasUnit.SaveXMLNode(pDoc: TXMLDocument; pNode: TDOMElement); begin inherited SaveXMLNode(pDoc, pNode); pNode.SetAttribute('unitname', fUnitName); pNode.SetAttribute('filename', fFileName); end; procedure TLPPasUnit.InternalCreateFormXML(pNode: TDOMNode); var lPackageName, lFileName, lUnitName: DOMString; lUnitNameAttr, lFileNameAttr, lPackageNameAttr, lExpandedAttr: TDOMNode; begin; lUnitNameAttr := pNode.Attributes.GetNamedItem('unitname'); if Assigned(lUnitNameAttr) then lUnitName := lUnitNameAttr.NodeValue; lFileNameAttr := pNode.Attributes.GetNamedItem('filename'); if Assigned(lFileNameAttr) then lFileName := lFileNameAttr.NodeValue; lPackageNameAttr := pNode.Attributes.GetNamedItem('packagename'); if Assigned(lPackageNameAttr) then lPackageName := lPackageNameAttr.NodeValue; Create(lUnitName, lFileName, lPackageName); end; constructor TLPPasUnit.Create(pUnitName, pFileName, pPackageName: String); begin inherited Create(pPackageName); fUnitName := pUnitName; fUnitNameUp := UpperCase(pUnitName); fFileName := pFileName; fFileNameUp := UpperCase(pFileName); end; { TCustomLazProfiler } procedure TCustomLazProfiler.SaveConfig(pDoc: TXMLDocument); var lNode: TDOMElement; begin lNode := pDoc.CreateElement(cXMLConfig); pDoc.DocumentElement.AppendChild(lNode); lNode.SetAttribute(cXMLConfig_Version, IntTostr(cSettingVersion)); lNode.SetAttribute(cXMLConfig_AutoStart, BoolToStr(fAutoStart, True)); lNode.SetAttribute(cXMLConfig_NeedsRebuild, BoolToStr(fNeedsRebuild, True)); lNode.SetAttribute(cXMLConfig_SortColumn, IntToStr(fSortColumn)); lNode.SetAttribute(cXMLConfig_SortDirection, IntToStr(fSortDirection)); lNode.SetAttribute(cXMLConfig_Active, BoolToStr(fActive, True)); end; procedure TCustomLazProfiler.LoadConfig(pDoc: TXMLDocument); var lSettingsVersionAttr, lAutostartAttr, lNeedsRebuildAttr, lSortColumnAttr, lSortDirectionAttr, lNode, lActiveAttr: TDOMNode; begin; lNode := pDoc.DocumentElement.FindNode(cXMLConfig); if Assigned(lNode) then begin lSettingsVersionAttr := lNode.Attributes.GetNamedItem(cXMLConfig_Version); if Assigned(lSettingsVersionAttr) then fSettingsVersion := StrToInt(lSettingsVersionAttr.NodeValue); lAutostartAttr := lNode.Attributes.GetNamedItem(cXMLConfig_AutoStart); if Assigned(lAutostartAttr) then fAutoStart := StrToBool(lAutostartAttr.NodeValue); lNeedsRebuildAttr := lNode.Attributes.GetNamedItem(cXMLConfig_NeedsRebuild); if Assigned(lNeedsRebuildAttr) then fNeedsRebuild := StrToBool(lNeedsRebuildAttr.NodeValue); lSortColumnAttr := lNode.Attributes.GetNamedItem(cXMLConfig_SortColumn); if Assigned(lSortColumnAttr) then fSortColumn := StrToInt(lSortColumnAttr.NodeValue); lSortDirectionAttr := lNode.Attributes.GetNamedItem(cXMLConfig_SortDirection); if Assigned(lSortDirectionAttr) then fSortDirection := StrToInt(lSortDirectionAttr.NodeValue); lActiveAttr := lNode.Attributes.GetNamedItem(cXMLConfig_Active); if Assigned(lActiveAttr) then fActive := StrToBool(lActiveAttr.NodeValue); end; end; procedure TCustomLazProfiler.SaveToFile(pFileName: String); var lFile, lLine: TStringList; i: Integer; begin lFile := TStringList.Create; lLine := TStringList.Create; try // header lLine.Delimiter := ';'; lLine.StrictDelimiter := True; lLine.Clear; lLine.Add(IntToStr(cSettingVersion)); lLine.Add(ifthen(fAutoStart, 'AutoStart', '')); lLine.Add(ifthen(fNeedsRebuild, 'NeedsRebuild', '')); lLine.Add(IntToStr(fSortColumn)); lLine.Add(IntToStr(fSortDirection)); lLine.Add(IntToStr(fUnitList.Count)); lLine.Add(IntToStr(fClassList.Count)); lLine.Add(IntToStr(fProcList.Count)); lFile.Add(lLine.DelimitedText); // units fUnitList.SaveToStringList(lFile); // classes fClassList.SaveToStringList(lFile); // procs fProcList.SaveToStringList(lFile); lFile.SaveToFile(pFileName); finally lLine.Free; lFile.Free; end; end; procedure TCustomLazProfiler.SaveXML(pFileName: String); var lDoc: TXMLDocument; lRootNode: TDOMElement; begin lDoc := TXMLDocument.Create; try lRootNode := lDoc.CreateElement(cXMLLazProfiler); lDoc.AppendChild(lRootNode); SaveConfig(lDoc); fPackageList.SaveXML(lDoc); fUnitList.SaveXML(lDoc); fClassList.SaveXML(lDoc); fProcList.SaveXML(lDoc); WriteXMLFile(lDoc, pFileName); finally lDoc.Free; end; end; function TCustomLazProfiler.LoadFromFile(pFileName: String): Boolean; var lFile, lLine, lTemp: TStringList; lVersion, lUnitCount, lClassCount, lProcCount: LongInt; lPasClass: TLPPasClass; lPasUnit: TLPPasUnit; lPasProc: TLPPasProc; lPasPackage: TLPPasPackage; i, j, p: Integer; begin if not FileExists(pFileName) then Exit(False); Result := True; fProcList.Clear; lFile := TStringList.Create; try lFile.LoadFromFile(pFileName); if lFile.Count >= 1 then begin if Pos('<?xml version=', lFile[0]) = 1 then begin lFile.Clear; LoadXML(pFileName); end else begin //WriteLn('*** LazProfiler: LoadFromFile: '+pFileName); lLine := TStringList.Create; lTemp := TStringList.Create; try lLine.Delimiter := ';'; lLine.StrictDelimiter := True; lLine.DelimitedText := lFile[0]; if lLine.Count >= 3 then begin lVersion := StrToInt(lLine[0]); If UpperCase(lLine[1]) = 'AUTOSTART' then fAutoStart := True; If UpperCase(lLine[2]) = 'NEEDSREBUILD' then fNeedsRebuild := True; if lVersion > 1 then begin fSortColumn := StrToInt(lLine[3]); fSortDirection := StrToInt(lLine[4]); lUnitCount := StrToInt(lLine[5]); lClassCount := StrToInt(lLine[6]); lProcCount := StrToInt(lLine[7]); end; end else Exit; fPackageList.Add(TLPPasPackage.Create('?')); lFile.Delete(0); if lVersion = 1 then begin if lFile.Count > 0 then fProcList.LoadFromStringList(lFile, lVersion); end else begin p := 0; if lUnitCount > 0 then begin; lTemp.Clear; for i := 0 to lUnitCount - 1 do begin lTemp.Add(lFile[p]); inc(p); end; fUnitList.LoadFromStringList(lTemp, lVersion); end; if lClassCount > 0 then begin; lTemp.Clear; for i := 0 to lClassCount - 1 do begin lTemp.Add(lFile[p]); inc(p); end; fClassList.LoadFromStringList(lTemp, lVersion); end; if lProcCount > 0 then begin; lTemp.Clear; for i := 0 to lProcCount - 1 do begin lTemp.Add(lFile[p]); inc(p); end; fProcList.LoadFromStringList(lTemp, lVersion); end; end; for i := 0 to fProcList.Count - 1 do begin lPasProc := fProcList[i]; // search package j := fPackageList.IndexOf(lPasProc.PackageName); if j >= 0 then begin lPasPackage := fPackageList[j] end else begin lPasPackage := TLPPasPackage.Create(lPasProc.PackageName); fPackageList.Add(lPasPackage); end; // search unit j := fUnitList.IndexOf(lPasProc.UnitName, lPasProc.FileName, lPasProc.PackageName); if j >= 0 then begin lPasUnit := fUnitList[j] end else begin lPasUnit := TLPPasUnit.Create(lPasProc.UnitName, lPasProc.FileName, lPasProc.PackageName); fUnitList.Add(lPasUnit); end; // search class j := fClassList.IndexOf(lPasProc.NameOfClass, lPasProc.UnitName, lPasProc.FileName, lPasProc.PackageName); if j >= 0 then begin lPasClass := fClassList[j] end else begin lPasClass := TLPPasClass.Create(lPasProc.NameOfClass, lPasProc.UnitName, lPasProc.FileName, lPasProc.PackageName); fClassList.Add(lPasClass); end; // connect lPasUnit.PasPackage := lPasPackage; lPasClass.PasPackage := lPasPackage; lPasClass.PasUnit := lPasUnit; lPasProc.PasPackage := lPasPackage; lPasProc.PasUnit := lPasUnit; lPasProc.PasClass := lPasClass; end; finally lTemp.Free; lLine.Free; end; end; end; //DebugLn(' Count='+IntToStr(fProcList.Count)); finally lFile.Free; end; end; function TCustomLazProfiler.LoadXML(pFileName: String): Boolean; var lDoc: TXMLDocument; lNodes, lNode: TDOMNode; i: Integer; lPasProc: TLPPasProc; lPasPackage: TLPPasPackage; lPasUnit: TLPPasUnit; lPasClass: TLPPasClass; j: SizeInt; begin //WriteLn('*** LazProfiler: LoadFromXMLFile: '+pFileName); if not FileExists(pFileName) then Exit(False); Result := True; fProcList.Clear; ReadXMLFile(lDoc, pFileName); try LoadConfig(lDoc); fPackageList.LoadXML(lDoc); fUnitList.LoadXML(lDoc); fClassList.LoadXML(lDoc); fProcList.LoadXML(lDoc); for i := 0 to fProcList.Count - 1 do begin lPasProc := fProcList[i]; // search package j := fPackageList.IndexOf(lPasProc.PackageName); if j >= 0 then begin lPasPackage := fPackageList[j] end else begin lPasPackage := TLPPasPackage.Create(lPasProc.PackageName); fPackageList.Add(lPasPackage); end; // search unit j := fUnitList.IndexOf(lPasProc.UnitName, lPasProc.FileName, lPasProc.PackageName); if j >= 0 then begin lPasUnit := fUnitList[j] end else begin lPasUnit := TLPPasUnit.Create(lPasProc.UnitName, lPasProc.FileName, lPasProc.PackageName); fUnitList.Add(lPasUnit); end; // search class j := fClassList.IndexOf(lPasProc.NameOfClass, lPasProc.UnitName, lPasProc.FileName, lPasProc.PackageName); if j >= 0 then begin lPasClass := fClassList[j] end else begin lPasClass := TLPPasClass.Create(lPasProc.NameOfClass, lPasProc.UnitName, lPasProc.FileName, lPasProc.PackageName); fClassList.Add(lPasClass); end; // connect lPasUnit.PasPackage := lPasPackage; lPasClass.PasPackage := lPasPackage; lPasClass.PasUnit := lPasUnit; lPasProc.PasPackage := lPasPackage; lPasProc.PasUnit := lPasUnit; lPasProc.PasClass := lPasClass; end; lNodes := lDoc.FindNode(cXMLRuns); if Assigned(lNodes) then with lNodes.ChildNodes do begin for i := 0 to Count - 1 do begin lNode := Item[i]; //Add(TprEnv.CreateFromXML(lEnvNode)); end; end; finally lDoc.Free; end; end; procedure TCustomLazProfiler.SetDefaults; begin fActive := False; fAutoStart := True; fNeedsRebuild := False; fSortColumn := cPackageCol; fSortDirection := 0; end; constructor TCustomLazProfiler.Create; begin inherited Create; fPackageList := TLPPasPackageList.Create(True); fUnitList := TLPPasUnitList.Create(True); fClassList := TLPPasClassList.Create(True); fProcList := TLPPasProcList.Create(True); SetDefaults; end; destructor TCustomLazProfiler.Destroy; begin fProcList.Free; fClassList.Free; fUnitList.Free; fPackageList.Free; inherited Destroy; end; { TLPStackFrame } procedure TLPStackFrame.Calc; var i: Integer; begin if fNet <> -1 then exit; { calc times } fNet := fTicksEnd - fTicksStart; fGross := fTicksExit - fTicksInit; fOverhead := fGross - fNet; { handle Childs } for i := 0 to fChildList.Count - 1 do begin fChildList[i].Calc; fNet := fNet - fChildList[i].fGross; fOverhead := fOverhead + fChildList[i].fOverhead; end; FreeAndNil(fChildList); { store infos } if Assigned(fPasProc) and fRunning then begin fPasProc.Count := fPasProc.Count + 1; fPasProc.fNet := fPasProc.fNet + fNet - fOff; fPasProc.fGross := fPasProc.fGross + fGross - fOverhead - fOff; end; end; procedure TLPStackFrame.CleanupChilds; var i: Integer; begin for i := 0 to fChildList.Count - 1 do fChildList[i].Calc; end; constructor TLPStackFrame.Create(pProc: TLPPasProc; pParent: TLPStackFrame); begin fPasProc := pProc; fParent := pParent; if Assigned(fParent) then fParent.fChildList.Add(Self); fNet := -1; fGross := -1; fChildList := TLPStackFrameList.Create; end; destructor TLPStackFrame.Destroy; begin fChildList.Free; inherited Destroy; end; { TLPPasProcList } constructor TLPPasProcList.Create(pOwnsObjects: Boolean); begin inherited Create(pOwnsObjects); fCallCount := 0; end; procedure TLPPasProcList.Init; var i: Integer; begin for i := 0 to Count -1 do Items[i].Init; end; procedure TLPPasProcList.Convert(pTicks: ticktype); var i: Integer; begin for i := 0 to Count - 1 do begin Items[i].Net := trunc(Items[i].Net / pTicks * 1000000000); Items[i].Gross := trunc(Items[i].Gross / pTicks * 1000000000); end; end; procedure TLPPasProcList.SaveToStringList(pList: TStringList); var lLine: TStringList; i: Integer; begin lLine := TStringList.Create; try lLine.Delimiter := ';'; lLine.StrictDelimiter := True; for i := 0 to Count - 1 do begin lLine.Clear; lLine.Add(Items[i].Name); lLine.Add(IntToStr(Items[i].Kind)); lLine.Add(Items[i].NameOfClass); lLine.Add(Items[i].UnitName); lLine.Add(Items[i].FileName); lLine.Add(IntToStr(Items[i].Row)); lLine.Add(IntToStr(Items[i].Count)); lLine.Add(IntToStr(Items[i].Net)); lLine.Add(IntToStr(Items[i].Gross)); lLine.Add(BoolToStr(Items[i].Instrument, True)); pList.Add(lLine.DelimitedText); end; finally lLine.Free; end; end; procedure TLPPasProcList.SaveXML(pDoc: TXMLDocument); var lNode: TDOMElement; i: Integer; begin lNode := pDoc.CreateElement(cXMLProcs); pDoc.DocumentElement.Appendchild(lNode); for i := 0 to Count - 1 do Items[i].SaveXML(pDoc, lNode); end; function TLPPasProcList.IndexOf(pName, pNameOfClass, pUnitName, pFileName, pPackageName: String): SizeInt; var lPasProc: TLPPasProc; i: Integer; begin pName := UpperCase(pName); pNameOfClass := UpperCase(pNameOfClass); pUnitName := UpperCase(pUnitName); pFileName := UpperCase(pFileName); for i := 0 to Count - 1 do begin lPasProc := Self[i]; if (lPasProc.NameUp = pName) and (lPasProc.NameOfClassUp = pNameOfClass) and (lPasProc.UnitNameUp = pUnitName) and (lPasProc.FileNameUp = pFileName) then Exit(i); end; Result := -1; end; procedure TLPPasProcList.LoadFromStringList(pList: TStringList; pVersion: Integer); var lLine: TStringList; i: Integer; begin lLine := TStringList.Create; try lLine.Delimiter := ';'; lLine.StrictDelimiter := True; if pList.Count = 0 then exit; for i := 0 to pList.Count - 1 do begin lLine.DelimitedText := pList[i]; if lLine.Count >= 9 then begin if pVersion = 1 then begin Add(TLPPasProc.Create(lLine[0], 0, lLine[1], lLine[2], lLine[3], '?', StrToInt(lLine[4]))); Last.Count := StrToInt(lLine[5]); Last.Net := StrToQWord(lLine[6]); Last.Gross := StrToQWord(lLine[7]); Last.Instrument := StrToBool(lLine[8]); end else begin Add(TLPPasProc.Create(lLine[0], StrToInt(lLine[1]), lLine[2], lLine[3], lLine[4], '?', StrToInt(lLine[5]))); Last.Count := StrToInt(lLine[6]); Last.Net := StrToQWord(lLine[7]); Last.Gross := StrToQWord(lLine[8]); Last.Instrument := StrToBool(lLine[9]); end; //if not Last.Instrument then // DebugLn('*** do not instrument '+Last.Name); end; end; finally lLine.Free; end; end; procedure TLPPasProcList.LoadXML(pDoc: TXMLDocument); var lNodes, lNode: TDOMNode; i: Integer; lNetSum, lGrossSum: QWord; lProc: TLPPasProc; begin Clear; lNetSum := 0; lGrossSum := 0; lNodes := pDoc.DocumentElement.FindNode(cXMLProcs); if Assigned(lNodes) then begin with lNodes.ChildNodes do begin for i := 0 to Count - 1 do begin lNode := Item[i]; lProc := TLPPasProc.CreateFromXML(lNode); Add(lProc); lNetSum := lNetSum + lProc.Net; lGrossSum := lGrossSum + lProc.Gross; end; end; for i := 0 to Count - 1 do Items[i].SetSums(lNetSum, lGrossSum); end; end; { TLazProfiler } function TLazProfiler.HWTicks: Ticktype; begin Result := fTimer.HWTimebase.Ticks() - fTimer.HWTimebase.TicksOverhead; end; function TLazProfiler.SysTicks: Ticktype; begin Result := fTimer.SysTimebase.Ticks() - fTimer.SysTimebase.TicksOverhead; end; function TLazProfiler.ThreadIndex(pThread: TThreadID): Integer; var lCurStackFrame: TLPStackFrame; i: SizeInt; begin Result := fThreads.IndexOf(Pointer(pThread)); if Result = -1 then begin Result := fThreads.Add(Pointer(pThread)); if fThreads.Count > Length(fCurStackFrame) then begin SetLength(fCurStackFrame, fThreads.Count + 100); SetLength(fPauseCount, fThreads.Count + 100); SetLength(fPauseStartTicks, fThreads.Count + 100); SetLength(fOffTicks, fThreads.Count + 100); for i := fThreads.Count to fThreads.Count + 99 do begin fPauseCount[i] := 0; fPauseStartTicks[i] := 0; fOffTicks[i] := 0; end; end; lCurStackFrame := TLPStackFrame.Create(fMasterProc, nil); lCurStackFrame.fTicksInit := Ticks(); lCurStackFrame.fTicksStart := lCurStackFrame.fTicksInit; fCurStackFrame[Result] := lCurStackFrame; end; end; procedure TLazProfiler.Lock; begin EnterCriticalsection(fLock); end; procedure TLazProfiler.UnLock; begin LeaveCriticalsection(fLock); end; procedure TLazProfiler.EnterProfiling(pProcID: Integer); var lTimeStamp: TickType; lCurStackFrame: TLPStackFrame; lIdx: Integer; begin lTimeStamp := Ticks(); Lock; try if pProcID >= fProcList.Count then begin WriteLn('TLazProfiler.EnterProfiling: pProcID >= fProcList.Count: '+IntToStr(pProcID)+'>='+IntToStr(fProcList.Count)); Exit; end; lIdx := ThreadIndex(ThreadID); lCurStackFrame := fCurStackFrame[lIdx]; lCurStackFrame := TLPStackFrame.Create(fProcList[pProcID], lCurStackFrame); fCurStackFrame[lIdx] := lCurStackFrame; lCurStackFrame.fRunning := fRunning; lCurStackFrame.fTicksInit := lTimeStamp; finally UnLock; end; lCurStackFrame.fTicksStart := Ticks(); end; procedure TLazProfiler.ExitProfiling(pProcID: Integer); var lTimeStamp: TickType; lCurStackFrame: TLPStackFrame; lIdx: Integer; begin lTimeStamp := Ticks(); Lock; try lIdx := ThreadIndex(ThreadID); lCurStackFrame := fCurStackFrame[lIdx]; lCurStackFrame.fTicksEnd := lTimeStamp; if pProcID >= fProcList.Count then begin WriteLn('TLazProfiler.ExitProfiling: pProcID >= fProcList.Count: '+IntToStr(pProcID)+'>='+IntToStr(fProcList.Count)); Exit; end; if lCurStackFrame.fPasProc <> fProcList[pProcID] then WriteLn('TLazProfiler.ExitProfiling: Stack mismatch: '+lCurStackFrame.fPasProc.Name+'<->'+fProcList[pProcID].name); if fPauseCount[lIdx] = 0 then begin lCurStackFrame.fOff := fOffTicks[lIdx]; fOffTicks[lIdx] := 0; end else lCurStackFrame.fOff := 0; lCurStackFrame.CleanupChilds; fCurStackFrame[lIdx] := lCurStackFrame.fParent; finally UnLock; end; lCurStackFrame.fTicksExit := Ticks(); end; procedure TLazProfiler.StartProfiling; begin fRunning := True; WriteLn('### LazProfiler: Start'); end; procedure TLazProfiler.PauseProfiling; var lIdx: Integer; begin lIdx := ThreadIndex(ThreadID); if fPauseCount[lIdx] = 0 then fPauseStartTicks[lIdx] := Ticks(); fPauseCount[lIdx] := fPauseCount[lIdx] + 1; end; procedure TLazProfiler.ContinueProfiling; var lIdx: Integer; begin lIdx := ThreadIndex(ThreadID); fPauseCount[lIdx] := fPauseCount[lIdx] - 1; if fRunning then begin if fPauseCount[lIdx] = 0 then begin if fPauseStartTicks[lIdx] <> 0 then fOffTicks[lIdx] := fOffTicks[lIdx] + (Ticks() - fPauseStartTicks[lIdx]) else fOffTicks[lIdx] := 0; fPauseStartTicks[lIdx] := 0; end; end else begin fOffTicks[lIdx] := 0; fPauseStartTicks[lIdx] := 0; end; end; procedure TLazProfiler.StopProfiling; begin fRunning := False; WriteLn('### LazProfiler: Stop'); end; constructor TLazProfiler.Create(pProgramm: String); var lCurStackFrame: TLPStackFrame; i: Integer; begin inherited Create; InitCriticalSection(fLock); fName := AppendPathDelim(ExtractFileDir(pProgramm))+ExtractFileNameOnly(pProgramm); fTimer := TEpikTimer.Create(nil); if fTimer.HWCapabilityDataAvailable and fTimer.HWTickSupportAvailable then begin Ticks := @HWTicks; fTicks := fTimer.HWTimebase.TicksFrequency; //WriteLn('### LazProfiler: HWTicks used. Freq='+IntToStr(fTicks)); end else begin Ticks := @SysTicks; fTicks := fTimer.SysTimebase.TicksFrequency; //WriteLn('### LazProfiler: SysTicks used. Freq='+IntToStr(fTicks)); end; fMasterProc := TLPPasProc.Create('Master', 0, '', '', '', '', -1); fThreads := TList.Create; lCurStackFrame := TLPStackFrame.Create(fMasterProc, nil); lCurStackFrame.fTicksInit := Ticks(); lCurStackFrame.fTicksStart := lCurStackFrame.fTicksInit; SetLength(fCurStackFrame, 100); SetLength(fPauseCount, 100); SetLength(fPauseStartTicks, 100); SetLength(fOffTicks, 100); for i := 0 to 99 do begin fPauseCount[i] := 0; fPauseStartTicks[i] := 0; fOffTicks[i] := 0; end; fCurStackFrame[fThreads.Add(Pointer(ThreadID))] := lCurStackFrame; fLoaded := LoadFromFile(fName+cSettingExtension); fRunning := fAutoStart; end; destructor TLazProfiler.Destroy; var i: Integer; lCurStackFrame: TLPStackFrame; begin fMasterProc.Free; for i := 0 to fThreads.Count - 1 do begin lCurStackFrame := fCurStackFrame[i]; lCurStackFrame.fTicksEnd := Ticks(); lCurStackFrame.fTicksExit := lCurStackFrame.fTicksEnd; lCurStackFrame.Calc; lCurStackFrame.Free; end; { calc percentages } { free resources } fThreads.Free; SetLength(fCurStackFrame, 0); SetLength(fPauseCount, 0); SetLength(fPauseStartTicks, 0); SetLength(fOffTicks, 0); fTimer.Free; if fTicks > 0 then fProcList.Convert(fTicks) else WriteLn('*** LazProfiler: fTicks='+IntToStr(fTicks)); if fLoaded then SaveXML(fName + cSettingExtension); DoneCriticalSection(fLock); inherited Destroy; end; { TLPPasProc } procedure TLPPasProc.Init; begin fCount := 0; fNet := 0; fGross := 0; end; procedure TLPPasProc.SetFileName(pFileName: String); begin if fFileName = pFileName then Exit; fFileName := pFileName; fFileNameUp := UpperCase(fFileName); end; procedure TLPPasProc.SetName(pName: String); begin if fName = pName then Exit; fName := pName; fNameUp := UpperCase(pName); end; constructor TLPPasProc.Create(pName: String; pKind: Integer; pNameOfClass, pUnitName, pFileName, pPackageName: String; pRow: Integer); begin inherited Create(pNameOfClass, pUnitName, pFileName, pPackageName); fName := pName; fNameUp := UpperCase(pName); fRow := pRow; fInstrument := pPackageName = '?'; fKind := pKind; Init; end; destructor TLPPasProc.Destroy; begin fCalls.Free; fCalledBy.Free; fCallsCount.Free; fCalledByCount.Free; inherited Destroy; end; procedure TLPPasProc.Calls(pProc: TLPPasProc); var i: SizeInt; begin if not Assigned(fCalls) then begin fCalls := TLPPasProcList.Create(False); fCallsCount := TIntegerList.Create; end; i := fCalls.IndexOf(pProc); if i = -1 then begin fCalls.Add(pProc); fCallsCount.Add(1); end else begin fCallsCount[i] := fCallsCount[i] + 1; end; end; procedure TLPPasProc.CalledBy(pProc: TLPPasProc); var i: SizeInt; begin if not Assigned(fCalledBy) then begin fCalledBy := TLPPasProcList.Create(False); fCalledByCount := TIntegerList.Create; end; i := fCalledBy.IndexOf(pProc); if i = -1 then begin fCalledBy.Add(pProc); fCalledByCount.Add(1); end else begin fCalledByCount[i] := fCalledByCount[i] + 1; end; end; procedure TLPPasProc.SetSums(pNetSum, pGrossSum: QWord); begin fPerNet := 0; fPerNetStr := ''; fPerGross := 0; fPerGrossStr := ''; if fCount > 0 then begin if (pNetSum > 0) then begin fPerNet := fNet * 100 * 1000 div pNetSum; fPerNetStr := Format('%2.3n', [fPerNet / 1000]); end; if (pGrossSum > 0) then begin fPerGross := fGross * 100 * 1000 div pGrossSum; fPerGrossStr := Format('%2.3n', [fPerGross / 1000]); end; end; end; function TLPPasProc.XMLNodeName: String; begin Result := cXMLProc; end; procedure TLPPasProc.SaveXMLNode(pDoc: TXMLDocument; pNode: TDOMElement); begin inherited SaveXMLNode(pDoc, pNode); pNode.SetAttribute('name', fName); pNode.SetAttribute('kind', IntToStr(fKind)); pNode.SetAttribute('row', IntToStr(fRow)); pNode.SetAttribute('count', IntToStr(fCount)); pNode.SetAttribute('net', IntToStr(fNet)); pNode.SetAttribute('gross', IntToStr(fGross)); pNode.SetAttribute('instrument', BoolToStr(fInstrument, True)); end; procedure TLPPasProc.LoadXMLNode(pNode: TDOMNode); var lCountAttr, lNetAttr, lGrossAttr, lIntrumentAttr: TDOMNode; begin inherited LoadXMLNode(pNode); lCountAttr := pNode.Attributes.GetNamedItem('count'); if Assigned(lCountAttr) then fCount := StrToInt(lCountAttr.NodeValue); lNetAttr := pNode.Attributes.GetNamedItem('net'); if Assigned(lNetAttr) then fNet := StrToQWord(lNetAttr.NodeValue); lGrossAttr := pNode.Attributes.GetNamedItem('gross'); if Assigned(lGrossAttr) then fGross := StrToQWord(lGrossAttr.NodeValue); lIntrumentAttr := pNode.Attributes.GetNamedItem('instrument'); if Assigned(lIntrumentAttr) then fInstrument := StrToBool(lIntrumentAttr.NodeValue); if fCount = 0 then begin fAvgNet := 0; fAvgGross := 0; fCountStr := ''; fSumNetStr := ''; fSumGrossStr := ''; fAvgNetStr := ''; fAvgGrossStr := ''; end else begin fAvgNet := fNet div fCount; fAvgGross := fGross div fCount; fCountStr := IntToStr(fCount); fSumNetStr := IntToTime(fNet); fSumGrossStr := IntToTime(fGross); fAvgNetStr := IntToTime(fAvgNet); fAvgGrossStr := IntToTime(fAvgGross); end; end; procedure TLPPasProc.InternalCreateFormXML(pNode: TDOMNode); var lName, lPackageName, lFileName, lUnitName, lNameOfClass: DOMString; lNameAttr, lKindAttr, lUnitNameAttr, lFileNameAttr, lPackageNameAttr, lNameOfClassAttr, lRowAttr: TDOMNode; lKind, lRow: LongInt; begin; lNameAttr := pNode.Attributes.GetNamedItem('name'); if Assigned(lNameAttr) then lName := lNameAttr.NodeValue; lKindAttr := pNode.Attributes.GetNamedItem('kind'); if Assigned(lKindAttr) then lKind := StrToInt(lKindAttr.NodeValue); lNameOfClassAttr := pNode.Attributes.GetNamedItem('nameofclass'); if Assigned(lNameOfClassAttr) then lNameOfClass := lNameOfClassAttr.NodeValue; lUnitNameAttr := pNode.Attributes.GetNamedItem('unitname'); if Assigned(lUnitNameAttr) then lUnitName := lUnitNameAttr.NodeValue; lFileNameAttr := pNode.Attributes.GetNamedItem('filename'); if Assigned(lFileNameAttr) then lFileName := lFileNameAttr.NodeValue; lPackageNameAttr := pNode.Attributes.GetNamedItem('packagename'); if Assigned(lPackageNameAttr) then lPackageName := lPackageNameAttr.NodeValue; lRowAttr := pNode.Attributes.GetNamedItem('row'); if Assigned(lRowAttr) then lRow := StrToInt(lRowAttr.NodeValue); Create(lName, lKind, lNameOfClass, lUnitName, lFileName, lPackageName, lRow); end; end.
unit WPRTEFormatBase; { ----------------------------------------------------------------------------- Copyright (C) 2002-2013 by wpcubed GmbH - Author: Julian Ziersch info: http://www.wptools.de mailto:support@wptools.de __ __ ___ _____ _ _____ / / /\ \ \/ _ \/__ \___ ___ | |___ |___ | \ \/ \/ / /_)/ / /\/ _ \ / _ \| / __| / / \ /\ / ___/ / / | (_) | (_) | \__ \ / / \/ \/\/ \/ \___/ \___/|_|___/ /_/ ***************************************************************************** WPRTEFormatBase - WPTools paragraph reformat routine ***************************************************************************** THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. ----------------------------------------------------------------------------- } interface uses Classes, SysUtils, WPRTEDefs, WPRTEDefsConsts, WPRTEPlatform; implementation function ParagraphReformat(par : TParagraph; Always: Boolean = FALSE; MaxW: Integer = 0; Options: Integer = 0): Integer; var TabPos, aIndentLeft, l, TabCountInPar, lmax, i, res, ii, Alignment: Integer; tp, LastBreakPos : Integer; cc: WideChar; TabKind: TTabKind; bAddLines: Boolean; ww, x, xo, lastx, w, tw, LastBreakPos_x : Integer; procedure ApplyAlign; var aa, jj, spccount, wor, a: Integer; ww, wo : Integer; begin if MaxW > 0 then ww := MaxW else if bAddLines then begin ww := x; par.Lines[l].RectWidth := Round(ww); end else ww := par.Lines[l].RectWidth; if (x < ww) then begin if Alignment = Integer(paralRight) then begin if par.CharPos[par.Lines[l].CharStart].xoff <> ww - x then par.CharPos[par.Lines[l].CharStart].xoff := ww - x; end else if Alignment = Integer(paralCenter) then par.CharPos[par.Lines[l].CharStart].xoff := (ww - x) div 2 else if (Alignment = Integer(paralBlock)) and ((i < par.CharCount) or (wpJustifyHardLinebreaks in par.RTFData.DataCollection.FormatOptions)) then begin jj := i; if jj >= par.CharCount then jj := par.CharCount - 1; aa := par.Lines[l].CharStart; a := aa; while a < jj do begin if par.CharItem[a] = #9 then aa := a; inc(a); end; a := aa; spccount := 0; while a < jj do begin if par.CharItem[a] = #32 then inc(spccount); inc(a); end; if spccount > 0 then begin wo := (ww - x) div spccount; wor := (ww - x) - wo * spccount; a := aa; while (a < jj) and (spccount > 0) do begin if par.CharItem[a] = #32 then begin dec(spccount); inc(par.CharPos[a].Width, wo); if a < par.CharCount - 1 then inc(par.CharPos[a + 1].xoff, wo); if wor > 0 then begin dec(wor); inc(par.CharPos[a].Width); if a < par.CharCount - 1 then inc(par.CharPos[a + 1].xoff); end; end; inc(a); end; end; end; end; end; function MakeWord(v: Integer): Word; begin if v < 0 then Result := 0 else Result := v and $FFFF; end; var iMaxLength: Integer; iBase, iHeight: Integer; function NextLine: Boolean; begin Result := TRUE; if (l >= lmax - 1) then begin if bAddLines then begin inc(lmax, 20); SetLength(par.Lines, lmax); end else begin Result := FALSE; exit; end; end; inc(l); end; var aTextObject: TWPTextObj; aRTFEngine: TWPRTFEngineBasis; b: Boolean; oh: Integer; ow : Integer; begin aRTFEngine := nil; Result := 1; bAddLines := (Options and 1) <> 0; if bAddLines or ((Options and 16)=16) then begin aRTFEngine := par.RTFData.DataCollection.RTFEngine; end; iBase := 0; iHeight := 0; lmax := Length(par.Lines); res := par.RTFProps.XPixelsPerInch; if (paprRightToLeft in par.prop) and par.RTFData.DataCollection._RTLAlwaysRightAligned then Alignment := Integer(paralRight) else Alignment := par.AGetDefInherited(WPAT_Alignment, 0); if bAddLines then begin if lmax <= 0 then begin lmax := (par.CharCount div 60); SetLength(par.Lines, lmax + 1); end; end else begin if (lmax < 0) or (paprRightToLeft in par.prop) or (par.RTFData = nil) or (par.RTFData.DataCollection.FLocked > 0) or (par.AGetDefInherited(WPAT_NumberSTYLE, 0) <> 0) or (wpFormatAsWebpage in par.RTFData.DataCollection.AsWebpage) or par.HasText(#9, false) then exit; if (Alignment = 3) and (((Options and 2) <> 0) or (wpfDisableJustifiedText in par.RTFData.DataCollection.FormatOptionsEx)) then Alignment := 0; if not Always and not WPAppServerMode and ((paprHasGraphics in par.prop) or (paprHasHyphenation in par.prop) or (par.TabstopCount > 0) or (Alignment = 3) or ((Alignment = 2) and ((par.LineCount > 1) or (par.AGetDefInherited(WPAT_NumberStyle, 0) <> 0) or (par.AGetDefInherited(WPAT_NumberMode, 0) <> 0))) ) then exit; end; iMaxLength := par.AGetDef(WPAT_MaxLength, par.RTFData.DataCollection.MaxParLength); if (Length(par.CharPos) < Length(par.CharItem)) or (Length(par.Lines)=0) then exit; x := 0; lastx := 0; TabPos := 0; LastBreakPos := -1; LastBreakPos_x := 0; l := 0; par.Lines[l].CharStart := 0; if bAddLines then begin w := maxw; end else begin w := par.Lines[l].RectWidth; end; i := 0; TabCountInPar := 0; if par.AGet(WPAT_IndentLeft, aIndentLeft) then aIndentLeft := MulDiv(aIndentLeft, res, 1440) else aIndentLeft := 0; if par.CharCount = 0 then begin if par.ParagraphType in [wpIsSTDPar, wpIsHTML_DIV] then begin if (paprIsTable in par.prop) then begin iHeight := 0; iBase := 0; end else begin iHeight := par._DefaultHeight; iBase := par._DefaultBase; end; end; end else while i < par.CharCount do begin cc := par.CharItem[i]; if not bAddLines and (par.CharPos[i].Height > par.Lines[l].Height) and ((Options and 2) = 0) and not (wpFormatAsWebpage in par.RTFData.DataCollection.AsWebpage) then exit; if cc = #9 then begin tp := 0; if not (wpfDontTabToIndentFirst in par.RTFData.DataCollection.FormatOptions) and (((TabCountInPar = 0) and (i = 0)) or ((wpfHangingIndentWithTab in par.RTFData.DataCollection.FormatOptions) and (i = 0) or (lastx < aIndentLeft))) and par.AGet(WPAT_IndentFirst, tp) then begin if tp > 0 then tp := 0 else tp := Round(-tp - lastx*res/1440); TabPos := par.TabstopGetFirstPos; if (TabPos > 0) and (TabPos < tp) then tp := -1; TabPos := par.TabstopGetFirstPos; if (TabPos > Round(x*res/1440)) and (TabPos < par.AGetDefInherited(WPAT_IndentLeft, 0)) then tp := -1 else begin tp := par.AGetDefInherited(WPAT_IndentLeft, 0) + Round(x*res/1440); end; end; Inc(TabCountInPar); if tp <= 0 then tp := par.TabstopGetNext( Round(x*res/1440), Round(w*res/1440), TabPos, TabKind, par.RTFData.DataCollection.Header.DefaultTabstop); if tp = 10000 then begin if not (wpFormatAsWebpage in par.RTFData.DataCollection.AsWebpage) then exit; end else if tp >= 0 then begin xo := MulDiv(TabPos, res, 1440); if l = 0 then xo := xo - aIndentLeft + par.AGetDefInherited(WPAT_IndentFirst, 0) else xo := xo - aIndentLeft; if TabKind in [tkRight, tkCenter] then begin ii := i + 1; ww := 0; while ii < par.CharCount do begin if (par.CharItem[ii] = #10) or (par.CharItem[ii] = #9) then break; Inc(ww, par.CharPos[ii].Width); inc(ii); end; if TabKind = tkCenter then ww := ww div 2; if x + ww < xo then begin tw := (xo - x - ww - 1); end else tw := 0; end else tw := xo - x; if (tw > 0) and (tw < $FFFF) then par.CharPos[i].Width := tw end; end; aTextObject := nil; if cc = TextObjCode then begin aTextObject := par.ObjectRef[i]; if (aTextObject <> nil) and (not aTextObject.IsImage or ((aTextObject.Mode * [wpobjRelativeToParagraph, wpobjRelativeToPage]) = [])) then begin if aTextObject.IsImage then begin ow := MulDiv(aTextObject.Width, res, 1440); oh := MulDiv(aTextObject.Height, res, 1440); end else begin ow := Round(par.CharPos[i].Width); oh := par.CharPos[i].Height; end; if aTextObject.ObjType = wpobjImage then par.CharPos[i].Base := 0; if aRTFEngine <> nil then aRTFEngine.MeasureObject( [wpMeasureInReformatPar], par, i, -1, Round(x), maxw, 0, $FFFF, nil, ow, oh, aTextObject, nil, 0, b ); if not bAddLines and (ow > w) then WPScaleWH(ow, oh, Round(w), -1); par.CharPos[i].Width := MakeWord(ow); par.CharPos[i].Height := MakeWord(oh); end; end; if cc = #10 then begin par.Lines[l].CharPLen := i + 1 - par.Lines[l].CharStart; LastBreakPos := -1; LastBreakPos_x := 0; par.Lines[l].Height := iHeight; par.Lines[l].Base := iBase; if (wpJustifySoftLineBreaks in par.RTFData.DataCollection.FormatOptions) or (wpJustifyHardLinebreaks in par.RTFData.DataCollection.FormatOptions) then ApplyAlign; if not NextLine then exit; par.Lines[l].CharStart := i + 1; par.Lines[l].CharPLen := 0; if bAddLines then par.Lines[l].RectWidth := maxw; w := par.Lines[l].RectWidth; par.CharPos[i].xoff := x - lastx; par.CharPos[i].Width := 1; x := 0; lastx := 0; iHeight := 0; inc(i); if i = par.CharCount then break; end else if (cc <> #32) and ({$IFNDEF NOWRAPWITH_MAXPAR}(x + par.CharPos[i].Width > w) or {$ENDIF}((iMaxLength > 0) and (i >= iMaxLength)) ) then begin if LastBreakPos > 0 then begin i := LastBreakPos; x := LastBreakPos_x; end else if i > 0 then dec(i); par.Lines[l].CharPLen := i - par.Lines[l].CharStart; if par.Lines[l].CharPLen <= 0 then begin par.Lines[l].CharPLen := 1; inc(i); end; par.Lines[l].Height := iHeight; par.Lines[l].Base := iBase; ApplyAlign; if not NextLine then exit; iHeight := 0; iBase := 0; par.Lines[l].CharStart := i; par.Lines[l].CharPLen := 0; LastBreakPos := -1; LastBreakPos_x := 0; if bAddLines then par.Lines[l].RectWidth := maxw; w := par.Lines[l].RectWidth; x := 0; lastx := 0; end else if cc = #32 then begin LastBreakPos := i + 1; LastBreakPos_x := x; if Alignment = 3 then par.CharPos[i].Width := par.CharPos[i].Height div 2; end; par.CharPos[i].xoff := x - lastx; lastx := x; Inc(x, par.CharPos[i].Width); if par.CharPos[i].Height > iHeight then iHeight := par.CharPos[i].Height; if par.CharPos[i].Base > iBase then iBase := par.CharPos[i].Base; inc(i); end; if bAddLines then begin lmax := l; SetLength(par.Lines, l + 1); end else if l < lmax - 1 then begin SetLength(par.Lines, 0); exit end else lmax := l; if lmax >= 0 then begin par.Lines[lmax].CharPLen := par.CharCount - par.Lines[lmax].CharStart; l := lmax; ApplyAlign; if par.Lines[lmax].CharPLen < 0 then par.Lines[lmax].CharPLen := 0; par.Lines[lmax].Height := iHeight; par.Lines[lmax].Base := iBase; end; exclude(par.prop, paprMustReformat); Result := 0; end; initialization pParagraphReformat := ParagraphReformat; end.
unit TestuRedisClusterHandle; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, uRedisCommand, StrUtils, Classes, uRedisCommon, SysUtils, uRedisHandle, Contnrs, uRedisClusterHandle; type // Test methods for class TRedisClusterHandle TestTRedisClusterHandle = class(TTestCase) strict private FRedisClusterHandle: TRedisClusterHandle; public procedure SetUp; override; procedure TearDown; override; published procedure TestAddNode; procedure TestStringSetExpire; procedure TestStringGetSet; procedure TestKey; end; const C_Key_Pre = 'Ö÷¼üC:'; C_Value_Pre = '"ÖµC": '; C_List_Key = 'Ö÷¼üC:list'; C_List_Value_Pre = 'ÖµC-list-'; implementation procedure TestTRedisClusterHandle.SetUp; begin FRedisClusterHandle := TRedisClusterHandle.Create; FRedisClusterHandle.Password := 'tcrq1234'; FRedisClusterHandle.AddNode('192.168.1.80', 6379); end; procedure TestTRedisClusterHandle.TearDown; begin FRedisClusterHandle.Free; FRedisClusterHandle := nil; end; procedure TestTRedisClusterHandle.TestAddNode; var ReturnValue: TRedisHandle; begin // TODO: Setup method call parameters ReturnValue := FRedisClusterHandle.AddNode('192.168.1.80', 6379); Check(Assigned(ReturnValue), 'AddNode Fail'); ReturnValue := FRedisClusterHandle.AddNode('192.168.1.80', 6380); Check(Assigned(ReturnValue), 'AddNode Fail'); ReturnValue := FRedisClusterHandle.AddNode('192.168.1.80', 6379); Check(Assigned(ReturnValue), 'AddNode Fail'); ReturnValue := FRedisClusterHandle.AddNode('192.168.1.80', 6380); Check(Assigned(ReturnValue), 'AddNode Fail'); Check(FRedisClusterHandle.GetNodeCount = 2, 'AddNode Fail'); // TODO: Validate method results end; procedure TestTRedisClusterHandle.TestKey; var aKey: string; begin aKey := C_Key_Pre + IntToStr(100); FRedisClusterHandle.StringSet(aKey, '123'); CheckTrue(FRedisClusterHandle.KeyExist(aKey), 'KeyExist Fail'); Status('KeyExist ok'); FRedisClusterHandle.KeySetExpire(aKey, 2); Sleep(2010); CheckTrue(not FRedisClusterHandle.KeyExist(aKey), 'KeyExist Fail'); Status('KeySetExpire ok'); FRedisClusterHandle.StringSet(aKey, '123'); FRedisClusterHandle.KeyDelete(aKey); CheckTrue(not FRedisClusterHandle.KeyExist(aKey), 'KeyDelete Fail'); Status('KeyDelete ok'); end; procedure TestTRedisClusterHandle.TestStringGetSet; var aKey, aValue, aNewValue: string; i: Integer; begin for i := 0 to 9 do begin aKey := C_Key_Pre + IntToStr(i); aNewValue := 'new:' + IntToStr(i); aValue := 'old:' + IntToStr(i); FRedisClusterHandle.StringSet(aKey, aValue); CheckTrue(aValue = FRedisClusterHandle.StringGetSet(aKey, aNewValue)); CheckTrue(aNewValue = FRedisClusterHandle.StringGet(aKey), 'StringGetSet fail'); Status(aKey + ' : ' + aValue + ',' + aNewValue); end; end; procedure TestTRedisClusterHandle.TestStringSetExpire; var aValue: string; aKey: string; i: Integer; begin for i := 0 to 9 do begin aKey := C_Key_Pre + IntToStr(i); aValue := C_Value_Pre + IntToStr(i); FRedisClusterHandle.StringSet(aKey, aValue, 15); Status('Set ' + aKey + ' : ' + aValue); end; end; initialization // Register any test cases with the test runner RegisterTest(TestTRedisClusterHandle.Suite); end.
unit k053251; interface const K053251_CI0=0; K053251_CI1=1; K053251_CI2=2; K053251_CI3=3; K053251_CI4=4; type k053251_chip=class constructor Create; destructor free; public dirty_tmap:array[0..4] of boolean; procedure reset; procedure lsb_w(direccion,valor:word); function get_priority(ci:byte):byte; function get_palette_index(ci:byte):byte; procedure write(direccion:word;valor:byte); private ram:array[0..$f] of byte; palette_index:array[0..4] of byte; procedure reset_indexes; end; var k053251_0:k053251_chip; procedure konami_sortlayers3(layer,pri:pbyte); implementation procedure konami_sortlayers3(layer,pri:pbyte); procedure SWAP(a,b:byte); var t:byte; begin if (pri[a]<pri[b]) then begin t:=pri[a];pri[a]:=pri[b];pri[b]:=t; t:=layer[a];layer[a]:=layer[b];layer[b]:=t; end; end; begin SWAP(0,1); SWAP(0,2); SWAP(1,2); end; constructor k053251_chip.Create; begin end; destructor k053251_chip.free; begin end; procedure k053251_chip.reset_indexes; begin self.palette_index[0]:=32*((self.ram[9] shr 0) and 3); self.palette_index[1]:=32*((self.ram[9] shr 2) and 3); self.palette_index[2]:=32*((self.ram[9] shr 4) and 3); self.palette_index[3]:=16*((self.ram[10] shr 0) and 7); self.palette_index[4]:=16*((self.ram[10] shr 3) and 7); end; procedure k053251_chip.reset; var f:byte; begin for f:=0 to $f do self.ram[f]:=0; for f:=0 to 4 do self.dirty_tmap[f]:=false; self.reset_indexes(); end; procedure k053251_chip.write(direccion:word;valor:byte); var i,newind:byte; begin valor:=valor and $3f; if (self.ram[direccion]<>valor) then begin self.ram[direccion]:=valor; case direccion of 9:begin // palette base index for i:=0 to 2 do begin newind:=32*((valor shr (2*i)) and 3); if (self.palette_index[i]<>newind) then begin self.palette_index[i]:=newind; self.dirty_tmap[i]:=true; end; end; end; 10:begin // palette base index for i:=0 to 1 do begin newind:=16*((valor shr (3*i)) and 7); if (self.palette_index[3+i]<>newind) then begin self.palette_index[3+i]:=newind; self.dirty_tmap[3+i]:=true; end; end; end; end; end; end; procedure k053251_chip.lsb_w(direccion,valor:word); begin self.write(direccion,valor and $ff); end; function k053251_chip.get_priority(ci:byte):byte; begin get_priority:=self.ram[ci]; end; function k053251_chip.get_palette_index(ci:byte):byte; begin get_palette_index:=self.palette_index[ci]; end; end.
{$I OVC.INC} {$B-} {Complete Boolean Evaluation} {$I+} {Input/Output-Checking} {$P+} {Open Parameters} {$T-} {Typed @ Operator} {$W-} {Windows Stack Frame} {$X+} {Extended Syntax} {$IFNDEF Win32} {$G+} {286 Instructions} {$N+} {Numeric Coprocessor} {$C MOVEABLE,DEMANDLOAD,DISCARDABLE} {$ENDIF} {*********************************************************} {* OVCSFPE.PAS 2.17 *} {* Copyright (c) 1995-98 TurboPower Software Co *} {* All rights reserved. *} {*********************************************************} unit OvcSfPe; {-Simple field property editor} {$I l3Define.inc } interface uses {$IFDEF Win32} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} Buttons, Classes, Controls, {$IfDef Delphi6} DesignIntf, DesignEditors, {$Else Delphi6} DsgnIntf, {$EndIf Delphi6} Graphics, Forms, StdCtrls, SysUtils, OvcConst, OvcData, OvcHelp; type TOvcfrmSimpleMask = class(TForm) btnOk: TBitBtn; btnCancel: TBitBtn; btnHelp: TBitBtn; cbxMaskCharacter: TComboBox; lblPictureChars: TLabel; procedure FormCreate(Sender: TObject); procedure cbxMaskCharacterChange(Sender: TObject); procedure btnHelpClick(Sender: TObject); protected { Private declarations } Mask : Char; end; type {property editor for picture mask} TSimpleMaskProperty = class(TCharProperty) public function GetAttributes: TPropertyAttributes; override; function AllEqual: Boolean; override; procedure Edit; override; end; implementation uses OvcSf, OvcAe, OvcTCSim; {$R *.DFM} procedure TOvcfrmSimpleMask.FormCreate(Sender: TObject); var I : Word; begin {load mask character strings} for I := stsmFirst to stsmLast do cbxMaskCharacter.Items.Add(GetOrphStr(I)); end; {!!.16} procedure TOvcfrmSimpleMask.cbxMaskCharacterChange(Sender: TObject); var I : Integer; S : string; function MinI(X, Y : Integer) : Integer; begin if X < Y then Result := X else Result := Y; end; begin {return the mask character} with cbxMaskCharacter do begin S := UpperCase(Text); if S > '' then for I := 0 to Items.Count-1 do if UpperCase(Copy(Items[I], 1, MinI(Length(S), Length(Items[I])))) = S then begin ItemIndex := I; Break; end; if ItemIndex > -1 then Mask := Items[ItemIndex][1] end; end; {*** TSimpleMaskProperty ***} type TLocalSF = class(TOvcCustomSimpleField); function TSimpleMaskProperty.GetAttributes: TPropertyAttributes; begin Result := [paDialog, paMultiSelect] end; function TSimpleMaskProperty.AllEqual: Boolean; begin Result := True; end; procedure TSimpleMaskProperty.Edit; var SfPE : TOvcfrmSimpleMask; I, J : Integer; C : TComponent; begin SfPE := TOvcfrmSimpleMask.Create(Application); try C := TComponent(GetComponent(0)); if C is TOvcCustomSimpleField then SfPE.Mask := TLocalSF(C).PictureMask else if C is TOvcSimpleArrayEditor then SfPE.Mask := TOvcSimpleArrayEditor(C).PictureMask else if C is TOvcTCSimpleField then SfPE.Mask := TOvcTCSimpleField(C).PictureMask; J := -1; {if only one field is selected select the combo box item} {that corresponds to the current mask character} if PropCount = 1 then begin with SfPE.cbxMaskCharacter do begin for I := 0 to Items.Count-1 do begin if Items[I][1] = SfPE.Mask then begin J := I; Break; end; end; ItemIndex := J; end; end; {show the form} SfPE.ShowModal; if SfPe.ModalResult = idOK then begin {update all selected components with new mask} for I := 1 to PropCount do begin C := TComponent(GetComponent(I-1)); if C is TOvcCustomSimpleField then TLocalSF(C).PictureMask := SfPE.Mask else if C is TOvcSimpleArrayEditor then TOvcSimpleArrayEditor(C).PictureMask := SfPE.Mask else if C is TOvcTCSimpleField then TOvcTCSimpleField(C).PictureMask := SfPE.Mask; end; Modified; end; finally SfPE.Free; end; end; procedure TOvcfrmSimpleMask.btnHelpClick(Sender: TObject); begin ShowHelpContext(hcSimpleFieldMask); end; end.
{ Steam Utilities Copyright (C) 2016, Simon J Stuart, All Rights Reserved Original Source Location: https://github.com/LaKraven/SteamUtils License: - You may use this library as you see fit, including use within commercial applications. - You may modify this library to suit your needs, without the requirement of distributing modified versions. - You may redistribute this library (in part or whole) individually, or as part of any other works. - You must NOT charge a fee for the distribution of this library (compiled or in its source form). It MUST be distributed freely. - This license and the surrounding comment block MUST remain in place on all copies and modified versions of this source code. - Modified versions of this source MUST be clearly marked, including the name of the person(s) and/or organization(s) responsible for the changes, and a SEPARATE "changelog" detailing all additions/deletions/modifications made. Disclaimer: - Your use of this source constitutes your understanding and acceptance of this disclaimer. - Simon J Stuart, nor any other contributor, may be held liable for your use of this source code. This includes any losses and/or damages resulting from your use of this source code, be they physical, financial, or psychological. - There is no warranty or guarantee (implicit or otherwise) provided with this source code. It is provided on an "AS-IS" basis. Donations: - While not mandatory, contributions are always appreciated. They help keep the coffee flowing during the long hours invested in this and all other Open Source projects we produce. - Donations can be made via PayPal to PayPal [at] LaKraven (dot) Com ^ Garbled to prevent spam! ^ } unit Steam.Api.Common.Intf; interface {$I ADAPT.inc} uses {$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES} System.Classes, {$ELSE} Classes, {$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES} ADAPT.Common.Intf, ADAPT.Common, ADAPT.Generics.Lists.Intf, ADAPT.Generics.Maps.Intf, Steam.Common.Intf; type // Forward Declarations ISteamApi = interface; ISteamWebApiInterfaceMethod = interface; ISteamWebApiInterface = interface; ISteamWebApiUtil = interface; ISteamApps = interface; // Generic Collections ISteamWebApiInterfaceMethodList = IADList<ISteamWebApiInterfaceMethod>; ISteamWebApiInterfaceList = IADList<ISteamWebApiInterface>; ISteamApi = interface(IADInterface) ['{2915FC43-626C-4F5D-8280-88329701CF0B}'] end; ISteamWebApiInterfaceMethod = interface(IADInterface) ['{A379A5CA-C512-4753-B52A-BA6972249380}'] end; ISteamWebApiInterface = interface(IADInterface) ['{FEE3007C-5EC1-4C60-B309-D1A2EF120703}'] // Getters function GetName: String; // Properties property Name: String read GetName; end; ISteamWebApiUtil = interface(ISteamApi) ['{17F1051C-47B6-43F0-8624-14BA28EDAB47}'] // Api Getters function GetSupportedApiList: ISteamWebApiInterfaceList; // Properties property SupportedApiList: ISteamWebApiInterfaceList read GetSupportedApiList; end; ISteamApps = interface(ISteamApi) ['{C028FD5E-BDA5-4677-877E-581EE3280582}'] // Api Getters function GetAppList: ISteamAppList; // Properties property AppList: ISteamAppList read GetAppList; end; implementation end.
unit rsEMC_TLB; interface uses Winapi.ActiveX; const rsEMCMajorVersion = 1; rsEMCMinorVersion = 0; LIBID_rsEMC: TGUID = '{073DCFC8-9A65-49E0-858D-45D4A4BC7904}'; // IID constants IID_IrsEMCAntenna: TGUID = '{554CFF64-EC3E-488E-8F63-0C3E3CB3C712}'; IID_IrsFreqMaskList: TGUID = '{9C601EF2-0768-4C1B-BAB4-2D98E5DF39F0}'; IID_IrsEMCRadioStation: TGUID = '{D43FAB7A-DC18-485E-A705-B13078C2EF48}'; IID_IrsEMCTx: TGUID = '{803EA695-5831-4235-9859-7E6CCF39565B}'; IID_IrsEMCRx: TGUID = '{D93509FF-E2D2-43DA-AE43-88D46A52B220}'; IID_IrsEMCDBStation: TGUID = '{C7685B75-8CD4-41F1-B3A3-96662772B48C}'; IID_IrsEMCCalcModeData: TGUID = '{DEF540FB-54D9-4404-B46E-7D61DCB691D8}'; IID_IrsEMCEChart: TGUID = '{1D976C64-EAFF-495E-AC42-D6D0CF429048}'; IID_IrsEMCEField: TGUID = '{EA46802E-359B-4B61-AF90-23E7D5329B69}'; // Enumerators type TSeaTemperature = type TOleEnum; const stNone = TSeaTemperature($00000000); stCold = TSeaTemperature($00000001); stWarm = TSeaTemperature($00000002); stBlackSea = TSeaTemperature($00000003); type TPolarization = type TOleEnum; const pNone = TPolarization($00000000); pVert = TPolarization($00000001); pHorz = TPolarization($00000002); type TIsotropType = type TOleEnum; const itNone = TIsotropType($00000000); itIsotropic = TIsotropType($00000001); itAnisotropic = TIsotropType($00000002); type TMultiInterferense = type TOleEnum; const miAdd = TMultiInterferense($00000000); miMultiply = TMultiInterferense($00000001); type TGroundCover = type TOleEnum; const gcNone = TGroundCover($00000000); gcRural = TGroundCover($00000001); gcOpenSuburban = TGroundCover($00000002); gcSuburban = TGroundCover($00000003); gcUrbanWooded = TGroundCover($00000004); gcDenseUrban = TGroundCover($00000005); type TAntennaKind = type TOleEnum; const akNone = TAntennaKind($00000000); akCollinear = TAntennaKind($00000001); akCollinearArray = TAntennaKind($00000002); akParabolic = TAntennaKind($00000003); type TSignalKind = type TOleEnum; const skService = TSignalKind($00000000); skInterference = TSignalKind($00000001); type TRadioKind = type TOleEnum; const rkBroadcast = TRadioKind($00000000); rkMobile = TRadioKind($00000001); type TDigitalOrAnalogue = type TOleEnum; const daNone = TDigitalOrAnalogue($00000000); daDigital = TDigitalOrAnalogue($00000001); daAnalogue = TDigitalOrAnalogue($00000002); type TClearanceFlag = type TOleEnum; const cfTx = TClearanceFlag($00000000); cfRx = TClearanceFlag($00000001); type TStationFlag = type TOleEnum; const sfTx = TStationFlag($00000001); sfRx = TStationFlag($00000002); sfMobile = TStationFlag($00000004); sfChecked = TStationFlag($00000008); sfTxIntermod = TStationFlag($00000010); type TStrengthFormat = type TOleEnum; const sfDBm = TStrengthFormat($00000000); sfDBW = TStrengthFormat($00000001); sfDBmcVm = TStrengthFormat($00000002); type TEMCJobType = type TOleEnum; const jtNo = TEMCJobType($00000001); jtSingleTrace = TEMCJobType($00000002); jtBlockage = TEMCJobType($00000004); jtMirror = TEMCJobType($00000008); jtHarmonic = TEMCJobType($00000010); jtIntermod = TEMCJobType($00000020); jtNear = TEMCJobType($00000040); jtEChart = TEMCJobType($00000080); jtPChart = TEMCJobType($00000100); jtBorderLine = TEMCJobType($00000200); jtBLIntraAzimuths = TEMCJobType($00000400); jtBLAzimuths = TEMCJobType($00000800); jtBLIntra = TEMCJobType($00001000); jtRoofTrace = TEMCJobType($00002000); type TGeterodin = type TOleEnum; const gdLowest = TGeterodin($FFFFFFFF); gdUndefined = TGeterodin($00000000); gdHighest = TGeterodin($00000001); type TFarZoneCalcMode = type TOleEnum; const cmFreeSpaceFlatEarth = TFarZoneCalcMode($00000000); cmHCM = TFarZoneCalcMode($00000001); cm1146 = TFarZoneCalcMode($00000002); cm1546 = TFarZoneCalcMode($00000003); cmHata = TFarZoneCalcMode($00000004); cmCost231Hata = TFarZoneCalcMode($00000005); cmCost231Wolfis = TFarZoneCalcMode($00000006); cmDeygout = TFarZoneCalcMode($00000007); type TNearZoneCalcMode = type TOleEnum; const cmOurSite = TNearZoneCalcMode($00000000); type TEMCErrorCode = type TOleEnum; const ecNone = TEMCErrorCode($00000000); ecUserTerminate = TEMCErrorCode($00000001); ecInvalidCalcMode = TEMCErrorCode($00000002); ecNotCalculated = TEMCErrorCode($00000003); ecNoRxInData = TEMCErrorCode($00000004); ecNoTxInData = TEMCErrorCode($00000005); ecTxCountFailed = TEMCErrorCode($00000006); ecAntennaHeight = TEMCErrorCode($00000007); ecTxAndRxInTheSamePoint = TEMCErrorCode($00000008); ecNoProfile = TEMCErrorCode($00000009); ecNoDistance = TEMCErrorCode($0000000A); ecNoMethodForFreq = TEMCErrorCode($0000000B); ecFreqNotInValidRange = TEMCErrorCode($0000000C); ecVeryLongDistance = TEMCErrorCode($0000000D); ecInvalidPolarization = TEMCErrorCode($0000000E); ecInvalidTimePercent = TEMCErrorCode($0000000F); ecInvalidAntennaKind = TEMCErrorCode($00000010); ecInvalidElevation = TEMCErrorCode($00000011); ecInvalidAzimuth = TEMCErrorCode($00000012); ecInvalidVienDNA = TEMCErrorCode($00000013); ecBandWidthInvalid = TEMCErrorCode($00000014); ecInvalidRSDataFormat = TEMCErrorCode($00000015); ecNoDistanceForChart = TEMCErrorCode($00000016); ecInvalidStrengthFormat = TEMCErrorCode($00000017); ecInvalidDeygoutGeometry = TEMCErrorCode($00000018); ecNoDll = TEMCErrorCode($00000019); ecBadDll = TEMCErrorCode($0000001A); type // Interfaces forward declarations IrsEMCAntenna = interface; IrsFreqMaskList = interface; IrsEMCRadioStation = interface; IrsEMCTx = interface; IrsEMCRx = interface; IrsEMCDBStation = interface; IrsEMCCalcModeData = interface; IrsEMCEChart = interface; IrsEMCEField = interface; type // Aliaces TAngle = type Double; TAntennaHorVertType = type WideString; TRealHeight = type Double; TStrength = type Double; TDistance = type Double; TFreq = type Double; TAzimuth = type TAngle; TPercent = type Byte; TPower = type Double; type // Records T3DPoint = record X: Double; Y: Double; Z: Double; end; TSector = record Center: TGeoPoint; Radius: TDistance; Bisectrix: TAzimuth; Opening: TAzimuth; end; TFreqMaskPoint = record DF: TFreq; Level: TStrength; end; type // Interfaces IrsEMCAntenna = interface(IUnknown) ['{554CFF64-EC3E-488E-8F63-0C3E3CB3C712}'] function Get_Azimuth: TAngle; safecall; procedure Set_Azimuth(AVal: TAngle); safecall; function Get_HorType: TAntennaHorVertType; safecall; procedure Set_HorType(const AVal: TAntennaHorVertType); safecall; function Get_VertType: TAntennaHorVertType; safecall; procedure Set_VertType(const AVal: TAntennaHorVertType); safecall; function Get_Ele: TAngle; safecall; procedure Set_Ele(AVal: TAngle); safecall; function Get_Isotrop: TIsotropType; safecall; procedure Set_Isotrop(AVal: TIsotropType); safecall; function Get_Height: TRealHeight; safecall; procedure Set_Height(AVal: TRealHeight); safecall; function Get_Polarization: TPolarization; safecall; procedure Set_Polarization(AVal: TPolarization); safecall; function Get_Kind: TAntennaKind; safecall; procedure Set_Kind(AVal: TAntennaKind); safecall; function Get_L: TRealHeight; safecall; procedure Set_L(AVal: TRealHeight); safecall; function Get_Tetta: TAngle; safecall; procedure Set_Tetta(AVal: TAngle); safecall; function Get_Gain: TStrength; safecall; procedure Set_Gain(AVal: TStrength); safecall; function Get_DP: TStrength; safecall; procedure Set_DP(AVal: TStrength); safecall; function DirectionGain(APointAzimuth: TAngle; APointElevation: TAngle): TStrength; safecall; property Azimuth: TAngle read Get_Azimuth write Set_Azimuth; property HorType: TAntennaHorVertType read Get_HorType write Set_HorType; property VertType: TAntennaHorVertType read Get_VertType write Set_VertType; property Ele: TAngle read Get_Ele write Set_Ele; property Isotrop: TIsotropType read Get_Isotrop write Set_Isotrop; property Height: TRealHeight read Get_Height write Set_Height; property Polarization: TPolarization read Get_Polarization write Set_Polarization; property Kind: TAntennaKind read Get_Kind write Set_Kind; property L: TRealHeight read Get_L write Set_L; property Tetta: TAngle read Get_Tetta write Set_Tetta; property Gain: TStrength read Get_Gain write Set_Gain; property DP: TStrength read Get_DP write Set_DP; end; IrsFreqMaskList = interface(IUnknown) ['{9C601EF2-0768-4C1B-BAB4-2D98E5DF39F0}'] function Get_Count: Integer; safecall; function Get_Items(AIdx: Integer): TFreqMaskPoint; safecall; procedure Add(AVal: TFreqMaskPoint); safecall; function OutOfMask(ADF: TFreq): WordBool; safecall; function Level(ADF: TFreq): TStrength; safecall; property Count: Integer read Get_Count; property Items[AIdx: Integer]: TFreqMaskPoint read Get_Items; default; end; IrsEMCRadioStation = interface(IUnknown) ['{D43FAB7A-DC18-485E-A705-B13078C2EF48}'] function Get_Tag: OLE_HANDLE; safecall; procedure Set_Tag(AVal: OLE_HANDLE); safecall; function Get_Color: OLE_COLOR; safecall; procedure Set_Color(AVal: OLE_COLOR); safecall; function Get_Flag: Cardinal; safecall; procedure Set_Flag(AVal: Cardinal); safecall; function Get_Id: Integer; safecall; procedure Set_Id(AVal: Integer); safecall; function Get_SectorId: Integer; safecall; procedure Set_SectorId(AVal: Integer); safecall; function Get_RoofId: Integer; safecall; procedure Set_RoofId(AVal: Integer); safecall; function Get_NetId: Integer; safecall; procedure Set_NetId(AVal: Integer); safecall; function Get_ClassSt: WideString; safecall; procedure Set_ClassSt(const AVal: WideString); safecall; function Get_Name: WideString; safecall; procedure Set_Name(const AVal: WideString); safecall; function Get_System: WideString; safecall; procedure Set_System(const AVal: WideString); safecall; function Get_StandardID: Integer; safecall; procedure Set_StandardID(AVal: Integer); safecall; function Get_DuplexStandart: WordBool; safecall; procedure Set_DuplexStandart(AVal: WordBool); safecall; function Get_Place: TGeoPoint; safecall; procedure Set_Place(AVal: TGeoPoint); safecall; function Get_RoofPlace: T3DPoint; safecall; procedure Set_RoofPlace(AVal: T3DPoint); safecall; function Get_ServiceArea: TDistance; safecall; procedure Set_ServiceArea(AVal: TDistance); safecall; function Get_Freq: TFreq; safecall; procedure Set_Freq(AVal: TFreq); safecall; function Get_DFreq: TFreq; safecall; procedure Set_DFreq(AVal: TFreq); safecall; function Get_Radiation: WideString; safecall; procedure Set_Radiation(const AVal: WideString); safecall; function Get_PathAttenuation: TStrength; safecall; procedure Set_PathAttenuation(AVal: TStrength); safecall; function Get_Antenna: IrsEMCAntenna; safecall; procedure Precalculate(ACurFreq: TFreq); safecall; function EToU(AE: TStrength): TStrength; safecall; function UToE(AU: TStrength): TStrength; safecall; function IsMobile: WordBool; safecall; function ServiceZone: TSector; safecall; procedure LoadFromStream(const AStrm: IStream); safecall; procedure SaveToStream(const AStrm: IStream); safecall; function Get_FreqMask: IrsFreqMaskList; safecall; function Get_Filter: IrsFreqMaskList; safecall; property Tag: OLE_HANDLE read Get_Tag write Set_Tag; property Color: OLE_COLOR read Get_Color write Set_Color; property Flag: Cardinal read Get_Flag write Set_Flag; property Id: Integer read Get_Id write Set_Id; property SectorId: Integer read Get_SectorId write Set_SectorId; property RoofId: Integer read Get_RoofId write Set_RoofId; property NetId: Integer read Get_NetId write Set_NetId; property ClassSt: WideString read Get_ClassSt write Set_ClassSt; property Name: WideString read Get_Name write Set_Name; property System: WideString read Get_System write Set_System; property StandardID: Integer read Get_StandardID write Set_StandardID; property DuplexStandart: WordBool read Get_DuplexStandart write Set_DuplexStandart; property Place: TGeoPoint read Get_Place write Set_Place; property RoofPlace: T3DPoint read Get_RoofPlace write Set_RoofPlace; property ServiceArea: TDistance read Get_ServiceArea write Set_ServiceArea; property Freq: TFreq read Get_Freq write Set_Freq; property DFreq: TFreq read Get_DFreq write Set_DFreq; property Radiation: WideString read Get_Radiation write Set_Radiation; property PathAttenuation: TStrength read Get_PathAttenuation write Set_PathAttenuation; property Antenna: IrsEMCAntenna read Get_Antenna; property FreqMask: IrsFreqMaskList read Get_FreqMask; property Filter: IrsFreqMaskList read Get_Filter; end; IrsEMCTx = interface(IrsEMCRadioStation) ['{803EA695-5831-4235-9859-7E6CCF39565B}'] function Get_MaPo: TPower; safecall; procedure Set_MaPo(AVal: TPower); safecall; function Get_TimePercent: TPercent; safecall; procedure Set_TimePercent(AVal: TPercent); safecall; function Get_Lambda: Double; safecall; procedure Set_Lambda(AVal: Double); safecall; property MaPo: TPower read Get_MaPo write Set_MaPo; property TimePercent: TPercent read Get_TimePercent write Set_TimePercent; property Lambda: Double read Get_Lambda write Set_Lambda; end; IrsEMCRx = interface(IrsEMCRadioStation) ['{D93509FF-E2D2-43DA-AE43-88D46A52B220}'] function Get_Selectivity: TStrength; safecall; procedure Set_Selectivity(AVal: TStrength); safecall; function Get_Protection: TStrength; safecall; procedure Set_Protection(AVal: TStrength); safecall; function Get_UHFBand: TFreq; safecall; procedure Set_UHFBand(AVal: TFreq); safecall; function Get_SelfIsolation: TStrength; safecall; procedure Set_SelfIsolation(AVal: TStrength); safecall; function Get_FreqInter: TFreq; safecall; procedure Set_FreqInter(AVal: TFreq); safecall; function Get_Geterodin: TGeterodin; safecall; procedure Set_Geterodin(AVal: TGeterodin); safecall; function Get_Blockage: TStrength; safecall; procedure Set_Blockage(AVal: TStrength); safecall; function Get_EMirror: TStrength; safecall; procedure Set_EMirror(AVal: TStrength); safecall; function Get_EIntermod: TStrength; safecall; procedure Set_EIntermod(AVal: TStrength); safecall; property Selectivity: TStrength read Get_Selectivity write Set_Selectivity; property Protection: TStrength read Get_Protection write Set_Protection; property UHFBand: TFreq read Get_UHFBand write Set_UHFBand; property SelfIsolation: TStrength read Get_SelfIsolation write Set_SelfIsolation; property FreqInter: TFreq read Get_FreqInter write Set_FreqInter; property Geterodin: TGeterodin read Get_Geterodin write Set_Geterodin; property Blockage: TStrength read Get_Blockage write Set_Blockage; property EMirror: TStrength read Get_EMirror write Set_EMirror; property EIntermod: TStrength read Get_EIntermod write Set_EIntermod; end; IrsEMCDBStation = interface(IUnknown) ['{C7685B75-8CD4-41F1-B3A3-96662772B48C}'] procedure Precalculate; safecall; procedure LoadFromStream(const AVal: IStream); safecall; procedure SaveToStream(const AVal: IStream); safecall; function IsMobile: WordBool; safecall; function Get_Id: Integer; safecall; procedure Set_Id(AVal: Integer); safecall; function Get_SectorId: Integer; safecall; procedure Set_SectorId(AVal: Integer); safecall; function Get_RoofId: Integer; safecall; procedure Set_RoofId(AVal: Integer); safecall; function Get_NetId: Integer; safecall; procedure Set_NetId(AVal: Integer); safecall; function Get_VariantNumber: Integer; safecall; procedure Set_VariantNumber(AVal: Integer); safecall; function Get_TableName: WideString; safecall; procedure Set_TableName(const AVal: WideString); safecall; function Get_Country: WideString; safecall; procedure Set_Country(const AVal: WideString); safecall; function Get_System: WideString; safecall; procedure Set_System(const AVal: WideString); safecall; function Get_StandardID: Integer; safecall; procedure Set_StandardID(AVal: Integer); safecall; function Get_Owner: WideString; safecall; procedure Set_Owner(const AVal: WideString); safecall; function Get_Hint: WideString; safecall; procedure Set_Hint(const AVal: WideString); safecall; function Get_Tx: IrsEMCTx; safecall; function Get_Rx: IrsEMCRx; safecall; property Id: Integer read Get_Id write Set_Id; property SectorId: Integer read Get_SectorId write Set_SectorId; property RoofId: Integer read Get_RoofId write Set_RoofId; property NetId: Integer read Get_NetId write Set_NetId; property VariantNumber: Integer read Get_VariantNumber write Set_VariantNumber; property TableName: WideString read Get_TableName write Set_TableName; property Country: WideString read Get_Country write Set_Country; property System: WideString read Get_System write Set_System; property StandardID: Integer read Get_StandardID write Set_StandardID; property Owner: WideString read Get_Owner write Set_Owner; property Hint: WideString read Get_Hint write Set_Hint; property Tx: IrsEMCTx read Get_Tx; property Rx: IrsEMCRx read Get_Rx; end; IrsEMCCalcModeData = interface(IUnknown) ['{DEF540FB-54D9-4404-B46E-7D61DCB691D8}'] function Get_FarMethodCount: Integer; safecall; function Get_FarMethod(AIdx: Integer): TFarZoneCalcMode; safecall; procedure AddFarMethod(AMethod: TFarZoneCalcMode); safecall; procedure ClearFarMethods; safecall; procedure EditFarMethods; safecall; function Get_MethodR: TDistance; safecall; procedure Set_MethodR(AVal: TDistance); safecall; function Get_OnlyFarZone: WordBool; safecall; procedure Set_OnlyFarZone(AVal: WordBool); safecall; function Get_NearMethod: TNearZoneCalcMode; safecall; procedure Set_NearMethod(AVal: TNearZoneCalcMode); safecall; function Get_CalculateSignal: WordBool; safecall; procedure Set_CalculateSignal(AVal: WordBool); safecall; function Get_UseProfile: WordBool; safecall; procedure Set_UseProfile(AVal: WordBool); safecall; function Get_UseMorpho: WordBool; safecall; procedure Set_UseMorpho(AVal: WordBool); safecall; function Get_LocationVariability: Double; safecall; procedure Set_LocationVariability(AVal: Double); safecall; function Get_SeaTem: TSeaTemperature; safecall; procedure Set_SeaTem(AVal: TSeaTemperature); safecall; function Get_HarmonicNumber: Integer; safecall; procedure Set_HarmonicNumber(AVal: Integer); safecall; function Get_BaseAzimuth: TAzimuth; safecall; procedure Set_BaseAzimuth(AVal: TAzimuth); safecall; function Get_JobType: TEMCJobType; safecall; procedure Set_JobType(AVal: TEMCJobType); safecall; function Get_KnownLoss: TStrength; safecall; procedure Set_KnownLoss(AVal: TStrength); safecall; function Get_GroundCover: TGroundCover; safecall; procedure Set_GroundCover(AVal: TGroundCover); safecall; function Get_StandardProfileIncrement: TDistance; safecall; procedure Set_StandardProfileIncrement(AVal: TDistance); safecall; property FarMethodCount: Integer read Get_FarMethodCount; property FarMethod[AIdx: Integer]: TFarZoneCalcMode read Get_FarMethod; default; property MethodR: TDistance read Get_MethodR write Set_MethodR; property OnlyFarZone: WordBool read Get_OnlyFarZone write Set_OnlyFarZone; property NearMethod: TNearZoneCalcMode read Get_NearMethod write Set_NearMethod; property CalculateSignal: WordBool read Get_CalculateSignal write Set_CalculateSignal; property UseProfile: WordBool read Get_UseProfile write Set_UseProfile; property UseMorpho: WordBool read Get_UseMorpho write Set_UseMorpho; property LocationVariability: Double read Get_LocationVariability write Set_LocationVariability; property SeaTem: TSeaTemperature read Get_SeaTem write Set_SeaTem; property HarmonicNumber: Integer read Get_HarmonicNumber write Set_HarmonicNumber; property BaseAzimuth: TAzimuth read Get_BaseAzimuth write Set_BaseAzimuth; property JobType: TEMCJobType read Get_JobType write Set_JobType; property KnownLoss: TStrength read Get_KnownLoss write Set_KnownLoss; property GroundCover: TGroundCover read Get_GroundCover write Set_GroundCover; property StandardProfileIncrement: TDistance read Get_StandardProfileIncrement write Set_StandardProfileIncrement; end; IrsEMCEChart = interface(IUnknown) ['{1D976C64-EAFF-495E-AC42-D6D0CF429048}'] function Get_AzimuthStep: TAzimuth; safecall; procedure Set_AzimuthStep(AVal: TAzimuth); safecall; function Get_Distance: TDistance; safecall; procedure Set_Distance(AVal: TDistance); safecall; function Get_RayCount: Integer; safecall; function Get_PointCount: Integer; safecall; function Get_CenterPoint: TGeoPoint; safecall; function Get_ErrorCode: TEMCErrorCode; safecall; function Get_ErrorMessage: WideString; safecall; function IsCalculated: WordBool; safecall; function Get_EC(AGeoP: TGeoPoint): TStrength; safecall; function Get_MaxEC: TStrength; safecall; function Get_MinEC: TStrength; safecall; function Get_ResultFmt: TStrengthFormat; safecall; procedure Set_ResultFmt(AVal: TStrengthFormat); safecall; function Get_NodeCount: Integer; safecall; function Get_NodePoint(AIdx: Integer): TGeoPoint; safecall; function Get_NodeStrength(AIdx: Integer): TStrength; safecall; procedure Run; safecall; function Get_Tx: IrsEMCTx; safecall; function Get_Rx: IrsEMCRx; safecall; function Get_CalcModeData: IrsEMCCalcModeData; safecall; function Get_EArray: VOID; safecall; property AzimuthStep: TAzimuth read Get_AzimuthStep write Set_AzimuthStep; property Distance: TDistance read Get_Distance write Set_Distance; property RayCount: Integer read Get_RayCount; property PointCount: Integer read Get_PointCount; property CenterPoint: TGeoPoint read Get_CenterPoint; property EC[AGeoP: TGeoPoint]: TStrength read Get_EC; property MaxEC: TStrength read Get_MaxEC; property MinEC: TStrength read Get_MinEC; property ResultFmt: TStrengthFormat read Get_ResultFmt write Set_ResultFmt; property NodeCount: Integer read Get_NodeCount; property NodePoint[AIdx: Integer]: TGeoPoint read Get_NodePoint; property NodeStrength[AIdx: Integer]: TStrength read Get_NodeStrength; property Tx: IrsEMCTx read Get_Tx; property Rx: IrsEMCRx read Get_Rx; property CalcModeData: IrsEMCCalcModeData read Get_CalcModeData; end; IrsEMCEField = interface(IrsEMCEChart) ['{EA46802E-359B-4B61-AF90-23E7D5329B69}'] function Get_MinGeoCorner: TGeoPoint; safecall; function Get_MaxGeoCorner: TGeoPoint; safecall; function Get_LatStep: TGeoCoord; safecall; function Get_LonStep: TGeoCoord; safecall; function Get_Poligons(ALevel: TStrength): IUnknown; safecall; property MinGeoCorner: TGeoPoint read Get_MinGeoCorner; property MaxGeoCorner: TGeoPoint read Get_MaxGeoCorner; property LatStep: TGeoCoord read Get_LatStep; property LonStep: TGeoCoord read Get_LonStep; property Poligons[ALevel: TStrength]: IUnknown read Get_Poligons; end;
{ CSI 1101-X, Winter 1999, A6q1 } { Mark Sattolo, student# 428500 } {* The Bracket Matching Algorithm used in this program --------------------------------------------------------- This follows very closely what was described in class. It is implemented in three procedures; the names are not the ones used in class but their functions are the same: Brackets, Process_right_bracket, Convert_left_to_right, Convert_to_postfix. Procedure BRACKETS: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Repeat the following until end-of-line: 1. Read the next character. 2. If it is NOT a right bracket, push it on the stack S. 3. If it is a right bracket, do the following (a) procedure PROCESS_RIGHT_BRACKET: Pop characters off of stack S and push them onto a temporary stack until you reach a left bracket (this is the bracket that matches with the right bracket you just read). Pop that bracket off of S. The temporary stack now contains all the characters that were in-between the two brackets, and they are in the same order that they were initially read (the first one read is on the top of the temporary stack). (b) procedure CONVERT_LEFT_TO_RIGHT: "Process" the characters between the two brackets (i.e. the ones that are on the temporary stack). In general you can do any sort of processing you like. For example, you could evaluate this expression. In the current program, the infix expression is converted to postfix (this is done by successive calls to "Convert_to_postfix"). (c) The processing in step (b), whatever it is, is assumed to return an "answer". In this case the answer returned is a string containing a postfix expression. PUSH this answer onto stack S. (d) When end-of-line is encountered, you need to do exactly the same processing as in step 3, EXCEPT: there is no left bracket on stack S to "match" with end-of-line, so the loop in 3(a) will not terminate. I could have written a separate procedure to handle end-of-line, but instead I used a "trick" which allows me to use the procedure "Process_right_bracket" when I encounter end-of-line. The "trick" is to treat beginning-of-line as a left bracket and end-of-line as its matching right bracket. The way this is implemented is simply to push a left bracket onto stack S just before reading begins. When end-of-line is encountered, "Process_right_bracket" is called and the left bracket representing beginning-of-line is sitting at the bottom of stack S. *} program EqnEval (input,output) ; uses EqnTPU ; { CONVERT_LEFT_TO_RIGHT - the given stack, "tokens", contains an infix expression with no brackets, just operators and operands, with top-to-bottom in "tokens" corresponding to left-to-right in the order the user entered the infix expression. The result ("result") is a postfix expression corresponding to the infix one given in "tokens". "tokens" itself becomes empty. This procedure does no error checking, so if an incorrect expression is entered between brackets it will crash. You are not required to fix this - but be careful not to enter expressions such as (1+). } procedure convert_left_to_right(var tokens: stack; var result: element); var L, OP, R: element; BEGIN L := top(tokens); pop(tokens); while (tokens.size > 0) do BEGIN pull(OP, tokens) ; pull(R, tokens) ; L := Eval(L, R, OP[1]) END; { while } result := L END; { proc convert_ltr } { PROCESS_RIGHT_BRACKET - pops items off of stack S and onto a temporary stack, BetweenBrackets, until a left bracket is encountered, at which time BetweenBrackets is passed to convert_left_to_right. The postfix expression returned by this is pushed onto S. } procedure process_right_bracket(var S:stack; var error:boolean); var BetweenBrackets: stack ; V: element ; done: boolean ; BEGIN create_stack(BetweenBrackets) ; done := false ; while (not done) do {*} BEGIN { detect missing left bracket } if (S.size <= 0) then BEGIN if not error then { if multiple omissions } writeln('Error: Missing left bracket(s). Processing was terminated because') ; error := true ; { destroy any existing nodes if an error was found } destroy(BetweenBrackets) ; { needed before 'exit' because this exits the } exit ; { entire procedure } END { if } {$} else BEGIN pull(V, S) ; if V = '(' then done := true else push(V, BetweenBrackets) ; END { else } END; { while } { detect mismatched brackets and prevent an error for the "nil" expression } {*} if (BetweenBrackets.size > 0) then BEGIN convert_left_to_right(BetweenBrackets,V); push(V, S) {*} END; { else } END; { proc process_rb } { BRACKETS - reads in one character at a time from the input line; if the character is not a ')' it pushes it onto a stack ("S"), if it is a ')' then process_right_bracket is called with stack "S". When end-of-line is reached process_right_bracket is called one more time - in order to make this call work correctly it is necessary to initially push onto "S" a '(' that corresponds to the imaginary ')' that end-of-line represents. } procedure Brackets (var V: element; var error:boolean) ; var S: stack ; E, X: element ; BEGIN V := '' ; { initialize V to prevent erroneous output for "nil" expression } error := false ; { set initial error to false } create_stack(S); push('(', S) ; {* trick to allow us to use same code for ')' and end-of-line *} readln(E) ; while (length(E) > 0) do BEGIN get_X(E, X) ; if X=')' then process_right_bracket(S, error) else push(X, S) ; END; { while } process_right_bracket(S, error) ; { do not process if S is empty } {*} if (S.size > 0) then {$} BEGIN pull(V, S) ; { detect missing right bracket } {*} if (S.size > 0) then BEGIN writeln('Error: Missing right bracket(s). Processing was terminated because') ; error := true ; END { if #2 } END; { if #1 } { destroy the existing nodes if an error was declared } if error then {$} destroy(S) ; END; { proc Brackets } procedure go ; var answer: element; error: boolean ; BEGIN writeln; writeln('Please enter a numeric expression: '); writeln(' <[ div = /, mult = *, power = ^, brackets = () ]> ') ; Brackets(answer, error); if error then writeln('your expression contained mismatched brackets.') else BEGIN write('Your expression evaluates to: '); writeln(answer) END { else } END; { proc go } BEGIN { main program } identify_myself ; repeat mem_count := 0 ; go ; if ( mem_count <> 0 ) then writeln('Memory Leak! Dynamic memory allocated but not returned: ', mem_count:0) ; writeln('Do you wish to continue (y or n) ?') ; readln(continue) until continue in [ 'n', 'N' ] ; writeln('PROGRAM ENDED.') END.
{ Faça um algoritmo utilizando sub-rotinas que leia um vetor de registros com os campos: nome, idade e sexo de N (N<=20) pessoas. Após a leitura faça: a) Imprima o Nome, idade e sexo das pessoas cuja idade seja maior que a idade da primeira pessoa. b) Imprima o Nome e idade de todas as mulheres. c) Imprima o Nome dos homens menores de 21 anos. } Program Exercicio7 ; Type reg_pessoa = record nome: string; sexo: char; idade: integer; end; vet_pessoas = array[1..20] of reg_pessoa; var pessoas:vet_pessoas; n:integer; Procedure cadastrarPessoas(var vet: vet_pessoas; n: integer); var sexo: char; i: integer; begin for i := 1 to n do begin write('Nome da pessoa ', i, ': '); readln(vet[i].nome); write('Idade da pessoa ', i, ': '); readln(vet[i].idade); repeat write('Sexo da pessoa ', i, '(Digite m ou f): '); readln(sexo); // sexo := UpperCase(sexo); ClrScr; until(sexo = 'm') or (sexo = 'f'); vet[i].sexo := sexo; end; end; procedure verificarQuantidade(var qtd:integer); begin repeat write('Digite a quantidade de pessoas entre 1 e 20: '); readln(n); until (qtd >0) and (qtd <= 20); end; procedure imprimirPessoasIdadeMaiorQue(idade:integer; pessoas:vet_pessoas; n:integer); var i:integer; begin writeln('Idade maiores que ',idade,' de ', pessoas[1].nome); for i := 1 to n do begin; if(pessoas[i].idade > idade) then writeln('-> ', pessoas[i].nome, ' (sexo: ',pessoas[i].sexo,'| idade: ',pessoas[i].idade,')'); end; end; procedure imprimirPessoasPorSexoeIdade(pessoas:vet_pessoas;sexo:char; idade:integer); var i:integer; begin for i := 1 to n do begin if((pessoas[i].sexo = sexo) and (pessoas[i].idade > idade)) then writeln('-> ', pessoas[i].nome, ' (sexo: ',pessoas[i].sexo,'| idade: ',pessoas[i].idade,')'); end; end; Begin verificarQuantidade(n); cadastrarPessoas(pessoas, n); imprimirPessoasIdadeMaiorQue(pessoas[1].idade, pessoas, n); //da para simplificar e por no método abaixo writeln('------------------Todas as Mulheres---------------'); imprimirPessoasPorSexoeIdade(pessoas, 'f', 0); //mulheres com idade acima de 0 anos writeln('------------------Todas os Homens acima de 21 anos---------------'); imprimirPessoasPorSexoeIdade(pessoas, 'm', 21); //homens com idade acima de 21 anos End.
{******************************************************************************} { } { Library: Fundamentals 5.00 } { File name: flcCryptoRandom.pas } { File version: 5.07 } { Description: Crypto random } { } { Copyright: Copyright (c) 2010-2021, David J Butler } { All rights reserved. } { This file is licensed under the BSD License. } { See http://www.opensource.org/licenses/bsd-license.php } { Redistribution and use in source and binary forms, with } { or without modification, are permitted provided that } { the following conditions are met: } { Redistributions of source code must retain the above } { copyright notice, this list of conditions and the } { following disclaimer. } { 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 REGENTS 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. } { } { Github: https://github.com/fundamentalslib } { E-mail: fundamentals.library at gmail.com } { } { Revision history: } { } { 2010/12/17 4.01 Initial version. } { 2013/09/25 4.02 UnicodeString version. } { 2015/05/05 4.03 Multiple PRNGs and PRSS and SHA512 hash in random block } { generator. } { 2016/01/09 5.04 Revised for Fundamentals 5. } { 2019/06/06 5.05 SecureRandomBytes function. } { 2020/02/13 5.06 Remove MD5 from generator. } { Use 8 random bits in generator for each secure } { random bit. } { 2020/07/07 5.07 NativeInt changes. } { } {******************************************************************************} {$INCLUDE ..\flcInclude.inc} {$INCLUDE flcCrypto.inc} unit flcCryptoRandom; interface uses { System } SysUtils, { Fundamentals } flcStdTypes; procedure SecureRandomBuf(var Buf; const Size: NativeInt); function SecureRandomBytes(const Size: NativeInt): TBytes; function SecureRandomStrB(const Size: NativeInt): RawByteString; function SecureRandomHexStr(const Digits: Integer; const UpperCase: Boolean = True): String; function SecureRandomHexStrB(const Digits: Integer; const UpperCase: Boolean = True): RawByteString; function SecureRandomHexStrU(const Digits: Integer; const UpperCase: Boolean = True): UnicodeString; function SecureRandomWord32: Word32; implementation uses { Fundamentals } flcUtils, flcRandom, flcCryptoUtils, flcCryptoHash; const SecureRandomBlockBits = 128; SecureRandomBlockSize = SecureRandomBlockBits div 8; // 16 bytes type TSecureRandomBlock = array[0..SecureRandomBlockSize - 1] of Byte; PSecureRandomBlock = ^TSecureRandomBlock; // produces a block of SecureRandomBlockSize bytes of secure random material procedure SecureRandomBlockGenerator(var Block: TSecureRandomBlock); const RandomDataBits = SecureRandomBlockBits * 8; // 1024 bits (128 bytes) RandomDataLen = RandomDataBits div 32; // 32 * Word32 var I : Integer; RData : array[0..RandomDataLen - 1] of Word32; S32 : Word32; H512 : T512BitDigest; H256 : T256BitDigest; begin try // initialise 1024 bits with multiple Pseudo Random Numbers Generators (PRNG) // and Pseudo Random System State (PRSS) FillChar(RData, SizeOf(RData), $FF); S32 := RandomSeed32; RData[0] := RData[0] xor S32; for I := 0 to RandomDataLen - 1 do RData[I] := RData[I] xor RandomUniform32; for I := 0 to RandomDataLen - 1 do RData[I] := RData[I] xor urnRandom32; S32 := RandomSeed32; RData[RandomDataLen - 1] := RData[RandomDataLen - 1] xor S32; // hash 1024 bits using SHA512 into 512 bits H512 := CalcSHA512(RData, SizeOf(RData)); // hash 512 bits using SHA256 into 256 bits H256 := CalcSHA256(H512, SizeOf(T512BitDigest)); // move 128 bits to secure random block Assert(SizeOf(H256) >= SecureRandomBlockSize); Move(H256, Block, SecureRandomBlockSize); finally SecureClearBuf(H256, SizeOf(T256BitDigest)); SecureClearBuf(H512, SizeOf(T512BitDigest)); SecureClearBuf(RData, SizeOf(RData)); end; end; procedure SecureRandomBuf(var Buf; const Size: NativeInt); var P : PSecureRandomBlock; L : NativeInt; B : TSecureRandomBlock; begin P := @Buf; L := Size; while L >= SecureRandomBlockSize do begin SecureRandomBlockGenerator(P^); Inc(P); Dec(L, SecureRandomBlockSize); end; if L > 0 then begin SecureRandomBlockGenerator(B); Move(B, P^, L); SecureClearBuf(B, SecureRandomBlockSize); end; end; function SecureRandomBytes(const Size: NativeInt): TBytes; begin SetLength(Result, Size); if Size <= 0 then exit; SecureRandomBuf(Pointer(Result)^, Size); end; function SecureRandomStrB(const Size: NativeInt): RawByteString; begin SetLength(Result, Size); if Size <= 0 then exit; SecureRandomBuf(Pointer(Result)^, Size); end; function SecureRandomHexStr(const Digits: Integer; const UpperCase: Boolean = True): String; var B : TSecureRandomBlock; S, T : String; L, N : Integer; P : PWord32; Q : PChar; begin if Digits <= 0 then begin Result := ''; exit; end; SetLength(S, Digits); Q := PChar(S); L := Digits; while L >= 8 do begin SecureRandomBlockGenerator(B); P := @B; N := SecureRandomBlockSize div 4; while (L >= 8) and (N > 0) do begin T := Word32ToHex(P^, 8, UpperCase); Move(PChar(T)^, Q^, 8 * SizeOf(Char)); SecureClearStr(T); Inc(Q, 8); Dec(N); Inc(P); Dec(L, 8); end; end; if L > 0 then begin SecureRandomBlockGenerator(B); P := @B; T := Word32ToHex(P^, L, UpperCase); Move(PChar(T)^, Q^, L * SizeOf(Char)); SecureClearStr(T); end; SecureClearBuf(B, SecureRandomBlockSize); Result := S; end; function SecureRandomHexStrB(const Digits: Integer; const UpperCase: Boolean): RawByteString; var B : TSecureRandomBlock; S, T : RawByteString; L, N : Integer; P : PWord32; Q : PByte; begin if Digits <= 0 then begin Result := ''; exit; end; SetLength(S, Digits); Q := PByte(S); L := Digits; while L >= 8 do begin SecureRandomBlockGenerator(B); P := @B; N := SecureRandomBlockSize div 4; while (L >= 8) and (N > 0) do begin T := Word32ToHexB(P^, 8, UpperCase); Move(PByte(T)^, Q^, 8); SecureClearStrB(T); Inc(Q, 8); Dec(N); Inc(P); Dec(L, 8); end; end; if L > 0 then begin SecureRandomBlockGenerator(B); P := @B; T := Word32ToHexB(P^, L, UpperCase); Move(PByte(T)^, Q^, L); SecureClearStrB(T); end; SecureClearBuf(B, SecureRandomBlockSize); Result := S; end; function SecureRandomHexStrU(const Digits: Integer; const UpperCase: Boolean): UnicodeString; var B : TSecureRandomBlock; S, T : UnicodeString; L, N : Integer; P : PWord32; Q : PWideChar; begin if Digits <= 0 then begin Result := ''; exit; end; SetLength(S, Digits); Q := PWideChar(S); L := Digits; while L >= 8 do begin SecureRandomBlockGenerator(B); P := @B; N := SecureRandomBlockSize div 4; while (L >= 8) and (N > 0) do begin T := Word32ToHexU(P^, 8, UpperCase); Move(PWideChar(T)^, Q^, 8 * SizeOf(WideChar)); SecureClearBuf(Pointer(T)^, 8 * SizeOf(WideChar)); Inc(Q, 8); Dec(N); Inc(P); Dec(L, 8); end; end; if L > 0 then begin SecureRandomBlockGenerator(B); P := @B; T := Word32ToHexU(P^, L, UpperCase); Move(PWideChar(T)^, Q^, L * SizeOf(WideChar)); SecureClearBuf(Pointer(T)^, 8 * SizeOf(WideChar)); end; SecureClearBuf(B, SecureRandomBlockSize); Result := S; end; function SecureRandomWord32: Word32; var L : Word32; begin SecureRandomBuf(L, SizeOf(Word32)); Result := L; SecureClearBuf(L, SizeOf(Word32)); end; end.
unit SettingsUnit; {$Z4} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "GblAdapterLib" // Модуль: "w:/garant6x/implementation/Garant/GblAdapterLib/SettingsUnit.pas" // Delphi интерфейсы для адаптера (.pas) // Generated from UML model, root element: <<Interfaces::Category>> garant6x::GblAdapterLib::Settings // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// interface uses SysUtils , IOUnit , BaseTypesUnit //#UC START# *4423F94903C8_45EEAA69036E_UNIT_FOR_Stream* //#UC END# *4423F94903C8_45EEAA69036E_UNIT_FOR_Stream* ; type IPropertyStringIDList = interface; { - предварительное описание IPropertyStringIDList. } IBaseSettingsManager = interface; { - предварительное описание IBaseSettingsManager. } ISettingsManager = interface; { - предварительное описание ISettingsManager. } IConfiguration = interface; { - предварительное описание IConfiguration. } IDefaultValuesChangesIndicator = interface; { - предварительное описание IDefaultValuesChangesIndicator. } IConfigurations = interface; { - предварительное описание IConfigurations. } IConfigurationManager = interface; { - предварительное описание IConfigurationManager. } IPermanentSettingsManager = interface; { - предварительное описание IPermanentSettingsManager. } PPropertyStringID = ^TPropertyStringID; TPropertyStringID = PAnsiChar; PPropertyType = ^TPropertyType; TPropertyType = ( PT_LONG , PT_STRING , PT_INT64 , PT_ULONG , PT_BOOLEAN ); // Интерфейс доступа к аттрибутам настройки. PPropertyDefinition = ^TPropertyDefinition; TPropertyDefinition = packed record rIsUnique: Bytebool; // Определяет "уникальность" своства. Уникальные свойства имеют одинаковое значение во всех конфигурациях, другими словами, уникальное свойство всегда присутствует как бы в одном экземпляре.Уникальные своства должны использоваться для настроек не зависящих от конфигурации.Значение по умолчанию: false rIsConstant: Bytebool; // Определяет возможность изменения значения настройки.Значение по умолчанию: false rType: TPropertyType; end; // Статус проверки обновления значений настроек в предустановленных конфигурациях PDefaultValuesChangesState = ^TDefaultValuesChangesState; TDefaultValuesChangesState = ( NO_CHANGES // значения не изменялись , UPDATED_WITH_COPY_ACTIVE_CONFIGURATION // Пользователь в момент смены настроек по умолчанию работает с одной из стандартных (предустановленных) конфигураций. - Делается копия текущей конфигурации. Имя: <имя конфигурации> + (сохраненная). Если конфигурация с таким именем уже cуществует -- то (сохраненная 2). - Для всех стандартных конфигураций настройки сбрасываются в значения по умолчанию. , UPDATED_WITH_ACTIVATE_PREDEFINED_CONFIGURATION // Пользователь в момент смены настроек работает с собственной конфигурацией (копией стандартной). - Для всех стандартных конфигураций настройки сбрасываются в значения по умолчанию - Пользователь переключается с его собственной конфигурации на "Стандартную" (первую в списке предустановленных) ); // Возвращается при попытке прочитать или присвоить через интерфейс ParameterValues значение по // типу, который не совпадает с реальным типом значения (реальный тип можно получить через свойство // value_type). EInvalidValueType = class (Exception); // тип конфигурации, различаем две предустановленные: Стандартная и ГАРАНТ 5x, все остальные - // пользовательские PConfigurationType = ^TConfigurationType; TConfigurationType = ( CT_STANDARD , CT_GARANT5X , CT_USER ); EConfigurationIsActiveNow = class (Exception); EConfigurationsNotDefined = class (Exception); IPropertyStringIDList = interface(IInterface) ['{DCCE2630-0409-48AF-A7B9-567B081CB9DE}'] function pm_GetCount: Integer; stdcall; procedure pm_SetCount(aValue: Integer); stdcall; { - методы для доступа к свойству Count. } procedure Clear; stdcall; {* очистить список. } procedure Delete(anIndex: Integer); stdcall; {* удаляет элемент по индексу Index. } property Count: Integer read pm_GetCount write pm_SetCount; {* число элементов в хранилище. } // property methods procedure pm_GetItem(anIndex: Integer; out aRet: IString); stdcall; procedure pm_SetItem(anIndex: Integer; const anItem: IString); stdcall; {-} // public methods function Add(const anItem: IString): Integer; stdcall; {* - добавляет элемент Item в конец. } procedure Insert(anIndex: Integer; const anItem: IString); stdcall; {* - вставляет элемент Item по индексу Index. } end;//IPropertyStringIDList IBaseSettingsManager = interface (IInterface) ['{6BC8FA39-42F0-45D2-8211-D14043AD16DD}'] function DontUseMe: Pointer; // Чтение свойства типа Boolean. // При успехе возвращает true. // Если свойство не существует возвращает false. // Если тип свойства не соответствует требуемому поднимается исключение InvalidValueType function GetBool ( const aId: TPropertyStringID; out aValue: Bytebool ): Bytebool; stdcall; // can raise EInvalidValueType // Чтение свойства типа int64. // При успехе возвращает true. // Если свойство не существует возвращает false. // Если тип свойства не соответствует требуемому поднимается исключение InvalidValueType function GetInt64 ( const aId: TPropertyStringID; out aValue: Int64 ): Bytebool; stdcall; // can raise EInvalidValueType // Чтение свойства типа long. // При успехе возвращает true. // Если свойство не существует возвращает false. // Если тип свойства не соответствует требуемому поднимается исключение InvalidValueType function GetLong ( const aId: TPropertyStringID; out aValue: Longint ): Bytebool; stdcall; // can raise EInvalidValueType // Чтение свойства типа String. // При успехе возвращает true. // Если свойство не существует возвращает false. // Если тип свойства не соответствует требуемому поднимается исключение InvalidValueType function GetString ( const aId: TPropertyStringID; out aValue {: IString} ): Bytebool; stdcall; // can raise EInvalidValueType // Чтение свойства типа unsigned long. // При успехе возвращает true. // Если свойство не существует возвращает false. // Если тип свойства не соответствует требуемому поднимается исключение InvalidValueType function GetUlong ( const aId: TPropertyStringID; out aValue: Longword ): Bytebool; stdcall; // can raise EInvalidValueType // возвращает true, если параметр с таким именем существует function IsExist ( const aId: TPropertyStringID ): Bytebool; stdcall; // Запись свойства типа Boolean. // Если свойство не существует, то оно создается в текущей конфигурации, value записывается как // значение по умолчанию и как текущее значение. // Если тип свойства не соответствует устанавливаемому поднимается исключение InvalidValueType procedure SetBool ( const aId: TPropertyStringID; aValue: Bytebool ); stdcall; // can raise EInvalidValueType // Запись свойства типа int64. // Если свойство не существует, то оно создается в текущей конфигурации, value записывается как // значение по умолчанию и как текущее значение. // Если тип свойства не соответствует устанавливаемому поднимается исключение InvalidValueType procedure SetInt64 ( const aId: TPropertyStringID; aValue: Int64 ); stdcall; // can raise EInvalidValueType // Запись свойства типа long. // Если свойство не существует, то оно создается в текущей конфигурации, value записывается как // значение по умолчанию и как текущее значение. // Если тип свойства не соответствует устанавливаемому поднимается исключение InvalidValueType procedure SetLong ( const aId: TPropertyStringID; aValue: Longint ); stdcall; // can raise EInvalidValueType // Запись свойства типа String. // Если свойство не существует, то оно создается в текущей конфигурации, value записывается как // значение по умолчанию и как текущее значение. // Если тип свойства не соответствует устанавливаемому поднимается исключение InvalidValueType procedure SetString ( const aId: TPropertyStringID; const aValue: PAnsiChar ); stdcall; // can raise EInvalidValueType // Запись свойства типа unsigned long. // Если свойство не существует, то оно создается в текущей конфигурации, value записывается как // значение по умолчанию и как текущее значение. // Если тип свойства не соответствует устанавливаемому поднимается исключение InvalidValueType procedure SetUlong ( const aId: TPropertyStringID; aValue: Longword ); stdcall; // can raise EInvalidValueType end; // Интерфейс работы с настройками. Обеспечивает создание новых свойств и их получение. Свойство // характеризуется строковым идентификатором. // Интерфейс может быть получен // 1. Из интерфейса Common, в этом случае он обеспечивает доступ к свойствам активной конфигурации. // 2. Из интерфейса Configuration, в этом случае обеспечивается работа со свойствами конкретной // конфигурации. ISettingsManager = interface (IBaseSettingsManager) ['{C2012FB8-DEC6-408A-8937-3D7E13CBC830}'] // возвращает структуру с атрибутами настройки function GetDefinition ( const aId: TPropertyStringID; const aDefinition: TPropertyDefinition ): Bytebool; stdcall; // возвращает true, если текущее значение НЕ равно значению по умолчанию, в противном случае // возвращает false function IsChanged ( const aId: TPropertyStringID ): Bytebool; stdcall; function IsChangedSet ( const aIdList: IPropertyStringIDList ): Bytebool; stdcall; // Устанавливает указанному свойству текущее значение равными значению по умолчанию procedure RestoreDefault ( const aId: TPropertyStringID ); stdcall; // can raise ECanNotFindData // записывает текущее значение свойства в качестве его значения по умолчанию procedure SaveAsDefault ( const aId: TPropertyStringID ); stdcall; // can raise ECanNotFindData end; // Интерфейс обеспечивающий работу с конкретной конфигурацией, является элементом списка // конфигураций. IConfiguration = interface (IInterface) ['{CB09ACB5-D582-477A-8D4F-98FC3766A1F9}'] function DontUseMe: Pointer; // возвращает копию конфигурации procedure Copy ( out aRet {: IConfiguration} ); stdcall; procedure GetSettings ( out aRet {: ISettingsManager} ); stdcall; // Комментарий или пояснение к конфигурации procedure GetHint (out aRet {: IString}); stdcall; procedure SetHint (const aHint: IString); stdcall; function GetId (): Longword; stdcall; // определяет возможность изменения значений по умолчанию для конфигурации function GetIsReadonly (): Bytebool; stdcall; // Имя конфигурации procedure GetName (out aRet {: IString}); stdcall; procedure SetName (const aName: IString); stdcall; // устанавливает для всех свойств конфигурации начальные значения procedure RestoreDefaultValues (); stdcall; // записывает текущие значения для всех свойств в качестве значений по умолчанию procedure SaveValuesAsDefault (); stdcall; function GetType (): TConfigurationType; stdcall; end; // Результат проверки обновления значений настроек в предустановленных конфигурациях // // если sate == UPDATED_WITH_COPY_ACTIVE_CONFIGURATION, то configuration содержит вновь созданную // пользовательскую конфигурацию - копию активной предустановленной // // если state == UPDATED_WITH_ACTIVATE_PREDEFINED_CONFIGURATION, то configuration содержит // предустановленную, на которую переключили пользователя IDefaultValuesChangesIndicator = interface (IInterface) ['{168D579E-071E-4626-93BD-7566FCAB780E}'] function DontUseMe: Pointer; procedure GetConfiguration (out aRet {: IConfiguration}); stdcall; function GetState (): TDefaultValuesChangesState; stdcall; end; IConfigurations = interface(IInterface) ['{CD0617AF-269F-4D25-9A15-52659D329272}'] function pm_GetCount: Integer; stdcall; procedure pm_SetCount(aValue: Integer); stdcall; { - методы для доступа к свойству Count. } procedure Clear; stdcall; {* очистить список. } procedure Delete(anIndex: Integer); stdcall; {* удаляет элемент по индексу Index. } property Count: Integer read pm_GetCount write pm_SetCount; {* число элементов в хранилище. } // property methods procedure pm_GetItem(anIndex: Integer; out aRet: IConfiguration); stdcall; procedure pm_SetItem(anIndex: Integer; const anItem: IConfiguration); stdcall; {-} // public methods function Add(const anItem: IConfiguration): Integer; stdcall; {* - добавляет элемент Item в конец. } procedure Insert(anIndex: Integer; const anItem: IConfiguration); stdcall; {* - вставляет элемент Item по индексу Index. } end;//IConfigurations // Интерфейс обеспечивающий работу со списком конфигураций. Доступен через интерфейс Common. IConfigurationManager = interface (IInterface) ['{C0C7A25C-7378-40EA-9593-32B590CC6D8E}'] function DontUseMe: Pointer; procedure GetConfigurations (out aRet {: IConfigurations}); stdcall; procedure DefaultValuesUpdateCheck ( out aRet {: IDefaultValuesChangesIndicator} ); stdcall; // возвращает активную конфигурацию procedure GetActive ( out aRet {: IConfiguration} ); stdcall; // Удаляет заданную конфигурацию. В случае попытки удалить активную конфигурацию возбуждает // исключение ConfigurationIsActiveNow procedure Remove ( const aConfiguration: IConfiguration ); stdcall; // can raise EConstantModify, EConfigurationIsActiveNow // Устанавливает заданную конфигурацией активной (текущей для интерфейса Settings, полученного // через Common) procedure SetActive ( const aConfiguration: IConfiguration ); stdcall; end; // настройки, не зависящие от конфигураций IPermanentSettingsManager = interface (IBaseSettingsManager) ['{4983A1B9-5021-4CE1-8C13-912831395FB8}'] end; implementation end.
unit Thermostat.Classes; interface uses SysUtils, Generics.Collections; type TThermostatState = class; TThermostat = class; TWaterLevel = (waterlevelOk, waterlevelLow); TThermostatStateList = class(TObjectList<TThermostatState>) end; TThermostatStateClass = class of TThermostatState; TThermostatState = class private FParent: TThermostatState; FStateList: TThermostatStateList; FState: TThermostatState; FThermostat: TThermostat; procedure SetParent(const Value: TThermostatState); procedure SetThermostat(const Value: TThermostat); procedure SetState(const Value: TThermostatState); protected function FindStateClass(AClass: TThermostatStateClass): TThermostatState; function CreateState(AClass: TThermostatStateClass): TThermostatState; public constructor Create; virtual; destructor Destroy; override; procedure Init; virtual; procedure Finish; virtual; procedure Execute; virtual; procedure ChangeState(AClass: TThermostatStateClass); function GetStateClass(AClass: TThermostatStateClass): TThermostatState; property Parent: TThermostatState read FParent write SetParent; property State: TThermostatState read FState write SetState; property Thermostat: TThermostat read FThermostat write SetThermostat; end; TThermostat = class private FRootState: TThermostatState; FSampleTemperature: Integer; FTargetTemperature: Integer; FWaterLevel: TWaterLevel; FActive: Boolean; FHeater: Boolean; procedure InitStates; function GetState: TThermostatState; procedure SetSampleTemperature(const Value: Integer); procedure SetTargetTemperature(const Value: Integer); procedure SetWaterLevel(const Value: TWaterLevel); procedure SetActive(const Value: Boolean); procedure SetHeater(const Value: Boolean); public constructor Create; destructor Destroy; override; procedure Run; property State: TThermostatState read GetState; property SampleTemperature: Integer read FSampleTemperature write SetSampleTemperature; property TargetTemperature: Integer read FTargetTemperature write SetTargetTemperature; property WaterLevel: TWaterLevel read FWaterLevel write SetWaterLevel; property Active: Boolean read FActive write SetActive; property Heater: Boolean read FHeater write SetHeater; end; implementation uses Thermostat.DisabledState; // init state { TThermostatState } procedure TThermostatState.ChangeState(AClass: TThermostatStateClass); var auxState: TThermostatState; begin Finish; if Assigned(Parent) then begin auxState := Parent.GetStateClass(AClass); Parent.State := auxState; auxState.Init; end; end; constructor TThermostatState.Create; begin inherited; FStateList := TThermostatStateList.Create(True); end; function TThermostatState.CreateState( AClass: TThermostatStateClass): TThermostatState; begin Result := AClass.Create; FStateList.Add(Result); Result.Parent := Self; Result.Thermostat := Thermostat; end; destructor TThermostatState.Destroy; begin FreeAndNil(FStateList); inherited; end; procedure TThermostatState.Execute; begin // do nothing end; function TThermostatState.FindStateClass( AClass: TThermostatStateClass): TThermostatState; begin for Result in FStateList do if Result.ClassType = AClass then Exit; Result := nil; end; procedure TThermostatState.Finish; begin // do nothing end; function TThermostatState.GetStateClass( AClass: TThermostatStateClass): TThermostatState; begin Result := FindStateClass(AClass); if Result = nil then Result := CreateState(AClass); end; procedure TThermostatState.Init; begin // do nothing end; procedure TThermostatState.SetParent(const Value: TThermostatState); begin FParent := Value; end; procedure TThermostatState.SetState(const Value: TThermostatState); begin FState := Value; end; procedure TThermostatState.SetThermostat(const Value: TThermostat); begin FThermostat := Value; end; { TThermostat } constructor TThermostat.Create; begin inherited; InitStates; end; destructor TThermostat.Destroy; begin FreeAndNil(FRootState); inherited; end; function TThermostat.GetState: TThermostatState; begin Result := FRootState.State; end; procedure TThermostat.InitStates; var auxState: TThermostatState; begin FRootState := TThermostatState.Create; FRootState.Thermostat := Self; auxState := FRootState.GetStateClass(TDisabledThermostatState); FRootState.State := auxState; auxState.Init; end; procedure TThermostat.Run; begin State.Execute; end; procedure TThermostat.SetActive(const Value: Boolean); begin FActive := Value; end; procedure TThermostat.SetHeater(const Value: Boolean); begin FHeater := Value; end; procedure TThermostat.SetSampleTemperature(const Value: Integer); begin FSampleTemperature := Value; end; procedure TThermostat.SetTargetTemperature(const Value: Integer); begin FTargetTemperature := Value; end; procedure TThermostat.SetWaterLevel(const Value: TWaterLevel); begin FWaterLevel := Value; end; end.
unit TestMarshalNullableUnit; interface uses TestFramework, REST.Json.Types, SysUtils, JSONNullableAttributeUnit, GenericParametersUnit, NullableBasicTypesUnit, TestBaseJsonMarshalUnit; type TTestNullableBooleanClass = class(TGenericParameters) private [JSONName('boolean_null')] [Nullable(True)] FTestNull: NullableBoolean; [JSONName('boolean_null_but_not_need_save')] [Nullable] FTestNullButNotNeedSave: NullableBoolean; [JSONName('boolean_not_null')] [Nullable] FTest: NullableBoolean; public function Etalon: String; property TestNull: NullableBoolean read FTestNull write FTestNull; property TestNullButNotNeedSave: NullableBoolean read FTestNullButNotNeedSave write FTestNullButNotNeedSave; property Test: NullableBoolean read FTest write FTest; end; TTestNullableStringClass = class(TGenericParameters) private [JSONName('string_null')] [Nullable(True)] FTestNull: NullableString; [JSONName('string_null_but_not_need_save')] [Nullable] FTestNullButNotNeedSave: NullableString; [JSONName('string_not_null')] [Nullable] FTest: NullableString; public function Etalon: String; property TestNull: NullableString read FTestNull write FTestNull; property TestNullButNotNeedSave: NullableString read FTestNullButNotNeedSave write FTestNullButNotNeedSave; property Test: NullableString read FTest write FTest; end; TTestNullableIntegerClass = class(TGenericParameters) private [JSONName('integer_null')] [Nullable(True)] FTestNull: NullableInteger; [JSONName('integer_null_but_not_need_save')] [Nullable] FTestNullButNotNeedSave: NullableInteger; [JSONName('integer_not_null')] [Nullable] FTest: NullableInteger; public function Etalon: String; property TestNull: NullableInteger read FTestNull write FTestNull; property TestNullButNotNeedSave: NullableInteger read FTestNullButNotNeedSave write FTestNullButNotNeedSave; property Test: NullableInteger read FTest write FTest; end; TTestNullableDoubleClass = class(TGenericParameters) private [JSONName('double_null')] [Nullable(True)] FTestNull: NullableDouble; [JSONName('double_null_but_not_need_save')] [Nullable] FTestNullButNotNeedSave: NullableDouble; [JSONName('double_not_null')] [Nullable] FTest: NullableDouble; public function Etalon: String; property TestNull: NullableDouble read FTestNull write FTestNull; property TestNullButNotNeedSave: NullableDouble read FTestNullButNotNeedSave write FTestNullButNotNeedSave; property Test: NullableDouble read FTest write FTest; end; TTestNullableObjectClass = class(TGenericParameters) private type TTestObject = class private FIntValue: integer; FBoolValue: boolean; FStringValue: String; FDoubleValue: double; FArrayValue: array of integer; [JSONName('nullableobject_null_optional')] [NullableObject(TTestObject)] FOptionalNullObject: NullableObject; [JSONName('nullableobject_null')] [NullableObject(TTestObject,True)] FNullObject: NullableObject; [JSONName('nullableobject_not_null')] [NullableObject(TTestObject,True)] FNotNullObject: NullableObject; public destructor Destroy; override; end; var [JSONName('object_null')] [NullableObject(TTestObject,True)] FTestNull: NullableObject; [JSONName('object_null_but_not_need_save')] [NullableObject(TTestObject)] FTestNullButNotNeedSave: NullableObject; [JSONName('object_not_null')] [NullableObject(TTestObject)] FTest: NullableObject; public destructor Destroy; override; function MakeTestObject(): TObject; function Etalon: String; property TestNull: NullableObject read FTestNull write FTestNull; property TestNullButNotNeedSave: NullableObject read FTestNullButNotNeedSave write FTestNullButNotNeedSave; property Test: NullableObject read FTest write FTest; end; TTestMarshalNullable = class(TTestCase) published procedure TestNullableBoolean(); procedure TestNullableString(); procedure TestNullableInteger(); procedure TestNullableDouble(); procedure TestNullableObject(); end; implementation { TTestNullableBooleanClass } function TTestNullableBooleanClass.Etalon: String; begin Result := '{"boolean_null":null,"boolean_not_null":true}'; end; { TTestNullableStringClass } function TTestNullableStringClass.Etalon: String; begin Result := '{"string_null":null,"string_not_null":"123"}'; end; { TTestMarshalNullable } procedure TTestMarshalNullable.TestNullableBoolean; var op: TTestNullableBooleanClass; begin op := TTestNullableBooleanClass.Create; try op.TestNull := NullableBoolean.Null; op.TestNullButNotNeedSave := NullableBoolean.Null; op.Test := True; CheckEquals(op.Etalon, op.ToJsonString); finally FreeAndNil(op); end; end; procedure TTestMarshalNullable.TestNullableDouble; var op: TTestNullableDoubleClass; begin op := TTestNullableDoubleClass.Create; try op.TestNull := NullableDouble.Null; op.TestNullButNotNeedSave := NullableDouble.Null; op.Test := 123.456; CheckEquals(op.Etalon, op.ToJsonString); finally FreeAndNil(op); end; end; procedure TTestMarshalNullable.TestNullableInteger; var op: TTestNullableIntegerClass; begin op := TTestNullableIntegerClass.Create; try op.TestNull := NullableInteger.Null; op.TestNullButNotNeedSave := NullableInteger.Null; op.Test := 123; CheckEquals(op.Etalon, op.ToJsonString); finally FreeAndNil(op); end; end; procedure TTestMarshalNullable.TestNullableObject; var op: TTestNullableObjectClass; begin op := TTestNullableObjectClass.Create; try op.TestNull := NullableObject.Null; op.TestNullButNotNeedSave := NullableObject.Null; op.Test := op.MakeTestObject; CheckEquals(op.Etalon, op.ToJsonString); finally FreeAndNil(op); end; end; procedure TTestMarshalNullable.TestNullableString; var op: TTestNullableStringClass; begin op := TTestNullableStringClass.Create; try op.TestNull := NullableString.Null; op.TestNullButNotNeedSave := NullableString.Null; op.Test := '123'; CheckEquals(op.Etalon, op.ToJsonString); finally FreeAndNil(op); end; end; { TTestNullableIntegerClass } function TTestNullableIntegerClass.Etalon: String; begin Result := '{"integer_null":null,"integer_not_null":123}'; end; { TTestNullableDoubleClass } function TTestNullableDoubleClass.Etalon: String; begin Result := '{"double_null":null,"double_not_null":123.456}'; end; { TTestNullableObjectClass } destructor TTestNullableObjectClass.Destroy; begin FTestNull.Free; FTestNullButNotNeedSave.Free; FTest.Free; inherited; end; function TTestNullableObjectClass.Etalon: String; begin Result := '{"object_null":null,' + '"object_not_null":{"intValue":123,"boolValue":true,"stringValue":"321",' + '"doubleValue":123.456,"arrayValue":[3,4,5],"nullableobject_null":null,' + '"nullableobject_not_null":{"intValue":111111,"boolValue":false,' + '"stringValue":"22222","doubleValue":789.123,"arrayValue":[8],' + '"nullableobject_null":null,"nullableobject_not_null":null}}}'; end; function TTestNullableObjectClass.MakeTestObject: TObject; var Res: TTestObject; SubObject: TTestObject; begin Res := TTestObject.Create; Res.FIntValue := 123; Res.FBoolValue := True; Res.FStringValue := '321'; Res.FDoubleValue := 123.456; SetLength(Res.FArrayValue, 3); Res.FArrayValue[0] := 3; Res.FArrayValue[1] := 4; Res.FArrayValue[2] := 5; Res.FOptionalNullObject := NullableObject.Null; Res.FNullObject := NullableObject.Null; SubObject := TTestObject.Create; SubObject.FIntValue := 111111; SubObject.FBoolValue := False; SubObject.FStringValue := '22222'; SubObject.FDoubleValue := 789.123; SetLength(SubObject.FArrayValue, 1); SubObject.FArrayValue[0] := 8; SubObject.FOptionalNullObject := NullableObject.Null; SubObject.FNullObject := NullableObject.Null; SubObject.FNotNullObject := NullableObject.Null; Res.FNotNullObject := SubObject; Result := Res; end; { TTestNullableObjectClass.TTestObject } destructor TTestNullableObjectClass.TTestObject.Destroy; begin FOptionalNullObject.Free; FNullObject.Free; FNotNullObject.Free; inherited; end; initialization // Register any test cases with the test runner RegisterTest('JSON\Marshal\', TTestMarshalNullable.Suite); end.
unit Esp32.Form.Main; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Bluetooth, System.Math.Vectors, FMX.Controls3D, FMX.Layers3D, FMX.Layouts, System.Bluetooth.Components, FMX.ListBox, FMX.Controls.Presentation, FMX.StdCtrls; type TForm1 = class(TForm) Bluetooth1: TBluetooth; Layout1: TLayout; Layout3D1: TLayout3D; Layout2: TLayout; btnListarDispositivos: TButton; cbxDispositivos: TComboBox; Layout3: TLayout; btnConectar: TButton; lblStatus: TLabel; Switch1: TSwitch; procedure btnListarDispositivosClick(Sender: TObject); procedure btnConectarClick(Sender: TObject); procedure Switch1Switch(Sender: TObject); private FSocket: TBluetoothSocket; function ConectarDispositivo(pDeviceName: String): boolean; { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} const UUID = '{00001101-0000-1000-8000-00805F9B34FB}'; procedure TForm1.btnConectarClick(Sender: TObject); begin if (cbxDispositivos.Selected <> nil) and (cbxDispositivos.Selected.Text <> '') then begin if ConectarDispositivo(cbxDispositivos.Selected.Text) then lblStatus.Text := 'Conectado' else lblStatus.Text := 'Desconectado'; end else begin ShowMessage('Selecione um dispositivo'); end; end; procedure TForm1.btnListarDispositivosClick(Sender: TObject); var lDevice: TBluetoothDevice; begin cbxDispositivos.Items.Clear; for lDevice in Bluetooth1.PairedDevices do begin cbxDispositivos.Items.Add(lDevice.DeviceName); end; end; function TForm1.ConectarDispositivo(pDeviceName: String): boolean; var lDevice: TBluetoothDevice; begin for lDevice in Bluetooth1.PairedDevices do begin if lDevice.DeviceName = pDeviceName then begin FSocket := lDevice.CreateClientSocket(StringToGUID(UUID),True); if FSocket <> nil then begin FSocket.Connect; Result := FSocket.Connected; end; end; end; end; procedure TForm1.Switch1Switch(Sender: TObject); var lDados: TBytes; begin if (FSocket <> nil) and (FSocket.Connected) then begin setLength(lDados,1); lDados[0] := Ord(Switch1.IsChecked); FSocket.SendData(lDados); end; end; end.
unit UAccessSimple; interface uses Classes, UAccessClient; type TSimpleClient = class(TObject) private FCaption: string; FLogin: string; FPassword: string; FDNS: string; FAuthorized: Boolean; FDateTime: TDateTime; FUID: string; FThread: Pointer; procedure SetCaption(const Value: string); procedure SetDateTime(const Value: TDateTime); procedure SetDNS(const Value: string); procedure SetLogin(const Value: string); procedure SetPassword(const Value: string); procedure SetThread(const Value: Pointer); procedure SetUID(const Value: string); procedure SetAuthorized(const Value: Boolean); public property Authorized: Boolean read FAuthorized write SetAuthorized; property Caption: string read FCaption write SetCaption; property Login: string read FLogin write SetLogin; property Password: string read FPassword write SetPassword; property DNS: string read FDNS write SetDNS; property DateTime: TDateTime read FDateTime write SetDateTime; property UID: string read FUID write SetUID; property Thread: Pointer read FThread write SetThread; constructor Create; end; TSimpleBase = class(TObject) private FCaption: string; FConfigFile: string; FUpdating: Boolean; FClient: TSAVAccessClient; FLastUpdate: TDateTime; FUploading: Boolean; procedure SetCaption(const Value: string); procedure SetConfigFile(const Value: string); procedure SetLastUpdate(const Value: TDateTime); procedure SetUploading(const Value: Boolean); procedure SetClient(const Value: TSAVAccessClient); procedure SetUpdating(const Value: Boolean); public property Caption: string read FCaption write SetCaption; property ConfigFile: string read FConfigFile write SetConfigFile; property Uploading: Boolean read FUploading write SetUploading; property Updating: Boolean read FUpdating write SetUpdating; property LastUpdate: TDateTime read FLastUpdate write SetLastUpdate; property Client: TSAVAccessClient read FClient write SetClient; constructor Create; destructor Destroy; override; end; TSimpleBases = class(TObject) private FItems: TList; FRootConfig: string; procedure SetItems(const Value: TList); procedure SetRootConfig(const Value: string); function GetCount: integer; public property Items: TList read FItems write SetItems; property RootConfig: string read FRootConfig write SetRootConfig; property Count: integer read GetCount; constructor Create; destructor Destroy; override; function GetItem(const aCaption: string): Pointer; function GetIndex(const aCaption: string): integer; procedure GetCaptions(aList: TStrings; const aConfigFile: Boolean = False); function GetCaption(const aIndex: Integer): string; procedure GetStatus(aList: TStrings); function GetItemInfo(const aCaption: string; aList: TStrings): Boolean; procedure Clear; function Add(const aCaption, aConfigFile: string): Boolean; overload; function Add(const aConfigFile: string): boolean; overload; function Update(const aIndex: Integer): Boolean; overload; function Update(const aCaption: string): Boolean; overload; function DisUpdate(const aCaption: string): Boolean; procedure Delete(const aIndex: Integer); end; TSimpleClients = class(TObject) private FItems: TList; FPasswordFile: string; procedure SetItems(const Value: TList); function GetCount: integer; procedure SetPasswordFile(const Value: string); public property Items: TList read FItems write SetItems; property Count: integer read GetCount; property PasswordFile: string read FPasswordFile write SetPasswordFile; constructor Create; destructor Destroy; override; procedure Clear; procedure Delete(const aIndex: Integer); procedure DisconnectAll; function GetIndex(const aUID: string): integer; function GetItem(const aUID: string): Pointer; function GetUserPasswMD5(const aLogin: string): string; function GetMD5(const aSource: string): string; end; implementation uses SysUtils, SAVLib, IdTCPServer, md5, Registry, Forms; { TSimpleBase } constructor TSimpleBase.Create; begin inherited; FLastUpdate := EncodeDate(2000, 01, 01); FUpdating := False; end; destructor TSimpleBase.Destroy; begin FClient.Free; inherited; end; procedure TSimpleBase.SetCaption(const Value: string); begin FCaption := AnsiUpperCase(Value); end; procedure TSimpleBase.SetClient(const Value: TSAVAccessClient); begin FClient := Value; end; procedure TSimpleBase.SetConfigFile(const Value: string); begin FConfigFile := Value; end; procedure TSimpleBase.SetLastUpdate(const Value: TDateTime); begin FLastUpdate := Value; end; procedure TSimpleBase.SetUpdating(const Value: Boolean); begin FUpdating := Value; end; procedure TSimpleBase.SetUploading(const Value: Boolean); begin FUploading := Value; end; { TSimpleBases } constructor TSimpleBases.Create; begin FItems := TList.Create; FRootConfig := ExtractFilePath(ParamStr(0)); end; destructor TSimpleBases.Destroy; begin Clear; FreeAndNil(Fitems); inherited; end; function TSimpleBases.GetIndex(const aCaption: string): integer; var i: Integer; s: string; begin Result := -1; i := 0; s := AnsiUpperCase(aCaption); while (i < FItems.Count) and (Result = -1) do begin if TSimpleBase(FItems[i]).Caption = s then Result := i; inc(i); end; end; function TSimpleBases.GetItem(const aCaption: string): Pointer; var i: Integer; begin Result := nil; i := GetIndex(aCaption); if i > -1 then Result := FItems.Items[i]; end; procedure TSimpleBases.SetItems(const Value: TList); begin FItems := Value; end; procedure TSimpleBases.GetCaptions(aList: TStrings; const aConfigFile: Boolean = False); var i: Integer; s: string; begin i := 0; aList.Clear; while i < FItems.Count do begin s := TSimpleBase(FItems[i]).Caption; if aConfigFile then s := s + '=[' + DateTimeToStr(TSimpleBase(FItems[i]).LastUpdate) + '] ' + TSimpleBase(FItems[i]).ConfigFile; aList.Add(s); inc(i); end; end; procedure TSimpleBases.Clear; var i: Integer; begin i := 0; while i < FItems.Count do begin TSimpleBase(FItems.Items[i]).Free; inc(i); end; FItems.Clear; end; function TSimpleBases.Add(const aCaption, aConfigFile: string): boolean; var i: integer; simplebas: TSimpleBase; aclient: TSAVAccessClient; s: string; begin s := AnsiUpperCase(aCaption); i := GetIndex(s); if i = -1 then begin simplebas := TSimpleBase.Create; simplebas.Caption := s; simplebas.ConfigFile := aConfigFile; aclient := TSAVAccessClient.Create(RootConfig + s); aclient.LoadFromFile(aConfigFile); simplebas.Client := aclient; FItems.Add(simplebas); Result := True; end else begin TSimpleBase(FItems.Items[i]).ConfigFile := aConfigFile; TSimpleBase(FItems.Items[i]).Client.LoadFromFile(aConfigFile); Result := False; end; end; procedure TSimpleBases.SetRootConfig(const Value: string); var s1, s2: string; begin if Value = '' then s1 := 'SAVAccessClient' else s1 := Value; s2 := GetSpecialFolderLocation(CSIDL_APPDATA, FOLDERID_RoamingAppData); if s2 = '' then s2 := GetCurrentDir; FRootConfig := IncludeTrailingPathDelimiter(IncludeTrailingPathDelimiter(s2) + s1); if not (DirectoryExists(FRootConfig)) then ForceDirectories(FRootConfig); end; function TSimpleBases.Update(const aIndex: Integer): Boolean; begin with TSimpleBase(FItems.Items[aIndex]) do begin Result := not Updating; if Result then begin Updating := True; try Client.Update; LastUpdate := Now; finally Updating := False; end; end; end; end; procedure TSimpleBases.Delete(const aIndex: Integer); begin if aIndex < FItems.Count then begin TSimpleBase(FItems.Items[aIndex]).Free; FItems.Delete(aIndex); end; end; function TSimpleBases.GetCount: integer; begin Result := FItems.Count; end; procedure TSimpleBases.GetStatus(aList: TStrings); var i: Integer; s: string; begin i := 0; aList.Clear; while i < FItems.Count do begin s := TSimpleBase(FItems[i]).Caption + '=' + BoolToStr(TSimpleBase(FItems[i]).Updating); aList.Add(s); inc(i); end; end; function TSimpleBases.GetItemInfo(const aCaption: string; aList: TStrings): boolean; var i: Integer; begin aList.Clear; i := GetIndex(aCaption); Result := i > -1; if Result then with TSimpleBase(FItems.Items[i]) do begin aList.Add('caption=' + Caption); aList.Add('lastupdate=' + DateTimeToStr(LastUpdate)); aList.Add('updating=' + BoolToStr(Updating)); aList.Add('config=' + ConfigFile); aList.Add('journals=' + Client.JournalsDir); aList.Add('domains=' + Client.DomainsDir); aList.Add('adgroups=' + Client.ADGroupsDir); aList.Add('groups=' + Client.GroupsDir); aList.Add('users=' + Client.UsersDir); end else aList.Add('Not found'); end; function TSimpleBases.Add(const aConfigFile: string): boolean; var sCapt: string; list: TStringList; begin Result := FileExists(aConfigFile); if Result then begin list := TStringList.Create; list.LoadFromFile(aConfigFile); sCapt := list.Values['caption']; FreeAndNil(list); if sCapt = '' then sCapt := ExtractFileName(aConfigFile); Result := Add(sCapt, aConfigFile); end; end; function TSimpleBases.Update(const aCaption: string): Boolean; var i: Integer; begin Result := False; i := GetIndex(aCaption); if i > -1 then Result := Update(i); end; function TSimpleBases.GetCaption(const aIndex: Integer): string; begin if aIndex < FItems.Count then Result := TSimpleBase(FItems[aIndex]).Caption else Result := ''; end; function TSimpleBases.DisUpdate(const aCaption: string): Boolean; var i: Integer; begin Result := False; i := GetIndex(aCaption); if i > -1 then begin TSimpleBase(FItems.Items[i]).Updating := False; Result := True; end; end; { TSimpleClients } procedure TSimpleClients.Clear; var i, n: Integer; begin n := Pred(FItems.Count); for i := 0 to n do Delete(i); FItems.Clear; end; constructor TSimpleClients.Create; var reg: TRegIniFile; begin FItems := TList.Create; // FPasswordFile := 'd:\ProjectsD\SAVAccess\managers.pwd'; reg := TRegIniFile.Create; FPasswordFile := reg.ReadString('SOFTWARE\SAVClient', 'pwd', ExtractFilePath(Application.ExeName) + 'users.pwd'); reg.CloseKey; FreeAndNil(reg); end; procedure TSimpleClients.Delete(const aIndex: Integer); begin if aIndex < FItems.Count then begin TObject(FItems.Items[aIndex]).Free; FItems.Delete(aIndex); end; end; destructor TSimpleClients.Destroy; begin Clear; FreeAndNil(Fitems); inherited; end; procedure TSimpleClients.DisconnectAll; var i: Integer; client1: TSimpleClient; thrt1: TIdPeerThread; begin for i := pred(FItems.Count) downto 0 do begin client1 := FItems.Items[i]; thrt1 := client1.thread; thrt1.Connection.DisconnectSocket; end; end; function TSimpleClients.GetCount: integer; begin Result := FItems.Count; end; function TSimpleClients.GetIndex(const aUID: string): integer; var i: Integer; begin Result := -1; i := 0; while (i < FItems.Count) and (Result = -1) do begin if TSimpleClient(FItems[i]).UID = aUID then Result := i; inc(i); end; end; function TSimpleClients.GetItem(const aUID: string): Pointer; var i: Integer; begin Result := nil; i := GetIndex(aUID); if i > -1 then Result := FItems.Items[i]; end; procedure TSimpleClients.SetItems(const Value: TList); begin FItems := Value; end; function TSimpleClients.GetUserPasswMD5(const aLogin: string): string; var list: TStringList; s: string; begin Result := ''; s := Trim(AnsiLowerCase(aLogin)); try list := TStringList.Create; list.LoadFromFile(FPasswordFile); Result := list.Values[aLogin]; finally FreeAndNil(list); end; end; procedure TSimpleClients.SetPasswordFile(const Value: string); begin FPasswordFile := Value; end; function TSimpleClients.GetMD5(const aSource: string): string; begin Result := MD5DigestToStr(MD5String(aSource)); end; { TSimpleClient } constructor TSimpleClient.Create; begin FLogin := ''; FPassword := ''; FCaption := ''; FDNS := ''; FUID := ''; FAuthorized := False; end; procedure TSimpleClient.SetAuthorized(const Value: Boolean); begin FAuthorized := Value; end; procedure TSimpleClient.SetCaption(const Value: string); begin FCaption := Value; end; procedure TSimpleClient.SetDateTime(const Value: TDateTime); begin FDateTime := Value; end; procedure TSimpleClient.SetDNS(const Value: string); begin FDNS := Value; end; procedure TSimpleClient.SetLogin(const Value: string); begin FLogin := Value; end; procedure TSimpleClient.SetPassword(const Value: string); begin FPassword := Value; end; procedure TSimpleClient.SetThread(const Value: Pointer); begin FThread := Value; end; procedure TSimpleClient.SetUID(const Value: string); begin FUID := Value; end; end.
(* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower Abbrevia * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1997-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* ABBREVIA: AbZipCry.pas 3.05 *} {*********************************************************} {* ABBREVIA: PKZip crypto units *} {* Based on information from Appnote.txt, shipped with *} {* PKWare's PKZip for Windows 2.5 *} {*********************************************************} {$I AbDefine.inc} unit AbZipCry; interface uses Classes, {$IFDEF MSWINDOWS} Windows, {$ENDIF} AbArcTyp, AbUtils, AbZipTyp; type TAbZipKeys = array [0..2] of DWORD; TAbZDecoder = class( TObject ) protected FZipKeys : TAbZipKeys; FBuffer : array [0..11] of Byte; FCRC : LongInt; FCheckByte : Boolean; FOnNeedPassword : TAbNeedPasswordEvent; FPassword : string; FRetries : Byte; FStream : TStream; function DecryptByte : Byte; {get the decryption byte} procedure DoOnNeedPassword( var NewPassword : string ); virtual; procedure InitKeys; {-Initialize Keys} public constructor Create(const aPassword : string; var aStream : TStream; aCRC : LongInt; aCheckByte : Boolean ); destructor Destroy; override; function Decode( c : Byte ) : Byte; {-returns a decoded byte} procedure DecodeBuffer( var Buffer; Count : Integer ); {-decodes the next Count bytes of Buffer} function Encode( c : Byte ) : Byte; {-returns an encoded byte} procedure EncodeBuffer( var Buffer; Count : Integer ); {-encodes the next Count bytes of Buffer} function ReadEncryptionHeader : Boolean; {-read and validate the encryption header} procedure WriteEncryptionHeader; {-initialize and create the encryption header} property OnNeedPassword : TAbNeedPasswordEvent read FOnNeedPassword write FOnNeedPassword; property Password : string write FPassword; property Retries : Byte read FRetries write FRetries; end; procedure AbUpdateKeys( c : Byte; var Keys : TAbZipKeys ); {-Updates the keys with c} implementation uses AbConst, AbExcept; const AbZipKeyInit1 = 305419896; AbZipKeyInit2 = 591751049; AbZipKeyInit3 = 878082192; AbZipMagicNumber = 134775813; { -------------------------------------------------------------------------- } constructor TAbZDecoder.Create(const aPassword : string; var aStream : TStream; aCRC : LongInt; aCheckByte : Boolean ); begin inherited Create; FPassword := aPassword; FStream := aStream; FCRC := aCRC; FCheckByte := aCheckByte; FRetries := 3; end; { -------------------------------------------------------------------------- } destructor TAbZDecoder.Destroy; begin inherited Destroy; end; { -------------------------------------------------------------------------- } function TAbZDecoder.Decode( c : Byte ) : Byte; var Temp : Word; begin Temp := Word( FZipKeys[2] ) or 2; Result := c xor ( ( Temp * ( Temp xor 1 ) ) shr 8 ); AbUpdateKeys( Result, FZipKeys ); end; { -------------------------------------------------------------------------- } procedure TAbZDecoder.DecodeBuffer( var Buffer; Count : Integer ); {-decodes the next Count bytes of Buffer} type TByteArray = array[0..65520] of Byte; var Buf : TByteArray absolute Buffer; i : Integer; Temp : Word; begin for i := 0 to pred( Count ) do begin Temp := Word( FZipKeys[2] ) or 2; Buf[i] := Buf[i] xor ( ( Temp * ( Temp xor 1 ) ) shr 8 ); {begin of AbUpdateKeys( Buf[i], FZipKeys );} FZipKeys[0] := AbUpdateCrc32( Buf[i], FZipKeys[0] ); FZipKeys[1] := FZipKeys[1] + ( FZipKeys[0] and $FF ); FZipKeys[1] := ( FZipKeys[1] * AbZipMagicNumber ) + 1; {FZipKeys[2] := AbUpdateCrc32( FZipKeys[1] shr 24, FZipKeys[2] );} FZipKeys[2] := AbCrc32Table[ Byte( FZipKeys[1] shr 24 xor DWORD( FZipKeys[2] ) ) ] xor ( (FZipKeys[2] shr 8) and $00FFFFFF ); {end of AbUpdateKeys( Buf[i], FZipKeys );} end; end; { -------------------------------------------------------------------------- } function TAbZDecoder.DecryptByte : Byte; {function has also been included as inline to Decode/Encode} var Temp : Word; begin Temp := Word( FZipKeys[2] ) or 2; Result := ( Temp * ( Temp xor 1 ) ) shr 8; end; { -------------------------------------------------------------------------- } procedure TAbZDecoder.DoOnNeedPassword( var NewPassword : string ); begin if Assigned( FOnNeedPassword ) then FOnNeedPassword( Self, NewPassword ) else raise EAbZipInvalidPassword.Create; end; { -------------------------------------------------------------------------- } function TAbZDecoder.Encode( c : Byte ) : Byte; {-returns an encoded byte} var t : Word; begin t := Word( FZipKeys[2] ) or 2; t := ( t * ( t xor 1 ) ) shr 8; AbUpdateKeys( c, FZipKeys ); Result := t xor c; end; { -------------------------------------------------------------------------- } procedure TAbZDecoder.EncodeBuffer( var Buffer; Count : Integer ); {-encodes the next Count bytes of Buffer} type TByteArray = array[0..65520] of Byte; var Buf : TByteArray absolute Buffer; i : Integer; t : Word; begin for i := 0 to pred( Count ) do begin t := Word( FZipKeys[2] ) or 2; t := ( t * ( t xor 1 ) ) shr 8; {begin of AbUpdateKeys( Buf[i], FZipKeys );} FZipKeys[0] := AbUpdateCrc32( Buf[i], FZipKeys[0] ); FZipKeys[1] := FZipKeys[1] + ( FZipKeys[0] and $FF ); FZipKeys[1] := ( FZipKeys[1] * AbZipMagicNumber ) + 1; {FZipKeys[2] := AbUpdateCrc32( FZipKeys[1] shr 24, FZipKeys[2] );} FZipKeys[2] := AbCrc32Table[ Byte( FZipKeys[1] shr 24 xor DWORD( FZipKeys[2] ) ) ] xor ( (FZipKeys[2] shr 8) and $00FFFFFF ); {end of AbUpdateKeys( Buf[i], FZipKeys );} Buf[i] := t xor Buf[i]; end; end; { -------------------------------------------------------------------------- } procedure TAbZDecoder.InitKeys; var i : Integer; begin FZipKeys[0] := AbZipKeyInit1; FZipKeys[1] := AbZipKeyInit2; FZipKeys[2] := AbZipKeyInit3; for i := 1 to Length( FPassword ) do AbUpdateKeys( Ord( FPassword[i] ), FZipKeys ); end; { -------------------------------------------------------------------------- } function TAbZDecoder.ReadEncryptionHeader : Boolean; type Bytes = packed record L1, L2, L3, L4 : Byte end; var i : Integer; Valid : Boolean; Attempts : Byte; Pos : LongInt; begin {save the current position} Pos := FStream.Position; Valid := False; Attempts := 0; while ( not Valid ) and (Attempts < Retries ) do begin InitKeys; {read the header} FStream.Seek( Pos, soFromBeginning ); FStream.Read( FBuffer[0], 12 ); for i := 0 to 11 do begin FBuffer[i] := FBuffer[i] xor DecryptByte; AbUpdateKeys( FBuffer[i], FZipKeys ); end; if FCheckByte then {version 2.0 or better} Valid := ( FBuffer[11] = Bytes( FCRC ).L4 ) else {prior to version 2.0} Valid := ( FBuffer[11] = Bytes( FCRC ).L4 ) and ( FBuffer[10] = Bytes( FCRC ).L3 ); if not Valid then DoOnNeedPassword( FPassword ); inc( Attempts ); end; if not Valid then raise EAbZipInvalidPassword.Create; Result := Valid; end; { -------------------------------------------------------------------------- } procedure TAbZDecoder.WriteEncryptionHeader; type Bytes = packed record L1, L2, L3, L4 : Byte end; var n : Integer; c : Byte; t : Word; begin InitKeys; for n := 0 to 9 do begin c := Random( 256 ); t := DecryptByte; AbUpdateKeys( c, FZipKeys ); FBuffer[n] := t xor c; end; InitKeys; for n := 0 to 9 do begin t := DecryptByte; AbUpdateKeys( FBuffer[n], FZipKeys ); FBuffer[n] := t xor FBuffer[n]; end; {now do FBuffer[10]} t := DecryptByte; AbUpdateKeys( Bytes( FCRC ).L3, FZipKeys ); FBuffer[10] := t xor Bytes( FCRC ).L3; {now do FBuffer[11]} t := DecryptByte; AbUpdateKeys( Bytes( FCRC ).L4, FZipKeys ); FBuffer[11] := t xor Bytes( FCRC ).L4; {now write it to the buffer} FStream.Write( FBuffer[0], 12 ); end; { -------------------------------------------------------------------------- } procedure AbUpdateKeys( c : Byte; var Keys : TAbZipKeys ); begin Keys[0] := AbUpdateCrc32( c, Keys[0] ); Keys[1] := Keys[1] + ( Keys[0] and $FF ); Keys[1] := ( Keys[1] * AbZipMagicNumber ) + 1; Keys[2] := AbUpdateCrc32( Keys[1] shr 24, Keys[2] ); end; end.
{ Subroutine SST_SYMBOL_LOOKUP_NAME (NAME, SYM_P, STAT) * * Look up an existing symbol in the currently active name spaces. * SYM_P is returned pointing to the symbol data block. * STAT is returned with an error if the symbol was not found, in which * case SYM_P is returned NIL. } module sst_symbol_lookup_name; define sst_symbol_lookup_name; %include 'sst2.ins.pas'; procedure sst_symbol_lookup_name ( {look up symbol in visible name spaces} in name: univ string_var_arg_t; {name of symbol to look up} out sym_p: sst_symbol_p_t; {returned pointer to symbol descriptor} out stat: sys_err_t); {completion status code} var uname: string_var132_t; {upcased symbol name string} name_p: string_var_p_t; {points to symbol name in hash table entry} scope_p: sst_scope_p_t; {points to curr scope looking up name in} sym_pp: sst_symbol_pp_t; {points to hash table user data area} label found; begin uname.max := sizeof(uname.str); {init local var string} sys_error_none (stat); {init STAT to indicate no error} sym_p := nil; {init pointer to indicate symbol not found} string_copy (name, uname); {make upper case copy of symbol name} string_upcase (uname); scope_p := sst_names_p; {init current scope to most local name space} while scope_p <> nil do begin {keep looping until reach top name space} string_hash_ent_lookup ( {look for raw name in this name space} scope_p^.hash_h, {hash table handle at this name space} name, {the name to look up} name_p, {returned pointer to stored name string} sym_pp); {returned pointer to hash entry user data} if sym_pp <> nil then goto found; {found symbol ?} string_hash_ent_lookup ( {look for upcased name in this name space} scope_p^.hash_h, {hash table handle at this name space} uname, {the name to look up} name_p, {returned pointer to stored name string} sym_pp); {returned pointer to hash entry user data} if sym_pp <> nil then goto found; {found symbol ?} scope_p := scope_p^.parent_p; {switch to next more global name space} end; {back and look in new name space} { * The symbol was not found in any of the currently active name spaces. } sys_stat_set (sst_subsys_k, sst_stat_sym_not_found_k, stat); {set error code} sys_stat_parm_vstr (name, stat); {pass symbol name to error code} return; { * The symbol was found. SYM_PP points to the user data pointer in the * hash table entry for this symbol. } found: sym_p := sym_pp^; {get pointer to symbol descriptor block} if sst_scope_p^.flag_ref_used then begin {flag referenced symbols as used ?} sym_p^.flags := {indicate symbol was "used"} sym_p^.flags + [sst_symflag_used_k]; end; end;
unit UTreeNode; interface uses SysUtils, ComCtrls; Type TIndex = 'a'..'z'; PtrTrieTree = ^TNode; TNode = class private Ptrs: array [TIndex] of TNode; eow: boolean; public Constructor Create; procedure Push (s: string; i:byte); procedure delete (var count:Integer;var Arr:array of string; s:string;wrd:string); function IsEmpty:boolean; procedure SetEow(ok:boolean); procedure print(treeView: TTreeView; parent:TTreeNode); function pop(var wrd:string):Boolean; destructor Destroy; override; end; implementation constructor TNode.Create; var ch:char; begin inherited Create; eow:=false; for ch:=low(TIndex) to High(TIndex) do Ptrs[ch]:=nil; end; Function TNode.IsEmpty: boolean; var chr:char; begin result:=true; chr:=Low(TIndex); repeat result:=Ptrs[chr]=nil; inc(chr); until (not result) or (chr = High(TIndex)) end; procedure TNode.SetEow(ok:Boolean); begin eow:=ok; end; procedure TNode.Push (s: string; i:byte); begin if ptrs[s[i]] = nil then ptrs[s[i]] := TNode.Create; if length(s)<=i then ptrs[s[i]].SetEow(true) else Ptrs[S[i]].Push(s,i+1); end; procedure TNode.print(treeView: TTreeView; parent:TTreeNode); var i:Char; newParent: TTreeNode; begin for i:= Low(TIndex) to high(TIndex) do if ptrs[i]<>nil then begin newParent := treeView.Items.AddChild(parent, i); ptrs[i].print(treeView, newParent); end; end; procedure TNode.delete (var count:Integer;var Arr:array of string; s:string;wrd:string); var ch: TIndex; begin if eow then begin if (length(wrd) <= length(s)) then if (copy(s,1,length(wrd))=wrd) then begin Arr[count]:=s; Inc(count); end; end; for ch:=Low(TIndex) to High(TIndex) do if Ptrs[ch]<>nil then Ptrs[ch].delete(count,arr,s+ch,wrd) end; function TNode.pop(var wrd: string): Boolean; var f: TIndex; begin if wrd = '' then begin Result:= eow; eow:= False; end else begin f:= wrd[1]; System.Delete(wrd, 1, 1); Result:= (ptrs[f] <> nil) and (ptrs[f].pop(wrd)); if Result and ptrs[f].IsEmpty then FreeAndNil(ptrs[f]); end; end; Destructor TNode.Destroy; var ch: TIndex; begin for ch:=low(TIndex) to High(TIndex) do if Ptrs[ch] <> nil then Ptrs[ch].Destroy; inherited Destroy; end; end.
unit GX_eAlign; {$I GX_CondDefine.inc} // Original author: Stefan Pettersson <stefpet@gmail.com> interface uses Classes, Controls, StdCtrls, Forms, Menus, GX_BaseForm; type TfmAlign = class(TfmBaseForm) btnOK: TButton; btnCancel: TButton; lstTokens: TListBox; lblToken: TLabel; btnConfig: TButton; cbxMode: TComboBox; procedure lstTokensDblClick(Sender: TObject); procedure btnConfigClick(Sender: TObject); public constructor Create(_Owner: TComponent); override; end; implementation {$R *.dfm} uses SysUtils, GX_OtaUtils, GX_GenericUtils, GX_ConfigurationInfo, GX_EditorExpert, GX_eSelectionEditorExpert, GX_eAlignOptions, Math, GX_dzVclUtils; const DEFAULT_WHITESPACE = 1; DEFAULT_TOKENS: array[0..10] of string = (':=', '=', '//', '{', '(*', '''', ':', '+', 'read', 'write', 'in '''); resourcestring SNoTokens = 'No tokens found to align on.'; type TGXAlignMode = (gamRightmost, gamFirstToken); TAlignExpert = class(TSelectionEditorExpert) private FWhitespace: Integer; FLastToken: string; FLastMode: TGXAlignMode; FTokens: TStringList; FSelectedText: string; function QueryUserForAlignToken(var Token: string; var Mode: TGXAlignMode): Boolean; protected function GetDisplayName: string; override; class function GetName: string; override; function ProcessSelected(Lines: TStrings): Boolean; override; procedure LoadConfiguration(Dialog: TfmAlign); procedure InternalLoadSettings(Settings: TExpertSettings); override; procedure InternalSaveSettings(Settings: TExpertSettings); override; public constructor Create; override; destructor Destroy; override; procedure Configure; override; function GetDefaultShortCut: TShortCut; override; function GetHelpString: string; override; function HasConfigOptions: Boolean; override; end; var AlignExpertInst: TAlignExpert; { TAlignExpert } constructor TAlignExpert.Create; begin inherited Create; FTokens := TStringList.Create; AlignExpertInst := Self; end; destructor TAlignExpert.Destroy; begin AlignExpertInst := nil; FreeAndNil(FTokens); inherited; end; procedure TAlignExpert.Configure; var Dlg: TfmAlignOptions; begin Dlg := TfmAlignOptions.Create(nil); try Dlg.edtWhitespace.Text := IntToStr(FWhitespace); Dlg.mmoTokens.Lines.Assign(FTokens); if Dlg.ShowModal = mrOk then begin FWhitespace := Min(StrToIntDef(Dlg.edtWhitespace.Text, 1), 100); FWhitespace := Max(FWhitespace, 0); FTokens.Assign(Dlg.mmoTokens.Lines); SaveSettings; end; finally FreeAndNil(Dlg); end; end; function TAlignExpert.GetDefaultShortCut: TShortCut; begin Result := scCtrl + scAlt + Ord('Z'); end; function TAlignExpert.GetDisplayName: string; resourcestring SAlignName = 'Align Lines'; begin Result := SAlignName; end; function TAlignExpert.GetHelpString: string; resourcestring SAlignHelp = ' This expert aligns the text of the selected lines at the first occurrence of a chosen token in each line. To use it, select a block of code in the code editor and activate this expert. '+ 'You may find this feature useful to align the right hand side of variable, field, or constant declarations and other similar lists.' + sLineBreak + ' There are two alignment modes. In the "Align at rightmost token" mode, the rightmost token found in the selected text becomes the column position the other lines are aligned to. '+ 'In the "Align at first token" mode, the first located token is used to determine the alignment column. In this second mode, any line whose token prefix is longer than the position of the first token will not be modified.' + sLineBreak + ' You can configure the list of tokens to align on as well as the minimum number of space characters that must precede a token that is being aligned.'; begin Result := SAlignHelp; end; class function TAlignExpert.GetName: string; begin Result := 'Align'; end; function TAlignExpert.HasConfigOptions: Boolean; begin Result := True; end; function TAlignExpert.ProcessSelected(Lines: TStrings): Boolean; resourcestring STokenListEmpty = 'The token list is empty.' + sLineBreak + 'Please add tokens using the configuration dialog.'; var TabSize: Integer; i: Integer; FirstIndex, PosIndex: Integer; RowLength, MaxRowLength: Integer; AlignIndex: Integer; Temp: string; MaxPos: Integer; LineSuffix: string; AlignToken: string; AlignMode: TGXAlignMode; begin Assert(Assigned(Lines)); Result := False; if Lines.Count < 2 then raise Exception.Create('Please select the lines of code to align first.'); if FTokens.Count = 0 then raise Exception.Create(STokenListEmpty); FSelectedText := Lines.Text; if not QueryUserForAlignToken(AlignToken, AlignMode) then Exit; FirstIndex := 0; RowLength := 0; MaxRowLength := 0; TabSize := GxOtaGetTabWidth; // Decide at what column to align by for i := 0 to Lines.Count - 1 do begin Temp := ExpandTabsInLine(Lines[i], TabSize); PosIndex := Pos(AlignToken, Temp); if (PosIndex > 0) and (FirstIndex = 0) then begin FirstIndex := PosIndex; // If first line contains token, only align based on that token if AlignMode = gamFirstToken then Break; end; if PosIndex > 0 then RowLength := Length(TrimRight(Copy(Temp, 1, PosIndex - 1))) + FWhitespace; if RowLength > MaxRowLength then MaxRowLength := RowLength; end; // Exit if nothing to align if FirstIndex = 0 then raise Exception.Create(SNoTokens); // Try to align at column of first found otherwise // align after the maximum length of a row if FirstIndex > MaxRowLength then AlignIndex := FirstIndex - 1 else AlignIndex := MaxRowLength; // Perform alignment for i := 0 to Lines.Count - 1 do begin PosIndex := Pos(AlignToken, Lines[i]); if PosIndex > 0 then begin Temp := TrimRight(Copy(Lines[i], 1, PosIndex - 1)); MaxPos := Max(AlignIndex - Length(ExpandTabsInLine(Temp, TabSize)), FWhitespace); LineSuffix := Copy(Lines[i], PosIndex, Length(Lines[i])); Lines[i] := Temp + StringOfChar(' ', MaxPos) + LineSuffix; end; end; Result := True; end; procedure TAlignExpert.InternalLoadSettings(Settings: TExpertSettings); var i: Integer; begin inherited InternalLoadSettings(Settings); // Do not localize any of the below items FWhitespace := Settings.ReadInteger('Whitespace', DEFAULT_WHITESPACE); Settings.ReadStrings('Tokens', FTokens, 'Tokens'); FLastToken := Settings.ReadString('Token', ''); FLastMode := TGXAlignMode(Settings.ReadEnumerated('Mode', TypeInfo(TGXAlignMode), Ord(FLastMode))); // If no tokens were found, create a default list of tokens if FTokens.Count = 0 then for i := Low(DEFAULT_TOKENS) to High(DEFAULT_TOKENS) do FTokens.Add(DEFAULT_TOKENS[i]); end; procedure TAlignExpert.InternalSaveSettings(Settings: TExpertSettings); begin inherited InternalSaveSettings(Settings); // Do not localize any of the below items Settings.WriteInteger('Whitespace', FWhitespace); Settings.WriteStrings('Tokens', FTokens, 'Tokens'); Settings.WriteString('Token', FLastToken); Settings.WriteEnumerated('Mode', TypeInfo(TGXAlignMode), Ord(FLastMode)); end; { TfmAlign } constructor TfmAlign.Create(_Owner: TComponent); begin inherited; TControl_SetMinConstraints(Self); end; procedure TfmAlign.lstTokensDblClick(Sender: TObject); begin ModalResult := mrOk; end; function TAlignExpert.QueryUserForAlignToken(var Token: string; var Mode: TGXAlignMode): Boolean; var Dialog: TfmAlign; begin Result := False; Mode := gamRightmost; Dialog := TfmAlign.Create(nil); try LoadConfiguration(Dialog); if Dialog.ShowModal = mrOk then begin Token := Dialog.lstTokens.Items[Dialog.lstTokens.ItemIndex]; if Dialog.cbxMode.ItemIndex > 0 then Mode := gamFirstToken; FLastToken := Token; FLastMode := Mode; SaveSettings; Result := True; end; finally FreeAndNil(Dialog); end; end; procedure TfmAlign.btnConfigClick(Sender: TObject); begin AlignExpertInst.Configure; AlignExpertInst.LoadConfiguration(Self); end; procedure TAlignExpert.LoadConfiguration(Dialog: TfmAlign); var LastIndex: Integer; begin AddStringsPresentInString(FTokens, Dialog.lstTokens.Items, FSelectedText); if Dialog.lstTokens.Count < 1 then raise Exception.Create(SNoTokens); LastIndex := Dialog.lstTokens.Items.IndexOf(FLastToken); if (FLastToken > '') and (LastIndex > -1) then Dialog.lstTokens.ItemIndex := LastIndex else Dialog.lstTokens.ItemIndex := 0; Dialog.cbxMode.ItemIndex := 0; if FLastMode <> gamRightmost then Dialog.cbxMode.ItemIndex := 1; end; initialization RegisterEditorExpert(TAlignExpert); end.
unit dmdMatFat75; interface uses Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, udmPadrao, DB, DBClient, ComCtrls, Bde.DBTables; type TdmodMatFat75 = class(TDataModule) qryRelatorioRec: TQuery; qryRelatorioOrd: TQuery; qryRelatorioRecFIL_ORIG: TStringField; qryRelatorioRecNR_CONTRATO: TIntegerField; qryRelatorioRecDT_EMISSAO: TDateTimeField; qryRelatorioRecVEICULO: TStringField; qryRelatorioRecNM_MOTORISTA: TStringField; qryRelatorioRecNM_PROPRIETARIO: TStringField; qryRelatorioRecVLRADIANTAMENTO: TFloatField; qryRelatorioRecVLRTOTAL: TFloatField; qryRelatorioRecAD_FILIAL: TStringField; qryRelatorioRecAD_AUTORIZACAO: TIntegerField; qryRelatorioRecAD_PARCELA: TIntegerField; qryRelatorioRecAD_VLRPARCELA: TFloatField; qryRelatorioRecAD_VLRTOTPARCS: TFloatField; qryRelatorioRecAD_STATUS: TStringField; qryRelatorioRecAD_OBS: TIntegerField; qryRelatorioRecVLRACERTO: TFloatField; qryRelatorioRecVLRSALDO: TFloatField; qryRelatorioOrdFIL_ORIG: TStringField; qryRelatorioOrdNR_CONTRATO: TFloatField; qryRelatorioOrdDT_EMISSAO: TDateTimeField; qryRelatorioOrdVEICULO: TStringField; qryRelatorioOrdNM_MOTORISTA: TStringField; qryRelatorioOrdNM_PROPRIETARIO: TStringField; qryRelatorioOrdVLRTOTAL: TFloatField; qryRelatorioOrdVLRADIANT: TFloatField; qryRelatorioOrdAD_FILIAL: TStringField; qryRelatorioOrdAD_AUTORIZACAO: TIntegerField; qryRelatorioOrdAD_PARCELA: TIntegerField; qryRelatorioOrdAD_VLRPARCELA: TFloatField; qryRelatorioOrdAD_VLRTOTPARCS: TFloatField; qryRelatorioOrdAD_STATUS: TStringField; qryRelatorioOrdAD_OBS: TIntegerField; qryRelatorioOrdVLRACERTO: TFloatField; qryRelatorioOrdVLRSALDO: TFloatField; qryRelatorioOrdSA_FILIAL: TStringField; qryRelatorioOrdSA_AUTORIZACAO: TIntegerField; qryRelatorioOrdSA_PARCELA: TIntegerField; qryRelatorioOrdSA_VLRPARCELA: TFloatField; qryRelatorioOrdSA_VLRTOTPARCS: TFloatField; qryRelatorioOrdSA_STATUS: TStringField; qryRelatorioOrdSA_OBS: TIntegerField; procedure DataModuleCreate(Sender: TObject); private FFilial: String; FDtIni: TDateTime; FDtFim: TDateTime; FProprietario: String; FMotorista: String; FVeiculo: String; function GetDtFim: TDateTime; function GetDtIni: TDateTime; function GetFilial: String; function GetMotorista: String; function GetProprietario: String; function GetVeiculo: String; procedure SetDtFim(const Value: TDateTime); procedure SetDtIni(const Value: TDateTime); procedure SetFilial(const Value: String); procedure SetMotorista(const Value: String); procedure SetProprietario(const Value: String); procedure SetVeiculo(const Value: String); public function Relatorio: Boolean; property Filial: String read GetFilial write SetFilial; property DtIni: TDateTime read GetDtIni write SetDtIni; property DtFim: TDateTime read GetDtFim write SetDtFim; property Proprietario: String read GetProprietario write SetProprietario; property Motorista: String read GetMotorista write SetMotorista; property Veiculo: String read GetVeiculo write SetVeiculo; end; var dmodMatFat75: TdmodMatFat75; implementation uses udmPrincipal; {$R *.dfm} { TdmodMatFat75 } function TdmodMatFat75.Relatorio: Boolean; begin //preenche qry da tabela STWOPETORD with qryRelatorioOrd do begin Close; SQL.Clear; SQL.Add('SELECT'); SQL.Add(' ORD.FIL_ORDEM AS FIL_ORIG,'); SQL.Add(' ORD.NR_ORDEM AS NR_CONTRATO,'); SQL.Add(' ORD.DT_ORDEM AS DT_EMISSAO,'); SQL.Add(' ORD.PLACA AS VEICULO,'); SQL.Add(' MOT.NOME AS NM_MOTORISTA,'); SQL.Add(' PRO.NOME AS NM_PROPRIETARIO,'); SQL.Add(' COALESCE(ORD.VLR_TOTAL, 0) AS VLRTOTAL,'); SQL.Add(' COALESCE(ORD.VLR_ADIANT, 0) AS VLRADIANT,'); SQL.Add(' AUT_ADI.FIL_ORIGEM AS AD_FILIAL,'); SQL.Add(' AUT_ADI.AUTORIZACAO AS AD_AUTORIZACAO,'); SQL.Add(' AUT_ADI.PARCELA AS AD_PARCELA,'); SQL.Add(' (SELECT SUM(CO.VL_PARCELA)'); SQL.Add(' FROM STWCPGTAUTP CO'); SQL.Add(' WHERE (CO.FIL_ORIGEM = AUT_ADI.FIL_ORIGEM'); SQL.Add(' AND CO.AUTORIZACAO = AUT_ADI.AUTORIZACAO'); SQL.Add(' AND CO.STATUS <> ' + QuotedStr('CA') + ')'); SQL.Add(' ) AS AD_VLRTOTPARCS,'); SQL.Add(' COALESCE(AUT_ADI.VL_PARCELA, 0) AS AD_VLRPARCELA,'); SQL.Add(' AUT_ADI.STATUS AS AD_STATUS,'); SQL.Add(' (SELECT COUNT(CO.AUTORIZACAO)'); SQL.Add(' FROM STWCPGTAUTP CO'); SQL.Add(' WHERE (CO.FIL_ORIGEM = AUT_ADI.FIL_ORIGEM'); SQL.Add(' AND CO.AUTORIZACAO = AUT_ADI.AUTORIZACAO'); SQL.Add(' AND CO.STATUS <> ' + QuotedStr('CA') + ')'); SQL.Add(' ) AS AD_OBS,'); SQL.Add(' (COALESCE(ORD.VLR_IRRF, 0) + COALESCE(ORD.VLR_ISS, 0) +'); SQL.Add(' COALESCE(ORD.ABASTECIMENTO, 0) + COALESCE(ORD.SEST_SENAT, 0) +'); SQL.Add(' COALESCE(ORD.EXPEDIENTE, 0) + COALESCE(ORD.VLR_DESCONTOS, 0) +'); SQL.Add(' COALESCE(ORD.MULTA, 0) - COALESCE(ORD.PEDAGIO, 0)) - COALESCE(ORD.VLR_OUTROS, 0) AS VLRACERTO,'); SQL.Add(' COALESCE(ORD.VLR_LIQ, 0) AS VLRSALDO,'); SQL.Add(' AUT_SAL.FIL_ORIGEM AS SA_FILIAL,'); SQL.Add(' AUT_SAL.AUTORIZACAO AS SA_AUTORIZACAO,'); SQL.Add(' AUT_SAL.PARCELA AS SA_PARCELA,'); SQL.Add(' COALESCE(AUT_SAL.VL_PARCELA, 0) AS SA_VLRPARCELA,'); SQL.Add(' (SELECT SUM(CO.VL_PARCELA)'); SQL.Add(' FROM STWCPGTAUTP CO'); SQL.Add(' WHERE (CO.FIL_ORIGEM = AUT_SAL.FIL_ORIGEM'); SQL.Add(' AND CO.AUTORIZACAO = AUT_SAL.AUTORIZACAO'); SQL.Add(' AND CO.STATUS <> ' + QuotedStr('CA') + ')'); SQL.Add(' ) AS SA_VLRTOTPARCS,'); SQL.Add(' AUT_SAL.STATUS AS SA_STATUS,'); SQL.Add(' (SELECT COUNT(CO.AUTORIZACAO)'); SQL.Add(' FROM STWCPGTAUTP CO'); SQL.Add(' WHERE (CO.FIL_ORIGEM = AUT_SAL.FIL_ORIGEM'); SQL.Add(' AND CO.AUTORIZACAO = AUT_SAL.AUTORIZACAO'); SQL.Add(' AND CO.STATUS <> ' + QuotedStr('CA') + ')'); SQL.Add(' ) AS SA_OBS'); SQL.Add('FROM STWOPETORD ORD'); SQL.Add('LEFT JOIN STWOPETMOT MOT'); SQL.Add(' ON (ORD.COD_MOT = MOT.CPF)'); SQL.Add('LEFT JOIN STWOPETMOT PRO'); SQL.Add(' ON (ORD.COD_PRO = PRO.CPF)'); SQL.Add('LEFT JOIN STWCPGTAUTP AUT_ADI'); SQL.Add(' ON (ORD.FIL_ORIG = AUT_ADI.FIL_ORIGEM'); SQL.Add(' AND ORD.AUTORIZACAO = AUT_ADI.AUTORIZACAO'); SQL.Add(' AND ORD.PARCELA = AUT_ADI.PARCELA'); SQL.Add(' AND (AUT_ADI.STATUS <> ' + QuotedStr('CA') + ' OR (AUT_ADI.AUTORIZACAO IS NULL)))'); SQL.Add('LEFT JOIN STWCPGTAUTP AUT_SAL'); SQL.Add(' ON (ORD.FIL_ORIG_PG = AUT_SAL.FIL_ORIGEM'); SQL.Add(' AND ORD.AUTORIZACAO_PG = AUT_SAL.AUTORIZACAO'); SQL.Add(' AND ORD.PARCELA_PG = AUT_SAL.PARCELA'); SQL.Add(' AND (AUT_SAL.STATUS <> ' + QuotedStr('CA') + ' OR (AUT_SAL.AUTORIZACAO IS NULL)))'); SQL.Add('WHERE ORD.DT_ORDEM BETWEEN :DT_INI AND :DT_FIM'); SQL.Add(' AND (ORD.STATUS <> ' + QuotedStr('CA') + 'OR (ORD.STATUS IS NULL))'); if Length(Trim(Filial)) > 0 then SQL.Add('AND ORD.FIL_ORDEM = ' + QuotedStr(Filial)); if Length(Trim(Proprietario)) > 0 then SQL.Add('AND PRO.CPF = ' + QuotedStr(Proprietario)); if Length(Trim(Motorista)) > 0 then SQL.Add('AND MOT.CPF = ' + QuotedStr(Motorista)); if Length(Trim(Veiculo)) > 0 then SQL.Add('AND ORD.PLACA = ' + QuotedStr(Veiculo)); ParamByName('DT_INI').AsDateTime := DtIni; ParamByName('DT_FIM').AsDateTime := DtFim; Open; end; //preenche qry da tabela STWCOLTREC with qryRelatorioRec do begin Close; SQL.Clear; SQL.Add('SELECT'); SQL.Add(' REC.FIL_ORIG AS FIL_ORIG,'); SQL.Add(' REC.RECIBO AS NR_CONTRATO,'); SQL.Add(' REC.DT_EMISSAO AS DT_EMISSAO,'); SQL.Add(' REC.VEICULO AS VEICULO,'); SQL.Add(' MOT.NOME AS NM_MOTORISTA,'); SQL.Add(' PRO.NOME AS NM_PROPRIETARIO,'); SQL.Add(' COALESCE(REC.ADIANTAMENTO, 0) AS VLRADIANTAMENTO,'); SQL.Add(' (COALESCE(REC.VLR_DIARIAS, 0) + COALESCE(REC.VLR_COLETAS, 0) +'); SQL.Add(' COALESCE(REC.VLR_ENTREGAS, 0) + COALESCE(REC.QUILOMETRAGEM, 0) +'); SQL.Add(' COALESCE(REC.REEMBOLSO, 0)) AS VLRTOTAL,'); SQL.Add(' AUT_REC.FIL_ORIGEM AS AD_FILIAL,'); SQL.Add(' AUT_REC.AUTORIZACAO AS AD_AUTORIZACAO,'); SQL.Add(' AUT_REC.PARCELA AS AD_PARCELA,'); SQL.Add(' COALESCE(AUT_REC.VL_PARCELA, 0) AS AD_VLRPARCELA,'); SQL.Add(' (SELECT SUM(CO.VL_PARCELA)'); SQL.Add(' FROM STWCPGTAUTP CO'); SQL.Add(' WHERE (CO.FIL_ORIGEM = AUT_REC.FIL_ORIGEM'); SQL.Add(' AND CO.AUTORIZACAO = AUT_REC.AUTORIZACAO'); SQL.Add(' AND CO.STATUS <> ' + QuotedStr('CA') + ')'); SQL.Add(' ) AS AD_VLRTOTPARCS,'); SQL.Add(' AUT_REC.STATUS AS AD_STATUS,'); SQL.Add(' (SELECT COUNT(CO.AUTORIZACAO)'); SQL.Add(' FROM STWCPGTAUTP CO'); SQL.Add(' WHERE (CO.FIL_ORIGEM = AUT_REC.FIL_ORIGEM'); SQL.Add(' AND CO.AUTORIZACAO = AUT_REC.AUTORIZACAO'); SQL.Add(' AND CO.STATUS <> ' + QuotedStr('CA') + ')'); SQL.Add(' ) AS AD_OBS,'); SQL.Add(' (COALESCE(REC.VLR_IRRF, 0) + COALESCE(REC.INPS, 0) +'); SQL.Add(' COALESCE(REC.SEST_SENAT, 0) + COALESCE(REC.DESCONTOS, 0)) AS VLRACERTO,'); SQL.Add(' COALESCE(REC.VLR_LIQUIDO, 0) AS VLRSALDO'); SQL.Add('FROM STWCOLTREC REC'); SQL.Add('LEFT JOIN STWOPETMOT MOT'); SQL.Add(' ON (REC.MOTORISTA = MOT.CPF)'); SQL.Add('LEFT JOIN STWOPETVEI VEI'); SQL.Add(' ON (REC.VEICULO = VEI.FROTA)'); SQL.Add('LEFT JOIN STWOPETMOT PRO'); SQL.Add(' ON (VEI.CGC_PRO = PRO.CPF)'); SQL.Add('LEFT JOIN STWCPGTAUTP AUT_REC'); SQL.Add(' ON (REC.FIL_ORIGEM = AUT_REC.FIL_ORIGEM'); SQL.Add(' AND REC.AUTORIZACAO = AUT_REC.AUTORIZACAO'); SQL.Add(' AND REC.PARCELA = AUT_REC.PARCELA'); SQL.Add(' AND (AUT_REC.STATUS <> ' + QuotedStr('CA') + ' OR (AUT_REC.AUTORIZACAO IS NULL)))'); SQL.Add('WHERE REC.DT_EMISSAO BETWEEN :DT_INI AND :DT_FIM'); SQL.Add(' AND (REC.STATUS <> ' + QuotedStr('CA') + ' OR (REC.STATUS IS NULL))'); if Length(Trim(Filial)) > 0 then SQL.Add('AND REC.FIL_ORIG = ' + QuotedStr(Filial)); if Length(Trim(Proprietario)) > 0 then SQL.Add('AND PRO.CPF = ' + QuotedStr(Proprietario)); if Length(Trim(Motorista)) > 0 then SQL.Add('AND MOT.CPF = ' + QuotedStr(Motorista)); if Length(Trim(Veiculo)) > 0 then SQL.Add('AND REC.VEICULO = ' + QuotedStr(Veiculo)); ParamByName('DT_INI').AsDateTime := DtIni; ParamByName('DT_FIM').AsDateTime := DtFim; Open; end; if (not qryRelatorioRec.IsEmpty) or (not qryRelatorioOrd.IsEmpty) then Result := True; end; procedure TdmodMatFat75.DataModuleCreate(Sender: TObject); begin qryRelatorioOrd.Close; qryRelatorioOrd.Connection := 'dtbConexaoBanco'; qryRelatorioRec.Close; qryRelatorioRec.Connection := 'dtbConexaoBanco'; end; function TdmodMatFat75.GetDtFim: TDateTime; begin Result := FDtFim; end; function TdmodMatFat75.GetDtIni: TDateTime; begin Result := FDtIni; end; function TdmodMatFat75.GetFilial: String; begin Result := FFilial; end; function TdmodMatFat75.GetMotorista: String; begin Result := FMotorista; end; function TdmodMatFat75.GetProprietario: String; begin Result := FProprietario; end; function TdmodMatFat75.GetVeiculo: String; begin Result := FVeiculo; end; procedure TdmodMatFat75.SetDtFim(const Value: TDateTime); begin FDtFim := Value; end; procedure TdmodMatFat75.SetDtIni(const Value: TDateTime); begin FDtIni := Value; end; procedure TdmodMatFat75.SetFilial(const Value: String); begin FFilial := Value; end; procedure TdmodMatFat75.SetMotorista(const Value: String); begin FMotorista := Value; end; procedure TdmodMatFat75.SetProprietario(const Value: String); begin FProprietario := Value; end; procedure TdmodMatFat75.SetVeiculo(const Value: String); begin FVeiculo := Value; end; end.
unit DockForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Menus; type TForm1 = class(TForm) PopupMenu1: TPopupMenu; menuToggleFloating: TMenuItem; Panel1: TPanel; Memo1: TMemo; Panel2: TPanel; Button2: TButton; Button3: TButton; ListBox1: TListBox; N1: TMenuItem; menuFloatPanel: TMenuItem; menuFloatMemo: TMenuItem; menuFloatListBox: TMenuItem; procedure FormCreate(Sender: TObject); procedure Panel1DockDrop(Sender: TObject; Source: TDragDockObject; X, Y: Integer); procedure ControlStartDock(Sender: TObject; var DragObject: TDragDockObject); procedure Panel1DockOver(Sender: TObject; Source: TDragDockObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure menuToggleFloatingClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure menuFloatPanelClick(Sender: TObject); procedure menuFloatMemoClick(Sender: TObject); procedure menuFloatListBoxClick(Sender: TObject); private DockFileName: string; public { Public declarations } end; var Form1: TForm1; implementation {uses DockHost;} {$R *.DFM} procedure TForm1.FormCreate(Sender: TObject); var FileStr: TFileStream; i: Integer; aRect: TRect; aCtrl: TControl; begin // just in case... if not Assigned (Panel1.DockManager) then raise Exception.Create ('No Dock Manager'); // or create one! // Panel1.DockManager := DefaultDockTreeClass.Create (Panel1); Panel1.DockOrientation := doHorizontal; // dock memo Memo1.Dock(Panel1, Rect (0, 0, 100, 100)); Panel1.DockManager.InsertControl(Memo1, alTop, Panel1); // dock listbox ListBox1.Dock(Panel1, Rect (0, 100, 100, 100)); Panel1.DockManager.InsertControl(ListBox1, alLeft, Panel1); // dock panel2 Panel2.Dock(Panel1, Rect (100, 0, 100, 100)); Panel1.DockManager.InsertControl(Panel2, alBottom, Panel1); // it is very hard to make this work properly! // Memo1.FloatingDockSiteClass := TForm2; // relaod the settings DockFileName := ExtractFilePath (Application.Exename) + 'dock.dck'; if FileExists (DockFileName) then begin FileStr := TFileStream.Create (DockFileName, fmOpenRead); try Panel1.DockManager.LoadFromStream (FileStr); finally FileStr.Free; end; end; Panel1.DockManager.ResetBounds (True); // fix up the floating panels for i := Panel1.DockClientCount - 1 downto 0 do begin // test the status // ShowMessage (Panel1.DockClients[i].ClassName); // ShowMessage (Panel1.DockClients[i].Parent.ClassName); aCtrl := Panel1.DockClients[i]; Panel1.DockManager.GetControlBounds(aCtrl, aRect); {ShowMessage ('Left.Top=' + IntToStr (aRect.Left) + '.' + IntToStr (aRect.Top) + ' - Right.Bottom=' + IntToStr (aRect.Right) + '.' + IntToStr (aRect.Bottom));} if (aRect.Bottom - aRect.Top <= 0) then begin aCtrl.ManualFloat (aCtrl.ClientRect); Panel1.DockManager.RemoveControl(aCtrl); end; end; end; procedure TForm1.Panel1DockDrop(Sender: TObject; Source: TDragDockObject; X, Y: Integer); begin Caption := 'Docked: ' + IntToStr (DockClientCount); end; procedure TForm1.ControlStartDock(Sender: TObject; var DragObject: TDragDockObject); begin Caption := 'Docking ' + (Sender as TComponent).Name; end; procedure TForm1.Panel1DockOver(Sender: TObject; Source: TDragDockObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin Caption := 'Docking: ' + Source.Control.Name; Accept := True; end; procedure TForm1.menuToggleFloatingClick(Sender: TObject); var aCtrl: TControl; begin aCtrl := Sender as TControl; // toggle the floating status if aCtrl.Floating then aCtrl.ManualDock (Panel1, nil, alBottom) else aCtrl.ManualFloat (Rect (100, 100, 200, 300)); end; procedure TForm1.FormDestroy(Sender: TObject); var FileStr: TFileStream; begin if Panel1.DockClientCount > 0 then begin FileStr := TFileStream.Create (DockFileName, fmCreate or fmOpenWrite); try Panel1.DockManager.SaveToStream (FileStr); finally FileStr.Free; end; end else // remove the file DeleteFile (DockFileName); end; procedure TForm1.menuFloatPanelClick(Sender: TObject); begin Panel2.ManualFloat (Rect (100, 100, 200, 300)); end; procedure TForm1.menuFloatMemoClick(Sender: TObject); begin Memo1.ManualFloat (Rect (100, 100, 200, 300)); end; procedure TForm1.menuFloatListBoxClick(Sender: TObject); begin ListBox1.ManualFloat (Rect (100, 100, 200, 300)); end; end.
//////////////////////////////////////////////////////////////////////////////// // // // FileName : SUIGrid.pas // Creator : Shen Min // Date : 2003-04-03 V1-V3 // 3003-07-04 V4 // Comment : // // Copyright (c) 2002-2003 Sunisoft // http://www.sunisoft.com // Email: support@sunisoft.com // //////////////////////////////////////////////////////////////////////////////// unit SUIGrid; interface {$I SUIPack.inc} uses Windows, Messages, SysUtils, Classes, Controls, Grids, Graphics, Forms, SUIThemes, SUIScrollBar, SUIMgr; type {$IFDEF SUIPACK_D5} TsuiCustomDrawGrid = class(TDrawGrid) {$ENDIF} {$IFDEF SUIPACK_D6UP} TsuiCustomDrawGrid = class(TCustomDrawGrid) {$ENDIF} private m_BorderColor : TColor; m_FocusedColor : TColor; m_SelectedColor : TColor; m_UIStyle : TsuiUIStyle; m_FileTheme : TsuiFileTheme; m_FixedFontColor: TColor; procedure SetBorderColor(const Value: TColor); procedure WMEARSEBKGND(var Msg : TMessage); message WM_ERASEBKGND; procedure SetUIStyle(const Value: TsuiUIStyle); procedure SetFocusedColor(const Value: TColor); procedure SetSelectedColor(const Value: TColor); procedure SetFixedFontColor(const Value: TColor); function GetCtl3D: Boolean; procedure SetFontColor(const Value: TColor); function GetFontColor: TColor; procedure SetFileTheme(const Value: TsuiFileTheme); protected procedure DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); override; procedure Paint(); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create (AOwner: TComponent); override; published property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme; property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle; property Color; property FixedColor; property BorderColor : TColor read m_BorderColor write SetBorderColor; property FocusedColor : TColor read m_FocusedColor write SetFocusedColor; property SelectedColor : TColor read m_SelectedColor write SetSelectedColor; property FixedFontColor : TColor read m_FixedFontColor write SetFixedFontColor; property FontColor : TColor read GetFontColor write SetFontColor; property Ctl3D read GetCtl3D; end; TsuiDrawGrid = class(TsuiCustomDrawGrid) published property Align; property Anchors; property BiDiMode; property BorderStyle; property ColCount; property Constraints; property DefaultColWidth; property DefaultRowHeight; property DefaultDrawing; property DragCursor; property DragKind; property DragMode; property Enabled; property FixedCols; property RowCount; property FixedRows; property Font; property GridLineWidth; property Options; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ScrollBars; property ShowHint; property TabOrder; property Visible; property VisibleColCount; property VisibleRowCount; property OnClick; property OnColumnMoved; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnDrawCell; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnGetEditMask; property OnGetEditText; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheelDown; property OnMouseWheelUp; property OnRowMoved; property OnSelectCell; property OnSetEditText; property OnStartDock; property OnStartDrag; property OnTopLeftChanged; end; TsuiStringGrid = class(TStringGrid) private m_BorderColor : TColor; m_FocusedColor : TColor; m_SelectedColor : TColor; m_UIStyle : TsuiUIStyle; m_FixedFontColor: TColor; m_FileTheme : TsuiFileTheme; procedure SetBorderColor(const Value: TColor); procedure SetFocusedColor(const Value: TColor); procedure SetSelectedColor(const Value: TColor); procedure SetUIStyle(const Value: TsuiUIStyle); procedure SetFixedFontColor(const Value: TColor); function GetCtl3D: Boolean; procedure SetFontColor(const Value: TColor); function GetFontColor: TColor; procedure SetFileTheme(const Value: TsuiFileTheme); function GetBGColor: TColor; procedure SetBGColor(const Value: TColor); function GetFixedBGColor: TColor; procedure SetFixedBGColor(const Value: TColor); procedure WMEARSEBKGND(var Msg : TMessage); message WM_ERASEBKGND; protected procedure DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); override; procedure Paint(); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create (AOwner: TComponent); override; published property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme; property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle; property BGColor : TColor read GetBGColor write SetBGColor; property BorderColor : TColor read m_BorderColor write SetBorderColor; property FocusedColor : TColor read m_FocusedColor write SetFocusedColor; property SelectedColor : TColor read m_SelectedColor write SetSelectedColor; property FixedFontColor : TColor read m_FixedFontColor write SetFixedFontColor; property FixedBGColor : TColor read GetFixedBGColor write SetFixedBGColor; property FontColor : TColor read GetFontColor write SetFontColor; property Ctl3D read GetCtl3D; end; implementation uses SUIPublic, SUIProgressBar; { TsuiCustomDrawGrid } constructor TsuiCustomDrawGrid.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [csOpaque]; BorderStyle := bsNone; BorderWidth := 1; UIStyle := GetSUIFormStyle(AOwner); FocusedColor := clGreen; SelectedColor := clYellow; ParentCtl3D := false; inherited Ctl3D := false; end; procedure TsuiCustomDrawGrid.DrawCell(ACol, ARow: Integer; ARect: TRect; AState: TGridDrawState); var R : TRect; begin if not DefaultDrawing then begin inherited; exit; end; R := ARect; try if gdFixed in AState then Exit; if gdSelected in AState then begin Canvas.Brush.Color := m_SelectedColor; end; if gdFocused in AState then begin Canvas.Brush.Color := m_FocusedColor; end; if AState = [] then Canvas.Brush.Color := Color; Canvas.FillRect(R); finally inherited; end; end; function TsuiCustomDrawGrid.GetCtl3D: Boolean; begin Result := false; end; function TsuiCustomDrawGrid.GetFontColor: TColor; begin Result := Font.Color; end; procedure TsuiCustomDrawGrid.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if ( (Operation = opRemove) and (AComponent = m_FileTheme) )then begin m_FileTheme := nil; SetUIStyle(SUI_THEME_DEFAULT); end; end; procedure TsuiCustomDrawGrid.Paint; begin inherited; DrawControlBorder(self, m_BorderColor, Color); end; procedure TsuiCustomDrawGrid.SetBorderColor(const Value: TColor); begin m_BorderColor := Value; Repaint(); end; procedure TsuiCustomDrawGrid.SetFileTheme(const Value: TsuiFileTheme); begin m_FileTheme := Value; SetUIStyle(m_UIStyle); end; procedure TsuiCustomDrawGrid.SetFixedFontColor(const Value: TColor); begin m_FixedFontColor := Value; Repaint(); end; procedure TsuiCustomDrawGrid.SetFocusedColor(const Value: TColor); begin m_FocusedColor := Value; Repaint(); end; procedure TsuiCustomDrawGrid.SetFontColor(const Value: TColor); begin Font.Color := Value; Repaint(); end; procedure TsuiCustomDrawGrid.SetSelectedColor(const Value: TColor); begin m_SelectedColor := Value; Repaint(); end; procedure TsuiCustomDrawGrid.SetUIStyle(const Value: TsuiUIStyle); var OutUIStyle : TsuiUIStyle; begin m_UIStyle := Value; if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then begin BorderColor := m_FileTheme.GetColor(SUI_THEME_CONTROL_BORDER_COLOR); FixedColor := m_FileTheme.GetColor(SUI_THEME_MENU_SELECTED_BACKGROUND_COLOR); Color := m_FileTheme.GetColor(SUI_THEME_CONTROL_BACKGROUND_COLOR); FixedFontColor := m_FileTheme.GetColor(SUI_THEME_MENU_SELECTED_FONT_COLOR); Font.Color := m_FileTheme.GetColor(SUI_THEME_MENU_FONT_COLOR); if (Font.Color = clWhite) then Font.Color := clBlack; end else begin BorderColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_CONTROL_BORDER_COLOR); FixedColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_MENU_SELECTED_BACKGROUND_COLOR); Color := GetInsideThemeColor(OutUIStyle, SUI_THEME_CONTROL_BACKGROUND_COLOR); FixedFontColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_MENU_SELECTED_FONT_COLOR); Font.Color := GetInsideThemeColor(OutUIStyle, SUI_THEME_MENU_FONT_COLOR); if (Font.Color = clWhite) then Font.Color := clBlack; end; end; procedure TsuiCustomDrawGrid.WMEARSEBKGND(var Msg: TMessage); begin Paint(); end; { TsuiStringGrid } constructor TsuiStringGrid.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [csOpaque]; BorderStyle := bsNone; BorderWidth := 1; UIStyle := GetSUIFormStyle(AOwner); FocusedColor := clLime; SelectedColor := clYellow; ParentCtl3D := false; inherited Ctl3D := false; end; procedure TsuiStringGrid.DrawCell(ACol, ARow: Integer; ARect: TRect; AState: TGridDrawState); var R : TRect; begin if not DefaultDrawing then begin inherited; exit; end; R := ARect; try if gdFixed in AState then Exit; if gdSelected in AState then begin Canvas.Brush.Color := m_SelectedColor; end; if gdFocused in AState then begin Canvas.Brush.Color := m_FocusedColor; end; if AState = [] then Canvas.Brush.Color := Color; Canvas.FillRect(R); finally if gdFixed in AState then begin Canvas.Font.Color := m_FixedFontColor; Canvas.TextRect(ARect, ARect.Left + 2, ARect.Top + 2, Cells[ACol, ARow]); end; inherited; end; end; function TsuiStringGrid.GetBGColor: TColor; begin Result := Color; end; function TsuiStringGrid.GetCtl3D: Boolean; begin Result := false; end; function TsuiStringGrid.GetFixedBGColor: TColor; begin Result := FixedColor; end; function TsuiStringGrid.GetFontColor: TColor; begin Result := Font.Color; end; procedure TsuiStringGrid.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if ( (Operation = opRemove) and (AComponent = m_FileTheme) )then begin m_FileTheme := nil; SetUIStyle(SUI_THEME_DEFAULT); end; end; procedure TsuiStringGrid.Paint; begin inherited; DrawControlBorder(self, m_BorderColor, Color, false); end; procedure TsuiStringGrid.SetBGColor(const Value: TColor); begin Color := Value; end; procedure TsuiStringGrid.SetBorderColor(const Value: TColor); begin m_BorderColor := Value; Repaint(); end; procedure TsuiStringGrid.SetFileTheme(const Value: TsuiFileTheme); begin m_FileTheme := Value; SetUIStyle(m_UIStyle); end; procedure TsuiStringGrid.SetFixedBGColor(const Value: TColor); begin FixedColor := Value; end; procedure TsuiStringGrid.SetFixedFontColor(const Value: TColor); begin m_FixedFontColor := Value; Repaint(); end; procedure TsuiStringGrid.SetFocusedColor(const Value: TColor); begin m_FocusedColor := Value; Repaint(); end; procedure TsuiStringGrid.SetFontColor(const Value: TColor); begin Font.Color := Value; Repaint(); end; procedure TsuiStringGrid.SetSelectedColor(const Value: TColor); begin m_SelectedColor := Value; Repaint(); end; procedure TsuiStringGrid.SetUIStyle(const Value: TsuiUIStyle); var OutUIStyle : TsuiUIStyle; begin m_UIStyle := Value; if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then begin BorderColor := m_FileTheme.GetColor(SUI_THEME_CONTROL_BORDER_COLOR); FixedColor := m_FileTheme.GetColor(SUI_THEME_MENU_SELECTED_BACKGROUND_COLOR); Color := m_FileTheme.GetColor(SUI_THEME_CONTROL_BACKGROUND_COLOR); FixedFontColor := m_FileTheme.GetColor(SUI_THEME_MENU_SELECTED_FONT_COLOR); Font.Color := m_FileTheme.GetColor(SUI_THEME_MENU_FONT_COLOR); if (Font.Color = clWhite) then Font.Color := clBlack; end else begin BorderColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_CONTROL_BORDER_COLOR); FixedColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_MENU_SELECTED_BACKGROUND_COLOR); Color := GetInsideThemeColor(OutUIStyle, SUI_THEME_CONTROL_BACKGROUND_COLOR); FixedFontColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_MENU_SELECTED_FONT_COLOR); Font.Color := GetInsideThemeColor(OutUIStyle, SUI_THEME_MENU_FONT_COLOR); if (Font.Color = clWhite) then Font.Color := clBlack; end; end; procedure TsuiStringGrid.WMEARSEBKGND(var Msg: TMessage); begin Paint(); end; end.
{$I OVC.INC} {$B-} {Complete Boolean Evaluation} {$I+} {Input/Output-Checking} {$P+} {Open Parameters} {$T-} {Typed @ Operator} {$W-} {Windows Stack Frame} {$X+} {Extended Syntax} {$IFNDEF Win32} {$G+} {286 Instructions} {$N+} {Numeric Coprocessor} {$C MOVEABLE,DEMANDLOAD,DISCARDABLE} {$ENDIF} {*********************************************************} {* OVCISEB.PAS 2.17 *} {* Copyright (c) 1995-98 TurboPower Software Co *} {* All rights reserved. *} {*********************************************************} unit OvcISEB; {-abstract incremental search edit control base class} interface uses {$IFDEF Win32} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} Classes, Controls, ExtCtrls, Forms, Graphics, Menus, StdCtrls, SysUtils, OvcBase, OvcExcpt; const DefAutoSearch = True; DefCaseSensitive = False; DefKeyDelay = 500; DefShowResults = True; type TOvcBaseISE = class(TCustomEdit) {.Z+} protected {private} {property variables} FAutoSearch : Boolean; FCaseSensitive : Boolean; FController : TOvcController; FKeyDelay : Integer; FPreviousText : string; FShowResults : Boolean; {internal variables} isTimer : Integer; {timer-pool handle} {property methods} procedure SetAutoSearch(Value : Boolean); procedure SetController(Value : TOvcController); procedure SetKeyDelay(Value : Integer); {internal methods} procedure isTimerEvent(Sender : TObject; Handle : Integer; Interval : Word; ElapsedTime : LongInt); protected procedure CreateWnd; override; procedure KeyUp(var Key : Word; Shift : TShiftState); override; procedure Notification(AComponent : TComponent; Operation : TOperation); override; {protected properties} property AutoSearch : Boolean read FAutoSearch write SetAutoSearch default DefAutoSearch; property CaseSensitive : Boolean read FCaseSensitive write FCaseSensitive default DefCaseSensitive; property Controller : TOvcController read FController write SetController; property KeyDelay : Integer read FKeyDelay write SetKeyDelay default DefKeyDelay; property ShowResults : Boolean read FShowResults write FShowResults default DefShowResults; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property PreviousText : string read FPreviousText write FPreviousText; function ISUpperCase(const S : string) : string; {return the UpperCase(S) if not CaseSensitive} {.Z-} {public methods} procedure PerformSearch; virtual; abstract; {search for Text} end; implementation {$IFDEF TRIALRUN} uses OrTrial; {$I ORTRIALF.INC} {$ENDIF} {*** TOvcBaseISE ***} constructor TOvcBaseISE.Create(AOwner : TComponent); begin inherited Create(AOwner); if (csDesigning in ComponentState) then Text := Name else Text := ''; {initialize property variables} FAutoSearch := DefAutoSearch; FCaseSensitive := DefCaseSensitive; FKeyDelay := DefKeyDelay; FShowResults := DefShowResults; isTimer := -1; end; procedure TOvcBaseISE.CreateWnd; var OurForm : TForm; {$IFDEF TRIALRUN} X : Integer; {$ENDIF} begin OurForm := GetImmediateParentForm(Self); {do this only when the component is first dropped on the form, not during loading} if (csDesigning in ComponentState) and not (csLoading in ComponentState) then ResolveController(OurForm, FController); if not Assigned(FController) and not (csLoading in ComponentState) then begin {try to find a controller on this form that we can use} FController := FindController(OurForm); {if not found and we are not designing, raise exception} if not Assigned(FController) and not (csDesigning in ComponentState) then raise ENoControllerAssigned.Create; end; inherited CreateWnd; {$IFDEF TRIALRUN} X := _CC_; if (X < ccRangeLow) or (X > ccRangeHigh) then Halt; X := _VC_; if (X < ccRangeLow) or (X > ccRangeHigh) then Halt; {$ENDIF} end; destructor TOvcBaseISE.Destroy; begin if Assigned(FController) and (isTimer > -1) then begin FController.TimerPool.Remove(isTimer); isTimer := -1; end; inherited Destroy; end; procedure TOvcBaseISE.isTimerEvent(Sender : TObject; Handle : Integer; Interval : Word; ElapsedTime : LongInt); begin {perform a search if modified} if Modified then begin Modified := False; isTimer := -1; PerformSearch; end; end; function TOvcBaseISE.ISUpperCase(const S : string) : string; {return the UpperCase(S) if not CaseSensitive} begin if not CaseSensitive then Result := UpperCase(S) else Result := S; end; procedure TOvcBaseISE.KeyUp(var Key : Word; Shift : TShiftState); var DoIt : Boolean; begin DoIt := True; if (ISUpperCase(Text) = PreviousText) then DoIt := False; inherited KeyUp(Key, Shift); {start/reset timer} if AutoSearch and DoIt then begin {see if we need to reset our timer} if (isTimer > -1) then Controller.TimerPool.Remove(isTimer); isTimer := Controller.TimerPool.AddOneTime(isTimerEvent, FKeyDelay); end; end; procedure TOvcBaseISE.Notification(AComponent : TComponent; Operation : TOperation); begin inherited Notification(AComponent, Operation); if (AComponent = FController) and (Operation = opRemove) then FController := nil else if (Operation = opInsert) and (FController = nil) and (AComponent is TOvcController) then FController := TOvcController(AComponent); end; procedure TOvcBaseISE.SetAutoSearch(Value : Boolean); begin if (Value <> FAutoSearch) then begin FAutoSearch := Value; RecreateWnd; end; end; procedure TOvcBaseISE.SetController(Value : TOvcController); begin FController := Value; {$IFDEF Win32} if Value <> nil then Value.FreeNotification(Self); {$ENDIF} end; procedure TOvcBaseISE.SetKeyDelay(Value : Integer); begin if (Value <> FKeyDelay) and (Value >= 0) then begin FKeyDelay := Value; end; end; end.
unit Enigma; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type /// <summary> /// Removes the specified item from the collection /// </summary> /// <param name="Item">The item to remove /// /// </param> /// <param name="Collection">The group containing the item /// </param> /// /// <remarks> /// If parameter "Item" is null, an exception is raised. /// <see cref="EArgumentNilException"/> /// </remarks> TEnigma2 = class(TForm) {$Region 'UI Members'} Label1: TLabel; Label2: TLabel; m_btnStart: TButton; StaticText1: TStaticText; StaticText2: TStaticText; StaticText3: TStaticText; StaticText4: TStaticText; m_lblOutputText: TStaticText; m_lblInputText: TStaticText; texiz: TEdit; m_rbxEncr: TRadioButton; m_rbxDecr: TRadioButton; texvl: TEdit; m_btnSpace: TButton; m_btnReset: TButton; m_btnNum1: TButton; m_btnNum2: TButton; m_btnNum3: TButton; m_btnNum4: TButton; m_btnNum5: TButton; m_btnNum6: TButton; m_btnNum7: TButton; m_btnNum8: TButton; m_btnNum9: TButton; m_btnNum0: TButton; {$endregion} {$region 'UI Callbacks'} procedure m_btnStartClick(Sender: TObject); procedure m_btnAClick(Sender: TObject); procedure m_btnBClick(Sender: TObject); procedure m_btnQClick(Sender: TObject); procedure m_btnWClick(Sender: TObject); procedure m_rbxEncrClick(Sender: TObject); procedure m_rbxDecrClick(Sender: TObject); procedure m_btnEClick(Sender: TObject); procedure m_btnRClick(Sender: TObject); procedure m_btnTClick(Sender: TObject); procedure m_btnYClick(Sender: TObject); procedure m_btnUClick(Sender: TObject); procedure m_btnIClick(Sender: TObject); procedure m_btnOClick(Sender: TObject); procedure m_btnPClick(Sender: TObject); procedure m_btnSClick(Sender: TObject); procedure m_btnDClick(Sender: TObject); procedure m_btnFClick(Sender: TObject); procedure m_btnGClick(Sender: TObject); procedure m_btnKeyHClick(Sender: TObject); procedure m_btnKeyJClick(Sender: TObject); procedure m_btnVClick(Sender: TObject); procedure m_btnKClick(Sender: TObject); procedure m_btnLClick(Sender: TObject); procedure m_btnZClick(Sender: TObject); procedure m_btnXClick(Sender: TObject); procedure m_btnCClick(Sender: TObject); procedure m_btnNClick(Sender: TObject); procedure m_btnMClick(Sender: TObject); procedure m_btnSpaceClick(Sender: TObject); procedure m_btnResetClick(Sender: TObject); procedure m_btnNum1Click(Sender: TObject); procedure m_btnNum2Click(Sender: TObject); procedure m_btnNum3Click(Sender: TObject); procedure m_btnNum4Click(Sender: TObject); procedure m_btnNum5Click(Sender: TObject); procedure m_btnNum6Click(Sender: TObject); procedure m_btnNum7Click(Sender: TObject); procedure m_btnNum8Click(Sender: TObject); procedure m_btnNum9Click(Sender: TObject); procedure m_btnNum0Click(Sender: TObject); {$endregion} private { Private declarations } public { Public declarations } end; const s0='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'; s1='M5NB1V2CXZ3AS4DFGH7JK8L9POI6UYTR_E0WQ'; var {$Region 'Global variables'} Enigma2: TEnigma2; str, str1 : String; textvl,encr,decr:String; pom,pom1:String; poz:integer; sd:boolean; {$endregion} implementation {$R *.dfm} procedure rot(v:char); var i,j,k,poz:integer; begin if sd=true then begin pom := str[1]; for i := 1 to 36 do str[i] := str[i + 1]; str[37]:=pom.Chars[1]; pom:=str1[37]; for i:=37 downto 2 do str1[i]:=str1[i-1]; str1[1]:=pom.Chars[1]; poz := 1; for i:=1 to 37 do if str[i]=v then poz:=i; end; if (sd = false) then begin pom:=str1[1]; for i:=1 to 36 do str1[i]:=str1[i+1]; str1[37]:=pom.Chars[1]; pom:=str[37]; for i:=37 downto 2 do str[i]:=str[i-1]; str[1]:=pom.Chars[1]; poz:=1; for i:=1 to 37 do if str[i]=v then poz:=i; end; end; //procedure TEnigma2.FormCreate1(Sender: TObject); //begin // //TODO:Init form // //ShowMessage('Enigma by Kris'); //end; {$region 'Buttons Callbacks'} procedure TEnigma2.m_btnStartClick(Sender: TObject); begin encr:=''; label1.Caption:=str; label2.Caption:=str1; texiz.Text:=''; texvl.Text:=''; textvl:=''; end; procedure TEnigma2.m_btnAClick(Sender: TObject); begin rot('A'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'A'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnBClick(Sender: TObject); begin rot('B'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'B'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnQClick(Sender: TObject); begin rot('Q'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'Q'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnWClick(Sender: TObject); begin rot('W'); label2.Caption:=str1; label1.Caption:=str; textvl:=textvl+'W'; texvl.text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_rbxEncrClick(Sender: TObject); begin str:=s0; str1:=s1; sd:=true; end; procedure TEnigma2.m_rbxDecrClick(Sender: TObject); begin str:=s1; str1:=s0; sd:=false; end; procedure TEnigma2.m_btnEClick(Sender: TObject); begin rot('E'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'E'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnRClick(Sender: TObject); begin rot('R'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'R'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnTClick(Sender: TObject); begin rot('T'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'T'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnYClick(Sender: TObject); begin rot('Y'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'Y'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnUClick(Sender: TObject); begin rot('U'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'U'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnIClick(Sender: TObject); begin rot('I'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'I'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnOClick(Sender: TObject); begin rot('O'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'O'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnPClick(Sender: TObject); begin rot('P'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'P'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnSClick(Sender: TObject); begin rot('S'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'S'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnDClick(Sender: TObject); begin rot('D'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'D'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnFClick(Sender: TObject); begin rot('F'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'F'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnGClick(Sender: TObject); begin rot('G'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'G'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnKeyHClick(Sender: TObject); begin rot('H'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'H'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnKeyJClick(Sender: TObject); begin rot('J'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'J'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnVClick(Sender: TObject); begin rot('v'); label2.Caption:=str1; label1.Caption:=str; encr:=encr+str1[poz]; textvl:=textvl+'V'; texvl.Text:=textvl; texiz.text:=encr; end; procedure TEnigma2.m_btnKClick(Sender: TObject); begin rot('K'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'K'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnLClick(Sender: TObject); begin rot('L'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'L'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnZClick(Sender: TObject); begin rot('Z'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'Z'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnXClick(Sender: TObject); begin rot('X'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'X'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnCClick(Sender: TObject); begin rot('C'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'C'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnNClick(Sender: TObject); begin rot('N'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'N'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnMClick(Sender: TObject); begin rot('M'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'M'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnSpaceClick(Sender: TObject); begin rot('_'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'_'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnResetClick(Sender: TObject); begin if sd=true then begin str:='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'; str1:='M5NB1V2CXZ3AS4DFGH7JK8L9POI6UYTR_E0WQ'; encr:=''; label1.Caption:=str; label2.Caption:=str1; texiz.Text:=''; texvl.Text:=''; textvl:=''; end; if sd = false then begin str1:='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'; str:='M5NB1V2CXZ3AS4DFGH7JK8L9POI6UYTR_E0WQ'; encr:=''; label1.Caption:=str; label2.Caption:=str1; texiz.Text:=''; texvl.Text:=''; textvl:=''; end; end; procedure TEnigma2.m_btnNum1Click(Sender: TObject); begin rot('1'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'1'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnNum2Click(Sender: TObject); begin rot('2'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'2'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnNum3Click(Sender: TObject); begin rot('3'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'3'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnNum4Click(Sender: TObject); begin rot('4'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'4'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnNum5Click(Sender: TObject); begin rot('5'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'5'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnNum6Click(Sender: TObject); begin rot('6'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'6'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnNum7Click(Sender: TObject); begin rot('7'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'7'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnNum8Click(Sender: TObject); begin rot('8'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'8'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnNum9Click(Sender: TObject); begin rot('9'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'9'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; procedure TEnigma2.m_btnNum0Click(Sender: TObject); begin rot('0'); label1.Caption:=str; label2.Caption:=str1; textvl:=textvl+'0'; texvl.Text:=textvl; encr:=encr+str1[poz]; texiz.text:=encr; end; {$endregion} end.
unit ShellUtils; interface uses StrUtils, RegUtils, SysUtils, Windows, ShellAPI , classes; type TRegExtensionInfo = record Caption : string; Description : string; IconPath : string; IconIndex : integer; NeedsIcon : boolean; DefaultIcon : THandle; Actions : TStringList; Commands : TStringList; end; procedure GetRegExtensionInfo( const Ext : string; var Info : TRegExtensionInfo ); procedure SetAsociateIcon( const Ext : string; const Value : string; Indx :integer); procedure SetDescription( const Ext, value : string ); procedure SetAction( const Ext, Action, Command : string); procedure SetExtension( const Ext, value : string); procedure DeleteAction( const Ext, Action : string); function ExtensionExist( const Ext : string ) : boolean; var RegistredExtensions : TStringList; implementation const UnkIconFile = 'SHELL32.DLL'; UnkIconFileIndx = 0; var UnkIcon : HICON; procedure GetRegExtensionInfo( const Ext : string; var Info : TRegExtensionInfo ); var IconHandlerKey : HKEY; ShellKey : HKEY; FileTypeKey : HKEY; ActionKey : HKEY; FileName : string; Indx : integer; Pos : integer; Size : word; Count : integer; A : array[0..MAX_PATH] of char; procedure SetDefaultIcon( NeedsIcon : boolean); begin Info.DefaultIcon := UnkIcon; Info.NeedsIcon := NeedsIcon; end; begin Info.Caption := Ext; Info.NeedsIcon := false; FileName := GetRegValue( HKEY_CLASSES_ROOT, ext); RegOpenKey( HKEY_CLASSES_ROOT, pchar(FileName), FileTypeKey); RegOpenKey( FileTypeKey, 'shell', ShellKey); Info.Description := GetRegValue( HKEY_CLASSES_ROOT, FileName); FileName := GetRegValue( FileTypeKey, 'DefaultIcon'); if RegOpenKey( FileTypeKey, 'Shellex\IconHandler', IconHandlerKey) = ERROR_SUCCESS then begin Info.NeedsIcon := true; RegCloseKey( IconHandlerKey); end else if FileName = '%1' then SetDefaultIcon( true ) else Info.NeedsIcon := false; if FileName = '' then Info.DefaultIcon := UnkIcon else if FileName <> '%1' then begin Pos := BackPos( ',', FileName, 0); if pos <> 0 then begin Indx := StrToInt( RightStr( FileName, Length( FileName) - pos)); Delete( FileName, Pos, MaxInt); end else Indx := 0; Info.IconPath := FileName; Info.IconIndex := indx; Info.DefaultIcon := ExtractIcon( hInstance, pchar(FileName), Indx); if Info.DefaultIcon = 0 then Info.DefaultIcon := UnkIcon; end; Count := 0; Info.Actions := TStringList.Create; Info.Commands := TStringList.Create; Size := MAX_PATH + 1; while RegEnumKey( ShellKey, Count, A, Size ) = NO_ERROR do begin Info.Actions.Add( string( A )); if RegOpenKey( ShellKey, A, ActionKey) = ERROR_SUCCESS then FileName := GetRegValue( ActionKey, 'command' ); RegCloseKey( ActionKey); Info.Commands.Add( FileName ); inc( Count ); Size := MAX_PATH + 1; end; RegCloseKey( ShellKey); RegCloseKey( FileTypeKey); end; procedure SetAsociateIcon( const Ext : string; const Value : string; Indx :integer); var FileTypeKey : HKEY; FileName : string; begin FileName := GetRegValue( HKEY_CLASSES_ROOT, ext); RegOpenKey( HKEY_CLASSES_ROOT, pchar(FileName), FileTypeKey); SetRegValue( FileTypeKey, 'DefaultIcon', value + ', ' + IntToStr(Indx)); end; procedure SetDescription( const Ext, value : string ); var FileName : string; begin FileName := GetRegValue( HKEY_CLASSES_ROOT, ext); SetRegValue( HKEY_CLASSES_ROOT, FileName, value); end; procedure SetAction( const Ext, Action, Command : string); var FileName : string; Key : HKEY; begin FileName := GetRegValue( HKEY_CLASSES_ROOT, ext); RegOpenKey( HKEY_CLASSES_ROOT, pchar(FileName), Key); SetRegValue( Key, 'shell\' + Action + '\Command', command); end; procedure SetExtension( const Ext, value : string); begin SetRegValue( HKEY_CLASSES_ROOT, Ext, value); end; procedure DeleteAction( const Ext, Action : string); var FileName : string; ShellKey : HKEY; begin FileName := GetRegValue( HKEY_CLASSES_ROOT, ext); RegOpenKey( HKEY_CLASSES_ROOT, pchar(FileName + '\Shell'), ShellKey); RegDeleteKey( ShellKey, pchar(Action)); end; function ExtensionExist( const Ext : string ) : boolean; var Key : HKey; begin Result := RegistredExtensions.IndexOf( Ext ) <> -1; end; var Count : integer; Size : integer; Ext : string; initialization RegistredExtensions := TStringList.Create; Count := 0; Size := MAX_PATH; SetLength( Ext, MAX_PATH ); while RegEnumKey( HKEY_CLASSES_ROOT, Count, pchar(Ext), Size ) = NO_ERROR do begin SetLength( Ext, strlen( pchar(Ext) )); if Ext[1] = '.' then RegistredExtensions.Add( Ext ); inc( Count ); SetLength( Ext, MAX_PATH ); end; RegistredExtensions.Sort; UnkIcon := ExtractIcon( hInstance, UnkIconFile, UnkIconFileIndx); finalization RegistredExtensions.Free; end.
program HashCalc; {$mode delphi} uses SysUtils, CalcAll; begin try if ParamCount = 1 then begin Writeln('File: ', ParamStr(1)); Writeln; CalcHash(ParamStr(1)); end else begin Writeln('Usage: > HashCalc filename'); Writeln('File: ', ExtractFileName(ParamStr(0))); Writeln; CalcHash(ParamStr(0)); end; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; Writeln; Write('Press <Enter> ..'); Readln; end.
unit Lisp; interface uses System.StrUtils, NativeFunctions, Classes, SysUtils, System.Generics.Collections, System.RegularExpressions, Data, Common, Modules, UserData, Collections; type /// <summary> /// DLisp interpreter. Provides everything needed for executing and loading /// DLisp code. /// </summary> TLisp = class(TRuntime) protected FGlobal : TContext; FModuleManager : TModuleManager; function GetGlobalContext : TContext; override; public /// <summary>Creates new DLisp interpreter</summary> constructor Create(); destructor Destroy(); override; /// <summary>Parses a string and returns equivalent DLisp code.</summary> /// <exception cref="Exception">When something goes wrong</exception> function Read(input : string) : Ref<TData>; override; /// <summary>Evaluates DLisp code in the given context.</summary> function Eval(code : DataRef; context : TContext) : DataRef; override; /// <summary>Parses and evaluates the input string in given context.</summary> function Eval(input : string; context : TContext) : DataRef; overload; override; /// <summary>Parses and evaluates the input string in the global context.</summary> function Eval(input : string) : DataRef; overload; /// <summary>Register a native function in global context.</summary> procedure RegisterFunction(fn : TFunction); end; implementation { TLisp } constructor TLisp.Create; var fn : TFunction; begin FGlobal := TContext.Create(nil); FModuleManager := TModuleManager.Create(Self); for fn in NativeFunctionList do begin Self.RegisterFunction(fn); end; FGlobal['nil'] := CreateRef(TNothing.Create()); FGlobal['*module-manager*'] := CreateRef(TDelphiObject.Create(FModuleManager)); end; destructor TLisp.Destroy; begin FGlobal.Free; FModuleManager.Free; inherited; end; function TLisp.Eval(code : DataRef; context : TContext) : DataRef; var list, evaluated : Ref<TList>; opName, symbol : TSymbol; expr : Ref<TData>; fn : TUserFunction; native : TNativeFunction; i : Integer; Data : TData; fnScope : TContext; className, dbg : string; j: Integer; captureList : TList; begin if code() is TSymbol then begin symbol := code() as TSymbol; if context.IsDefined(symbol.Value) then begin Result := context[symbol.Value]; end else begin Result := code; end; end else if code() is TList then begin list := Ref<TList>(code); if list[0]() is TSymbol then symbol := list[0]() as TSymbol else symbol := nil; {$IFDEF DEBUG} className := list[0]().className; dbg := list.ToString; {$ENDIF} if (symbol <> nil) and (FGlobal.IsDefined(symbol.Value)) and (FGlobal[symbol.Value]() is TNativeFunction) then begin native := FGlobal[symbol.Value]() as TNativeFunction; Result := native.Apply(Self, context, list); end else if (list[0]() is TNativeFunction) then begin Result := (list[0]() as TNativeFunction).Apply(Self, context, list); end else if list().Executable then begin // this looks like a function application; evaluate all arguments evaluated := TRef<TList>.Create(TList.Create()); for i := 0 to list.Size - 1 do begin evaluated.Add(Eval(list[i], context)); end; if not(evaluated[0]() is TUserFunction) then begin if (symbol <> nil) and (symbol.Value.StartsWith(':')) then begin Result := _get(Self, context, TRef<TList>.Create(TList.Create( [CreateRef(TSymbol.Create('get')), evaluated[1], evaluated[0]]))); Exit; end; raise Exception.Create('Unkown function "' + evaluated[0]().Value + '"'); end; fn := evaluated[0]() as TUserFunction; fnScope := TContext.Create(fn.context); // args[0] = function name // args[1] = function arguments // args[2:] = function body expressions // register arguments in context for i := 0 to fn.Args().Size - 1 do begin symbol := fn.Args()[i]() as TSymbol; if symbol.Value <> '&' then begin fnScope[symbol.Value] := evaluated[i + 1]; end else begin // following the & character, the next format argument symbol is // assigned a list that captures all remaining parameter that were // passed to the function symbol := fn.Args()[i + 1]() as TSymbol; captureList := TList.Create(); fnScope[symbol.Value] := CreateRef(captureList); // add remaining arguments to capture list for j := i + 1 to evaluated().Size - 1 do begin captureList.Add(evaluated[j]); end; dbg := fnScope.ToString; break; end; end; // execute the function code for i := 2 to fn.code().Size - 1 do begin Result := Eval(fn.code()[i], fnScope); end; // Clear the arguments from the context again for i := 0 to fn.Args().Size - 1 do begin symbol := fn.Args()[i]() as TSymbol; if fnScope.IsDefined(symbol.Value) then fnScope.Remove(symbol.Value); end; fnScope.Free; end else Result := code; end else begin Result := code; end; end; function TLisp.Eval(input : string; context : TContext) : DataRef; begin Result := Eval(read(input), context); end; function TLisp.GetGlobalContext : TContext; begin Result := FGlobal; end; function TLisp.Read(input : string) : Ref<TData>; var i, j : Integer; inString : Boolean; list : Ref<TList>; item : Ref<TData>; text : string; charsTrimmed : Integer; anonymousFunction : Boolean; function IsWhitespace(c : Char) : Boolean; begin Result := (c = ' ') or (c = chr(9)) or (c = chr(10)) or (c = chr(13)); end; function IsParenthesis(c : Char) : Boolean; begin Result := (c = ')') or (c = ']') or (c = '}') or (c = '(') or (c = '[') or (c = '{'); end; begin text := input.Trim; // remove all comments text := TRegEx.Replace(text, ';.*$', ''); charsTrimmed := input.Length - text.Length; input := text; if Length(text) = 0 then Exit(CreateRef(TNothing.Create)); // check for #( prefix which denotes an anonymous function def. if (input[1] = '#') and (input[2] = '(') then begin charsTrimmed := charsTrimmed + 1; input := input.Substring(1); anonymousFunction := True; end else anonymousFunction := False; // check for atom if (input[1] <> '(') and (input[1] <> '[') and (input[1] <> '{') then begin // search for end of atom if input[1] <> '"' then begin // something not a string (i.e. a number or symbol) i := 2; while (i <= Length(input)) and (not IsWhitespace(input[i])) and (not IsParenthesis(input[i])) do begin i := i + 1; end; text := input.Substring(0, i - 1); if TInteger.Match(text) then Result := CreateRef(TInteger.Create(text)) else if TFloat.Match(text) then Result := CreateRef(TFloat.Create(text)) else if TBoolean.Match(text) then Result := CreateRef(TBoolean.Create(text)) else if TSymbol.Match(text) then Result := CreateRef(TSymbol.Create(text)) else Result := CreateRef(TAtom.Create(text)); text := Result().className; Result().ConsumedCharacters := i - 1; end else begin // parsing a string i := 2; while (i <= Length(input)) do begin if (input[i] <> '"') then i := i + 1 else if (input[i - 1] = '\') then i := i + 1 else break; end; // including closing quote (i - 1 + 1 = i) text := input.Substring(1, i - 2); Result := CreateRef(TString.Create(text)); Result().ConsumedCharacters := i; end; Result().ConsumedCharacters := Result().ConsumedCharacters + charsTrimmed; Exit(Result); end; // assume it's a list i := 2; list := TRef<TList>.Create(TList.Create()); if anonymousFunction then list.Add(CreateRef(TSymbol.Create('anonymous-function'))) else if input[1] = '[' then list.Add(CreateRef(TSymbol.Create('list'))) else if input[1] = '{' then list.Add(CreateRef(TSymbol.Create('dict'))); while i <= Length(input) do begin if (input[i] = ')') or (input[i] = ']') or (input[i] = '}') then begin i := i + 1; break; end; item := read(input.Substring(i - 1)); i := i + item.ConsumedCharacters; if not(item is TNothing) then list.Add(item); end; list.ConsumedCharacters := i - 1 + charsTrimmed; Result := Ref<TData>(list); end; procedure TLisp.RegisterFunction(fn : TFunction); var native : TNativeFunction; begin if fn is TNativeFunction then begin native := fn as TNativeFunction; FGlobal[native.name] := CreateRef(native); end; end; function TLisp.Eval(input : string) : DataRef; begin Result := Eval(input, FGlobal); end; initialization finalization end.
unit fileutilwin; { FileUtilWin Version 1.0.0 Copyright (C) 2018 by James O. Dreher License: https://opensource.org/licenses/MIT 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. } {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, LazFileUtils; function ChildPath(aPath: string): string; function ParentPath(aPath: string): string; function JoinPath(aDir, aFile: string): string; function CopyDirWin(sourceDir, targetDir: string): boolean; function CopyFileWin(sourcePath, targetPath: string; Flags: TCopyFileFlags=[cffOverwriteFile]; PreserveAttributes: boolean=true): boolean; function DelDirWin(targetDir: string; OnlyChildren: boolean=False): boolean; function DelFileWin(targetFile: string): boolean; function FilenameIsDir(aPath: string): boolean; function FilenameIsFile(aPath: string): boolean; const DS=DirectorySeparator; LE=LineEnding; implementation function FilenameIsDir(aPath: string): boolean; begin Result:=False; if ExtractFileName(aPath)='' then Result:=True; end; function FileNameIsFile(aPath: string): boolean; begin Result:=True; if ExtractFileName(aPath)='' then Result:=False; end; function ChildPath(aPath: string): string; begin aPath:=ExpandFileName(ChompPathDelim(aPath)); Result:=Copy(aPath,aPath.LastIndexOf(DS)+2) end; function ParentPath(aPath: string): string; begin Result:=ExpandFileName(IncludeTrailingPathDelimiter(aPath) + '..'); end; function JoinPath(aDir, aFile: string): string; begin Result:=CleanAndExpandDirectory(aDir)+Trim(aFile); end; function CopyDirWin(sourceDir, targetDir: string): boolean; var FileInfo: TSearchRec; sourceFile, targetFile: String; begin Result:=false; sourceDir:=CleanAndExpandDirectory(sourceDir); targetDir:=CleanAndExpandDirectory(targetDir); if FindFirstUTF8(sourceDir+GetAllFilesMask,faAnyFile,FileInfo)=0 then begin repeat if (FileInfo.Name<>'.') and (FileInfo.Name<>'..') and (FileInfo.Name<>'') then begin sourceFile:=sourceDir+FileInfo.Name; targetFile:=targetDir+FileInfo.Name; if (FileInfo.Attr and faDirectory)>0 then begin if not ForceDirectories(targetDir) then exit; if not CopyDirWin(sourceFile, targetFile) then exit; end else begin if not CopyFileWin(sourceFile, targetFile) then exit; end; end; until FindNextUTF8(FileInfo)<>0; end; FindCloseUTF8(FileInfo); Result:=true; end; function CopyFileWin(sourcePath, targetPath: string; Flags: TCopyFileFlags=[cffOverwriteFile]; PreserveAttributes: boolean=true): boolean; var attrSource, attrTarget: integer; targetDir: string; begin Result:=false; sourcePath:=CleanAndExpandFilename(sourcePath); targetPath:=CleanAndExpandFilename(targetPath); if FilenameIsDir(targetPath) then begin targetDir:=targetPath; targetPath:=targetDir+ExtractFileName(sourcePath); end else begin targetDir:=ExtractFilePath(targetPath); end; if not ForceDirectories(targetDir) then exit; if PreserveAttributes then attrSource:=FileGetAttrUTF8(sourcePath); if cffOverwriteFile in Flags then begin if FileExists(targetPath) then begin attrTarget:=FileGetAttrUTF8(targetPath); if (attrTarget and faReadOnly)>0 then FileSetAttrUTF8(targetPath, attrTarget-faReadOnly) else if (attrTarget and faHidden)>0 then FileSetAttrUTF8(targetPath, attrTarget-faHidden); end; end; if not FileUtil.CopyFile(sourcePath, targetPath, Flags) then exit; if PreserveAttributes then FileSetAttrUTF8(targetPath, attrSource); Result:=true; end; function DelDirWin(targetDir: string; OnlyChildren: boolean=False): boolean; var FileInfo: TSearchRec; targetFile: String; begin Result:=false; if not DirectoryExistsUTF8(targetDir) then exit; targetDir:=CleanAndExpandDirectory(targetDir); if FindFirstUTF8(targetDir+GetAllFilesMask,faAnyFile,FileInfo)=0 then begin repeat if (FileInfo.Name<>'.') and (FileInfo.Name<>'..') and (FileInfo.Name<>'') then begin targetFile:=targetDir+FileInfo.Name; if (FileInfo.Attr and faDirectory)>0 then begin if not DelDirWin(targetFile, false) then exit; end else begin if (FileInfo.Attr and faReadOnly)>0 then FileSetAttrUTF8(targetFile, FileInfo.Attr-faReadOnly); if not DeleteFileUTF8(targetFile) then exit; end; end; until FindNextUTF8(FileInfo)<>0; end; FindCloseUTF8(FileInfo); if (not OnlyChildren) and (not RemoveDirUTF8(targetDir)) then exit; Result:=true; end; function DelFileWin(targetFile: string): boolean; begin Result:=DeleteFileUTF8(targetFile); end; end.
unit History; { The History unit contains all history list constants used in the FreeVision Library. } interface const hiConfig = 1; hiDirectories = 2; { non-specific } hiDesktop = 3; hiCurrentDirectories = 1; hiFiles = 4; implementation end.
unit family_of_curves_lib; interface uses table_func_lib,streaming_class_lib,classes; type TFamilyMember=class(table_func) private fparam: Real; published property param: Real read fparam write fparam; end; TFamilyOfCurves=class(TStreamingClass) private fCount: Integer; fTolerance: Real; fZeroBounds: Boolean; list: TList; procedure readCount(reader: TReader); procedure writeCount(writer: TWriter); procedure update_list; function Interpolate(t1,t2: TFamilyMember;x,param: Real): Real; function getValue(x,param: Real): Real; protected procedure DefineProperties(filer: TFiler); override; public difficult_interp: Boolean; constructor Create(owner: TComponent); override; destructor Destroy; override; // procedure AddPoint(x,param,value: Real); procedure AddCurve(t: table_func;param: Real); property Value[x,param: Real]: Real read getValue; default; property Count: Integer read fCount; published property Tolerance: Real read fTolerance write fTolerance; property ZeroBounds: Boolean read fZeroBounds write fZeroBounds; end; implementation uses Math,SysUtils; function Compare(p1,p2: Pointer): Integer; begin Result:=CompareValue(TFamilyMember(p1).param,TFamilyMember(p2).param); end; procedure TFamilyOfCurves.DefineProperties(filer: TFiler); begin filer.DefineProperty('count',readCount,writeCount,count<>0); end; procedure TFamilyOfCurves.readCount(reader: TReader); begin fCount:=reader.ReadInteger; end; procedure TFamilyOfCurves.writeCount(writer: TWriter); begin writer.writeInteger(fCount); end; constructor TFamilyOfCurves.Create(owner: TComponent); begin inherited Create(owner); list:=TList.Create; end; destructor TFamilyOfCurves.Destroy; begin list.Free; inherited Destroy; end; procedure TFamilyOfCurves.update_list; var i: Integer; begin if list.Count<>Count then begin list.Clear; for i:=0 to ComponentCount-1 do list.Add(Components[i]); list.Sort(compare); end; end; function TFamilyofCurves.Interpolate(t1,t2: TFamilyMember;x,param: Real): Real; var r,xl,xr,f0: Real; rx,ry,rz: Real; ny,k,distl,distr: Real; i: Integer; begin r:=(param-t1.param)/(t2.param-t1.param); f0:=t1[x]*(1-r)+t2[x]*r; if difficult_interp=false then Result:=f0 else begin //ищем перпендикуляры на оба графика xl:=x; xr:=x; for i:=0 to 10 do begin rx:=x-xl; ry:=f0-t1[x]; rz:=r; //nx=1, nz=0 ny:=t1.derivative(xl); k:=(rx+ry*ny)/(1+ny*ny); distl:=sqrt(sqr(rx-k)+sqr(ry-k*ny)+sqr(rz)); xl:=xl+k; rx:=x-xr; ry:=f0-t2[x]; rz:=1-r; ny:=t2.derivative(xr); k:=(rx+ry*ny)/(1+ny*ny); distr:=sqrt(sqr(rx-k)+sqr(ry-k*ny)+sqr(rz)); xr:=xr+k; f0:=(t1[xl]*distr+t2[xr]*distl)/(distl+distr); end; Result:=f0; end; end; function TFamilyOfCurves.getValue(x,param: Real): Real; var i,j,k: Integer; // r: Real; label Found; begin i:=0; j:=count-1; //цикл может не выполниться, если массив пустой (High(X)=-1) if j<i then begin Result:=NAN; Exit; end; update_list; if param>TFamilyMember(list[j]).param then begin if ZeroBounds then Result:=0 else Result:=TFamilyMember(list[count-1])[x]; exit; end else if param<TFamilyMember(list[0]).param then begin if ZeroBounds then Result:=0 else Result:=TFamilyMember(list[0])[x]; exit; end; dec(j); //последний элемент не нужен! k:=0; while j>=i do begin k:=(i+j) shr 1; if param<TFamilyMember(list[k]).param then j:=k-1 else if param>TFamilyMember(list[k]).param then i:=k+1 else goto found; end; if param<TFamilyMember(list[k]).param then dec(k); if k<0 then begin Result:=TFamilyMember(list[0])[x]; exit; end; found: Result:=Interpolate(TFamilyMember(list[k]),TFamilyMember(list[k+1]),x,param); // r:=(param-TFamilyMember(list[k]).param)/(TFamilyMember(list[k+1]).param-TFamilyMember(list[k]).param); // Result:=TFamilyMember(list[k])[x]*(1-r)+TFamilyMember(list[k+1])[x]*r; end; procedure TFamilyOfCurves.AddCurve(t: table_func;param: Real); var f: TFamilyMember; begin f:=TFamilyMember.Create(self); f.SetSubComponent(false); f.assign(t); f.param:=param; List.Add(f); List.Sort(Compare); inc(fCount); end; initialization RegisterClasses([TFamilyMember,TFamilyOfCurves]); end.
unit xpr.bytecode; { Author: Jarl K. Holta License: GNU Lesser GPL (http://www.gnu.org/licenses/lgpl.html) stuff } {$I express.inc} interface uses Classes, SysUtils, xpr.express, xpr.dictionary, xpr.opcodes, xpr.mmgr, xpr.utils, xpr.objbase; type TObjectArray = array of TEpObject; TLoopInfo = record Pos,Id:Int32; end; TLoopInfoArray = array of TLoopInfo; TStringToIntMap = specialize TDictionary<string, Int32>; TIntToStringMap = specialize TDictionary<Int32, string>; (* Bytecode *) PBytecode = ^TBytecode; TBytecode = class Code: TOperationArray; DocPos: TDocPosArray; Variables: TObjectArray; Constants: TObjectArray; GC: TGarbageCollector; // debugging VarNames: TStringArray; DebugHints: TIntToStringMap; constructor Create(ACode:TOperationArray; AConstants:TObjectArray; ADocPos:TDocPosArray; NumVars:Int32; MemMgr:TGarbageCollector); virtual; destructor Destroy; override; function ToString: string; override; end; (* "Variable context" *) TVarContext = record Names: TStringArray; //Names can contain duplicates (different scopes and such) NamesToNumbers: TStringToIntMap; //The map belongs to a single scope (no duplicates) end; (* Compiler context *) TCompilerContext = class(TObject) Code: TOperationArray; DocPos: TDocPosArray; GC: TGarbageCollector; Constants: TObjectArray; Vars: TVarContext; DestVars: TIntArray; PatchCount: SizeInt; PatchPositions: TLoopInfoArray; DebugHints: TIntToStringMap; constructor Create(); destructor Destroy; override; function CodeSize: SizeInt; inline; function GetNone: Int32; function RegisterConst(value:TEpObject): Int32; inline; function RegisterVar(name:String; Redeclare:Boolean=True): Int32; inline; function getTempVar: Int32; inline; function LookupVar(name:String; Pos:TDocPos): Int32; inline; function Emit(bc:EBytecode; arg:Int32; Pos:TDocPos): Int32; inline; procedure Patch(pos:Int32; bc:EBytecode; arg:Int32=0); inline; procedure PatchArg(pos:Int32; arg:Int32); inline; procedure PushDestVar(varId:Int32); inline; function PopDestVar: Int32; inline; function RemoveDestVarIf(location:Int32): Boolean; inline; procedure DebugHint(hint:string); inline; procedure PreparePatch(AddDebugSym:Boolean=True; DEBUG_SYM:String='LOOP_START'); inline; procedure PopPatch(AddDebugSym:Boolean=True; DEBUG_SYM:String='LOOP_END'); inline; procedure RunPatch(oldOp:EBytecode; newOp:EBytecode=JUMP; newArg:Int32=0); function Bytecode: TBytecode; end; TStringToOpcode = specialize TDictionary<string, EBytecode>; var OperatorToOpcode: TStringToOpcode; implementation uses xpr.errors; (*============================================================================ Program bytecode representation ============================================================================*) constructor TBytecode.Create(ACode:TOperationArray; AConstants:TObjectArray; ADocPos:TDocPosArray; NumVars:Int32; MemMgr:TGarbageCollector); var i:Int32; begin Code := ACode; DocPos := ADocPos; Constants := AConstants; GC := MemMgr; SetLength(Variables, NumVars); for i:=0 to NumVars-1 do Variables[i] := Constants[0]; //None end; destructor TBytecode.Destroy; begin if DebugHints <> nil then DebugHints.Destroy; GC.Destroy; //this will clean up whatever's left inherited; end; function TBytecode.ToString: string; var i,x:Int32; t,tmpstr:string; begin Result := '[LGREEN]PROGRAM:'+#13#10; for i:=0 to High(self.code) do begin WriteStr(t,Code[i].code); x := Length(t); if DebugHints.Contains(i) then Result += '[LYELLOW]'+DebugHints[i]+#13#10; Result += Format(' #%-6d %s %'+IntToStr(20-x)+'d', [i, t, Code[i].arg]); t := ''; if (Code[i].code = LOAD_CONST) then begin tmpstr := Constants[Code[i].arg].AsString; if Length(tmpstr) > 10 then begin SetLength(tmpstr, 10); tmpstr += '..'; end; t := ' ['+ tmpstr +']'; end else if (Code[i].code = LOAD) then begin t := ' ['+self.VarNames[Code[i].arg]+']'; end; Result += Format(' %-20s %s', [t, 'Pos:'+DocPos[i].ToString]); Result += #13#10; end; end; (*============================================================================ Compiler context for the AST . ============================================================================*) constructor TCompilerContext.Create(); begin GC := TGarbageCollector.Create(); Vars.NamesToNumbers := TStringToIntMap.Create(@HashStr); DebugHints := TIntToStringMap.Create(@HashInt32); Self.RegisterConst(GC.AllocNone(2)); end; destructor TCompilerContext.Destroy; begin //DebugHints is handled by TBytecode Vars.NamesToNumbers.Destroy; inherited; end; function TCompilerContext.CodeSize: SizeInt; begin Result := Length(Code); end; function TCompilerContext.GetNone: Int32; begin Result := 0; //None should always be `0` end; function TCompilerContext.RegisterConst(value:TEpObject): Int32; begin Result := Length(Constants); SetLength(Constants, Result + 1); Constants[Result] := value; end; function TCompilerContext.RegisterVar(Name:String; Redeclare:Boolean=True): Int32; var id:Int32; begin if (not Redeclare) and Vars.NamesToNumbers.Get(Name, id) then Exit(id); Result := Length(Vars.Names); SetLength(Vars.Names, Result + 1); Vars.Names[Result] := Name; Vars.NamesToNumbers[name] := Result; end; function TCompilerContext.getTempVar: Int32; begin Result := Length(Vars.Names); SetLength(Vars.Names, Result + 1); end; function TCompilerContext.LookupVar(Name:String; Pos:TDocPos): Int32; begin Result := Vars.NamesToNumbers.GetDef(Name, -1); if Result = -1 then RaiseExceptionFmt(eSyntaxError, eUndefinedIdentifier, [Name], Pos); end; function TCompilerContext.Emit(Bc:EBytecode; Arg:Int32; Pos:TDocPos): Int32; begin Result := Length(Code); SetLength(Code, Result+1); Code[Result].code := Bc; Code[Result].arg := Arg; SetLength(DocPos, Result+1); DocPos[Result] := Pos; end; procedure TCompilerContext.Patch(pos:Int32; bc:EBytecode; arg:Int32=0); begin Code[pos].code := bc; Code[pos].arg := arg; end; procedure TCompilerContext.PatchArg(pos:Int32; arg:Int32); begin Code[pos].arg := arg; end; // Add a new destination variable procedure TCompilerContext.PushDestVar(varId:Int32); var L:Int32; begin L := Length(DestVars); SetLength(DestVars, L+1); DestVars[L] := varId; end; //get the topmost destvar, and remove it function TCompilerContext.PopDestVar: Int32; var top:Int32; begin top := High(DestVars); if top < 0 then Result := -1 else begin Result := DestVars[top]; SetLength(DestVars, top); end; end; // remove the topmost destvar if it matches the given location function TCompilerContext.RemoveDestVarIf(location:Int32): Boolean; var top:Int32; begin top := High(DestVars); Result := False; if (top >= 0) and (location = DestVars[top]) then begin SetLength(DestVars, top); Result := True; end; end; //debugging hint procedure TCompilerContext.DebugHint(hint:string); begin DebugHints.Add(Length(Code), hint); end; // push right before a loop starts // it's needed for "continue" and "break" statements. procedure TCompilerContext.PreparePatch(AddDebugSym:Boolean=True; DEBUG_SYM:String='LOOP_START'); var L:Int32; begin L := Length(PatchPositions); SetLength(PatchPositions, L+1); PatchPositions[L].Pos := Length(Code); PatchPositions[L].ID := PatchCount; if AddDebugSym then DebugHint(DEBUG_SYM+' #'+IntToStr(PatchCount)); Inc(PatchCount); end; //pop it off at the end of a loop //but only after you've called "PatchContinue" and "PatchBreak" with the new jump pos procedure TCompilerContext.PopPatch(AddDebugSym:Boolean=True; DEBUG_SYM:String='LOOP_END'); var L:Int32; begin L := High(PatchPositions); if AddDebugSym then DebugHint(DEBUG_SYM+' #'+IntToStr(PatchPositions[L].ID)); SetLength(PatchPositions, L); end; // patches all the jumps of the type `__CONTINUE` / `__BREAK` // swaps it out with a normal "JUMP", and replaces the argument procedure TCompilerContext.RunPatch(oldOp:EBytecode; newOp:EBytecode=JUMP; newArg:Int32=0); var i,patchStart:Int32; begin patchStart := PatchPositions[High(PatchPositions)].Pos; if patchStart < 0 then patchStart := 0; for i:=patchStart to High(Code) do if Code[i].code = oldOp then begin Code[i].code := newOp; Code[i].arg := newArg; end; end; // builds the bytecode which is what's executed at runtime. function TCompilerContext.Bytecode: TBytecode; begin Result := TBytecode.Create(Code, Constants, DocPos, Length(Vars.Names), GC); Result.DebugHints := DebugHints; Result.VarNames := Vars.Names; end; procedure InitModule(); begin OperatorToOpcode := TStringToOpcode.Create(@HashStr); (* assign operations *) OperatorToOpcode.Add(':=', ASGN); OperatorToOpcode.Add('+=', INPLACE_ADD); OperatorToOpcode.Add('-=', INPLACE_SUB); OperatorToOpcode.Add('*=', INPLACE_MUL); OperatorToOpcode.Add('/=', INPLACE_DIV); (* arithmetic operations *) OperatorToOpcode.Add('+', BIN_ADD); OperatorToOpcode.Add('-', BIN_SUB); OperatorToOpcode.Add('*', BIN_MUL); OperatorToOpcode.Add('div', BIN_DIV); OperatorToOpcode.Add('/', BIN_FDIV); OperatorToOpcode.Add('%', BIN_MOD); (* equality operations *) OperatorToOpcode.Add('=', BIN_EQ); OperatorToOpcode.Add('!=', BIN_NE); OperatorToOpcode.Add('<', BIN_LT); OperatorToOpcode.Add('>', BIN_GT); OperatorToOpcode.Add('<=', BIN_LE); OperatorToOpcode.Add('>=', BIN_GE); (* logical operations *) OperatorToOpcode.Add('and', BIN_AND); OperatorToOpcode.Add('or', BIN_OR); (* binary operations *) OperatorToOpcode.Add('&', BIN_BAND); OperatorToOpcode.Add('|', BIN_BOR); OperatorToOpcode.Add('^', BIN_BXOR); end; initialization InitModule(); end.