text
stringlengths
14
6.51M
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmScrollableControl Purpose : Finally got tired of having to implement a scrolling control each time I wanted one. So here is a base control.... Date : 04-14-2002 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmScrollableControl; interface {$I CompilerDefines.INC} uses Windows, Messages, Forms, Classes, Controls, StdCtrls, dialogs, sysutils; type TScrollEvent = procedure(Sender:TObject; ScrollBar:integer) of object; TrmCustomScrollableControl = class(TCustomControl) private { Private declarations } fIndex: integer; fTopIndex: integer; fxPos: integer; fOnScroll: TScrollEvent; fShowFocusRect: boolean; FHideSelection: boolean; fMultiSelect: boolean; FScrollBars: TScrollStyle; fSelStart: integer; fSelEnd : integer; FBorderStyle: TBorderStyle; fmousebusy : boolean; fVeritcalScrollByChar: boolean; procedure wmSize(var MSG: TWMSize); message wm_size; procedure WMVScroll(var Msg: TWMVScroll); message WM_VSCROLL; procedure WMHScroll(var Msg: TWMHScroll); message WM_HSCROLL; procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE; procedure CMBorderChanged(var Message: TMessage); message CM_BORDERCHANGED; procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED; procedure setIndex(const Value: integer); function GetHScrollPos: integer; function GetVScrollPos: integer; procedure SetHScrollPos(const Value: integer); procedure SetVScrollPos(const Value: integer); procedure SetShowFocusRect(const Value: boolean); procedure SetHideSelection(const Value: boolean); function GetHScrollSize: integer; function GetVScrollSize: integer; procedure setMultiselect(const Value: boolean); procedure SetSelCount(const Value: integer); procedure SetSelStart(const Value: integer); function GetSelCount: integer; procedure SetScrollBars(const Value: TScrollStyle); procedure SetBorderStyle(const Value: TBorderStyle); protected procedure SetTopIndex(const Value: integer); procedure CreateParams(var Params: TCreateParams); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; override; procedure ScrollToVisible; procedure UpdateVScrollBar; procedure UpdateHScrollBar; procedure DoItemIndexChange; virtual; procedure CalcMultiSelect(oldIndex, oldSelStart, oldSelEnd:integer); procedure VerticalScrollChange(sender:TObject); virtual; procedure HorizontalScrollChange(sender:TObject); virtual; function MaxItemLength: integer; virtual; function MaxItemCount:integer; virtual; function VisibleItems: integer; virtual; function MaxItemHeight: integer; virtual; function MaxItemWidth: integer; virtual; property InternalTopIndex : integer read fTopIndex write SetTopIndex; property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsNone; property ScrollBars: TScrollStyle read FScrollBars write SetScrollBars default ssNone; property Multiselect : boolean read fMultiSelect write setMultiselect; property ItemIndex: integer read fIndex write setIndex default -1; property VScrollPos: integer read GetVScrollPos write SetVScrollPos; property HScrollPos: integer read GetHScrollPos write SetHScrollPos; property VScrollSize: integer read GetVScrollSize; property HScrollSize: integer read GetHScrollSize; property HideSelection:boolean read FHideSelection write SetHideSelection default false; property SelStart : integer read fSelStart write SetSelStart; property SelCount : integer read GetSelCount write SetSelCount; property ShowFocusRect: boolean read fShowFocusRect write SetShowFocusRect default true; property OnScroll: TScrollEvent read fOnScroll write fOnScroll; property VeritcalScrollByChar: boolean read fVeritcalScrollByChar write fVeritcalScrollByChar; public { Public declarations } constructor create(aowner: TComponent); override; end; implementation uses Math, rmlibrary; { TrmCustomScrollableControl } constructor TrmCustomScrollableControl.create(aowner: TComponent); begin inherited; fmousebusy := false; ControlStyle := controlstyle + [csopaque]; height := 200; width := 400; fIndex := -1; fTopIndex := 0; fSelStart := fIndex; fSelEnd := fIndex; fXPos := 0; fShowFocusRect := true; FHideSelection := false; end; procedure TrmCustomScrollableControl.CreateParams(var Params: TCreateParams); const BorderStyles: array[TBorderStyle] of DWORD = (0, WS_BORDER); ScrollBar: array[TScrollStyle] of DWORD = (0, WS_HSCROLL, WS_VSCROLL, WS_HSCROLL or WS_VSCROLL); begin inherited CreateParams(Params); with Params do begin Style := Style or BorderStyles[FBorderStyle] or ScrollBar[FScrollBars]; if NewStyleControls and Ctl3D and (FBorderStyle = bsSingle) then begin Style := Style and not WS_BORDER; ExStyle := ExStyle or WS_EX_CLIENTEDGE; end; WindowClass.style := WindowClass.style and not (CS_HREDRAW or CS_VREDRAW); end; end; function TrmCustomScrollableControl.GetHScrollPos: integer; var wScrollInfo: TScrollInfo; begin if (fScrollBars = ssHorizontal) or (FScrollBars = ssBoth) then begin with wScrollInfo do begin cbSize := sizeof(TScrollInfo); fMask := SIF_POS; end; if GetScrollInfo(Handle, SB_HORZ, wScrollInfo) then result := wScrollInfo.nPos else result := 0; end else result := fxPos; end; function TrmCustomScrollableControl.GetVScrollPos: integer; var wScrollInfo: TScrollInfo; begin if (fScrollBars = ssVertical) or (FScrollBars = ssBoth) then begin with wScrollInfo do begin cbSize := sizeof(TScrollInfo); fMask := SIF_POS; end; if GetScrollInfo(Handle, SB_VERT, wScrollInfo) then result := wScrollInfo.nPos else result := 0; end else result := InternalTopIndex; end; procedure TrmCustomScrollableControl.ScrollToVisible; begin if not (csCreating in ControlState) then begin if (InternalTopIndex < fIndex) then begin if (InternalTopIndex + (VisibleItems - 1) < fIndex) then InternalTopIndex := SetInRange(findex - (visibleItems-1), 0, MaxItemCount); end else if fIndex < InternalTopIndex then InternalTopIndex := fIndex; if InternalTopIndex < 0 then begin InternalTopIndex := 0; fIndex := 0; Try DoItemIndexChange; except //Do nothing... end; end; end; end; procedure TrmCustomScrollableControl.SetHScrollPos(const Value: integer); var wScrollInfo: TScrollInfo; begin if (fScrollBars = ssHorizontal) or (FScrollBars = ssBoth) then begin with wScrollInfo do begin cbSize := sizeof(TScrollInfo); fMask := SIF_POS; nPos := Value; end; fxPos := SetScrollInfo(Handle, SB_HORZ, wScrollInfo, true); end else fxPos := SetInRange(Value, 0, HScrollSize); Invalidate; end; procedure TrmCustomScrollableControl.setIndex(const Value: integer); begin if MaxItemCount > 0 then begin fIndex := SetInRange(Value, 0, MaxItemCount-1); fSelStart := fIndex; fSelEnd := fIndex; ScrollToVisible; UpdateVScrollBar; Invalidate; Try DoItemIndexChange; except //Do nothing... end; end; end; procedure TrmCustomScrollableControl.SetVScrollPos(const Value: integer); var wScrollInfo: TScrollInfo; begin if (fScrollBars = ssVertical) or (FScrollBars = ssBoth) then begin with wScrollInfo do begin cbSize := sizeof(TScrollInfo); fMask := SIF_POS or SIF_DISABLENOSCROLL; nMin := 0; nMax := 0; nPos := Value; end; InternalTopIndex := SetScrollInfo(Handle, SB_VERT, wScrollInfo, true); end else begin InternalTopIndex := SetInRange(value, 0, VScrollSize); end; Invalidate; end; procedure TrmCustomScrollableControl.UpdateVScrollBar; var wScrollInfo: TScrollInfo; begin if csloading in componentstate then exit; if csDestroying in ComponentState then exit; fTopIndex := SetInRange(fTopIndex, 0, VScrollSize); if (fScrollBars = ssVertical) or (FScrollBars = ssBoth) then begin with wScrollInfo do begin cbSize := sizeof(TScrollInfo); fMask := SIF_POS or SIF_RANGE or SIF_DISABLENOSCROLL; nMin := 0; nMax := VScrollSize; nPos := fTopIndex; end; SetScrollInfo(Handle, SB_VERT, wScrollInfo, True); fTopIndex := VScrollPos; end; VerticalScrollChange(self); if assigned(fOnScroll) then fOnScroll(self, SB_VERT); end; procedure TrmCustomScrollableControl.UpdateHScrollBar; var wScrollInfo: TScrollInfo; begin if csloading in componentstate then exit; if csDestroying in ComponentState then exit; fxPos := SetInRange(fxPos, 0, HScrollSize); if (fScrollBars = ssHorizontal) or (FScrollBars = ssBoth) then begin with wScrollInfo do begin cbSize := sizeof(TScrollInfo); fMask := SIF_POS or SIF_RANGE or SIF_DISABLENOSCROLL; nMin := 0; nMax := HScrollSize; nPos := fxPos; end; SetScrollInfo(Handle, SB_HORZ, wScrollInfo, True); fxPos := HScrollPos; end; HorizontalScrollChange(self); if assigned(fOnScroll) then fOnScroll(self, SB_HORZ); end; function TrmCustomScrollableControl.VisibleItems: integer; begin result := ClientHeight div MaxItemHeight; end; procedure TrmCustomScrollableControl.WMHScroll(var Msg: TWMHScroll); begin inherited; case Msg.ScrollCode of SB_BOTTOM: fxPos := MaxItemLength - clientwidth; SB_LINEDOWN: inc(fxPos, MaxItemWidth); SB_LINEUP: dec(fxPos, MaxItemWidth); SB_TOP: fxPos := 0; SB_PAGEDOWN: inc(fxPos, (MaxItemLength - clientwidth) div 2); SB_PAGEUP: dec(fxPos, (MaxItemLength - clientwidth) div 2); SB_THUMBPOSITION: fxPos := Msg.Pos; SB_THUMBTRACK: fxPos := Msg.Pos; else exit; end; UpdateHScrollBar; Invalidate; end; procedure TrmCustomScrollableControl.wmSize(var MSG: TWMSize); begin UpdatevScrollBar; UpdateHScrollBar; inherited; end; procedure TrmCustomScrollableControl.WMVScroll(var Msg: TWMVScroll); begin inherited; case Msg.ScrollCode of SB_BOTTOM: InternalTopIndex := MaxItemCount - VisibleItems; SB_LINEDOWN: InternalTopIndex := InternalTopIndex+1; SB_LINEUP: InternalTopIndex := InternalTopIndex-1; SB_TOP: InternalTopIndex := 0; SB_PAGEDOWN: InternalTopIndex := InternalTopIndex+VisibleItems; SB_PAGEUP: InternalTopIndex := InternalTopIndex-VisibleItems; SB_THUMBPOSITION: InternalTopIndex := Msg.Pos; SB_THUMBTRACK: InternalTopIndex := Msg.Pos; else exit; end; UpdateVScrollBar; Invalidate; end; procedure TrmCustomScrollableControl.WMGetDlgCode(var Message: TWMGetDlgCode); begin Message.Result := DLGC_WANTARROWS; end; procedure TrmCustomScrollableControl.KeyDown(var Key: Word; Shift: TShiftState); var wOldSelEnd, wOldindex, wOldSelStart: integer; dX: integer; begin inherited; wOldindex := fIndex; wOldSelStart := fSelStart; wOldSelEnd := fSelEnd; if fVeritcalScrollByChar then dX:=Canvas.TextWidth('X') else dX:=1; case key of vk_end: fIndex := MaxItemCount - 1; vk_DOWN: inc(fIndex); vk_up: dec(fIndex); vk_home: fIndex := 0; VK_Right: begin if (shift = []) then inc(fxPos, dX) else if (shift = [ssCtrl]) then fxPos := MaxItemLength - ClientWidth; end; VK_LEFT: begin if (shift = []) then dec(fxPos, dX) else if (shift = [ssCtrl]) then fxPos := 0; end; vk_next: inc(fIndex, VisibleItems - 1); vk_prior: Dec(fIndex, VisibleItems - 1); else exit; end; if MaxItemCount > 0 then fIndex := SetInRange(fIndex, 0, MaxItemCount-1) else fIndex := -1; if (shift = [ssShift]) and (fMultiSelect) then CalcMultiSelect(wOldIndex, wOldSelStart, wOldSelEnd) else begin fSelStart := fIndex; fSelEnd := fIndex; end; Try DoItemIndexChange; except //Do nothing... end; ScrollToVisible; UpdateVScrollBar; UpdateHScrollBar; Invalidate; end; procedure TrmCustomScrollableControl.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var wOldSelEnd, wOldindex, wOldSelStart: integer; begin inherited; wOldindex := fIndex; wOldSelStart := fSelStart; wOldSelEnd := fSelEnd; if Button = mbLeft then begin if CanFocus then setfocus; if y < 0 then y := -MaxItemHeight; if y > clientheight then y := clientheight+MaxItemHeight; if MaxItemCount > 0 then fIndex := SetInRange(InternalTopIndex + (y div maxitemheight), 0, MaxItemCount-1) else fIndex := -1; if (ssShift in Shift) and (fMultiSelect) then CalcMultiSelect(wOldIndex, wOldSelStart, wOldSelEnd) else begin fSelStart := fIndex; fSelEnd := fIndex; end; if fIndex <> wOldIndex then begin Try DoItemIndexChange; except //Do nothing... end; ScrollToVisible; UpdateVScrollBar; UpdateHScrollBar; end; Invalidate; end; end; procedure TrmCustomScrollableControl.MouseMove(Shift: TShiftState; X, Y: Integer); var wOldSelEnd, wOldindex, wOldSelStart: integer; begin inherited; wOldindex := fIndex; wOldSelStart := fSelStart; wOldSelEnd := fSelEnd; if focused and (ssLeft in Shift) then begin if CanFocus then setfocus; if MaxItemCount > 0 then fIndex := SetInRange(InternalTopIndex + (y div maxitemheight), 0, MaxItemCount-1) else fIndex := -1; if (fMultiSelect) then CalcMultiSelect(wOldIndex, wOldSelStart, wOldSelEnd) else begin fSelStart := fIndex; fSelEnd := fIndex; end; if fIndex <> wOldIndex then begin Try DoItemIndexChange; except //Do nothing... end; ScrollToVisible; UpdateVScrollBar; UpdateHScrollBar; repaint; end else invalidate; sleep(1); //fix for scrolling too quick! end; end; procedure TrmCustomScrollableControl.SetShowFocusRect(const Value: boolean); begin if fShowFocusRect <> Value then begin fShowFocusRect := Value; invalidate; end; end; function TrmCustomScrollableControl.GetHScrollSize: integer; begin if MaxItemLength - ClientWidth < 0 then result := 0 else result := (MaxItemLength - ClientWidth); end; function TrmCustomScrollableControl.GetVScrollSize: integer; begin if MaxItemCount - VisibleItems < 0 then result := 0 else result := (MaxItemCount - VisibleItems); end; function TrmCustomScrollableControl.DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; begin inherited DoMouseWheel(Shift, WheelDelta, MousePos); result := true; InternalTopIndex := SetInRange(vScrollPos + ((WheelDelta div 120) * -1), 0, VScrollSize); UpdateVScrollBar; invalidate; end; procedure TrmCustomScrollableControl.SetTopIndex(const Value: integer); begin if (MaxItemCount - VisibleItems)-1 < 0 then fTopIndex := 0 else fTopIndex := setinrange(Value, 0, (MaxItemCount - VisibleItems)); UpdateVScrollBar; invalidate; end; procedure TrmCustomScrollableControl.SetHideSelection(const Value: boolean); begin FHideSelection := Value; Invalidate; end; procedure TrmCustomScrollableControl.setMultiselect(const Value: boolean); begin fMultiSelect := Value; if not fMultiSelect then begin fSelStart := fIndex; fSelEnd := fIndex; end; invalidate; end; procedure TrmCustomScrollableControl.SetSelCount(const Value: integer); begin if fMultiSelect then fSelEnd := fSelStart + value else fSelEnd := fSelStart; fIndex := fSelEnd; Try DoItemIndexChange; except //Do nothing... end; Invalidate; end; procedure TrmCustomScrollableControl.SetSelStart(const Value: integer); begin fSelStart := Value; fSelEnd := Value; fIndex := value; Try DoItemIndexChange; except //Do nothing... end; invalidate; end; function TrmCustomScrollableControl.GetSelCount: integer; begin Result := fSelEnd - fSelStart; end; procedure TrmCustomScrollableControl.SetBorderStyle(const Value: TBorderStyle); begin if FBorderStyle <> Value then begin FBorderStyle := Value; RecreateWnd; end; end; procedure TrmCustomScrollableControl.SetScrollBars( const Value: TScrollStyle); begin if FScrollBars <> Value then begin FScrollBars := Value; RecreateWnd; end; end; function TrmCustomScrollableControl.MaxItemCount: integer; begin result := 0; end; function TrmCustomScrollableControl.MaxItemLength: integer; begin result := 0; end; function TrmCustomScrollableControl.MaxItemHeight: integer; begin result := 0; end; function TrmCustomScrollableControl.MaxItemWidth: integer; begin result := 0; end; procedure TrmCustomScrollableControl.CalcMultiSelect(oldIndex, oldSelStart, oldSelEnd:integer); begin if (OldIndex - findex) < 0 then //Down movement... begin if (OldIndex = OldSelEnd) then //continue down movement... begin fSelStart := OldSelStart; fSelEnd := fIndex; end else //Start a downmovement... begin if (fIndex > OldSelEnd) then //possible big down movement begin if (OldSelEnd <> OldSelStart) then //last selection wasn't a single line... begin fSelStart := OldSelEnd; fSelEnd := fIndex; end else //last selection was a single line... begin fSelStart := OldSelStart; fSelEnd := fIndex; end; end else //nope. only a small down movement... begin fSelStart := fIndex; fSelEnd := OldSelEnd; end; end; end else begin //Up movement... if (OldIndex = OldSelStart) then //continue up movement... begin fSelStart := fIndex; fSelEnd := OldSelEnd; end else //Start a up movement... begin if (fIndex < OldSelStart) then //possible up down movement begin if (OldSelEnd <> OldSelStart) then //last selection wasn't a single line... begin fSelStart := fIndex; fSelEnd := OldSelStart; end else //last selection was a single line... begin fSelStart := fIndex; fSelEnd := OldSelEnd; end; end else //nope. only a small up movement... begin fSelStart := OldSelStart; fSelEnd := fIndex; end; end; end; end; procedure TrmCustomScrollableControl.CMBorderChanged( var Message: TMessage); begin inherited; Invalidate; end; procedure TrmCustomScrollableControl.CMCtl3DChanged(var Message: TMessage); begin if NewStyleControls and (FBorderStyle = bsSingle) then RecreateWnd; inherited; end; procedure TrmCustomScrollableControl.HorizontalScrollChange( sender: TObject); begin //Do Nothing... end; procedure TrmCustomScrollableControl.VerticalScrollChange(sender: TObject); begin //Do Nothing... end; procedure TrmCustomScrollableControl.DoItemIndexChange; begin //Do Nothing... end; end.
unit GABasicFunctions; interface function PowerBase2(_exponent: integer): integer; implementation function PowerBase2(_exponent: integer): integer; var i : integer; begin Result := 1; if _exponent > 0 then begin for i := 1 to _exponent do begin Result := Result * 2; end; end; end; end.
unit BCEditor.Language; interface resourcestring { BCEditor.CompletionProposal } SBCEditorCannotInsertItemAtPosition = 'Cannot insert item at position %d.'; { BCEditor.Editor.Base } SBCEditorScrollInfoTopLine = 'Top line: %d'; SBCEditorScrollInfo = '%d - %d'; SBCEditorSearchStringNotFound = 'Search string ''%s'' not found'; SBCEditorSearchMatchNotFound = 'Search match not found.%sRestart search from the beginning of the file?'; SBCEditorRightMarginPosition = 'Position: %d'; SBCEditorSearchEngineNotAssigned = 'Search engine has not been assigned'; { BCEditor.Editor.KeyCommands } SBCEditorDuplicateShortcut = 'Shortcut already exists'; { BCEditor.MacroRecorder } SBCEditorCannotRecord = 'Cannot record macro; already recording or playing'; SBCEditorCannotPlay = 'Cannot playback macro; already playing or recording'; SBCEditorCannotPause = 'Can only pause when recording'; SBCEditorCannotResume = 'Can only resume when paused'; { BCEditor.Print.Preview } SBCEditorPreviewScrollHint = 'Page: %d'; { BCEditor.TextBuffer } SBCEditorListIndexOutOfBounds = 'Invalid stringlist index %d'; SBCEditorInvalidCapacity = 'Stringlist capacity cannot be smaller than count'; { BCEditor.Highlighter.JSONImporter } SBCEditorImporterFileNotFound = 'File ''%s'' not found'; implementation end.
unit u2DUtils; interface uses Windows, Math; function RectInRect(ROuter: TRect; RInner: TRect): Boolean; function RectSquare(R: TRect): Double; function RectInRectPercent(ROuter: TRect; RInner: TRect): Byte; function RectIntersectWithRectPercent(ROuter: TRect; RInner: TRect): Byte; function MoveRect(R: TRect; Dx, Dy: Integer): TRect; function RectWidth(R: TRect): Integer; function RectHeight(R: TRect): Integer; function NormalizeRect(R: TRect): TRect; implementation function RectInRect(ROuter: TRect; RInner: TRect): Boolean; begin Result := PtInRect(ROuter, RInner.TopLeft) and PtInRect(ROuter, RInner.BottomRight); end; function RectSquare(R: TRect): Double; begin Result := (R.Right - R.Left) * (R.Bottom - R.Top); end; function RectInRectPercent(ROuter: TRect; RInner: TRect): Byte; begin Result := 0; if RectInRect(ROuter, RInner) or EqualRect(ROuter, RInner) then begin if IsRectEmpty(ROuter) then begin Result := 100; Exit; end; Result := Round(100 * RectSquare(RInner) / RectSquare(ROuter)); end; end; function RectIntersectWithRectPercent(ROuter: TRect; RInner: TRect): Byte; var R: TRect; begin ROuter := NormalizeRect(ROuter); RInner := NormalizeRect(RInner); IntersectRect(R, ROuter, RInner); if IsRectEmpty(R) then Exit(0); Result := Round(100 * RectSquare(R) / RectSquare(RInner)); end; function MoveRect(R: TRect; Dx, Dy: Integer): TRect; begin Result.Left := R.Left + Dx; Result.Right := R.Right + Dx; Result.Top := R.Top + Dy; Result.Bottom := R.Bottom + Dy; end; function RectWidth(R: TRect): Integer; begin Result := R.Right - R.Left; end; function RectHeight(R: TRect): Integer; begin Result := R.Bottom - R.Top; end; function NormalizeRect(R: TRect): TRect; begin Result.Left := Min(R.Left, R.Right); Result.Right := Max(R.Left, R.Right); Result.Top := Min(R.Top, R.Bottom); Result.Bottom := Max(R.Top, R.Bottom); end; end.
// Copyright (c) 2009, ConTEXT Project Ltd // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. unit GpProfH; interface const PR_FREQUENCY = 0; // .prf tags, never reuse them, always add new! PR_ENTERPROC = 1; PR_EXITPROC = 2; PR_UNITTABLE = 3; PR_CLASSTABLE = 4; PR_PROCTABLE = 5; PR_PROCSIZE = 6; PR_ENDDATA = 7; PR_STARTDATA = 8; PR_ENDHEADER = 9; PR_COMPTICKS = 10; PR_COMPTHREADS = 11; PR_PRFVERSION = 12; PR_STARTCALIB = 13; PR_ENDCALIB = 14; PR_DIGEST = 15; PR_DIGTHREADS = 16; PR_DIGUNITS = 17; PR_DIGCLASSES = 18; PR_DIGPROCS = 19; PR_DIGFREQ = 20; PR_ENDDIGEST = 21; PR_DIGESTVER = 22; PR_DIGCALLG = 23; PR_DIGENDCG = -1; CALIB_CNT = 1000; CMD_MESSAGE = 'GPPROFILE_COMMAND'; CMD_DONE = 0; PRF_VERSION = 4; PRF_DIGESTVER = 3; implementation end.
unit ThPicture; interface uses SysUtils, Classes, Graphics, ThChangeNotifier; type TThCustomPicture = class(TThChangeNotifier) public class procedure SetPictureFolders( const inPublishFolder, inProjectFolder: string); private FHeight: Integer; FPictureData: TPicture; FPicturePath: string; FPictureUrl: string; FOwner: TComponent; FResolvedPicturePath: string; FUseDesignSize: Boolean; FWidth: Integer; protected function GetPictureData: TPicture; function GetGraphic: TGraphic; procedure SetHeight(const Value: Integer); procedure SetPicturePath(const Value: string); procedure SetPictureUrl(const Value: string); procedure SetPictureData(const Value: TPicture); procedure SetUseDesignSize(const Value: Boolean); procedure SetWidth(const Value: Integer); protected property Owner: TComponent read FOwner; property PictureData: TPicture read GetPictureData write SetPictureData; property PictureUrl: string read FPictureUrl write SetPictureUrl; property PicturePath: string read FPicturePath write SetPicturePath; property ResolvedPicturePath: string read FResolvedPicturePath; public constructor Create(AOwner: TComponent); destructor Destroy; override; function AspectHeight(inWidth: Integer): Integer; function AspectWidth(inHeight: Integer): Integer; function HasGraphic: Boolean; procedure Assign(Source: TPersistent); override; procedure ResolvePicturePath; procedure SetPaths(const inPath, inUrl: string); public property Graphic: TGraphic read GetGraphic; property Width: Integer read FWidth write SetWidth; property Height: Integer read FHeight write SetHeight; property UseDesignSize: Boolean read FUseDesignSize write SetUseDesignSize default true; end; // TThPicture = class(TThCustomPicture) public property PictureData; published property PictureUrl; property PicturePath; end; implementation uses ThPathUtils; var PublishedImagesFolder: string; ProjectImagesFolder: string; { TThCustomPicture } class procedure TThCustomPicture.SetPictureFolders( const inPublishFolder, inProjectFolder: string); begin PublishedImagesFolder := inPublishFolder; ProjectImagesFolder := inProjectFolder; end; constructor TThCustomPicture.Create(AOwner: TComponent); begin inherited Create; FOwner := AOwner; FPictureData := TPicture.Create; FUseDesignSize := true; end; destructor TThCustomPicture.Destroy; begin FPictureData.Free; inherited; end; procedure TThCustomPicture.Assign(Source: TPersistent); begin if not (Source is TThCustomPicture) then inherited else with TThCustomPicture(Source) do begin Self.PictureUrl := PictureUrl; Self.PicturePath := PicturePath; Self.Width := Width; Self.Height := Height; //Self.PictureData.Assign(PictureData); end; end; function PictureHasGraphic(inPicture: TPicture): Boolean; begin Result := (inPicture.Graphic <> nil) and not (inPicture.Graphic.Empty); end; function TThCustomPicture.HasGraphic: Boolean; begin Result := PictureHasGraphic(PictureData); end; function TThCustomPicture.GetGraphic: TGraphic; begin Result := PictureData.Graphic; end; { procedure TThCustomPicture.MarshallPicture; var f: string; begin try f := ThAppendPath(PictureSource, ExtractFileName(ResolvedPicturePath)); if FileExists(f) then begin ForceDirectories(ExtractFilePath(ResolvedPicturePath)); ThMemCopyFile(f, ResolvedPicturePath); end; except end; end; } function TThCustomPicture.GetPictureData: TPicture; begin if PicturePath <> '' then begin //if not FileExists(ResolvedPicturePath) then // MarshallPicture; if not PictureHasGraphic(FPictureData) and FileExists(ResolvedPicturePath) then try // Will repeat this part over and over if the file is somehow // not loadable (e.g. wrong format). // Should be a trap for that here. FPictureData.LoadFromFile(ResolvedPicturePath); if UseDesignSize and PictureHasGraphic(FPictureData) then begin Width := FPictureData.Width; Height := FPictureData.Height; end; except FPictureData.Graphic := nil; end; end; Result := FPictureData; end; procedure TThCustomPicture.ResolvePicturePath; begin if ThIsFullPath(PicturePath) then FResolvedPicturePath := PicturePath else begin FResolvedPicturePath := ThAppendPath(PublishedImagesFolder, PicturePath); if not FileExists(FResolvedPicturePath) then FResolvedPicturePath := ThAppendPath(ProjectImagesFolder, PicturePath); end; // FResolvedPicturePath := ThAppendPath(PictureRoot, PicturePath); end; procedure TThCustomPicture.SetPaths(const inPath, inUrl: string); begin FPicturePath := inPath; ResolvePicturePath; FPictureUrl := inUrl; FPictureData.Graphic := nil; Change; end; procedure TThCustomPicture.SetPicturePath(const Value: string); begin if (FPicturePath <> Value) then begin FPicturePath := Value; ResolvePicturePath; FPictureData.Graphic := nil; if (csDesigning in Owner.ComponentState) then GetPictureData; Change; end; end; procedure TThCustomPicture.SetPictureData(const Value: TPicture); begin FPictureData.Assign(Value); Change; end; procedure TThCustomPicture.SetPictureUrl(const Value: string); begin FPictureUrl := Value; Change; end; function TThCustomPicture.AspectHeight(inWidth: Integer): Integer; begin Result := inWidth * Height div Width; end; function TThCustomPicture.AspectWidth(inHeight: Integer): Integer; begin Result := inHeight * Width div Height; end; procedure TThCustomPicture.SetHeight(const Value: Integer); begin FHeight := Value; end; procedure TThCustomPicture.SetUseDesignSize(const Value: Boolean); begin FUseDesignSize := Value; end; procedure TThCustomPicture.SetWidth(const Value: Integer); begin FWidth := Value; end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright � 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Types; interface uses System.Generics.Defaults, VSoft.SemanticVersion; {$SCOPEDENUMS ON} type TPackageVersion = VSoft.SemanticVersion.TSemanticVersion; TClientVersion = VSoft.SemanticVersion.TSemanticVersion; //Note : This type is serialized in options, changing names or order may break things! TVerbosity = (Quiet, Normal, Detailed, Debug); TSourceType = (Folder, DPMServer); //TODO : Decide on min delphi version supported. Ideally go back as far as possible TCompilerVersion = ( UnknownVersion, RSXE2, RSXE3, RSXE4, RSXE5, RSXE6, RSXE7, RSXE8, RS10_0, RS10_1, RS10_2, RS10_3, RS10_4, RS11_0, RS12_0 ); TCompilerVersions = set of TCompilerVersion; //covering all bases here. TDPMPlatform = ( UnknownPlatform, Win32, Win64, WinArm32, //reserved for future use WinArm64, //reserved for future use OSX32, OSX64, OSXARM64, AndroidArm32, AndroidArm64, AndroidIntel32, //reserved for future use AndroidIntel64, //reserved for future use iOS32, iOS64, //reserved for future use LinuxIntel32, //reserved for future use LinuxIntel64, LinuxArm32, //reserved for future use LinuxArm64 //reserved for future use ); TDPMPlatforms = set of TDPMPlatform; TDPMUIFrameworkType = ( None, VCL, FMX ); TConstProc<T> = reference to procedure(const Arg1 : T); TConstProc<T1, T2> = reference to procedure(const Arg1 : T1; const Arg2 : T2); TConstProc<T1, T2, T3> = reference to procedure(const Arg1 : T1; const Arg2 : T2; const Arg3 : T3); TConstProc<T1, T2, T3, T4> = reference to procedure(const Arg1 : T1; const Arg2 : T2; const Arg3 : T3; const Arg4 : T4); TPackageVersionComparer = class(TInterfacedObject, IEqualityComparer<TPackageVersion>) protected function Equals(const Left, Right : TPackageVersion) : Boolean; reintroduce; function GetHashCode(const Value : TPackageVersion) : Integer; reintroduce; end; function DesignTimePlatform(const target : TCompilerVersion) : TDPMPlatform; function StringToCompilerVersion(const value : string) : TCompilerVersion; function StringToDPMPlatform(const value : string) : TDPMPlatform; function CompilerToString(const value : TCompilerVersion) : string; function CompilerToStringNoPoint(const value : TCompilerVersion) : string; function CompilerCodeName(const value : TCompilerVersion) : string; function CompilerWithCodeName(const value : TCompilerVersion) : string; function IsValidCompilerString(const value : string) : boolean; function IsValidPlatformString(const value : string) : boolean; function DPMPlatformToString(const value : TDPMPlatform) : string; function DPMPlatformToDisplayString(const value : TDPMPlatform) : string; function DPMPlatformToBDString(const value : TDPMPlatform) : string; function DPMPlatformsToString(const value : TDPMPlatforms; const sep : string = ',') : string; function CompilerToLibSuffix(const compiler : TCompilerVersion) : string; function CompilerToBDSVersion(const compiler : TCompilerVersion) : string; //returns the delphi compiler version function CompilerToCompilerVersionIntStr(const compiler : TCompilerVersion) : string; function ProjectVersionToCompilerVersion(const value : string) : TCompilerVersion; function IsAmbigousProjectVersion(const value : string; var versions : string) : boolean; function ProjectPlatformToDPMPlatform(const value : string) : TDPMPlatform; function AllPlatforms(const compiler : TCompilerVersion) : TDPMPlatforms; function StringToUIFrameworkType(const value : string) : TDPMUIFrameworkType; function UIFrameworkTypeToString(const value : TDPMUIFrameworkType) : string; implementation // For Delphi XE3 and up: {$IF CompilerVersion >= 24.0 } {$LEGACYIFEND ON} {$IFEND} uses {$IF CompilerVersion >= 29.0} System.Hash, {$IFEND} System.TypInfo, System.SysUtils, DPM.Core.Utils.Strings; function DesignTimePlatform(const target : TCompilerVersion) : TDPMPlatform; begin result := TDPMPlatform.Win32; //currently all delphi IDE's are 32 bit, but that might change in the future. end; function StringToCompilerVersion(const value : string) : TCompilerVersion; var iValue : integer; sValue : string; begin sValue := value; if not TStringUtils.StartsWith(sValue, 'RS') then sValue := 'RS' + sValue; sValue := StringReplace(sValue, '.', '_', [rfReplaceAll]); //we changed it to include the _0 - some packages might not have that. if sValue = 'RS11' then sValue := 'RS11_0'; iValue := GetEnumValue(typeInfo(TCompilerVersion), sValue); if iValue = -1 then result := TCompilerVersion.UnknownVersion else result := TCompilerVersion(iValue); end; function StringToDPMPlatform(const value : string) : TDPMPlatform; var iValue : integer; begin iValue := GetEnumValue(typeInfo(TDPMPlatform), value); if iValue = -1 then begin if value = 'Android' then result := TDPMPlatform.AndroidArm32 else if value = 'Android64' then result := TDPMPlatform.AndroidArm64 else if value = 'Linux64' then result := TDPMPlatform.LinuxIntel64 else result := TDPMPlatform.UnknownPlatform end else result := TDPMPlatform(iValue); end; function IsValidPlatformString(const value : string) : boolean; begin result := StringToDPMPlatform(value) <> TDPMPlatform.UnknownPlatform; end; function StringToUIFrameworkType(const value : string) : TDPMUIFrameworkType; var iValue : integer; begin iValue := GetEnumValue(typeInfo(TDPMUIFrameworkType), value); if iValue = -1 then result := TDPMUIFrameworkType.None else result := TDPMUIFrameworkType(iValue); end; function UIFrameworkTypeToString(const value : TDPMUIFrameworkType) : string; begin result := GetEnumName(TypeInfo(TDPMUIFrameworkType), ord(value)); end; function CompilerToString(const value : TCompilerVersion) : string; begin result := GetEnumName(TypeInfo(TCompilerVersion), ord(value)); Delete(result, 1, 2); // remove RS result := StringReplace(result, '_', '.', [rfReplaceAll]); end; function CompilerToStringNoPoint(const value : TCompilerVersion) : string; var i : integer; begin result := CompilerToString(value); i := pos('.', result); if i > 0 then Delete(result, i, length(result)); end; function IsValidCompilerString(const value : string) : boolean; begin result := StringToCompilerVersion(value) <> TCompilerVersion.UnknownVersion; end; function DPMPlatformToDisplayString(const value : TDPMPlatform) : string; begin case value of TDPMPlatform.UnknownPlatform: Result := 'Unknown' ; TDPMPlatform.Win32: result := 'Windows 32-bit' ; TDPMPlatform.Win64: result := 'Windows 64-bit'; TDPMPlatform.WinArm32: result := 'Windows 32-bit ARM'; TDPMPlatform.WinArm64: result := 'Windows 64-bit ARM'; TDPMPlatform.OSX32: result := 'macOS 32-bit'; TDPMPlatform.OSX64: result := 'macOS 64-bit'; TDPMPlatform.OSXARM64: result := 'macOS ARM 64-bit'; TDPMPlatform.AndroidArm32: result := 'Andriod 32-bit ARM'; TDPMPlatform.AndroidArm64: result := 'Andriod 64-bit ARM'; TDPMPlatform.AndroidIntel32: result := 'Andriod 32-bit Intel'; TDPMPlatform.AndroidIntel64: result := 'Andriod 64-bit Intel'; TDPMPlatform.iOS32: result := 'iOS 32-bit'; TDPMPlatform.iOS64: result := 'iOS 64-bit'; TDPMPlatform.LinuxIntel32: result := 'Linux 32-bit'; TDPMPlatform.LinuxIntel64: result := 'Linux 64-bit'; TDPMPlatform.LinuxArm32: result := 'Linux 32-bit ARM'; TDPMPlatform.LinuxArm64: result := 'Linux 64-bit ARM'; end; end; function DPMPlatformToString(const value : TDPMPlatform) : string; begin case value of TDPMPlatform.AndroidArm32: result := 'Android'; TDPMPlatform.AndroidArm64: result := 'Android64'; else result := GetEnumName(TypeInfo(TDPMPlatform), ord(value)); end; end; function DPMPlatformToBDString(const value : TDPMPlatform) : string; begin case value of TDPMPlatform.AndroidArm32 : result := 'Android'; TDPMPlatform.AndroidArm64 : result := 'Android64'; else result := GetEnumName(TypeInfo(TDPMPlatform), ord(value)); end; end; function DPMPlatformsToString(const value : TDPMPlatforms; const sep : string = ',') : string; var p : TDPMPlatform; i : integer; begin result := ''; i := 0; for p in value do begin if i = 0 then result := DPMPlatformToString(p) else result := result + sep + DPMPlatformToString(p); Inc(i); end; end; function AllPlatforms(const compiler : TCompilerVersion) : TDPMPlatforms; begin result := []; case compiler of TCompilerVersion.RSXE2 : result := [TDPMPlatform.Win32, TDPMPlatform.Win64, TDPMPlatform.OSX32]; TCompilerVersion.RSXE3, TCompilerVersion.RSXE4, TCompilerVersion.RSXE5, TCompilerVersion.RSXE6, TCompilerVersion.RSXE7, TCompilerVersion.RSXE8 : result := [TDPMPlatform.Win32, TDPMPlatform.Win64, TDPMPlatform.OSX32, TDPMPlatform.iOS32, TDPMPlatform.AndroidArm32]; TCompilerVersion.RS10_0, TCompilerVersion.RS10_1 : result := [TDPMPlatform.Win32, TDPMPlatform.Win64, TDPMPlatform.OSX32, TDPMPlatform.iOS32, TDPMPlatform.AndroidArm32]; TCompilerVersion.RS10_2 : result := [TDPMPlatform.Win32, TDPMPlatform.Win64, TDPMPlatform.OSX32, TDPMPlatform.iOS32, TDPMPlatform.AndroidArm32, TDPMPlatform.LinuxIntel64]; TCompilerVersion.RS10_3 : result := [TDPMPlatform.Win32, TDPMPlatform.Win64, TDPMPlatform.OSX32, TDPMPlatform.iOS32, TDPMPlatform.AndroidArm32, TDPMPlatform.LinuxIntel64, TDPMPlatform.AndroidArm64, TDPMPlatform.OSX64]; TCompilerVersion.RS10_4 : result := [TDPMPlatform.Win32, TDPMPlatform.Win64, TDPMPlatform.OSX64, TDPMPlatform.iOS32, TDPMPlatform.iOS64, TDPMPlatform.AndroidArm32, TDPMPlatform.AndroidArm64, TDPMPlatform.LinuxIntel64]; TCompilerVersion.RS11_0 : result := [TDPMPlatform.Win32, TDPMPlatform.Win64, TDPMPlatform.OSXARM64, TDPMPlatform.OSX64, TDPMPlatform.iOS64, TDPMPlatform.AndroidArm32, TDPMPlatform.AndroidArm64, TDPMPlatform.LinuxIntel64]; TCompilerVersion.RS12_0 : result := [TDPMPlatform.Win32, TDPMPlatform.Win64, TDPMPlatform.OSXARM64, TDPMPlatform.OSX64, TDPMPlatform.iOS64, TDPMPlatform.AndroidArm32, TDPMPlatform.AndroidArm64, TDPMPlatform.LinuxIntel64]; else raise Exception.Create('AllPlatforms is missing for : ' + CompilerToString(compiler)); end; end; function CompilerCodeName(const value : TCompilerVersion) : string; begin case value of TCompilerVersion.RS10_0 : result := 'Seattle'; TCompilerVersion.RS10_1 : result := 'Berlin'; TCompilerVersion.RS10_2 : result := 'Tokyo'; TCompilerVersion.RS10_3 : result := 'Rio'; TCompilerVersion.RS10_4 : result := 'Sydney'; TCompilerVersion.RS11_0 : result := 'Alexandria'; TCompilerVersion.RS12_0 : result := 'Dunno'; else result := ''; end; end; function CompilerWithCodeName(const value : TCompilerVersion) : string; var codeName : string; begin result := CompilerToString(value); codeName := CompilerCodeName(value); if codeName <> '' then result := result + ' ' + codeName; end; function CompilerToLibSuffix(const compiler : TCompilerVersion) : string; begin case compiler of TCompilerVersion.RSXE2 : result := '160'; TCompilerVersion.RSXE3 : result := '170'; TCompilerVersion.RSXE4 : result := '180'; TCompilerVersion.RSXE5 : result := '190'; TCompilerVersion.RSXE6 : result := '200'; TCompilerVersion.RSXE7 : result := '210'; TCompilerVersion.RSXE8 : result := '220'; TCompilerVersion.RS10_0 : result := '230'; TCompilerVersion.RS10_1 : result := '240'; TCompilerVersion.RS10_2 : result := '250'; TCompilerVersion.RS10_3 : result := '260'; TCompilerVersion.RS10_4 : result := '270'; TCompilerVersion.RS11_0 : result := '280'; TCompilerVersion.RS12_0 : result := '290'; else raise Exception.Create('LibSuffix is missing for : ' + CompilerToString(compiler)); end; end; function CompilerToBDSVersion(const compiler : TCompilerVersion) : string; begin case compiler of TCompilerVersion.RSXE2 : result := '9.0'; TCompilerVersion.RSXE3 : result := '10.0'; TCompilerVersion.RSXE4 : result := '11.0'; TCompilerVersion.RSXE5 : result := '12.0'; TCompilerVersion.RSXE6 : result := '14.0'; TCompilerVersion.RSXE7 : result := '15.0'; TCompilerVersion.RSXE8 : result := '16.0'; TCompilerVersion.RS10_0 : result := '17.0'; TCompilerVersion.RS10_1 : result := '18.0'; TCompilerVersion.RS10_2 : result := '19.0'; TCompilerVersion.RS10_3 : result := '20.0'; TCompilerVersion.RS10_4 : result := '21.0'; TCompilerVersion.RS11_0 : result := '22.0'; TCompilerVersion.RS12_0 : result := '23.0'; else raise Exception.Create('BDSVersion is missing for : ' + CompilerToString(compiler)); end; end; function CompilerToCompilerVersionIntStr(const compiler : TCompilerVersion) : string; begin case compiler of //2010 = 21 //XE = 22 TCompilerVersion.RSXE2 : result := '23'; TCompilerVersion.RSXE3 : result := '24'; TCompilerVersion.RSXE4 : result := '25'; TCompilerVersion.RSXE5 : result := '26'; TCompilerVersion.RSXE6 : result := '27'; TCompilerVersion.RSXE7 : result := '28'; TCompilerVersion.RSXE8 : result := '29'; TCompilerVersion.RS10_0 : result := '30'; TCompilerVersion.RS10_1 : result := '31'; TCompilerVersion.RS10_2 : result := '32'; TCompilerVersion.RS10_3 : result := '33'; TCompilerVersion.RS10_4 : result := '34'; TCompilerVersion.RS11_0 : result := '35'; TCompilerVersion.RS12_0 : result := '36'; else raise Exception.Create('BDSVersion is missing for : ' + CompilerToString(compiler)); end; end; function ProjectPlatformToDPMPlatform(const value : string) : TDPMPlatform; begin //TODO : flesh this out! non win platforms will not works result := StringToDPMPlatform(value); end; function IsAmbigousProjectVersion(const value : string; var versions : string) : boolean; var elements : TArray<string>; major : integer; minor : integer; begin result := false; if value = '' then exit; elements := TStringUtils.SplitStr(Trim(value), '.'); major := StrToIntDef(elements[0], -1); if major = -1 then exit; if length(elements) > 1 then minor := StrToIntDef(elements[1], -1) else minor := 0; if minor = -1 then exit; case major of 14 : begin case minor of 4 : begin result := true; //ambiguous could be xe3 update 2 versions := 'XE3 Update 2 / XE4'; end; end; end; 15 : begin case minor of 3 : begin result := true; //ambiguous could be xe6 versions := 'XE5 / XE6'; end; end; end; 18 : begin case minor of 1 : begin result := true; //ambiguous could be 10.0 Update 1 and Delphi 10.1 versions := '10.0 Update 1 / 10.1'; end; 2 : begin result := true; //ambigous could be 10.1 Update 1 and Delphi 10.2 versions := '10.1 Update 1 / 10.2'; end; end; end; end; end; //garnered from stackoverflow and the versions of delphi I have installed //todo - need checking function ProjectVersionToCompilerVersion(const value : string) : TCompilerVersion; var elements : TArray<string>; major : integer; minor : integer; begin result := TCompilerVersion.UnknownVersion; if value = '' then exit; elements := TStringUtils.SplitStr(Trim(value), '.'); major := StrToIntDef(elements[0], -1); if major = -1 then exit; if length(elements) > 1 then minor := StrToIntDef(elements[1], -1) else minor := 0; if minor = -1 then exit; case major of 13 : result := TCompilerVersion.RSXE2; 14 : begin case minor of 0..3 : result := TCompilerVersion.RSXE3; 4 : result := TCompilerVersion.RSXE4; //ambiguous could be xe3 update 2 else result := TCompilerVersion.RSXE4; end; end; 15 : begin case minor of 0..3 : result := TCompilerVersion.RSXE5; else result := TCompilerVersion.RSXE6; end; end; 16 : result := TCompilerVersion.RSXE7; 17 : result := TCompilerVersion.RSXE8; 18 : begin case minor of 0..1 : result := TCompilerVersion.RS10_0; 2 : result := TCompilerVersion.RS10_1; 3..4 : result := TCompilerVersion.RS10_2; 5..8 : result := TCompilerVersion.RS10_3; //18.8 for 10.3.3 end; end; 19 : begin begin case minor of 0..2 : result := TCompilerVersion.RS10_4; else //.3 is 11.0, .4 is ll.1, .5 is 11.2/3 result := TCompilerVersion.RS11_0; end; end; end; 20 : result := TCompilerVersion.RS12_0; else raise EArgumentOutOfRangeException.Create('Unknown project version'); end; end; { TPackageVersionComparer } function TPackageVersionComparer.Equals(const Left, Right : TPackageVersion) : Boolean; begin result := Left = Right; end; function TPackageVersionComparer.GetHashCode(const Value : TPackageVersion) : Integer; var s : string; begin s := Value.ToString; {$IF CompilerVersion >= 29.0} Result := System.Hash.THashBobJenkins.GetHashValue(s); {$ELSE} // {$LEGACYIFEND ON} Result := BobJenkinsHash(PChar(s)^, SizeOf(Char) * Length(s), 0); {$IFEND} end; end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * 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. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uCEFRequest; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefRequestRef = class(TCefBaseRefCountedRef, ICefRequest) protected function IsReadOnly: Boolean; function GetUrl: ustring; function GetMethod: ustring; function GetPostData: ICefPostData; procedure GetHeaderMap(const HeaderMap: ICefStringMultimap); procedure SetUrl(const value: ustring); procedure SetMethod(const value: ustring); procedure SetReferrer(const referrerUrl: ustring; policy: TCefReferrerPolicy); function GetReferrerUrl: ustring; function GetReferrerPolicy: TCefReferrerPolicy; procedure SetPostData(const value: ICefPostData); procedure SetHeaderMap(const HeaderMap: ICefStringMultimap); function GetFlags: TCefUrlRequestFlags; procedure SetFlags(flags: TCefUrlRequestFlags); function GetFirstPartyForCookies: ustring; procedure SetFirstPartyForCookies(const url: ustring); procedure Assign(const url, method: ustring; const postData: ICefPostData; const headerMap: ICefStringMultimap); function GetResourceType: TCefResourceType; function GetTransitionType: TCefTransitionType; function GetIdentifier: UInt64; public class function UnWrap(data: Pointer): ICefRequest; class function New: ICefRequest; end; implementation uses uCEFMiscFunctions, uCEFLibFunctions, uCEFPostData; function TCefRequestRef.IsReadOnly: Boolean; begin Result := PCefRequest(FData).is_read_only(PCefRequest(FData)) <> 0; end; procedure TCefRequestRef.Assign(const url, method: ustring; const postData: ICefPostData; const headerMap: ICefStringMultimap); var u, m: TCefString; begin u := cefstring(url); m := cefstring(method); PCefRequest(FData).set_(PCefRequest(FData), @u, @m, CefGetData(postData), headerMap.Handle); end; function TCefRequestRef.GetFirstPartyForCookies: ustring; begin Result := CefStringFreeAndGet(PCefRequest(FData).get_first_party_for_cookies(PCefRequest(FData))); end; function TCefRequestRef.GetFlags: TCefUrlRequestFlags; begin Result := PCefRequest(FData)^.get_flags(PCefRequest(FData)); end; procedure TCefRequestRef.GetHeaderMap(const HeaderMap: ICefStringMultimap); begin PCefRequest(FData)^.get_header_map(PCefRequest(FData), HeaderMap.Handle); end; function TCefRequestRef.GetIdentifier: UInt64; begin Result := PCefRequest(FData)^.get_identifier(PCefRequest(FData)); end; function TCefRequestRef.GetMethod: ustring; begin Result := CefStringFreeAndGet(PCefRequest(FData)^.get_method(PCefRequest(FData))) end; function TCefRequestRef.GetPostData: ICefPostData; begin Result := TCefPostDataRef.UnWrap(PCefRequest(FData)^.get_post_data(PCefRequest(FData))); end; function TCefRequestRef.GetResourceType: TCefResourceType; begin Result := PCefRequest(FData).get_resource_type(FData); end; function TCefRequestRef.GetTransitionType: TCefTransitionType; begin Result := PCefRequest(FData).get_transition_type(FData); end; function TCefRequestRef.GetUrl: ustring; begin Result := CefStringFreeAndGet(PCefRequest(FData)^.get_url(PCefRequest(FData))) end; class function TCefRequestRef.New: ICefRequest; begin Result := UnWrap(cef_request_create); end; procedure TCefRequestRef.SetFirstPartyForCookies(const url: ustring); var str: TCefString; begin str := CefString(url); PCefRequest(FData).set_first_party_for_cookies(PCefRequest(FData), @str); end; procedure TCefRequestRef.SetFlags(flags: TCefUrlRequestFlags); begin PCefRequest(FData)^.set_flags(PCefRequest(FData), PByte(@flags)^); end; procedure TCefRequestRef.SetHeaderMap(const HeaderMap: ICefStringMultimap); begin PCefRequest(FData)^.set_header_map(PCefRequest(FData), HeaderMap.Handle); end; procedure TCefRequestRef.SetMethod(const value: ustring); var v: TCefString; begin v := CefString(value); PCefRequest(FData)^.set_method(PCefRequest(FData), @v); end; procedure TCefRequestRef.SetReferrer(const referrerUrl: ustring; policy: TCefReferrerPolicy); var u: TCefString; begin u := CefString(referrerUrl); PCefRequest(FData)^.set_referrer(PCefRequest(FData), @u, policy); end; function TCefRequestRef.GetReferrerUrl: ustring; begin Result := CefStringFreeAndGet(PCefRequest(FData)^.get_referrer_url(PCefRequest(FData))); end; function TCefRequestRef.GetReferrerPolicy: TCefReferrerPolicy; begin Result := PCefRequest(FData)^.get_referrer_policy(PCefRequest(FData)); end; procedure TCefRequestRef.SetPostData(const value: ICefPostData); begin if value <> nil then PCefRequest(FData)^.set_post_data(PCefRequest(FData), CefGetData(value)); end; procedure TCefRequestRef.SetUrl(const value: ustring); var v: TCefString; begin v := CefString(value); PCefRequest(FData)^.set_url(PCefRequest(FData), @v); end; class function TCefRequestRef.UnWrap(data: Pointer): ICefRequest; begin if data <> nil then Result := Create(data) as ICefRequest else Result := nil; end; end.
(* WinGraph: HDO 1995-2004, JH 2003, GHO 2010, HDO 2011 -------- Simple module for generating Windows graphics using Borland Pascal or FreePascal (in Turbo Pascal mode: -Mtp). ==========================================================================*) UNIT WinGraph; INTERFACE USES {$IFDEF FPC} Windows; {$ELSE} WinTypes; {$ENDIF} TYPE RedrawProcType = PROCEDURE (dc: HDC; wnd: HWnd; r: TRect); MousePressedProcType = PROCEDURE (dc: HDC; wnd: HWnd; x, y: INTEGER); VAR redrawProc: RedrawProcType; (*SHOULD be set in main program*) mousePressedProc: MousePressedProcType; (*MAY be set in main program*) {$IFDEF FPC} PROCEDURE MoveTo(dc: HDC; x, y: INTEGER); (*calls MoveToEx for Win32 API*) {$ENDIF} PROCEDURE WGMain; (*HAS TO be called in main program to start message loop*) IMPLEMENTATION USES {$IFNDEF FPC} WinProcs, {$ENDIF} Strings; CONST applName = 'WinGraph: Windows Graphics'; {$IFDEF FPC} PROCEDURE MoveTo(dc: HDC; x, y: INTEGER); BEGIN MoveToEx(dc, x, y, NIL); END; (*MoveTo*) {$ENDIF} (* FrameWindowProc: callback function, called whenever an event for the frame window occurs *) FUNCTION FrameWindowProc {$IFDEF FPC} (wnd: HWnd; msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; StdCall; EXPORT; {$ELSE} (wnd: HWnd; msg: WORD; wParam: WORD; lParam: LONGINT): LONGINT; EXPORT; {$ENDIF} VAR ps: TPaintStruct; r: TRect; dc: HDC; BEGIN FrameWindowProc := 0; CASE msg OF wm_destroy: PostQuitMessage(0); wm_paint: IF @redrawProc <> NIL THEN BEGIN dc := BeginPaint(wnd, ps); GetClientRect(wnd, r); redrawProc(dc, wnd, r); EndPaint(wnd, ps); END; (*IF*) wm_lButtonDown: BEGIN IF @mousePressedProc <> NIL THEN mousePressedProc(GetDC(wnd), wnd, LoWord(lParam), HiWord(lParam)); END ELSE BEGIN FrameWindowProc := DefWindowProc(wnd, msg, wParam, lParam); END; END; (*CASE*) END;(*FrameWindowProc*) PROCEDURE WGMain; VAR wndClass: TWndClass; wnd: HWnd; msg: TMsg; BEGIN IF hPrevInst = 0 THEN BEGIN (*first call*) wndClass.style := cs_hRedraw OR cs_vRedraw; {$IFDEF FPC} wndClass.lpfnWndProc := WndProc(@FrameWindowProc); {$ELSE} wndClass.lpfnWndProc := @FrameWindowProc; {$ENDIF} wndClass.cbClsExtra := 0; wndClass.cbWndExtra := 0; wndClass.hInstance := 0; wndClass.hIcon := 0; wndClass.hCursor := 0; wndClass.hbrBackground := 0; wndClass.lpszMenuName := applName; (*BPC: ext. syntax compiler option*) wndClass.lpszClassName := applName; (*BPC: ext. syntax compiler option*) wndClass.hInstance := hInstance; wndClass.hIcon := LoadIcon(0, idi_application); wndClass.hCursor := LoadCursor(0, idc_arrow); wndClass.hbrBackground := GetStockObject(white_brush); IF Ord(RegisterClass(wndClass)) = 0 THEN BEGIN MessageBox(0, 'RegisterClass for window failed', NIL, mb_Ok); Halt; END; (*IF*) END; (*IF*) wnd := CreateWindow(applName, applName, ws_overlappedWindow, 40, 40, 800, 600, 0, 0, hInstance, NIL); ShowWindow(wnd, cmdShow); UpdateWindow(wnd); (*update client area by sending wm_paint*) WHILE GetMessage(msg, 0, 0, 0) DO BEGIN TranslateMessage(msg); (*translate key messages*) DispatchMessage(msg); (*dispatch to windows callback function*) END; (*WHILE*) END; (*WGMain*) PROCEDURE Redraw_Default(dc: HDC; wnd: HWnd; r: TRect); FAR; VAR txt: ARRAY [0..255] OF CHAR; BEGIN StrCopy(txt, 'Redraw_Default: no other Redraw prodecure installed'); TextOut(dc, 10, 10, txt, StrLen(txt)); END; (*MousePressed_Default*) PROCEDURE MousePressed_Default(dc: HDC; wnd: HWnd; x, y: INTEGER); FAR; BEGIN WriteLn('MousePressed_Default: no other MousePressed procedure installed'); END; (*MousePressed_Default*) BEGIN (*WinGraph*) redrawProc := Redraw_Default; mousePressedProc := MousePressed_Default; END. (*WinGraph*)
unit model_implementation; {$mode objfpc}{$H+} interface uses Classes, SysUtils, math,gdata, rdata, surface, idrisi_proc, lateralredistribution, carboncycling,variables; procedure Carbon; Procedure export_txt; procedure test_AD; implementation procedure test_AD; var C12_profile: array of single; i,t: integer; K,v: array of single; test_file1,test_file2:textfile; C12_ini_top,C12_ini_bot:single; begin setlength(C12_profile,layer_num+2); C12_ini_top:=1.5; C12_ini_bot:=0.1; for i:=1 to layer_num do begin C12_profile[i]:=C12_ini_top-(i-1)*(C12_ini_top-C12_ini_bot)/layer_num; end; assignfile(test_file1,'D:/ZhengangW/integrate_model/test_file1.txt'); rewrite(test_file1); for i:=1 to layer_num do begin writeln(test_file1,C12_profile[i]); end; closefile(test_file1); K:=K_coefficient; v:=v_coefficient; for t:=1 to 100 do begin if unstable= FALSE then Adevection_diffusion(K,v,C12_profile,unstable); end; assignfile(test_file2,'D:/ZhengangW/integrate_model/test_file2.txt'); rewrite(test_file2); for i:=1 to layer_num do begin writeln(test_file2,C12_profile[i]); end; closefile(test_file2); end; procedure Carbon; var i,j,t,k,m: integer; Cin,r,C13_in,C14_in: array of single; temp_A12,temp_S12,temp_P12: array of single; temp_A13,temp_S13,temp_P13: array of single; temp_A14,temp_S14,temp_P14: array of single; temp_CLAY, temp_SILT, temp_SAND, temp_ROCK,temp_Cs137: array of single; A12_content,S12_content,P12_content: single; A13_content,S13_content,P13_content: single; A14_content,S14_content,P14_content: single; Clay_content,Silt_content,Sand_content,Rock_content,Cs137_content: single; C13C12ratio_input,C14C12ratio_input: single; deltaC13_input,DeltaC14_input,Rate_Cs137_input:single; output_file:textfile; C13_input, C14_input,Cs137_input:textfile; C13_num, C14_num,Cs137_num: integer; C13_year, C14_year,Cs137_year:array of integer; C13_series,C14_series,Cs137_series:array of single; year_loop,year_loop_num: integer; K_coe,v_coe:array of single; temp_Cstock,temp_Csactivity: single; temp_file:textfile; begin setlength(temp_A12,layer_num+2); setlength(temp_S12,layer_num+2); setlength(temp_P12,layer_num+2); setlength(temp_A13,layer_num+2); setlength(temp_S13,layer_num+2); setlength(temp_P13,layer_num+2); setlength(temp_A14,layer_num+2); setlength(temp_S14,layer_num+2); setlength(temp_P14,layer_num+2); setlength(temp_CLAY,layer_num+2); setlength(temp_SILT,layer_num+2); setlength(temp_SAND,layer_num+2); setlength(temp_ROCK,layer_num+2); setlength(temp_CS137,layer_num+2); Setlength(C13_in,layer_num+2); Setlength(C14_in,layer_num+2); writeln('Initilize carbon and profile'); Carbon_Initilization; Texture_Initialization; Cs137_Initialization; writeln('allocate C input'); Cin:=input_allocation2; writeln('extrapolate mineralization rate'); r:=mineralization_extrapolation; K_coe:=K_coefficient; v_coe:=v_coefficient; assignfile(C13_input,c13filename); reset(C13_input); readln(C13_input,C13_num); setlength(C13_year,C13_num+2); setlength(C13_series,C13_num+2); for i:=1 to C13_num do begin readln(C13_input,C13_year[i],C13_series[i]); end; closefile(C13_input); assignfile(C14_input,c14filename); reset(C14_input); readln(C14_input,C14_num); setlength(C14_year,C14_num+2); setlength(C14_series,C14_num+2); for i:=1 to C14_num do begin readln(C14_input,C14_year[i],C14_series[i]); end; closefile(C14_input); assignfile(Cs137_input,cs137filename); reset(Cs137_input); readln(Cs137_input,Cs137_num); setlength(Cs137_year,Cs137_num+2); setlength(Cs137_series,Cs137_num+2); for i:=1 to Cs137_num do begin readln(Cs137_input,Cs137_year[i],Cs137_series[i]); end; closefile(Cs137_input); writeln('erosion and C cycling'); year_loop_num:=floor((erosion_end_year-erosion_start_year)/time_step); assignfile(temp_file,'F:/Geoscientific model development/integrate_model/Calibration/Catchments/data/c_profile1.txt'); rewrite(temp_file); for year_loop:=1 to year_loop_num do begin //writeln('erosion'); t:=erosion_start_year+(year_loop-1)*time_step; //writeln(inttostr(t)); if (t<C13_year[1]) OR (t>C13_year[C14_num]) then begin DeltaC13_input:=DeltaC13_input_default; end else begin for m:=1 to C13_num do begin if (t=C13_year[m]) then DeltaC13_input:=C13_series[m]; // it is ratio, not need to multiply the time-step end; end; C13C12ratio_input:=deltaC13_to_ratio(deltaC13_input); for i:=1 to layer_num do begin C13_in[i]:=Cin[i]*C13C12ratio_input; end; if (t<C14_year[1]) OR (t>C14_year[C14_num]) then begin DeltaC14_input:=DeltaC14_input_default; end else begin for m:=1 to C14_num do begin if (t=C14_year[m]) then DeltaC14_input:=C14_series[m]; // it is ratio, not need to multiply the time-step end; end; C14C12ratio_input:=DeltaC14_to_ratio(DeltaC14_input,deltaC13_input); for i:= 1 to layer_num do begin C14_in[i]:=Cin[i]*C14C12ratio_input; end; if (t<Cs137_year[1]) OR (t>Cs137_year[Cs137_num]) then begin Rate_Cs137_input:=Cs137_input_default; end else begin for m:=1 to Cs137_num do begin if (t=Cs137_year[m]) then Rate_Cs137_input:=Cs137_series[m]*time_step; // it is amount, need to multiply the time-step end; end; Water(WATEREROS,A12_eros, S12_eros, P12_eros,A13_eros, S13_eros, P13_eros, A14_eros, S14_eros, P14_eros,Clay_eros, Silt_eros, Sand_eros,Rock_eros,Cs137_eros, LS, RKCP, ktc, TFCA, ra, BD); //writeln('profile evolution'); for i:=1 to nrow do for j:=1 to ncol do //for i:=1 to 1 do //for j:=10 to 10 do begin for k:=1 to layer_num do begin temp_A12[k]:=A12[k,i,j]; temp_S12[k]:=S12[k,i,j]; temp_P12[k]:=P12[k,i,j]; temp_A13[k]:=A13[k,i,j]; temp_S13[k]:=S13[k,i,j]; temp_P13[k]:=P13[k,i,j]; temp_A14[k]:=A14[k,i,j]; temp_S14[k]:=S14[k,i,j]; temp_P14[k]:=P14[k,i,j]; temp_CLAY[k]:=CLAY[k,i,j]; temp_SILT[k]:=SILT[k,i,j]; temp_SAND[k]:=SAND[k,i,j]; temp_ROCK[k]:=ROCK[k,i,j]; temp_Cs137[k]:=CS137[k,i,j]; end; if (WATEREROS[i,j]>0) AND (WATEREROS[i,j]*time_step< depth/100/2) then // case of deposition, deposition depth should be lower than half of the depth considered begin A12_content:=A12_EROS[i,j]/WATEREROS[i,j]; // get the C content S12_content:=S12_EROS[i,j]/WATEREROS[i,j]; P12_content:=P12_EROS[i,j]/WATEREROS[i,j]; A13_content:=A13_EROS[i,j]/WATEREROS[i,j]; // get the C content S13_content:=S13_EROS[i,j]/WATEREROS[i,j]; P13_content:=P13_EROS[i,j]/WATEREROS[i,j]; A14_content:=A14_EROS[i,j]/WATEREROS[i,j]; // get the C content S14_content:=S14_EROS[i,j]/WATEREROS[i,j]; P14_content:=P14_EROS[i,j]/WATEREROS[i,j]; Clay_content:=Clay_EROS[i,j]/WATEREROS[i,j]; // get the C content Silt_content:=Silt_EROS[i,j]/WATEREROS[i,j]; Sand_content:=Sand_EROS[i,j]/WATEREROS[i,j]; Rock_content:=Rock_EROS[i,j]/WATEREROS[i,j]; Cs137_content:=Cs137_EROS[i,j]/WATEREROS[i,j]; Evolution_deposition(WATEREROS[i,j]*time_step,A12_content,temp_A12); Evolution_deposition(WATEREROS[i,j]*time_step,S12_content,temp_S12); Evolution_deposition(WATEREROS[i,j]*time_step,P12_content,temp_P12); Evolution_deposition(WATEREROS[i,j]*time_step,A13_content,temp_A13); Evolution_deposition(WATEREROS[i,j]*time_step,S13_content,temp_S13); Evolution_deposition(WATEREROS[i,j]*time_step,P13_content,temp_P13); Evolution_deposition(WATEREROS[i,j]*time_step,A14_content,temp_A14); Evolution_deposition(WATEREROS[i,j]*time_step,S14_content,temp_S14); Evolution_deposition(WATEREROS[i,j]*time_step,P14_content,temp_P14); Evolution_deposition(WATEREROS[i,j]*time_step,Clay_content,temp_Clay); Evolution_deposition(WATEREROS[i,j]*time_step,Silt_content,temp_Silt); Evolution_deposition(WATEREROS[i,j]*time_step,Sand_content,temp_Sand); Evolution_deposition(WATEREROS[i,j]*time_step,Rock_content,temp_Rock); Evolution_deposition(WATEREROS[i,j]*time_step,Cs137_content,temp_Cs137); end else if (WATEREROS[i,j]<0) AND (abs(WATEREROS[i,j]*time_step)<depth/100/2) then // case of erosion, erosion depth should be lower than half of the depth considered begin Evolution_erosion(-WATEREROS[i,j]*time_step,temp_A12); Evolution_erosion(-WATEREROS[i,j]*time_step,temp_S12); Evolution_erosion(-WATEREROS[i,j]*time_step,temp_P12); Evolution_erosion(-WATEREROS[i,j]*time_step,temp_A13); Evolution_erosion(-WATEREROS[i,j]*time_step,temp_S13); Evolution_erosion(-WATEREROS[i,j]*time_step,temp_P13); Evolution_erosion(-WATEREROS[i,j]*time_step,temp_A14); Evolution_erosion(-WATEREROS[i,j]*time_step,temp_S14); Evolution_erosion(-WATEREROS[i,j]*time_step,temp_P14); Evolution_erosion(-WATEREROS[i,j]*time_step,temp_Clay); Evolution_erosion(-WATEREROS[i,j]*time_step,temp_Silt); Evolution_erosion(-WATEREROS[i,j]*time_step,temp_Sand); Evolution_erosion(-WATEREROS[i,j]*time_step,temp_Rock); Evolution_erosion(-WATEREROS[i,j]*time_step,temp_Cs137); end; Carbon_Cycling(k1,k2,k3,hAS,hAP,hSP,Cin,r,temp_A12,temp_S12,temp_P12); Carbon_Cycling(k1*C13_discri,k2*C13_discri,k3*C13_discri,hAS,hAP,hSP,C13_in,r,temp_A13,temp_S13,temp_P13); Carbon_Cycling(k1*C14_discri,k2*C14_discri,k3*C14_discri,hAS,hAP,hSP,C14_in,r,temp_A14,temp_S14,temp_P14); tillage_mix(temp_A12); tillage_mix(temp_S12); tillage_mix(temp_P12); tillage_mix(temp_A13); tillage_mix(temp_S13); tillage_mix(temp_P13); tillage_mix(temp_A14); tillage_mix(temp_S14); tillage_mix(temp_P14); Cs137_fallout(Rate_Cs137_input,temp_Cs137); tillage_mix(temp_Cs137); C14_decay(temp_A14); C14_decay(temp_S14); C14_decay(temp_P14); Cs137_decay(temp_Cs137); if unstable= FALSE then begin Adevection_diffusion(K_coe,v_coe,temp_A12,unstable); Adevection_diffusion(K_coe,v_coe,temp_S12,unstable); Adevection_diffusion(K_coe,v_coe,temp_P12,unstable); Adevection_diffusion(K_coe,v_coe,temp_A13,unstable); Adevection_diffusion(K_coe,v_coe,temp_S13,unstable); Adevection_diffusion(K_coe,v_coe,temp_P13,unstable); Adevection_diffusion(K_coe,v_coe,temp_A14,unstable); Adevection_diffusion(K_coe,v_coe,temp_S14,unstable); Adevection_diffusion(K_coe,v_coe,temp_P14,unstable); Adevection_diffusion(K_coe,v_coe,temp_Cs137,unstable); end; tillage_mix(temp_A12); tillage_mix(temp_S12); tillage_mix(temp_P12); tillage_mix(temp_A13); tillage_mix(temp_S13); tillage_mix(temp_P13); tillage_mix(temp_A14); tillage_mix(temp_S14); tillage_mix(temp_P14); tillage_mix(temp_Clay); tillage_mix(temp_Silt); tillage_mix(temp_Sand); tillage_mix(temp_Rock); tillage_mix(temp_Cs137); for k:=1 to layer_num do begin A12[k,i,j]:=temp_A12[k]; S12[k,i,j]:=temp_S12[k]; P12[k,i,j]:=temp_P12[k]; A13[k,i,j]:=temp_A13[k]; S13[k,i,j]:=temp_S13[k]; P13[k,i,j]:=temp_P13[k]; A14[k,i,j]:=temp_A14[k]; S14[k,i,j]:=temp_S14[k]; P14[k,i,j]:=temp_P14[k]; Clay[k,i,j]:=temp_Clay[k]; Silt[k,i,j]:=temp_Silt[k]; Sand[k,i,j]:=temp_Sand[k]; Rock[k,i,j]:=temp_Rock[k]; Cs137[k,i,j]:=temp_Cs137[k]; end; end; for k:=1 to layer_num do begin if k=layer_num then write(temp_file,A12[k,9,2]+S12[k,9,2]+P12[k,9,2],char(13)) else write(temp_file,A12[k,9,2]+S12[k,9,2]+P12[k,9,2],char(9)); end; end; closefile(temp_file); for i:=1 to nrow do for j:=1 to ncol do begin temp_Cstock:=0; temp_Csactivity:=0; for k:=1 to layer_num do begin temp_Cstock:=temp_Cstock+(A12[k,i,j]+S12[k,i,j]+P12[k,i,j]+A13[k,i,j]+S13[k,i,j]+P13[k,i,j]+A14[k,i,j]+S14[k,i,j]+P14[k,i,j])*depth_interval; temp_Csactivity:=temp_Csactivity+CS137[k,i,j]*depth_interval; end; C_STOCK[i,j]:=temp_Cstock/100/100*BD; // unit kg/m2 CS137_ACTIVITY[i,j]:=temp_Csactivity/100*BD; // unit Bq/m2 end; end; Procedure export_txt; var A12_file,A13_file,A14_file:textfile; S12_file,S13_file,S14_file:textfile; P12_file,P13_file,P14_file:textfile; CLAY_file, SILT_file, SAND_file, ROCK_file,CS137_file:textfile; i,j,k:integer; begin assignfile(A12_file,'A12.txt'); rewrite(A12_file); assignfile(A13_file,'A13.txt'); rewrite(A13_file); assignfile(A14_file,'A14.txt'); rewrite(A14_file); assignfile(S12_file,'S12.txt'); rewrite(S12_file); assignfile(S13_file,'S13.txt'); rewrite(S13_file); assignfile(S14_file,'S14.txt'); rewrite(S14_file); assignfile(P12_file,'P12.txt'); rewrite(P12_file); assignfile(P13_file,'P13.txt'); rewrite(P13_file); assignfile(P14_file,'P14.txt'); rewrite(P14_file); assignfile(CLAY_file,'CLAY.txt'); rewrite(CLAY_file); assignfile(SILT_file,'SILT.txt'); rewrite(SILT_file); assignfile(SAND_file,'SAND.txt'); rewrite(SAND_file); assignfile(ROCK_file,'ROCK.txt'); rewrite(ROCK_file); assignfile(CS137_file,'Cs137.txt'); rewrite(CS137_file); for k:=1 to layer_num do for i:=1 to nrow do for j:=1 to ncol do begin if (i=nrow) AND (j=ncol) then begin write(A12_file,A12[k,i,j]); write(A12_file,char(13)); write(A13_file,A13[k,i,j]); write(A13_file,char(13)); write(A14_file,A14[k,i,j]); write(A14_file,char(13)); write(S12_file,S12[k,i,j]); write(S12_file,char(13)); write(S13_file,S13[k,i,j]); write(S13_file,char(13)); write(S14_file,S14[k,i,j]); write(S14_file,char(13)); write(P12_file,P12[k,i,j]); write(P12_file,char(13)); write(P13_file,P13[k,i,j]); write(P13_file,char(13)); write(P14_file,P14[k,i,j]); write(P14_file,char(13)); write(CLAY_file,CLAY[k,i,j]); write(CLAY_file,char(13)); write(SILT_file,SILT[k,i,j]); write(SILT_file,char(13)); write(SAND_file,SAND[k,i,j]); write(SAND_file,char(13)); write(ROCK_file,ROCK[k,i,j]); write(ROCK_file,char(13)); write(CS137_file,CS137[k,i,j]); write(CS137_file,char(13)); end else begin write(A12_file,A12[k,i,j]); write(A12_file,char(9)); write(A13_file,A13[k,i,j]); write(A13_file,char(9)); write(A14_file,A14[k,i,j]); write(A14_file,char(9)); write(S12_file,S12[k,i,j]); write(S12_file,char(9)); write(S13_file,S13[k,i,j]); write(S13_file,char(9)); write(S14_file,S14[k,i,j]); write(S14_file,char(9)); write(P12_file,P12[k,i,j]); write(P12_file,char(9)); write(P13_file,P13[k,i,j]); write(P13_file,char(9)); write(P14_file,P14[k,i,j]); write(P14_file,char(9)); write(CLAY_file,CLAY[k,i,j]); write(CLAY_file,char(9)); write(SILT_file,SILT[k,i,j]); write(SILT_file,char(9)); write(SAND_file,SAND[k,i,j]); write(SAND_file,char(9)); write(ROCK_file,ROCK[k,i,j]); write(ROCK_file,char(9)); write(CS137_file,CS137[k,i,j]); write(CS137_file,char(9)); end; end; closefile(A12_file);closefile(A13_file);closefile(A14_file); closefile(S12_file);closefile(S13_file);closefile(S14_file); closefile(P12_file);closefile(P13_file);closefile(P14_file); closefile(CLAY_file);closefile(SILT_file);closefile(SAND_file);closefile(ROCK_file);closefile(CS137_file); end; end.
unit FDiskExport; (*==================================================================== Progress info window for exporting disks to text format ======================================================================*) interface uses {$ifdef mswindows} WinTypes,WinProcs, {$ELSE} LCLIntf, LCLType, LMessages, {$ENDIF} Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, UApiTypes, UStringList; type TFormDiskExport = class(TForm) ButtonCancel: TButton; LabelWhatDoing: TLabel; SaveDialogExportToText: TSaveDialog; OpenDialogExportFormat: TOpenDialog; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure ButtonCancelClick(Sender: TObject); private bCanRun : boolean; ///FilesList : TQStringList; {for capturing and sorting files} FilesList : TStringList; {for capturing and sorting files} public bStopIt : boolean; DBaseHandle : PDBaseHandle; procedure Run(var Info); message WM_User; procedure UpdateProgress; procedure OnDatabaseBegin; procedure OnDatabaseEnd; procedure OnDiskBegin; procedure OnDiskEnd; procedure OnFolderBegin; procedure OnFolderEnd; procedure OnFirstColumnBegin; procedure OnEachColumnBegin; procedure OnFile; procedure OnEachColumnEnd; procedure OnLastColumnEnd; end; var FormDiskExport: TFormDiskExport; implementation uses UAPi, UExport, ULang, UExceptions, FDiskPrintSelect, FSettings, UBaseUtils; {$R *.dfm} //---CallBack Functions-------------------------------------------------------- // We use pointer to functions, so that they cannot be the methods of the object. // Thus, these callback functions pass the call to the appropriate method procedure CallBackWhenChange(var Stop: boolean); begin FormDiskExport.UpdateProgress; Application.ProcessMessages; Stop := FormDiskExport.bStopIt; end; //----------------------------------------------------------------------------- procedure OnDatabaseBeginNotify; begin FormDiskExport.OnDatabaseBegin; end; //----------------------------------------------------------------------------- procedure OnDatabaseEndNotify; begin FormDiskExport.OnDatabaseEnd; end; //----------------------------------------------------------------------------- procedure OnDiskBeginNotify; begin FormDiskExport.OnDiskBegin; end; //----------------------------------------------------------------------------- procedure OnDiskEndNotify; begin FormDiskExport.OnDiskEnd; end; //----------------------------------------------------------------------------- procedure OnFolderBeginNotify; begin FormDiskExport.OnFolderBegin; end; //----------------------------------------------------------------------------- procedure OnFolderEndNotify; begin FormDiskExport.OnFolderEnd; end; //----------------------------------------------------------------------------- procedure OnFirstColumnBeginNotify; begin FormDiskExport.OnFirstColumnBegin; end; //----------------------------------------------------------------------------- procedure OnEachColumnBeginNotify; begin FormDiskExport.OnEachColumnBegin; end; //----------------------------------------------------------------------------- procedure OnFileNotify; begin FormDiskExport.OnFile; end; //----------------------------------------------------------------------------- procedure OnEachColumnEndNotify; begin FormDiskExport.OnEachColumnEnd; end; //----------------------------------------------------------------------------- procedure OnLastColumnEndNotify; begin FormDiskExport.OnLastColumnEnd; end; //---TFormDiskExport----------------------------------------------------------- procedure TFormDiskExport.FormCreate(Sender: TObject); begin bCanRun := false; OpenDialogExportFormat.InitialDir := ExtractFilePath(ParamStr(0)) + lsExportFolder; SaveDialogExportToText.InitialDir := ExtractFilePath(ParamStr(0)) + lsExportFolder; end; //----------------------------------------------------------------------------- procedure TFormDiskExport.FormShow(Sender: TObject); begin bStopIt := false; bCanRun := true; LabelWhatDoing.Caption := lsPreparingToExport; // Posts message to self - this assures the window is displayed before // the export starts. The WM_User message is handled by the Run() PostMessage(Self.Handle, WM_User, 0, 0); end; //----------------------------------------------------------------------------- // Called by WM_User message - makes the export, by calling the engine - the // engine calls the callback functions. procedure TFormDiskExport.Run (var Info); var MsgText: array[0..256] of char; SearchIn: TSearchIn; begin if not bCanRun then exit; bCanRun := false; bStopIt := false; ///FilesList := TQStringList.Create; FilesList := TStringList.Create; ///FilesList.Sorted := true; FilesList.Duplicates := dupAccept; FormSettings.UpdateGlobalFormatSettings; try FormDiskPrintSelect.RadioButtonSelectedDisks.Enabled := QI_GetSelectedCount (DBaseHandle) > 0; FormDiskPrintSelect.Caption := lsExportSelection; FormDiskPrintSelect.LabelWhat.Caption := lsExportWhat; if FormDiskPrintSelect.ShowModal <> mrOk then begin FreeObjects(FilesList); FilesList.Free; ModalResult := mrCancel; exit; end; with FormDiskPrintSelect do begin SearchIn := siActualDiskDir; if RadioButtonActDiskWhole.Checked then SearchIn := siActualDisk; if RadioButtonSelectedDisks.Checked then SearchIn := siSelectedDisks; end; OpenDialogExportFormat.Filter := lsFilterDatabase; if not OpenDialogExportFormat.Execute then begin FreeObjects(FilesList); FilesList.Free; ModalResult := mrCancel; exit; end; OpenDialogExportFormat.InitialDir := ExtractFilePath(OpenDialogExportFormat.FileName); DBaseExport.Init(OpenDialogExportFormat.FileName, DBaseHandle); if (not DBaseExport.bFormatVerified) then begin NormalErrorMessage(lsNotValidFormatFile); FreeObjects(FilesList); FilesList.Free; ModalResult := mrCancel; exit; end; SaveDialogExportToText.DefaultExt := DBaseExport.sDefaultExt; if DBaseExport.sFileFilter <> '' then SaveDialogExportToText.Filter := DBaseExport.sFileFilter + '|' + lsDefaultFilter else SaveDialogExportToText.Filter := lsDefaultFilter; if not SaveDialogExportToText.Execute then begin FreeObjects(FilesList); FilesList.Free; ModalResult := mrCancel; exit; end; SaveDialogExportToText.InitialDir := ExtractFilePath(SaveDialogExportToText.FileName); DBaseExport.OpenOutputFile(SaveDialogExportToText.FileName); QI_SetNotifyProcs (DBaseHandle, CallBackWhenChange, OnDatabaseBeginNotify, OnDatabaseEndNotify, OnDiskBeginNotify, OnDiskEndNotify, OnFolderBeginNotify, OnFolderEndNotify, OnFileNotify); QI_IterateFiles (DBaseHandle, SearchIn, stDataNotify); QI_DelNotifyProcs (DBaseHandle); DBaseExport.CloseOutputFile; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do FatalErrorMessage(EFatal.Message); on E: Exception do Application.MessageBox(StrPCopy(MsgText, E.Message), lsError, mb_Ok or mb_IconExclamation); end; FreeObjects(FilesList); FilesList.Free; ModalResult := mrOk; end; //----------------------------------------------------------------------------- procedure TFormDiskExport.UpdateProgress; begin LabelWhatDoing.Caption := lsProcessed + FormatNumber(DBaseExport.iFileCounter) + lsFiles_Written + FormatSize(DBaseExport.iWritten, true); end; //----------------------------------------------------------------------------- procedure TFormDiskExport.OnDatabaseBegin; begin DBaseExport.OnDatabaseBegin; end; //----------------------------------------------------------------------------- procedure TFormDiskExport.OnDatabaseEnd; begin DBaseExport.OnDatabaseEnd; end; //----------------------------------------------------------------------------- procedure TFormDiskExport.OnDiskBegin; begin DBaseExport.OnDiskBegin; end; //----------------------------------------------------------------------------- procedure TFormDiskExport.OnDiskEnd; begin DBaseExport.OnDiskEnd; end; //----------------------------------------------------------------------------- procedure TFormDiskExport.OnFolderBegin; begin DBaseExport.OnFolderBegin; end; //----------------------------------------------------------------------------- procedure TFormDiskExport.OnFolderEnd; begin DBaseExport.OnFolderEnd; end; //----------------------------------------------------------------------------- procedure TFormDiskExport.OnFirstColumnBegin; begin DBaseExport.OnFirstColumnBegin; end; //----------------------------------------------------------------------------- procedure TFormDiskExport.OnEachColumnBegin; begin DBaseExport.OnEachColumnBegin; end; //----------------------------------------------------------------------------- procedure TFormDiskExport.OnFile; begin DBaseExport.OnFile; end; //----------------------------------------------------------------------------- procedure TFormDiskExport.OnEachColumnEnd; begin DBaseExport.OnEachColumnEnd; end; //----------------------------------------------------------------------------- procedure TFormDiskExport.OnLastColumnEnd; begin DBaseExport.OnLastColumnEnd; end; //----------------------------------------------------------------------------- procedure TFormDiskExport.ButtonCancelClick(Sender: TObject); begin bStopIt := true; end; //----------------------------------------------------------------------------- end.
unit frmSelectHashCypher; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Classes, Controls, Dialogs, Forms, Graphics, Grids, Menus, Messages, OTFEFreeOTFEBase_U, SDUForms, StdCtrls, SysUtils, VolumeFileAPI, Windows; { TODO -otdk -cui : doesnt look good - replace custom draw with simple grid } type TfrmSelectHashCypher = class (TSDUForm) Label1: TLabel; sgCombinations: TStringGrid; pbOK: TButton; pbCancel: TButton; Label2: TLabel; miPopup: TPopupMenu; miHashDetails: TMenuItem; miCypherDetails: TMenuItem; Label3: TLabel; procedure FormCreate(Sender: TObject); procedure miHashDetailsClick(Sender: TObject); procedure miCypherDetailsClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure sgCombinationsClick(Sender: TObject); procedure sgCombinationsDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure FormDestroy(Sender: TObject); procedure sgCombinationsDblClick(Sender: TObject); procedure pbOKClick(Sender: TObject); private HashDriverKernelModeNames: TStringList; HashGUIDs: TStringList; CypherDriverKernelModeNames: TStringList; CypherGUIDs: TStringList; procedure EnableDisableControls(); public FreeOTFEObj: TOTFEFreeOTFEBase; procedure AddCombination( HashDriverKernelModeName: String; HashGUID: TGUID; CypherDriverKernelModeName: String; CypherGUID: TGUID ); function SelectedCypherDriverKernelModeName(): String; function SelectedCypherGUID(): TGUID; function SelectedHashDriverKernelModeName(): String; function SelectedHashGUID(): TGUID; end; implementation {$R *.DFM} uses ComObj, // Required for GUIDToString OTFEFreeOTFE_U, SDUi18n, SDUGeneral; procedure TfrmSelectHashCypher.FormCreate(Sender: TObject); begin sgCombinations.ColWidths[0] := sgCombinations.Width; HashDriverKernelModeNames := TStringList.Create(); HashGUIDs := TStringList.Create(); CypherDriverKernelModeNames := TStringList.Create(); CypherGUIDs := TStringList.Create(); end; // Add a particular hash/cypher combination to the list of combinations the // user may select from procedure TfrmSelectHashCypher.AddCombination( HashDriverKernelModeName: String; HashGUID: TGUID; CypherDriverKernelModeName: String; CypherGUID: TGUID ); var tmpHashDetails: TFreeOTFEHash; tmpCypherDetails: TFreeOTFECypher_v3; tmpHashDriverDetails: TFreeOTFEHashDriver; tmpCypherDriverDetails: TFreeOTFECypherDriver; prettyHashDriverName: String; prettyCypherDriverName: String; prettyHashName: String; prettyCypherName: String; hashText: String; cypherText: String; summaryLine: String; cellContents: String; begin // Store the details... HashDriverKernelModeNames.Add(HashDriverKernelModeName); HashGUIDs.Add(GUIDToString(HashGUID)); CypherDriverKernelModeNames.Add(CypherDriverKernelModeName); CypherGUIDs.Add(GUIDToString(CypherGUID)); // >2 because we always have one fixed row, and one data row // Also checks if 1st cell on that data row is populated if ((sgCombinations.RowCount > 1) or (sgCombinations.Cells[0, 0] <> '')) then begin sgCombinations.RowCount := sgCombinations.RowCount + 1; end; // Hash details... prettyHashName := ''; hashText := ''; if (HashDriverKernelModeName <> '') then begin prettyHashDriverName := '???'; if FreeOTFEObj.GetHashDriverHashes(HashDriverKernelModeName, tmpHashDriverDetails) then prettyHashDriverName := tmpHashDriverDetails.Title + ' (' + FreeOTFEObj.VersionIDToStr(tmpHashDriverDetails.VersionID) + ')'; prettyHashName := '???'; if FreeOTFEObj.GetSpecificHashDetails(HashDriverKernelModeName, HashGUID, tmpHashDetails) then prettyHashName := FreeOTFEObj.GetHashDisplayTitle(tmpHashDetails); hashText := SDUParamSubstitute(_('Hash implementation: %1'), [prettyHashDriverName]) + SDUCRLF + ' ' + SDUParamSubstitute(_('Kernel mode driver: %1'), [HashDriverKernelModeName]) + SDUCRLF + ' ' + SDUParamSubstitute( _('Algorithm GUID: %1'), [GUIDToString(HashGUID)]); end; // Cypher details... prettyCypherName := ''; cypherText := ''; if (CypherDriverKernelModeName <> '') then begin prettyCypherDriverName := '???'; if FreeOTFEObj.GetCypherDriverCyphers(CypherDriverKernelModeName, tmpCypherDriverDetails) then prettyCypherDriverName := tmpCypherDriverDetails.Title + ' (' + FreeOTFEObj.VersionIDToStr(tmpCypherDriverDetails.VersionID) + ')'; prettyCypherName := '???'; if FreeOTFEObj.GetSpecificCypherDetails(CypherDriverKernelModeName, CypherGUID, tmpCypherDetails) then prettyCypherName := FreeOTFEObj.GetCypherDisplayTitle(tmpCypherDetails); cypherText := SDUParamSubstitute(_('Cypher implementation: %1'), [prettyCypherDriverName]) + SDUCRLF + ' ' + SDUParamSubstitute( _('Kernel mode driver: %1'), [CypherDriverKernelModeName]) + SDUCRLF + ' ' + SDUParamSubstitute(_('Algorithm GUID: %1'), [GUIDToString(CypherGUID)]); end; // Work out cell layout... if ((HashDriverKernelModeName <> '') and (CypherDriverKernelModeName <> '')) then cellContents := prettyHashName + ' / ' + prettyCypherName + SDUCRLF + hashText + SDUCRLF + cypherText else if (HashDriverKernelModeName <> '') then cellContents := prettyHashName + SDUCRLF + hashText else if (CypherDriverKernelModeName <> '') then cellContents := prettyCypherName + SDUCRLF + cypherText else summaryLine := _('Error! Please report seeing this!'); // -1 because we index from zero sgCombinations.Cells[0, (sgCombinations.RowCount - 1)] := cellContents; EnableDisableControls(); end; procedure TfrmSelectHashCypher.miHashDetailsClick(Sender: TObject); begin FreeOTFEObj.ShowHashDetailsDlg( SelectedHashDriverKernelModeName(), SelectedHashGUID() ); end; procedure TfrmSelectHashCypher.miCypherDetailsClick(Sender: TObject); begin FreeOTFEObj.ShowCypherDetailsDlg( SelectedCypherDriverKernelModeName(), SelectedCypherGUID() ); end; procedure TfrmSelectHashCypher.EnableDisableControls(); var rowSelected: Boolean; begin rowSelected := (sgCombinations.Row >= 0); miHashDetails.Enabled := rowSelected; miCypherDetails.Enabled := rowSelected; pbOK.Enabled := rowSelected; end; function TfrmSelectHashCypher.SelectedHashDriverKernelModeName(): String; begin Result := HashDriverKernelModeNames[sgCombinations.Row]; end; function TfrmSelectHashCypher.SelectedHashGUID(): TGUID; begin Result := StringToGUID(HashGUIDs[sgCombinations.Row]); end; function TfrmSelectHashCypher.SelectedCypherDriverKernelModeName(): String; begin Result := CypherDriverKernelModeNames[sgCombinations.Row]; end; function TfrmSelectHashCypher.SelectedCypherGUID(): TGUID; begin Result := StringToGUID(CypherGUIDs[sgCombinations.Row]); end; procedure TfrmSelectHashCypher.FormShow(Sender: TObject); begin EnableDisableControls(); end; procedure TfrmSelectHashCypher.sgCombinationsClick(Sender: TObject); begin EnableDisableControls(); end; // This taken from news posting by "Peter Below (TeamB)" <100113.1...@compuXXserve.com> // Code tidied up a little to reflect different style procedure TfrmSelectHashCypher.sgCombinationsDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); var S: String; drawrect: trect; begin S := (Sender as TStringgrid).Cells[ACol, ARow]; if (Length(S) > 0) then begin drawrect := Rect; DrawText( TStringGrid(Sender).canvas.handle, PChar(S), Length(S), drawrect, (dt_calcrect or dt_wordbreak or dt_left) ); if ((drawrect.bottom - drawrect.top) > TStringGrid(Sender).RowHeights[ARow]) then begin TStringGrid(Sender).RowHeights[ARow] := (drawrect.bottom - drawrect.top); end else begin drawrect.Right := Rect.right; TStringGrid(Sender).canvas.fillrect(drawrect); DrawText( TStringGrid(Sender).canvas.handle, PChar(S), Length(S), drawrect, (dt_wordbreak or dt_left) ); end; end; end; procedure TfrmSelectHashCypher.FormDestroy(Sender: TObject); begin HashDriverKernelModeNames.Free(); HashGUIDs.Free(); CypherDriverKernelModeNames.Free(); CypherGUIDs.Free(); end; procedure TfrmSelectHashCypher.sgCombinationsDblClick(Sender: TObject); begin if (pbOK.Enabled) then begin pbOKClick(Sender); end; end; procedure TfrmSelectHashCypher.pbOKClick(Sender: TObject); begin ModalResult := mrOk; end; end.
unit Unit1; interface uses FMX.Forms, FMX.Edit, FMX.StdCtrls, System.Sensors.Components, FMX.Controls, System.Classes, FMX.Types, System.Sensors, {$IFDEF MSWINDOWS} Winapi.ShellAPI, Winapi.Windows; {$ENDIF MSWINDOWS} {$IFDEF POSIX} Posix.Stdlib; {$ENDIF POSIX} type TForm1 = class(TForm) LocationSensor1: TLocationSensor; Edit1: TEdit; Edit2: TEdit; Button1: TButton; Label1: TLabel; Label2: TLabel; AniIndicator1: TAniIndicator; Button2: TButton; procedure Button1Click(Sender: TObject); procedure LocationSensor1LocationChanged(Sender: TObject; const OldLocation, NewLocation: TLocationCoord2D); procedure Button2Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } fOpenURL: string; public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} uses System.SysUtils; procedure TForm1.Button1Click(Sender: TObject); begin AniIndicator1.Visible := True; AniIndicator1.Enabled := True; LocationSensor1.OnLocationChanged := LocationSensor1LocationChanged; LocationSensor1.Active := True; end; procedure TForm1.Button2Click(Sender: TObject); begin {$IFDEF MSWINDOWS} ShellExecute(0, 'OPEN', PChar(fOpenURL), '', '', SW_SHOWNORMAL); {$ENDIF MSWINDOWS} {$IFDEF POSIX} _system(PAnsiChar('open ' + AnsiString(fOpenURL))); {$ENDIF POSIX} end; procedure TForm1.FormCreate(Sender: TObject); begin System.SysUtils.FormatSettings.DecimalSeparator := '.'; end; procedure TForm1.LocationSensor1LocationChanged(Sender: TObject; const OldLocation, NewLocation: TLocationCoord2D); const GoogleMapsURL: String = 'https://maps.google.com/maps?q=%s,%s'; begin AniIndicator1.Enabled := False; AniIndicator1.Visible := False; Edit1.Text := FloatToStr(NewLocation.Latitude); Edit2.Text := FloatToStr(NewLocation.Longitude); fOpenURL := Format(GoogleMapsURL, [NewLocation.Latitude.ToString, NewLocation.Longitude.ToString]); end; end.
unit ufrmBarangCompetitor; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterBrowse, StdCtrls, ExtCtrls, ActnList, System.Actions, Math, uConn, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus, cxCurrencyEdit, ufraFooter4Button, cxButtons, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxPC; type TfrmBarangCompetitor = class(TfrmMasterBrowse) actlstBarangCompetitor: TActionList; actAddBarangKompetitor: TAction; actEditBarangKompetitor: TAction; actDeleteBarangKompetitor: TAction; actRefreshBarangKompetitor: TAction; pnlTop: TPanel; lbl2: TLabel; dtStart: TcxDateEdit; dtEnd: TcxDateEdit; lbl3: TLabel; lbl4: TLabel; edtProductCode: TEdit; pnlButtom: TPanel; lbl5: TLabel; lbl6: TLabel; Label1: TLabel; edtProductname: TEdit; edtSuplierName: TEdit; lbl7: TLabel; lbl8: TLabel; edtDisc1: TEdit; lbl9: TLabel; lbl10: TLabel; edtDisc3: TEdit; lbl11: TLabel; edtDisc2: TEdit; curedtPurchPrice: TcxCurrencyEdit; curedtNettoPrice: TcxCurrencyEdit; lbl13: TLabel; lbl16: TLabel; edtSatBuy: TEdit; edtSatNetto: TEdit; lbl17: TLabel; lbl18: TLabel; lbl19: TLabel; edtmarkUp: TEdit; CURedtSellingPrice: TcxCurrencyEdit; lbl1: TLabel; edtcompttCode: TEdit; lbl20: TLabel; lbl15: TLabel; cxGridViewColumn1: TcxGridDBColumn; cxGridViewColumn2: TcxGridDBColumn; cxGridViewColumn3: TcxGridDBColumn; cxGridViewColumn4: TcxGridDBColumn; cxGridViewColumn5: TcxGridDBColumn; btnShow: TcxButton; procedure FormShow(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure actAddExecute(Sender: TObject); procedure actDeleteBarangKompetitorExecute(Sender: TObject); procedure actEditExecute(Sender: TObject); procedure actRefreshExecute(Sender: TObject); procedure btnShowClick(Sender: TObject); procedure edt1Change(Sender: TObject); procedure cbpCompetitorCloseUp(Sender: TObject); procedure edtProductCodeChange(Sender: TObject); procedure edtcompttCodeChange(Sender: TObject); procedure cbpCompetitorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormCreate(Sender: TObject); procedure strgGridRowChanging(Sender: TObject; OldRow, NewRow: Integer; var Allow: Boolean); private { Private declarations } Competitor: TDataSet; dataCompetitorBrgDtl: TDataSet; dataOwnGoods: TDataSet; procedure LoadDropDownData(ACombo: TColumnComboBox; AColsOfData: Integer); procedure FindDataOnGrid(AText: String); procedure showOwnGoods(); procedure clearOwnGoods(); procedure setDialogBarang(); procedure setDialogBarang4ShowEdit(); public { Public declarations } end; var frmBarangCompetitor: TfrmBarangCompetitor; implementation uses uTSCommonDlg, ufrmDialogBarangCompetitor, ufrmSearchProduct, uConstanta; {$R *.dfm} procedure TfrmBarangCompetitor.FormShow(Sender: TObject); begin inherited; lblHeader.Caption:='COMPETITOR PRODUCT'; dtStart.Date := now; dtEnd.Date := now; actRefreshExecute(Self); end; procedure TfrmBarangCompetitor.FormDestroy(Sender: TObject); begin inherited; frmBarangCompetitor := nil; end; procedure TfrmBarangCompetitor.actAddExecute(Sender: TObject); begin inherited; // if ID <> 0 then begin setDialogBarang(); if frmDialogBarangCompetitor.IsProcessSuccessfull then begin actRefreshExecute(Self); CommonDlg.ShowConfirm(atAdd); end; frmDialogBarangCompetitor.Free end // if frmmain ;// else CommonDlg.ShowError(ER_UNIT_NOT_SPECIFIC); end; procedure TfrmBarangCompetitor.actDeleteBarangKompetitorExecute( Sender: TObject); begin { if not Assigned(BarangCompetitor) then BarangCompetitor := TBarangCompetitor.Create; if strgGrid.Cells[0,strgGrid.Row]='0' then Exit; if MasterNewUnit.ID <> 0 then begin if (CommonDlg.Confirm('Are you sure want to delete product competitor ("'+ strgGrid.Cells[1,strgGrid.row] +'")?') = mrYes) then begin if BarangCompetitor.DeleteBarangCompetitorDetil(StrToInt(strgGrid.Cells[7,strgGrid.Row])) then begin actRefreshBarangKompetitorExecute(Self); CommonDlg.ShowConfirm(atDelete); end; //end barangco end; //end commondlg end //end MasterNewUnit.ID else CommonDlg.ShowError(ER_UNIT_NOT_SPECIFIC); } end; procedure TfrmBarangCompetitor.actEditExecute(Sender: TObject); begin inherited; // if strgGrid.Cells[0,strgGrid.Row]='0' then Exit; // if MasterNewUnit.ID <> 0 then begin setDialogBarang4ShowEdit(); if frmDialogBarangCompetitor.IsProcessSuccessfull then begin actRefreshExecute(Self); CommonDlg.ShowConfirm(atEdit); end; frmDialogBarangCompetitor.Free end // if frmmain ;// else CommonDlg.ShowError(ER_UNIT_NOT_SPECIFIC); end; procedure TfrmBarangCompetitor.actRefreshExecute(Sender: TObject); var tempBool: Boolean; begin inherited; { if not Assigned(DaftarCompetitor) then DaftarCompetitor := TDaftarCompetitor.Create; Competitor := DaftarCompetitor.GetDataCompetitor(MasterNewUnit.ID); LoadDropDownData(cbpCompetitor,Competitor.RecordCount); cbpCompetitor.Value := cbpCompetitor.Cells[1,1]; edtcompttCode.Text := cbpCompetitor.Cells[2,cbpCompetitor.Row]; } btnShowClick(Self); tempBool:= True; strgGridRowChanging(Self,1,1,tempBool); end; procedure TfrmBarangCompetitor.btnShowClick(Sender: TObject); var i: integer; tempBool: Boolean; begin {dataCompetitorBrgDtl := BarangCompetitor.GetBarangCompetitor (MasterNewUnit.ID, StrToInt(cbpCompetitor.Cells[0,cbpCompetitor.Row]), dtStart.Date, dtEnd.Date,edtProductCode.Text); with strgGrid do begin Clear; RowCount := dataCompetitorBrgDtl.RecordCount + 1; ColCount := 5; strgGrid.Cells[0,0] := 'No.'; strgGrid.Cells[1,0] := 'Code'; strgGrid.Cells[2,0] := 'Convertion'; strgGrid.Cells[3,0] := 'Selling Price'; strgGrid.Cells[4,0] := 'UOM'; if dataCompetitorBrgDtl.RecordCount > 0 then begin for i:=1 to dataCompetitorBrgDtl.RecordCount do begin Cells[0,i] := inttostr(i); Cells[1,i] := dataCompetitorBrgDtl.FieldByName('CODE').AsString; Cells[2,i] := dataCompetitorBrgDtl.FieldByName('CONVERS').AsString; Cells[3,i] := dataCompetitorBrgDtl.FieldByName('HARGA_JUAL').AsString; Alignments[3,i] := taRightJustify; Cells[4,i] := dataCompetitorBrgDtl.FieldByName('SATUAN').AsString; Cells[5,i] := dataCompetitorBrgDtl.FieldByName('NAME').AsString; Cells[6,i] := dataCompetitorBrgDtl.FieldByName('HARGA_JUAL').AsString; Cells[7,i] := dataCompetitorBrgDtl.FieldByName('KBD_ID').AsString; dataCompetitorBrgDtl.Next; end;//for end else begin RowCount := 2; Cells[0,1] := '0'; strgGrid.Cells[5,1] := '----'; end; FixedRows := 1; AutoSize := true; end; tempBool:= True; strgGridRowChanging(Self,1,1,tempBool); } end; procedure TfrmBarangCompetitor.edt1Change(Sender: TObject); begin end; //================ R ====================== procedure TfrmBarangCompetitor.LoadDropDownData(ACombo: TColumnComboBox; AColsOfData: Integer); begin {Flush the old data} // ACombo.ClearGridData; {Make sure the allocated storage is big enough} // ACombo.RowCount := AColsOfData+1; // ACombo.ColCount := 3; {Load the data} // ACombo.AddRow(['0',' NAME ',' CODE ']); // Competitor := DaftarCompetitor.GetDataCompetitor(MasterNewUnit.ID); if Competitor <> nil then begin while not Competitor.Eof do begin try // ACombo.AddRow([Competitor.FieldByName('KOMPT_ID').AsString, // Competitor.FieldByName('KOMPT_NAME').AsString, // Competitor.FieldByName('KOMPT_CODE').AsString]); except end; Competitor.Next; end;// end while end;// if comptt {Now shring the grid so its just big enough for the data} // cbpCompetitor.FixedRows := 1; // ACombo.SizeGridToData; //trik to activate acombo // ACombo.Value := ACombo.Cells[0,0]; // ACombo.LookupActive := False; end; procedure TfrmBarangCompetitor.FindDataOnGrid(AText: String); var resPoint: TPoint; begin if (AText <> '') then begin { resPoint := strgGrid.Find(Point(0,0),AText,[fnIncludeFixed]); if (resPoint.Y <> -1) then begin strgGrid.ScrollInView(resPoint.X, resPoint.Y); strgGrid.SelectRows(resPoint.Y, 1); end; } end; end; procedure TfrmBarangCompetitor.cbpCompetitorCloseUp(Sender: TObject); begin inherited; // edtcompttCode.Text := cbpCompetitor.Cells[2,cbpCompetitor.Row]; end; procedure TfrmBarangCompetitor.edtProductCodeChange(Sender: TObject); var tempBool: Boolean; begin inherited; FindDataOnGrid(edtProductCode.Text); // strgGridRowChanging(Self,0,strgGrid.Row,tempBool); end; procedure TfrmBarangCompetitor.edtcompttCodeChange(Sender: TObject); var dataSearchCodeKomptt: TDataSet; begin inherited; // dataSearchCodeKomptt := DaftarCompetitor.SearchCompetitorByCode(edtcompttCode.Text); // if dataSearchCodeKomptt.RecordCount > 0 then // cbpCompetitor.Value := dataSearchCodeKomptt.FieldByName('KOMPT_NAME').AsString; end; procedure TfrmBarangCompetitor.showOwnGoods(); begin edtSuplierName.Text := dataOwnGoods.FieldByName('SUP_NAME').AsString; edtDisc1.Text := dataOwnGoods.FieldByName('BRGSUP_DISC1').AsString; edtDisc2.Text := dataOwnGoods.FieldByName('BRGSUP_DISC2').AsString; edtDisc3.Text := dataOwnGoods.FieldByName('BRGSUP_DISC3').AsString; curedtPurchPrice.Value := dataOwnGoods.FieldByName('BRGSUP_BUY_PRICE').AsCurrency; edtSatBuy.Text := dataOwnGoods.FieldByName('BRGSUP_SAT_CODE_BUY').AsString; curedtNettoPrice.Value := dataOwnGoods.FieldByName('BRGSUP_BUY_PRICE_DISC').AsCurrency; edtSatNetto.Text := dataOwnGoods.FieldByName('BRGSUP_SAT_CODE_BUY').AsString; edtmarkUp.Text := dataOwnGoods.FieldByName('BHJ_MARK_UP').AsString; CURedtSellingPrice.Value := dataOwnGoods.FieldByName('BHJ_SELL_PRICE_DISC').AsCurrency; end; procedure TfrmBarangCompetitor.clearOwnGoods(); begin edtSuplierName.Text := ''; edtDisc1.Text := ''; edtDisc2.Text := ''; edtDisc3.Text := ''; curedtPurchPrice.Value := 0; edtSatBuy.Text := ''; curedtNettoPrice.Value := 0; edtSatNetto.Text := ''; edtmarkUp.Text := ''; CURedtSellingPrice.Value := 0; end; procedure TfrmBarangCompetitor.setDialogBarang(); var searchUOM: TDataSet; arrParamUOM: TArr; begin if not Assigned(frmDialogBarangCompetitor) then Application.CreateForm(TfrmDialogBarangCompetitor, frmDialogBarangCompetitor); { if not Assigned(DaftarCompetitor) then DaftarCompetitor := TDaftarCompetitor.Create; Competitor := DaftarCompetitor.GetDataCompetitor(MasterNewUnit.ID); LoadDropDownData(frmDialogBarangCompetitor.cbpCompetitor,Competitor.RecordCount); frmDialogBarangCompetitor.edtcompttCode.Text := edtcompttCode.Text; frmDialogBarangCompetitor.edtcompttCodeChange(Self); SetLength(arrParamUOM,1); arrParamUOM[0].tipe := ptInteger; arrParamUOM[0].data := MasterNewUnit.ID; if not Assigned(Satuan) then Satuan := TSatuan.Create; frmDialogBarangCompetitor.cbbUOM.Clear; searchUOM := Satuan.GetListSatuan(arrParamUOM); if searchUOM.RecordCount > 0 then begin searchUOM.First; while not(searchUOM.Eof) do begin frmDialogBarangCompetitor.cbbUOM.AddItem(searchUOM.FieldByName('SAT_CODE').AsString,frmDialogBarangCompetitor.cbbUOM); searchUOM.Next; end; end; // if recordcount frmDialogBarangCompetitor.frmSuiMasterDialog.Caption := 'Add Competitor Product (Survey)'; frmDialogBarangCompetitor.FormMode := fmAdd; frmDialogBarangCompetitor.cbpCompetitorCloseUp(Self); frmDialogBarangCompetitor.dtSurvey.Date := Now; frmDialogBarangCompetitor.DialogUnit := MasterNewUnit.ID; frmDialogBarangCompetitor.FLoginId := FLoginId; frmDialogBarangCompetitor.countSave := 0; //reset count SetFormPropertyAndShowDialog(frmDialogBarangCompetitor); } end; procedure TfrmBarangCompetitor.setDialogBarang4ShowEdit(); var searchUOM: TDataSet; arrParamUOM: TArr; begin if not Assigned(frmDialogBarangCompetitor) then Application.CreateForm(TfrmDialogBarangCompetitor, frmDialogBarangCompetitor); { if not Assigned(DaftarCompetitor) then DaftarCompetitor := TDaftarCompetitor.Create; Competitor := DaftarCompetitor.GetDataCompetitor(MasterNewUnit.ID); LoadDropDownData(frmDialogBarangCompetitor.cbpCompetitor,Competitor.RecordCount); SetLength(arrParamUOM,1); arrParamUOM[0].tipe := ptInteger; arrParamUOM[0].data := MasterNewUnit.ID; if not Assigned(Satuan) then Satuan := TSatuan.Create; frmDialogBarangCompetitor.cbbUOM.Clear; searchUOM := Satuan.GetListSatuan(arrParamUOM); if searchUOM.RecordCount > 0 then begin searchUOM.First; while not(searchUOM.Eof) do begin frmDialogBarangCompetitor.cbbUOM.AddItem(searchUOM.FieldByName('SAT_CODE').AsString,frmDialogBarangCompetitor.cbbUOM); searchUOM.Next; end; end; // if recordcount frmDialogBarangCompetitor.frmSuiMasterDialog.Caption := 'Edit Competitor Product (Survey)'; frmDialogBarangCompetitor.FormMode := fmEdit; frmDialogBarangCompetitor.DialogUnit := MasterNewUnit.ID; frmDialogBarangCompetitor.FLoginId := FLoginId; frmDialogBarangCompetitor.KBD_ID := StrToInt(strgGrid.Cells[7,strgGrid.Row]); frmDialogBarangCompetitor.edtcompttCode.Text := edtcompttCode.Text; frmDialogBarangCompetitor.edtcompttCodeChange(Self); if not Assigned(BarangCompetitor) then BarangCompetitor := TBarangCompetitor.Create; frmDialogBarangCompetitor.dtSurvey.Date := BarangCompetitor.SearchTGLKompttBRGByID(StrToInt(cbpCompetitor.Cells[0,cbpCompetitor.Row])); frmDialogBarangCompetitor.edtProductCode.Text := strgGrid.Cells[1,strgGrid.Row]; frmDialogBarangCompetitor.edtProductCodeChange(Self); frmDialogBarangCompetitor.curedtSellPrice.Value := StrToCurr(strgGrid.Cells[6,strgGrid.Row]); frmDialogBarangCompetitor.fedtConvert.Value := StrToFloat(strgGrid.Cells[2,strgGrid.Row]); frmDialogBarangCompetitor.fedtConvertChange(Self); frmDialogBarangCompetitor.cbbUOM.Text := strgGrid.Cells[4,strgGrid.Row]; SetFormPropertyAndShowDialog(frmDialogBarangCompetitor); } end; procedure TfrmBarangCompetitor.cbpCompetitorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if(Key=VK_DELETE)and(ssctrl in Shift)then Key:= VK_NONAME; if(Key=Vk_ESCAPE) then actCloseExecute(Self); end; procedure TfrmBarangCompetitor.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if(Key = VK_F5) then begin if not assigned(frmDialogSearchProduct) then frmDialogSearchProduct := TfrmDialogSearchProduct.Create(Application); frmDialogSearchProduct.Modul := mNone; SetFormPropertyAndShowDialog(frmDialogSearchProduct); if frmDialogSearchProduct.IsProcessSuccessfull = True then edtProductCode.Text := frmDialogSearchProduct.ProductCode; frmDialogSearchProduct.Free; end; if(Key = 13) then btnShowClick(Self); end; procedure TfrmBarangCompetitor.FormCreate(Sender: TObject); begin inherited; KeyPreview := True; end; procedure TfrmBarangCompetitor.strgGridRowChanging(Sender: TObject; OldRow, NewRow: Integer; var Allow: Boolean); begin inherited; {edtProductname.Text := strgGrid.Cells[5,NewRow]; if strgGrid.Cells[0,NewRow] <> '0' then begin dataOwnGoods := BarangCompetitor.SearchOwnGoods(strgGrid.Cells[1,NewRow]); if dataOwnGoods.RecordCount > 0 then begin showOwnGoods(); end else clearOwnGoods(); end else clearOwnGoods(); } end; end.
unit uPortableClasses; interface uses Generics.Collections, System.Classes, System.SyncObjs, VCL.Graphics, uMemory; const DEFAULT_PORTABLE_DEVICE_NAME = 'Unknown Device'; EMPTY_PATH = '?\\NULL'; type TDeviceType = (dtCamera, dtVideo, dtPhone, dtOther); TPortableItemType = (piStorage, piDirectory, piImage, piVideo, piFile); TPortableEventType = (peDeviceConnected, peDeviceDisconnected, peItemAdded, peItemRemoved); TPortableEventTypes = set of TPortableEventType; IPDItem = interface; IPDevice = interface; TFillItemsCallBack = procedure(ParentKey: string; Packet: TList<IPDItem>; var Cancel: Boolean; Context: Pointer) of object; TFillDevicesCallBack = procedure(Packet: TList<IPDevice>; var Cancel: Boolean; Context: Pointer) of object; TPortableEventCallBack = procedure(EventType: TPortableEventType; DeviceID: string; ItemKey: string; ItemPath: string) of object; IPBaseInterface = interface function GetErrorCode: HRESULT; property ErrorCode: HRESULT read GetErrorCode; end; TPDProgressCallBack = procedure(Sender: TObject; BytesTotal, BytesDone: Int64; var Break: Boolean) of object; IPDItem = interface(IPBaseInterface) function GetItemType: TPortableItemType; function GetName: string; function GetItemKey: string; function GetFullSize: Int64; function GetFreeSize: Int64; function GetItemDate: TDateTime; function GetDeviceID: string; function GetDeviceName: string; function GetIsVisible: Boolean; function GetWidth: Integer; function GetHeight: Integer; function ExtractPreview(var PreviewImage: TBitmap): Boolean; function SaveToStream(S: TStream): Boolean; function SaveToStreamEx(S: TStream; CallBack: TPDProgressCallBack): Boolean; function GetInnerInterface: IUnknown; function Clone: IPDItem; property ItemType: TPortableItemType read GetItemType; property Name: string read GetName; property ItemKey: string read GetItemKey; property FullSize: Int64 read GetFullSize; property FreeSize: Int64 read GetFreeSize; property ItemDate: TDateTime read GetItemDate; property DeviceID: string read GetDeviceID; property DeviceName: string read GetDeviceName; property IsVisible: Boolean read GetIsVisible; property InnerInterface: IUnknown read GetInnerInterface; property Width: Integer read GetWidth; property Height: Integer read GetHeight; end; IPDevice = interface(IPBaseInterface) function GetName: string; function GetDeviceID: string; function GetBatteryStatus: Byte; function GetDeviceType: TDeviceType; procedure FillItems(ItemKey: string; Items: TList<IPDItem>); procedure FillItemsWithCallBack(ItemKey: string; CallBack: TFillItemsCallBack; Context: Pointer); function GetItemByKey(ItemKey: string): IPDItem; function GetItemByPath(Path: string): IPDItem; function Delete(ItemKey: string): Boolean; property Name: string read GetName; property DeviceID: string read GetDeviceID; property BatteryStatus: Byte read GetBatteryStatus; property DeviceType: TDeviceType read GetDeviceType; end; IPManager = interface(IPBaseInterface) procedure FillDevices(Devices: TList<IPDevice>); procedure FillDevicesWithCallBack(CallBack: TFillDevicesCallBack; Context: Pointer); function GetDeviceByName(DeviceName: string): IPDevice; function GetDeviceByID(DeviceID: string): IPDevice; end; IPEventManager = interface procedure RegisterNotification(EventTypes: TPortableEventTypes; CallBack: TPortableEventCallBack); procedure UnregisterNotification(CallBack: TPortableEventCallBack); end; TPortableItemName = class(TObject) private FDevID: string; FItemKey: string; FParentItemKey: string; FPath: string; public constructor Create(ADevID: string; AItemKey: string; AParentItemKey: string; APath: string); property DevID: string read FDevID; property ItemKey: string read FItemKey; property ParentItemKey: string read FParentItemKey; property Path: string read FPath; end; /////////////////////////////////////// /// /// Connection between path's and item keys (WIA/WPD) /// /////////////////////////////////////// TPortableItemNameCache = class(TObject) private FSync: TCriticalSection; FItems: TList<TPortableItemName>; public constructor Create; destructor Destroy; override; procedure ClearDeviceCache(DevID: string); function GetPathByKey(DevID: string; ItemKey: string): string; function GetParentKey(DevID: string; ItemKey: string): string; function GetKeyByPath(DevID: string; Path: string): string; procedure AddName(DevID: string; ItemKey, ParentKey: string; Path: string); end; function PortableItemNameCache: TPortableItemNameCache; implementation var FPortableItemNameCache: TPortableItemNameCache = nil; function PortableItemNameCache: TPortableItemNameCache; begin if FPortableItemNameCache = nil then FPortableItemNameCache := TPortableItemNameCache.Create; Result := FPortableItemNameCache end; { TPortableItemCache } procedure TPortableItemNameCache.AddName(DevID, ItemKey, ParentKey, Path: string); var Item: TPortableItemName; begin FSync.Enter; try for Item in FItems do if (Item.DevID = DevID) and (Item.ItemKey = ItemKey) then begin Item.FPath := Path; Exit; end; Item := TPortableItemName.Create(DevID, ItemKey, ParentKey, Path); FItems.Add(Item); finally FSync.Leave; end; end; procedure TPortableItemNameCache.ClearDeviceCache(DevID: string); var I: Integer; begin FSync.Enter; try for I := FItems.Count - 1 downto 0 do if FItems[I].FDevID = DevID then FItems.Delete(I); finally FSync.Leave; end; end; constructor TPortableItemNameCache.Create; begin FSync := TCriticalSection.Create; FItems := TList<TPortableItemName>.Create; end; destructor TPortableItemNameCache.Destroy; begin F(FSync); FreeList(FItems); inherited; end; function TPortableItemNameCache.GetKeyByPath(DevID, Path: string): string; var I: Integer; begin Result := EMPTY_PATH; FSync.Enter; try for I := FItems.Count - 1 downto 0 do if (FItems[I].FDevID = DevID) and (FItems[I].Path = Path) then Result := FItems[I].ItemKey; finally FSync.Leave; end; end; function TPortableItemNameCache.GetParentKey(DevID, ItemKey: string): string; var I: Integer; begin Result := ''; FSync.Enter; try for I := FItems.Count - 1 downto 0 do if (FItems[I].FDevID = DevID) and (FItems[I].ItemKey = ItemKey) then Result := FItems[I].ParentItemKey; finally FSync.Leave; end; end; function TPortableItemNameCache.GetPathByKey(DevID, ItemKey: string): string; var I: Integer; begin Result := ''; FSync.Enter; try for I := FItems.Count - 1 downto 0 do if (FItems[I].FDevID = DevID) and (FItems[I].ItemKey = ItemKey) then Result := FItems[I].Path; finally FSync.Leave; end; end; { TPortableItemName } constructor TPortableItemName.Create(ADevID, AItemKey, AParentItemKey, APath: string); begin FDevID := ADevID; FItemKey := AItemKey; FParentItemKey := AParentItemKey; FPath := APath; end; initialization finalization F(FPortableItemNameCache); end.
unit uFrmLanguage; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, System.StrUtils, System.Win.Registry, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Imaging.pngimage, Dmitry.Utils.System, uDBForm, uInstallUtils, uMemory, uConstants, uInstallTypes, uTranslate, uLogger, uInstallZip, uLangUtils, uInstallRuntime, uRuntime; type TLanguageItem = class(TObject) public Name: string; Code: string; Image: TPngImage; LangCode: Integer; constructor Create; destructor Destroy; override; end; TFormLanguage = class(TDBForm) LbLanguages: TListBox; BtnOk: TButton; LbInfo: TLabel; lbVersion: TLabel; procedure LbLanguagesClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure LbLanguagesDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure LbLanguagesMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure BtnOkClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormDestroy(Sender: TObject); procedure LbLanguagesDblClick(Sender: TObject); private { Private declarations } procedure LoadLanguage; procedure LoadLanguageList; protected { Protected declarations } function GetFormID : string; override; public { Public declarations } end; var FormLanguage: TFormLanguage; implementation {$R *.dfm} procedure LoadLanguageFromSetupData(var Language : TLanguage; var LanguageCode : string); var LanguageFileName : string; MS : TMemoryStream; begin if LanguageCode = '--' then LanguageCode := 'EN'; LanguageFileName := Format('%s%s.xml', [LanguageFileMask, LanguageCode]); try MS := TMemoryStream.Create; try GetRCDATAResourceStream(SetupDataName, MS); Language := TLanguage.CreateFromXML(ReadFileContent(MS, LanguageFileName)); finally F(MS); end; except on e : Exception do EventLog(e.Message); end; end; { TFormLanguage } procedure TFormLanguage.BtnOkClick(Sender: TObject); begin LbLanguagesClick(Sender); ModalResult := idOk; Hide; end; procedure TFormLanguage.FormCreate(Sender: TObject); begin LanguageInitCallBack := LoadLanguageFromSetupData; LoadLanguageList; LoadLanguage; ActivateBackgroundApplication(Handle); end; procedure TFormLanguage.FormDestroy(Sender: TObject); var I : Integer; begin for I := 0 to LbLanguages.Count - 1 do LbLanguages.Items.Objects[I].Free; end; procedure TFormLanguage.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then BtnOkClick(Sender); if Key = VK_ESCAPE then Close; end; function TFormLanguage.GetFormID: string; begin Result := 'InstallLanguage'; end; procedure TFormLanguage.LbLanguagesClick(Sender: TObject); var I : Integer; SelectedIndex : Integer; begin SelectedIndex := -1; for I := 0 to LbLanguages.Count - 1 do if LbLanguages.Selected[I] then SelectedIndex := I; if (SelectedIndex > -1) then begin TTranslateManager.Instance.Language := TLanguageItem(LbLanguages.Items.Objects[SelectedIndex]).Code; LoadLanguage; end; LbLanguages.Refresh; end; procedure TFormLanguage.LbLanguagesDblClick(Sender: TObject); var Pos : TPoint; Index : Integer; begin GetCursorPos(Pos); Pos := LbLanguages.ScreenToClient(Pos); Index := LbLanguages.ItemAtPos(Pos, True); if (Index > -1) and (Index < LbLanguages.Count) then BtnOkClick(Sender); end; procedure TFormLanguage.LbLanguagesDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var Language : TLanguageItem; Bitmap : TBitmap; PngBitmap : TBitmap; BackColor : TColor; begin if Index < 0 then Exit; Language := TLanguageItem(LbLanguages.Items.Objects[Index]); Bitmap := TBitmap.Create; Bitmap.PixelFormat := pf24Bit; try Bitmap.Width := Rect.Right - Rect.Left; Bitmap.Height := Rect.Bottom - Rect.Top; if LbLanguages.Selected[Index] then BackColor := clHighlight else BackColor := clWindow; Bitmap.Canvas.Pen.Color := BackColor; Bitmap.Canvas.Brush.Color := BackColor; Bitmap.Canvas.Rectangle(0, 0, Bitmap.Width, Bitmap.Height); if LbLanguages.Selected[Index] then Bitmap.Canvas.Font.Color := clHighlightText else Bitmap.Canvas.Font.Color := clWindowText; Bitmap.Canvas.TextOut(Language.Image.Width + 6, Bitmap.Height div 2 - Bitmap.Canvas.TextHeight(Language.Name) div 2, Language.Name); PngBitmap := TBitmap.Create; try PngBitmap.PixelFormat := pf24bit; Language.Image.Draw(Bitmap.Canvas, System.Classes.Rect(2, 2, 2 + Language.Image.Width, 2 + Language.Image.Height)); finally F(PngBitmap); end; LbLanguages.Canvas.Draw(Rect.Left, Rect.Top, Bitmap); finally F(Bitmap); end; end; procedure TFormLanguage.LbLanguagesMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin LbLanguages.Refresh; end; procedure TFormLanguage.LoadLanguage; begin BeginTranslate; try Caption := L('Select language'); BtnOk.Caption := L('Ok'); LbInfo.Caption := L('Please, select language of PhotoDB install') + ':'; finally EndTranslate; end; end; procedure TFormLanguage.LoadLanguageList; var MS: TMemoryStream; FileList: TStrings; Size: Int64; I: Integer; LangCode: Integer; Language: TLanguage; LangItem: TLanguageItem; ImageStream: TMemoryStream; PNG: TPNGImage; Reg: TRegistry; CurentLanguage: string; begin CurentLanguage := ''; if IsApplicationInstalled then begin Reg := TRegistry.Create(KEY_READ); try Reg.RootKey := HKEY_LOCAL_MACHINE; Reg.OpenKey(RegRoot, False); CurentLanguage := Reg.ReadString('Language'); finally F(Reg); end; end; LbLanguages.Clear; MS := TMemoryStream.Create; try GetRCDATAResourceStream(SetupDataName, MS); ProgramVersionString := ReadFileContent(MS, 'VERSION.INFO'); InstallVersion := StringToRelease(ProgramVersionString); lbVersion.Caption := ReleaseToString(InstallVersion); FileList := TStringList.Create; try FillFileList(MS, FileList, Size); //try to find language xml files for I := 0 to FileList.Count - 1 do begin if StartsStr(LanguageFileMask, FileList[I]) and EndsStr('.xml', FileList[I]) then begin Language := TLanguage.CreateFromXML(ReadFileContent(MS, FileList[I])); try ImageStream := TMemoryStream.Create; try LangItem := TLanguageItem.Create; ExtractStreamFromStorage(MS, ImageStream, Language.ImageName, nil); PNG := TPNGImage.Create; try ImageStream.Seek(0, soFromBeginning); PNG.LoadFromStream(ImageStream); LangItem.Image := PNG; PNG := nil; finally F(PNG); end; LangItem.Name := Language.Name; LangItem.Code := StringReplace(StringReplace(FileList[I], LanguageFileMask, '', []), ExtractFileExt(FileList[I]), '', []); LangItem.LangCode := Language.LangCode; LbLanguages.Items.AddObject(Language.Name, LangItem); finally F(ImageStream); end; finally F(Language); end; end; end; finally F(FileList); end; finally F(MS); end; LbLanguages.Selected[0] := True; if CurentLanguage = '' then begin LangCode := PrimaryLangID(GetUserDefaultUILanguage); for I := 0 to LbLanguages.Items.Count - 1 do if TLanguageItem(LbLanguages.Items.Objects[I]).LangCode = LangCode then begin LbLanguages.Selected[I] := True; LbLanguagesClick(Self); end; end else begin for I := 0 to LbLanguages.Items.Count - 1 do if AnsiLowerCase(TLanguageItem(LbLanguages.Items.Objects[I]).Code) = AnsiLowerCase(CurentLanguage) then begin LbLanguages.Selected[I] := True; LbLanguagesClick(Self); end; end; LoadLanguage; end; { TLangageItem } constructor TLanguageItem.Create; begin Image := nil; end; destructor TLanguageItem.Destroy; begin F(Image); inherited; end; end.
{$I-,Q-,R-,S-} {Problema 12: Ensamblaje DNA [Competencia Woburn, 2005] El Granjero Juan ha encontrado la secuencia DNA de su vaca productora de leche campeona, las secuencias DNA de Bessie son listas ordenadas (cadenas) conteniendo las letras 'A', 'C', 'G', y 'T'. Como es usual para secuencias DNA, los resultados son un conjunto de cadenas que son fragmentos secuenciados de DNA, no cadenas enteras DNA. Un par de cadenas como 'GATTA' y 'TACA' lo más posible es que representen la cadena 'GATTACA' en tanto que los caracteres que se superponen son mezclados, desde que ellos fueron posiblemente duplicados en el proceso de secuenciación. Mezclar un par de cadenas requiere encontrar la mayor superposici˛n entre las dos y luego eliminarla en tanto las dos cadenas se concatenan. Las superposiciones son entre el final de una cadena y el comienzo de otra cadena, NUNCA EN EL MEDIO DE UNA CADENA. Por ejemplo, las cadenas 'GATTACA' and 'TTACA' se suporponen completamente. Por otra parte las cadenas 'GATTACA' y 'TTA' no tienen ninguna superposición, desde que los caracteres coincidentes aparecen en la mitad de la otra cadena, no al comienzo de la otra. Aquí hay algunos ejemplos de mezclar cadenas, incluyendo aquellas sin superposición: GATTA + TACA -> GATTACA TACA + GATTA -> TACAGATTA TACA + ACA -> TACA TAC + TACA -> TACA ATAC + TACA -> ATACA TACA + ACAT -> TACAT Dado un conjunto de N (2 <= N <= 7) secuencias DNA todas las cuales tienen longitudes en el rango 1..7, encuentre e imprima la secuecia más corta posible obtenible mezclando repetidamente todas las N cadenas usando el procedimiento antes descrito. Todas las cadenas deben ser mezcladas en la secuencia resultante para la secuencia resultante. NOMBRE DEL PROBLEMA: dna FORMATO DE ENTRADA: * Línea 1: Un solo entero N * Líneas 2..N+1: Cada línea contiene una sola subsecuencia DNA ENTRADA EJEMPLO (archivo dna.in): 4 GATTA TAGG ATCGA CGCAT FORMATO DE SALIDA: * Línea 1: La longitud de la cadena más corta posible obtenida mezclando las subsecuencias. Es siempre posible - y requerido - mezclar todas las cadenas de la entrada para obtener esta cadena. SALIDA EJEMPLO (archivo dna.out): 13 DETALLES DE LA SALIDA: Tal cadena es "CGCATCGATTAGG". } var fe,fs : text; n,m,sol : longint; tab : array[1..8] of string; mk : array[1..8] of boolean; procedure open; var i : longint; begin assign(fe,'dna.in'); reset(fe); assign(fs,'dna.out'); rewrite(fs); readln(fe,n); for i:=1 to n do readln(fe,tab[i]); close(fe); end; function conc(x,y : string) : string; var i,j,k,t : longint; s1,s2 : string; ok : boolean; begin j:=1; s1:=''; for i:=length(x)-length(y) + 1 to length(x) do begin if x[i] = y[1] then begin t:=j+1; ok:=true; for k:=i+1 to length(x) do if x[k] <> y[t] then begin ok:=false; break; end else inc(t); if ok then begin for k:=1 to i do s1:=s1 + x[k]; for k:=j+1 to length(y) do s1:=s1 + y[k]; conc:=s1; exit; end; end; end; conc:=x+y; end; procedure comb(x,y : longint; st : string); var i : longint; s : string; begin if y = n then begin if x < sol then sol:=x; end else for i:=1 to n do if not mk[i] then begin mk[i]:=true; s:=conc(st,tab[i]); comb(length(s),y+1,s); mk[i]:=false; end; end; procedure work; var i : longint; begin sol:=maxlongint; for i:=1 to n do begin fillchar(mk,sizeof(mk),false); mk[i]:=true; comb(length(tab[i]),1,tab[i]); end; writeln(fs,sol); close(fs); end; begin open; work; end.
unit UntMainMenu; interface uses Forms, Classes, Dialogs, Controls, StdCtrls, UntRestClient; type TMainForm = class(TForm) btnLogin: TButton; btnObterEscritorio: TButton; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnLoginClick(Sender: TObject); procedure btnObterEscritorioClick(Sender: TObject); private FRestClient: TRestClient; end; var MainForm: TMainForm; implementation {$R *.dfm} procedure TMainForm.FormCreate(Sender: TObject); begin FRestClient := TRestClient.Create; FRestClient.Username := 'admin@intsys.com.br'; FRestClient.Password := 'qkpm@1106'; FRestClient.Host := 'http://localhost:60610/api'; FRestClient.SigInPath := 'security/token'; end; procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction); begin FRestClient.Free; end; procedure TMainForm.btnLoginClick(Sender: TObject); begin if FRestClient.SigIn then begin showMessage('Login efetuado com sucesso!'); end else begin showMessage('Usuário e senha inválida!'); end; end; procedure TMainForm.btnObterEscritorioClick(Sender: TObject); var params: TStringList; begin if not FRestClient.IsLogged then begin ShowMessage('Precisa efetuar login primeiro!'); exit; end; params := TStringList.Create; try params.Values['cpfcnpj'] := '00000000000000'; FRestClient.Get('escritorios') finally params.Free; end; end; end.
unit CouponCls; interface uses contnrs, SysUtils; type TCoupon = class private FIdPromo: integer; // = IdDiscont FIdPreinventory: integer; FIdModel: integer; FRewardAmount: double; FAmountType: string; FIsFree: boolean; FCashierShouldWarn: boolean; FNeedsPhysicalCoupon: boolean; FCouponCode: string; FDocumentId: integer; FSellingPrice: double; public constructor create(); destructor destroy(); override; property IdPromo: integer read FIdPromo write FIdPromo; property IdPreInventory: integer read FIdPreinventory write FIdPreinventory; property IdModel: integer read FIdModel write FIdModel; property RewardAmount: double read FRewardAmount write FRewardAmount; property AmountType: string read FAmountType write FAmountType; property CashierShouldWarn: boolean read FCashierShouldWarn write FCashierShouldWarn; property NeedsPhysicalCoupon: boolean read FNeedsPhysicalCoupon write FNeedsPhysicalCoupon; property CouponCode: string read FCouponCode write FCouponCode; property DocumentId: integer read FDocumentId write FDocumentId; property SellingPrice: double read FSellingPrice write FSellingPrice; end; implementation { TCoupon } constructor TCoupon.create; begin // end; destructor TCoupon.destroy; begin inherited; end; end.
unit SDL2_SimpleGUI_Element; {:< The Element Class Unit and its supporting types } { Simple GUI is a generic SDL2/Pascal GUI library by Matthias J. Molski, get more infos here: https://github.com/Free-Pascal-meets-SDL-Website/SimpleGUI. It is based upon LK GUI by Lachlan Kingsford for SDL 1.2/Free Pascal, get it here: https://sourceforge.net/projects/lkgui. Written permission to re-license the library has been granted to me by the original author. Copyright (c) 2016-2020 Matthias J. Molski 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. } interface uses Classes, SysUtils, SDL2, SDL2_SimpleGUI_Base; type TGUI_Element = class; // forward declaration { TGUI_Element_LL } {: Linked list of GUI Elements - used to store the list of children in TGUI_Element } TGUI_Element_LL = class public Next: TGUI_Element_LL; Prev: TGUI_Element_LL; Data: TGUI_Element; {: Check for last element. If the next element to the current element is not nil, check the next element with last-function. If the next element is nil, the current element is last (last element found). } function Last: TGUI_Element_LL; {: A new GUI element LL is added as "last". The former "last" is the new previous element ("NewPrev"). } procedure AddItem(InData: TGUI_Element); procedure PushToLast; constructor Create; destructor Destroy; override; procedure Dump; //< For Debugging end; {: Basic GUI element from which others are derived } TGUI_Element = class public {: Renders controls to rendering target - but is really designed to _not_ be overwritten by children - controls should render themselves in 'Render' The Render is done in the order of the ElementLL with the last item in the LL being the last item rendered (ie - on top) It renders all children contained in the linked list (GUI_Element_LL) of ONE specific gui element (GUI_Element). The PGUI_Element data is stored in the field "data" for each element of the linked list. ATTENTION: The child gui element may also contain some own children (likely) which also will be rendered. Since the calling gui element is master, ALL children in existence are drawn. } procedure Paint; virtual; {: Renders GUI element to rendering target. Should be overwritten by actual GUI element class. } procedure Render; virtual; {: Constructor - empty for basic GUI element. } constructor Create; {: Destructor is recursive - it will call its children. } destructor Destroy; override; {: Adds a child element The child GUI_Element is added to the children field of calling GUI_Element. The child's parent is set to calling GUI_Element. } procedure AddChild(Child: TGUI_Element); virtual; {: Sets the parent of the element } procedure SetParent(NewParent: TGUI_Element); virtual; {: Returns the parent of the element } function GetParent: TGUI_Element; {: Get the SDL2 window that the control is associated with } function GetWindow: PSDL_Window; {: SDL2: Get the renderer that the control is associated with } function GetRenderer: PSDL_Renderer; //Accessors for the generic properties { TODO : introduce _real_ properties } procedure SetWidth(NewWidth: Word); virtual; function GetWidth: Word; virtual; procedure SetHeight(NewHeight: Word); virtual; function GetHeight: Word; virtual; procedure SetLeft(NewLeft: Word); virtual; function GetLeft: Word; virtual; procedure SetTop(NewTop: Word); virtual; function GetTop: Word; virtual; procedure SetLL(NewLL: TGUI_Element_LL); function GetLL: TGUI_Element_LL; procedure SetEnabled(NewEnabled: Boolean); virtual; function GetEnabled: Boolean; virtual; // Push to front and change to look selected if necessary { TODO : introduce _real_ properties } procedure SetSelected(NewState: Boolean); virtual; function GetSelected: Boolean; procedure UnselectChildren; virtual; procedure SetSelectable(NewState: Boolean); function GetSelectable: Boolean; function GetChildren: TGUI_Element_LL; // Gets absolute coordinates of control recursively { TODO : introduce _real_ properties } function GetAbsLeft: Word; virtual; function GetAbsTop: Word; virtual; //Whether or not the control sends the 'normal' events to itself //when it passes them to children too. By default false procedure SetRecieveAllEvents(NewState: Boolean); function GetRecieveAllEvents: Boolean; procedure SetVisible(NewVisible: Boolean); virtual; function GetVisible: Boolean; virtual; {: Called when size of a parent changes in case control needs to make adjustments of its own. } procedure ParentSizeCallback(NewW, NewH: Word); virtual; {: SendSizeCallback is called when those messages need to be sent by this control } procedure SendSizeCallback(NewW, NewH: Word); {: This callback routine is executed once after a child got added to its parent. This allows childs to react to their addition, e.g. the Image element can render texture after the parents Renderer is known to it. } procedure ChildAddedCallback; virtual; {: Returns true if MouseEnter has been called and MouseExit hasn't yet been } function GetMouseEntered: Boolean; {: Returns true if X, Y is in the control. Mostly to neaten up code but could be used to implement non-rectangular controls } function InControl(X, Y: Integer): Boolean; virtual; { There are two types of events: - Ctrl events which are used by the controls themselves - these should only really be overwritten by new or modified widgets. Even then, the should still call the inherited procedures. Some (like setting) the mouseentered variable in ctrl_MouseEnter() are particularly important. - Normal events which are the ones that should be overwritten on a per control basis. The Ctrl events call the necessary normal ones. } procedure ctrl_MouseEnter(); virtual; procedure ctrl_MouseExit(); virtual; procedure ctrl_MouseDown(X, Y: Word; Button: UInt8); virtual; procedure ctrl_MouseUp(X, Y: Word; Button: UInt8); virtual; procedure ctrl_MouseMotion(X, Y: Word; ButtonState: UInt8); virtual; procedure ctrl_TextInput(TextIn: TSDLTextInputArray); virtual; procedure ctrl_MouseClick(X, Y: Word; Button: UInt8); virtual; procedure ctrl_Selected; virtual; procedure ctrl_LostSelected; virtual; procedure ctrl_KeyDown(KeySym: TSDL_KeySym); virtual; procedure ctrl_KeyUp(KeySym: TSDL_KeySym); virtual; procedure ctrl_Resize; virtual; {: SDL_Passthrough passes raw SDL events to every control on the form - even invisible/inactive ones } procedure ctrl_SDLPassthrough(e: PSDL_Event); virtual; procedure MouseEnter(); virtual; procedure MouseExit(); virtual; procedure MouseDown(X, Y: Word; Button: UInt8); virtual; procedure MouseUp(X, Y: Word; Button: UInt8); virtual; procedure MouseMotion(X, Y: Word; ButtonState: UInt8); virtual; procedure TextInput(TextIn: TSDLTextInputArray); virtual; procedure MouseClick(X, Y: Word; Button: UInt8); virtual; procedure Selected; virtual; procedure LostSelected; virtual; procedure KeyDown(KeySym: TSDL_KeySym); virtual; procedure KeyUp(KeySym: TSDL_KeySym); virtual; procedure Resize; virtual; procedure SetDbgName(Name: string); function GetDbgName: string; protected DbgName: string; Window: PSDL_Window; Renderer: PSDL_Renderer; RecieveAllEvents, CurSelected, Selectable: Boolean; Children, MyLL: TGUI_Element_LL; Parent: TGUI_Element; //Generic properties of any GUI element. These are all relative to their //respective parents { TODO : introduce _real_ properties } Width, Height: Word; Left, Top: Word; //Visible effects whether or not the element is RenderAbsed, AS WELL as //whether or not it will recieve events { TODO : introduce _real_ properties } Visible: Boolean; Enabled: Boolean; MouseEntered: Boolean; ButtonStates: array[0..7] of Boolean; private end; implementation { TGUI_Element_LL } function TGUI_Element_LL.Last: TGUI_Element_LL; begin if Next <> nil then Last := Next.Last else Last := Self; end; procedure TGUI_Element_LL.AddItem(InData: TGUI_Element); var NewPrev: TGUI_Element_LL; begin NewPrev := Last; Last.Next := TGUI_Element_LL.Create; Last.Data := InData; Last.Data.SetLL(Last); Last.Next := nil; Last.Prev := NewPrev; end; procedure TGUI_Element_LL.Dump; begin if Data <> nil then Write(Data.GetDbgName) else Write('nil'); if Next <> nil then begin Write('->'); Next.Dump; end else writeln; end; constructor TGUI_Element_LL.Create; begin end; destructor TGUI_Element_LL.Destroy; begin if Data <> nil then begin FreeAndNil(Data); inherited Destroy; end; if Next <> nil then FreeAndNil(Next); end; procedure TGUI_Element_LL.PushToLast; begin if Next <> nil then begin Prev.Next := Next; Next.Prev := Prev; Prev := Last; Prev.Next := Self; Next := nil; end; end; { TGUI_Element } procedure TGUI_Element.SetEnabled(NewEnabled: Boolean); begin Enabled := NewEnabled; end; function TGUI_Element.GetEnabled: Boolean; begin GetEnabled := Enabled; end; procedure TGUI_Element.AddChild(Child: TGUI_Element); var Next: TGUI_Element_LL; begin GetChildren.AddItem(Child); Child.SetParent(Self); { SDL2 conv.: VERY IMPORTANT If a child is added by AddChild() while it's parent hasn't been set (see e.g. Titlebar for Form), the Renderer and window aren't available to the child. - Hence, if the parent gets added by AddChild() itself to its parent (see e.g. Form gets added to Master), the following checks if it has children (Titlebar) and if so, if their Renderer and window are set, if not, re-set parent. This makes dynamic addition of subchilds from within the elements possible (like adding the Titlebar for a Form element); the alternative would be the programmer to request to add the Titlebar manually (ugly). } if Assigned(Child.GetChildren.Next) then begin Next := Child.GetChildren.Next; while Assigned(Next) do begin if (not Assigned(Next.Data.GetRenderer)) or (not Assigned( Next.Data.GetWindow)) then Next.Data.SetParent(Child); Next := Next.Next; end; end; Child.ChildAddedCallback; end; procedure TGUI_Element.SetParent(NewParent: TGUI_Element); begin Parent := NewParent; if (not Assigned(Parent.Renderer)) or (not Assigned(Parent.Window)) then Exit else begin Window := Parent.Window; Renderer := Parent.Renderer; ParentSizeCallback(Parent.GetWidth, Parent.GetHeight); end; end; function TGUI_Element.GetParent: TGUI_Element; begin GetParent := Parent; end; procedure TGUI_Element.Paint; var Next: TGUI_Element_LL; Dest: TSDL_Rect; begin if Assigned(Renderer) and Visible then begin //This renders the individual elements according to their render //implementation. Render; Next := Children.Next; while Assigned(Next) do begin Next.Data.Paint; Next := Next.Next; end; end; end; procedure TGUI_Element.ParentSizeCallback(NewW, NewH: Word); begin end; procedure TGUI_Element.Render; begin { nothing to render here, because abstract class } end; constructor TGUI_Element.Create; begin Children := TGUI_Element_LL.Create; // Just to stop any dodginess when creating surfaces Height := 50; Width := 50; Window := nil; Renderer := nil; SetRecieveAllEvents(False); Selectable := True; SetEnabled(True); SetVisible(True); end; destructor TGUI_Element.Destroy; begin if Assigned(Renderer) then SDL_DestroyRenderer(Renderer); if Assigned(Window) then SDL_DestroyWindow(Window); FreeAndNil(Children); inherited Destroy; end; procedure TGUI_Element.SetWidth(NewWidth: Word); begin Width := NewWidth; ctrl_Resize; SendSizeCallback(NewWidth, Height); end; function TGUI_Element.GetWidth: Word; begin Getwidth := Width; end; procedure TGUI_Element.SetHeight(NewHeight: Word); begin Height := NewHeight; ctrl_Resize; SendSizeCallback(Width, NewHeight); end; function TGUI_Element.GetHeight: Word; begin GetHeight := Height; end; procedure TGUI_Element.SetLeft(NewLeft: Word); begin Left := NewLeft; end; function TGUI_Element.GetLeft: Word; begin GetLeft := Left; end; procedure TGUI_Element.SetTop(NewTop: Word); begin Top := NewTop; end; function TGUI_Element.GetTop: Word; begin GetTop := Top; end; procedure TGUI_Element.SetLL(NewLL: TGUI_Element_LL); begin MyLL := NewLL; end; function TGUI_Element.GetLL: TGUI_Element_LL; begin GetLL := MyLL; end; function TGUI_Element.GetAbsLeft: Word; begin if Parent = nil then GetAbsLeft := 0 else GetAbsLeft := Parent.GetAbsLeft + Left; end; function TGUI_Element.GetAbsTop: Word; begin if Parent = nil then GetAbstop := 0 else GetAbstop := Parent.GetAbstop + Top; end; procedure TGUI_Element.SetVisible(NewVisible: Boolean); begin Visible := NewVisible; end; function TGUI_Element.GetVisible: Boolean; begin GetVisible := Visible; end; procedure TGUI_Element.SetSelected(NewState: Boolean); begin //write (newstate, ' called ', getdbgname, ' '); //Parent^.Children^.Dump; if NewState then begin if (not curselected) and selectable then begin Parent.UnSelectChildren; CurSelected := True; ctrl_Selected; MyLL.PushToLast; end; end else begin if curselected and selectable then begin ctrl_LostSelected; UnSelectChildren; CurSelected := False; end; end; //Parent^.Children^.Dump; end; function TGUI_Element.GetSelected: Boolean; begin GetSelected := CurSelected; end; procedure TGUI_Element.UnselectChildren; var Next: TGUI_Element_LL; begin Next := Children.Next; while Next <> nil do begin Next.Data.SetSelected(False); Next := Next.Next; end; end; function TGUI_Element.GetChildren: TGUI_Element_LL; begin GetChildren := Children; end; procedure TGUI_Element.SetSelectable(NewState: Boolean); begin Selectable := NewState; end; function TGUI_Element.GetSelectable: Boolean; begin GetSelectable := Selectable; end; procedure TGUI_Element.SetRecieveAllEvents(NewState: Boolean); begin RecieveAllEvents := NewState; end; function TGUI_Element.GetRecieveAllEvents: Boolean; begin GetRecieveAllEvents := RecieveAllEvents; end; function TGUI_Element.GetWindow: PSDL_Window; begin GetWindow := Window; end; function TGUI_Element.GetRenderer: PSDL_Renderer; begin GetRenderer := Renderer; end; procedure TGUI_Element.SendSizeCallback(NewW, NewH: Word); var Next: TGUI_Element_LL; begin Next := Children.Next; while Next <> nil do begin Next.Data.ParentSizeCallback(NewW, NewH); Next := Next.Next; end; end; procedure TGUI_Element.ChildAddedCallback; begin end; function TGUI_Element.InControl(X, Y: Integer): Boolean; begin if (getleft <= X) and (getwidth + getleft >= X) and (gettop <= Y) and (gettop + getheight >= Y) then InControl := True else InControl := False; end; function TGUI_Element.GetMouseEntered: Boolean; begin GetMouseEntered := MouseEntered; end; procedure TGUI_Element.ctrl_MouseEnter(); var Next: TGUI_Element_LL; begin //writeln(dbgname, ' received MouseEnter event'); Next := Children; while Next <> nil do begin if Next.Data <> nil then if Next.Data.GetMouseEntered then Next.Data.ctrl_MouseExit; Next := Next.Next; end; Next := Parent.Children; while Next <> nil do begin if Next.Data <> nil then if Next.Data.GetMouseEntered then Next.Data.ctrl_MouseExit; Next := Next.Next; end; MouseEntered := True; end; procedure TGUI_Element.ctrl_MouseExit(); var Next: TGUI_Element_LL; curbutton: Word; begin //writeln(dbgname, ' received MouseExit event'); MouseEntered := False; Next := Children; while Next <> nil do begin if Next.Data <> nil then if Next.Data.GetMouseEntered then Next.Data.ctrl_MouseExit; Next := Next.Next; end; for curbutton := low(ButtonStates) to High(ButtonStates) do ButtonStates[CurButton] := False; end; procedure TGUI_Element.ctrl_MouseDown(X, Y: Word; Button: UInt8); var Prev: TGUI_Element_LL; passed: Boolean; begin //writeln(dbgname, ' recieved MouseDown event ', x, ',', y, ',', Button); Prev := Children.Last; passed := False; // Pass the event to children if required while (Prev <> nil) and (passed = False) do begin if Prev.Data <> nil then with Prev.Data do begin // If the mouse motion is within the control if InControl(X, Y) and Visible then begin passed := True; // Pass translated mouse movement to control ctrl_MouseDown(X - getleft, Y - gettop, Button); SetSelected(True); end; end; Prev := Prev.Prev; end; if (not passed) or RecieveAllEvents then begin UnselectChildren; ButtonStates[Button] := True; MouseDown(X, Y, Button); end; end; procedure TGUI_Element.ctrl_MouseUp(X, Y: Word; Button: UInt8); var Prev: TGUI_Element_LL; passed: Boolean; begin //writeln(dbgname, ' recieved MouseUp event ', x, ',', y, ',', Button); Prev := Children.Last; passed := False; // Pass the event to children if required while (Prev <> nil) and (passed = False) do begin if Prev.Data <> nil then with Prev.Data do begin // If the mouse motion is within the control if InControl(X, Y) and Visible then begin passed := True; // Pass translated mouse movement to control ctrl_MouseUp(X - getleft, Y - gettop, Button); end; end; Prev := Prev.Prev; end; // If it hasn't been passed, or the element will recieve it regardless, // do what the control does if (not passed) or RecieveAllEvents then if ButtonStates[Button] then begin MouseUp(X, Y, Button); ctrl_MouseClick(X, Y, Button); ButtonStates[Button] := False; end else MouseUp(X, Y, Button); end; procedure TGUI_Element.ctrl_MouseClick(X, Y: Word; Button: UInt8); begin MouseClick(X, Y, Button); end; procedure TGUI_Element.ctrl_MouseMotion(X, Y: Word; ButtonState: UInt8); var Prev, Next: TGUI_Element_LL; passed: Boolean; begin // Check if MouseMotion needs to go to any children //writeln(dbgname, ' received MouseMotion event ', x, ',', y, ',', ButtonState); Prev := Children.Last; passed := False; while (Prev <> nil) and (passed = False) do begin if Prev.Data <> nil then with Prev.Data do begin // If the mouse motion is within the control if InControl(X, Y) and Visible then begin passed := True; // Pass a mouse entered event if appropriate if not GetMouseEntered then ctrl_MouseEnter; // Pass translated mouse movement to control ctrl_MouseMotion(X - getleft, Y - gettop, ButtonState); end else begin // If the mouse is outside the control and it still thinks its within // the control, issue the MouseExit event if GetMouseEntered then ctrl_MouseExit; // Issue mouse exits to children too Next := Self.Children.Next; while Next <> nil do begin if Next.Data.GetMouseEntered then Next.Data.ctrl_MouseExit; Next := Next.Next; end; end; end; Prev := Prev.Prev; end; if not passed then MouseMotion(X, Y, ButtonState); end; procedure TGUI_Element.ctrl_TextInput(TextIn: TSDLTextInputArray); var Next: TGUI_Element_LL; begin //writeln(dbgname, ' received TextInput event ', TextIn); TextInput(TextIn); Next := Children.Next; while (Next <> nil) do begin if Next.Data.GetSelected then Next.Data.ctrl_TextInput(TextIn); Next := Next.Next; end; end; procedure TGUI_Element.ctrl_Selected; begin selected; end; procedure TGUI_Element.ctrl_LostSelected; begin lostselected; end; procedure TGUI_Element.ctrl_KeyDown(KeySym: TSDL_KeySym); var Next: TGUI_Element_LL; begin KeyDown(KeySym); Next := Children.Next; while (Next <> nil) do begin if Next.Data.GetSelected then Next.Data.ctrl_KeyDown(KeySym); Next := Next.Next; end; end; procedure TGUI_Element.ctrl_KeyUp(KeySym: TSDL_KeySym); var Next: TGUI_Element_LL; begin KeyUp(KeySym); Next := Children.Next; while (Next <> nil) do begin if Next.Data.GetSelected then Next.Data.ctrl_KeyUp(KeySym); Next := Next.Next; end; end; procedure TGUI_Element.ctrl_Resize; begin Resize; end; procedure TGUI_Element.Selected; begin end; procedure TGUI_Element.LostSelected; begin end; procedure TGUI_Element.ctrl_SDLPassthrough(e: PSDL_Event); var Next: TGUI_Element_LL; begin Next := Children.Next; while (Next <> nil) do begin Next.Data.ctrl_SDLPassthrough(e); Next := Next.Next; end; end; procedure TGUI_Element.MouseEnter(); begin end; procedure TGUI_Element.MouseExit(); begin end; procedure TGUI_Element.MouseDown(X, Y: Word; Button: UInt8); begin end; procedure TGUI_Element.MouseUp(X, Y: Word; Button: UInt8); begin end; procedure TGUI_Element.MouseMotion(X, Y: Word; ButtonState: UInt8); begin end; procedure TGUI_Element.TextInput(TextIn: TSDLTextInputArray); begin end; procedure TGUI_Element.MouseClick(X, Y: Word; Button: UInt8); begin //writeln(dbgname, ' issued unhandled MouseClick event ', x, ',', y, ',', Button); end; procedure TGUI_Element.KeyDown(KeySym: TSDL_KeySym); begin end; procedure TGUI_Element.KeyUp(KeySym: TSDL_KeySym); begin end; procedure TGUI_Element.Resize; begin end; procedure TGUI_Element.SetDbgName(Name: string); begin DbgName := Name; end; function TGUI_Element.GetDbgName: string; begin GetDbgName := DbgName; end; begin end.
unit DebugMessageSaver; interface uses Classes, Forms, SysUtils, DateUtils; type TDebugMessageSaver = class private FNeedSave: Boolean; FSaveFilesPath: AnsiString; FStreamLog: TFileStream; FMaxSize: integer; procedure DeleteFiles(const Path, ext: AnsiString; const days: integer); procedure SetSaveFilesPath(const Value: AnsiString); function DateTime2Str(const DT: TDateTime): AnsiString; procedure SetMaxSize(const Value: integer); public destructor Destroy; override; procedure AfterConstruction; override; property SaveFilesPath: AnsiString read FSaveFilesPath write SetSaveFilesPath; procedure SaveDebugMessage(const DebugMessage: AnsiString); property MaxSize: integer read FMaxSize write SetMaxSize; end; implementation { TDebugMessageSaver } procedure TDebugMessageSaver.AfterConstruction; begin inherited; if FMaxSize=0 then FMaxSize := 64; end; function TDebugMessageSaver.DateTime2Str(const DT: TDateTime): AnsiString; var AYear, AMonth, ADay, AHour, AMinute, ASecond, AMilliSecond :word; begin DecodeDateTime(DT, AYear, AMonth, ADay, AHour, AMinute, ASecond, AMilliSecond); Ayear := Ayear mod 100; Result := format('%2.2d%2.2d%2.2d%2.2d%2.2d%2.2d', [AYear, AMonth, ADay, AHour, AMinute, ASecond]); end; procedure TDebugMessageSaver.DeleteFiles(const Path, ext: AnsiString; const days: integer); var sr: TSearchRec; FileAttrs: Integer; begin FileAttrs := faAnyFile; if FindFirst(Path+'\'+ext, FileAttrs, sr) = 0 then begin repeat if DaysBetween(FileDateToDateTime(sr.Time),Today)>days then DeleteFile(Path+'\'+sr.Name); until FindNext(sr) <> 0; FindClose(sr); end; end; destructor TDebugMessageSaver.Destroy; begin if Assigned(FStreamLog) then FreeAndNil(FStreamLog); inherited; end; procedure TDebugMessageSaver.SaveDebugMessage( const DebugMessage: AnsiString); var Str: AnsiString; lsDirName: AnsiString; lsFileName: AnsiString; begin if FNeedSave then begin Str := DateTimeToStr(Now)+': '+DebugMessage+#13#10; try if not Assigned(FStreamLog) then begin if Pos(':',FSaveFilesPath)<>0 then lsDirName := FSaveFilesPath else lsDirName := ExtractFilePath(Application.ExeName)+'\'+FSaveFilesPath; if ( not DirectoryExists(lsDirName)) then begin CreateDir(lsDirName); end; DeleteFiles(lsDirName,'*.txt',15); lsFileName := lsDirName+'\'+DateTime2Str(Now)+'log.txt'; FStreamLog := TFileStream.Create(lsFileName, fmCreate); FStreamlog.Free; FStreamlog := nil; FStreamLog := TFileStream.Create(lsFileName, fmOpenReadWrite+fmShareDenyNone); end; {$WARNINGS OFF} FStreamLog.WriteBuffer(Pointer(Str)^,Length(Str)); {$WARNINGS ON} if FStreamLog.Size>FMaxSize*1024 then FreeAndNil(FStreamLog); except end; end; end; procedure TDebugMessageSaver.SetMaxSize(const Value: integer); begin FMaxSize := Value; end; procedure TDebugMessageSaver.SetSaveFilesPath(const Value: AnsiString); begin FNeedSave := Trim(Value)<>''; FSaveFilesPath := Value; end; end.
unit XLSReadII2; { ******************************************************************************** ******* XLSReadWriteII V2.00 ******* ******* ******* ******* Copyright(C) 1999,2006 Lars Arvidsson, Axolot Data ******* ******* ******* ******* email: components@axolot.com ******* ******* URL: http://www.axolot.com ******* ******************************************************************************** ** Users of the XLSReadWriteII component must accept the following ** ** disclaimer of warranty: ** ** ** ** XLSReadWriteII is supplied as is. The author disclaims all warranties, ** ** expressedor implied, including, without limitation, the warranties of ** ** merchantability and of fitness for any purpose. The author assumes no ** ** liability for damages, direct or consequential, which may result from the ** ** use of XLSReadWriteII. ** ******************************************************************************** } {$I XLSRWII2.inc} {$B-} {$R-} {$H+} interface uses Classes, SysUtils, Windows, Messages, BIFFRecsII2, CellFormats2, SheetData2, XLSStream2, XLSReadWriteII2, XLSUtils2, Dialogs, DecodeFormula2, XLSFonts2, ExcelMaskII2, Validate2, Math, RecordStorage2, Escher2, MergedCells2; type TSharedFormula = record Row1,Row2: word; Col1,Col2: byte; Len: word; Formula: PByteArray; end; type TXLSReadII = class(TObject) protected PBuf: PByteArray; FXLS: TXLSReadWriteII2; FCurrSheet: integer; FXLSStream: TXLSStream; FBoundsheets: TStringList; FBoundsheetIndex: integer; Header: TBIFFHeader; FSharedFormulas: array of TSharedFormula; FBIFFVer: longword; FLastARRAY: PByteArray; FLastARRAYSize: integer; FIsXLS137: boolean; // The file is created with XLSReadWrite 1.37 CurrRecs: TRecordStorage; InsertRecord: boolean; // File prefix procedure RREC_FILEPASS; procedure RREC_INTERFACEHDR; procedure RREC_ADDMENU; procedure RREC_DELMENU; procedure RREC_INTERFACEEND; procedure RREC_WRITEACCESS; procedure RREC_FILESHAREING; procedure RREC_CODEPAGE; procedure RREC_DSF; procedure RREC_FNGROUPCOUNT; procedure RREC_WINDOWPROTECT; procedure RREC_PROTECT; procedure RREC_PASSWORD; procedure RREC_PROT4REV; procedure RREC_PROT4REVPASS; procedure RREC_WINDOW1; procedure RREC_BACKUP; procedure RREC_HIDEOBJ; procedure RREC_1904; procedure RREC_PRECISION; procedure RREC_REFRESHALL; procedure RREC_BOOKBOOL; procedure RREC_PALETTE; procedure RREC_FONT; procedure RREC_FORMAT; procedure RREC_XF; procedure RREC_STYLE; procedure RREC_NAME; procedure RREC_SUPBOOK; procedure RREC_EXTERNNAME; procedure RREC_XCT; procedure RREC_EXTERNCOUNT; procedure RREC_EXTERNSHEET; procedure RREC_USESELFS; procedure RREC_BOUNDSHEET; procedure RREC_COUNTRY; procedure RREC_RECALCID; procedure RREC_MSODRAWINGGROUP; procedure RREC_MSO_0866; procedure RREC_SST; procedure RREC_EXTSST; procedure RREC_EOF; // Sheet prefix procedure RREC_CALCMODE; procedure RREC_CALCCOUNT; procedure RREC_REFMODE; procedure RREC_ITERATION; procedure RREC_DELTA; procedure RREC_SAVERECALC; procedure RREC_PRINTHEADERS; procedure RREC_PRINTGRIDLINES; procedure RREC_GRIDSET; procedure RREC_GUTS; procedure RREC_DEFAULTROWHEIGHT; procedure RREC_WSBOOL; procedure RREC_HORIZONTALPAGEBREAKS; procedure RREC_VERTICALPAGEBREAKS; procedure RREC_HEADER; procedure RREC_FOOTER; procedure RREC_HCENTER; procedure RREC_VCENTER; procedure RREC_PLS; procedure RREC_SETUP; procedure RREC_LEFTMARGIN; procedure RREC_RIGHTMARGIN; procedure RREC_TOPMARGIN; procedure RREC_BOTTOMMARGIN; procedure RREC_DEFCOLWIDTH; procedure RREC_FILTERMODE; procedure RREC_AUTOFILTERINFO; procedure RREC_COLINFO; procedure RREC_DIMENSIONS; // Sheet data procedure RREC_INTEGER_20; procedure RREC_NUMBER_20; procedure RREC_LABEL_20; procedure RREC_ROW; procedure RREC_BLANK; procedure RREC_BOOLERR; procedure RREC_FORMULA; procedure RREC_FORMULA_30; procedure RREC_NUMBER; procedure RREC_RK; procedure RREC_MULRK; procedure RREC_MULBLANK; procedure RREC_LABELSST; procedure RREC_LABEL; procedure RREC_RSTRING; procedure RREC_NOTE; procedure READ_SHRFMLA; // Sheet suffix procedure RREC_MSODRAWING; procedure RREC_MSODRAWINGSELECTION; procedure RREC_WINDOW2; procedure RREC_SCL; procedure RREC_PANE; procedure RREC_SELECTION; procedure RREC_SHEETLAYOUT; procedure RREC_SHEETPROTECTION; procedure RREC_DVAL; procedure RREC_MERGEDCELLS; procedure RREC_CONDFMT; procedure RREC_HLINK; procedure Clear; procedure ClearSharedFmla; procedure ReadFormulaVal(Col,Row,FormatIndex: integer; Value: double; Formula: PByteArray; Len,DataSz: integer); procedure FixupSharedFormula(LeftCol,TopRow,ACol,ARow: integer); public constructor Create(XLS: TXLSReadWriteII2); destructor Destroy; override; procedure LoadFromStream(Stream: TStream); end; implementation constructor TXLSReadII.Create(XLS: TXLSReadWriteII2); begin FXLS := XLS; FXLSStream := TXLSStream.Create(FXLS.VBA); FXLSStream.SaveVBA := XLS.PreserveMacros; FBoundsheets := TStringList.Create; end; destructor TXLSReadII.Destroy; begin FXLSStream.Free; FBoundsheets.Free; ClearSharedFmla; FreeMem(FLastARRAY); inherited Destroy; end; procedure TXLSReadII.Clear; begin FCurrSheet := -1; FBoundsheets.Clear; FBoundsheetIndex := -1; end; procedure TXLSReadII.ClearSharedFmla; var i: integer; begin for i := 0 to High(FSharedFormulas) do FreeMem(FSharedFormulas[i].Formula); SetLength(FSharedFormulas,0); end; procedure TXLSReadII.LoadFromStream(Stream: TStream); var i,V,ProgressCount: integer; Count: integer; InUSERSVIEW: boolean; begin InUSERSVIEW := False; Count := 0; Clear; FXLS.WriteDefaultData := False; try {$ifdef USE_MSSTORAGE} FXLSStream.ExtraObjects := FXLS.ExtraObjects; FXLSStream.SourceStream := Stream; {$endif} FXLS.Version := FXLSStream.OpenStorageRead(FXLS.Filename); GetMem(PBuf,FXLS.MaxBuffsize); CurrRecs := FXLS.Records; if FXLS.Version <= xvExcel21 then begin for i := 0 to DEFAULT_FORMAT do FXLS.Formats.Add; end; ProgressCount := 0; if Assigned(FXLS.OnProgress) then FXLS.OnProgress(Self,0); try while FXLSStream.ReadHeader(Header) = SizeOf(TBIFFHeader) do begin if FXLS.Aborted then Exit; if Header.Length > FXLS.MaxBuffsize then begin // Invalid record size ReAllocMem(PBuf,Header.Length); // FXLSStream.Seek(Header.Length,soFromCurrent); // Continue; end else if (Header.RecID and INTERNAL_PLACEHOLDER) <> 0 then raise Exception.Create('Bad record in file') // BOFPos in BOUNDSHEET will not have correect values when reading // encrypted files, as BOFPos is written unencrypted. else if ((Header.RecID and $FF) <> BIFFRECID_BOF) and (Header.RecId <> BIFFRECID_SST) and // (Header.RecId <> BIFFRECID_MSO_0866) and (Header.RecId <> BIFFRECID_MSODRAWINGGROUP) and (Header.RecId <> BIFFRECID_MSODRAWING) then FXLSStream.Read(PBuf^,Header.Length); if Assigned(FXLS.OnProgress) then begin V := Round((FXLSStream.Pos / FXLSStream.Size) * 100); if V > ProgressCount then begin ProgressCount := V; FXLS.OnProgress(Self,ProgressCount); end; end; // if ((Header.RecID and $FF) <> BIFFRECID_BOF) and (Header.RecID <> BIFFRECID_EXCEL9FILE) then // CurrRecs.Add(Header,PBuf); if InUSERSVIEW then begin if Header.RecID = BIFFRECID_USERSVIEWEND then InUSERSVIEW := False; Continue; end; InsertRecord := True; case Header.RecID of BIFFRECID_EOF: begin CurrRecs.UpdateDefault(Header,PBuf); InsertRecord := False; ClearSharedFmla; if (FBoundsheets.Count <= 0) or (FBoundsheetIndex >= (FBoundsheets.Count - 1)) then begin Break; end; end; // File prefix // BIFFRECID_OBPROJ: InsertRecord := False; // BIFFRECID_EXCEL9FILE: InsertRecord := False; BIFFRECID_FILEPASS: RREC_FILEPASS; BIFFRECID_INTERFACEHDR: RREC_INTERFACEHDR; BIFFRECID_INTERFACEEND: RREC_INTERFACEEND; BIFFRECID_WRITEACCESS: RREC_WRITEACCESS; BIFFRECID_FILESHAREING: RREC_FILESHAREING; BIFFRECID_CODEPAGE: RREC_CODEPAGE; BIFFRECID_DSF: RREC_DSF; BIFFRECID_FNGROUPCOUNT: RREC_FNGROUPCOUNT; BIFFRECID_WINDOWPROTECT: RREC_WINDOWPROTECT; BIFFRECID_PROTECT: RREC_PROTECT; BIFFRECID_PASSWORD: RREC_PASSWORD; BIFFRECID_PROT4REV: RREC_PROT4REV; BIFFRECID_PROT4REVPASS: RREC_PROT4REVPASS; BIFFRECID_WINDOW1: RREC_WINDOW1; BIFFRECID_BACKUP: RREC_BACKUP; BIFFRECID_HIDEOBJ: RREC_HIDEOBJ; BIFFRECID_1904: RREC_1904; BIFFRECID_PRECISION: RREC_PRECISION; BIFFRECID_REFRESHALL: RREC_REFRESHALL; BIFFRECID_BOOKBOOL: RREC_BOOKBOOL; BIFFRECID_PALETTE: RREC_PALETTE; BIFFRECID_FONT,$0231: RREC_FONT; BIFFRECID_FORMAT: RREC_FORMAT; BIFFRECID_XF_30, BIFFRECID_XF_40, BIFFRECID_XF: RREC_XF; // STYLE (inbyggda) måste finnas, annars så fungerar inte "style" // knapparna i Excel. // BIFFRECID_STYLE: RREC_STYLE; BIFFRECID_NAME,$0218: RREC_NAME; BIFFRECID_SUPBOOK: RREC_SUPBOOK; BIFFRECID_EXTERNNAME,$0223: RREC_EXTERNNAME; BIFFRECID_XCT: RREC_XCT; BIFFRECID_EXTERNCOUNT: RREC_EXTERNCOUNT; BIFFRECID_EXTERNSHEET: RREC_EXTERNSHEET; BIFFRECID_USESELFS: RREC_USESELFS; BIFFRECID_BOUNDSHEET: RREC_BOUNDSHEET; BIFFRECID_COUNTRY: RREC_COUNTRY; BIFFRECID_RECALCID: RREC_RECALCID; BIFFRECID_MSODRAWINGGROUP: RREC_MSODRAWINGGROUP; BIFFRECID_MSO_0866: RREC_MSO_0866; BIFFRECID_SST: RREC_SST; BIFFRECID_EXTSST: RREC_EXTSST; // Sheet prefix BIFFRECID_CALCMODE: RREC_CALCMODE; BIFFRECID_CALCCOUNT: RREC_CALCCOUNT; BIFFRECID_REFMODE: RREC_REFMODE; BIFFRECID_ITERATION: RREC_ITERATION; BIFFRECID_DELTA: RREC_DELTA; BIFFRECID_SAVERECALC: RREC_SAVERECALC; BIFFRECID_PRINTHEADERS: RREC_PRINTHEADERS; BIFFRECID_PRINTGRIDLINES: RREC_PRINTGRIDLINES; BIFFRECID_GRIDSET: RREC_GRIDSET; BIFFRECID_GUTS: RREC_GUTS; BIFFRECID_DEFAULTROWHEIGHT: RREC_DEFAULTROWHEIGHT; BIFFRECID_WSBOOL: RREC_WSBOOL; BIFFRECID_HORIZONTALPAGEBREAKS:RREC_HORIZONTALPAGEBREAKS; BIFFRECID_VERTICALPAGEBREAKS: RREC_VERTICALPAGEBREAKS; BIFFRECID_HEADER: RREC_HEADER; BIFFRECID_FOOTER: RREC_FOOTER; BIFFRECID_HCENTER: RREC_HCENTER; BIFFRECID_VCENTER: RREC_VCENTER; BIFFRECID_PLS: RREC_PLS; BIFFRECID_SETUP: RREC_SETUP; BIFFRECID_LEFTMARGIN: RREC_LEFTMARGIN; BIFFRECID_RIGHTMARGIN: RREC_RIGHTMARGIN; BIFFRECID_TOPMARGIN: RREC_TOPMARGIN; BIFFRECID_BOTTOMMARGIN: RREC_BOTTOMMARGIN; BIFFRECID_DEFCOLWIDTH: RREC_DEFCOLWIDTH; BIFFRECID_FILTERMODE: RREC_FILTERMODE; BIFFRECID_AUTOFILTERINFO: RREC_AUTOFILTERINFO; BIFFRECID_COLINFO: RREC_COLINFO; BIFFRECID_DIMENSIONS_20: begin // DIMENSIONS_20 has the value $0000. This record was used in excel // 5 files created with XLSReadWrite 1.x, in order to pad the file // size. if (FXLS.Version = xvExcel50) or FIsXLS137 then InsertRecord := False else RREC_DIMENSIONS; end; BIFFRECID_DIMENSIONS: RREC_DIMENSIONS; // Sheet cells/data BIFFRECID_INDEX: begin InsertRecord := False; if FXLS.Version <= xvExcel40 then CurrRecs := FXLS.Sheets[FCurrSheet]._Int_Records; end; BIFFRECID_DBCELL: InsertRecord := False; BIFFRECID_INTEGER_20: RREC_INTEGER_20; BIFFRECID_NUMBER_20: RREC_NUMBER_20; BIFFRECID_LABEL_20: RREC_LABEL_20; BIFFRECID_ROW: RREC_ROW; BIFFRECID_BLANK: RREC_BLANK; BIFFRECID_BOOLERR: RREC_BOOLERR; BIFFRECID_FORMULA: RREC_FORMULA; BIFFRECID_FORMULA_30, BIFFRECID_FORMULA_40: RREC_FORMULA_30; BIFFRECID_MULBLANK: RREC_MULBLANK; BIFFRECID_RK, BIFFRECID_RK7: RREC_RK; BIFFRECID_MULRK: RREC_MULRK; BIFFRECID_NUMBER: RREC_NUMBER; BIFFRECID_LABELSST: RREC_LABELSST; BIFFRECID_LABEL: RREC_LABEL; BIFFRECID_RSTRING: RREC_RSTRING; BIFFRECID_NOTE: RREC_NOTE; // Sheet suffix BIFFRECID_MSODRAWING: RREC_MSODRAWING; BIFFRECID_MSODRAWINGSELECTION: RREC_MSODRAWINGSELECTION; BIFFRECID_WINDOW2: RREC_WINDOW2; { BIFFRECID_SCL: RREC_SCL; } BIFFRECID_PANE: RREC_PANE; BIFFRECID_SELECTION: RREC_SELECTION; BIFFRECID_SHEETLAYOUT: RREC_SHEETLAYOUT; BIFFRECID_SHEETPROTECTION: RREC_SHEETPROTECTION; BIFFRECID_MERGEDCELLS: RREC_MERGEDCELLS; BIFFRECID_CONDFMT: RREC_CONDFMT; BIFFRECID_HLINK: RREC_HLINK; BIFFRECID_DVAL: RREC_DVAL; BIFFRECID_USERBVIEW: InsertRecord := False; BIFFRECID_USERSVIEWBEGIN: begin InsertRecord := False; InUSERSVIEW := True; end; // 0000: InsertRecord := False; // Dummy recors used by XLSReadWrite 1.37 else begin if (Header.RecID and $FF) = BIFFRECID_BOF then begin ClearSharedFmla; FXLSStream.ReadUnencryptedSync(PBuf^,Header.Length); InsertRecord := False; case PRecBOF8(PBuf).SubStreamType of $0005: begin // Workbook globals if Header.Length > 256 then raise Exception.Create('Invalid BOF size'); FXLS.IsMac := (FXLS.Version >= xvExcel97) and ((PRecBOF8(PBuf).FileHistoryFlags and $00000010) = $00000010); CurrRecs := FXLS.Records; CurrRecs.UpdateDefault(Header,PBuf); FIsXLS137 := (PRecBOF8(PBuf).BuildYear = 1998) and (PRecBOF8(PBuf).FileHistoryFlags = 0) and (PRecBOF8(PBuf).LowBIFF = 6); end; $0040, // BIFF4 Macro sheet $0006, // VB Module $0010: begin // Worksheet Inc(FBoundsheetIndex); Inc(FCurrSheet); case PRecBOF8(PBuf).SubStreamType of $0040: FXLS.Sheets.Add(wtExcel4Macro); $0006: FXLS.Sheets.Add(wtVBModule); $0010: FXLS.Sheets.Add(wtSheet); end; FXLS.Sheets[FCurrSheet]._Int_HasDefaultRecords := True; if FXLS.Version <= xvExcel40 then FXLS.Sheets[FCurrSheet].Name := 'Sheet1' else begin FXLS.Sheets[FCurrSheet].Name := ExcelStrToWideString(FBoundsheets[FBoundsheetIndex]); FXLS.Sheets[FCurrSheet].Hidden := THiddenState(FBoundsheets.Objects[FBoundsheetIndex]); FXLS.Sheets[FCurrSheet]._Int_SheetIndex := FBoundsheetIndex; CurrRecs := FXLS.Sheets[FCurrSheet]._Int_Records; CurrRecs.UpdateDefault(Header,PBuf); end; FBIFFVer := PRecBOF8(PBuf).LowBIFF; end; $0020: begin // Chart Inc(FBoundsheetIndex); FXLS.SheetCharts.LoadFromStream(FXLSStream,ExcelStrToWideString(FBoundsheets[FBoundsheetIndex]),PBuf,FXLS.Fonts,FBoundsheetIndex); //raise Exception.Create('Chart unhandled'); end; $0100: begin // BIFF4 Workbook globals raise Exception.Create('BIFF4 Workbook unhandled'); end; end; end end; end; if InsertRecord then CurrRecs.AddRec(Header,PBuf); Inc(Count); end; except on E: Exception do raise Exception.CreateFmt('Error on reading record # %d, %.4X Offs: %.8X' + #13 + E.Message,[Count,Header.RecId,FXLSStream.Pos]); end; {$ifndef USE_MSSTORAGE} if FXLSStream.SaveVBA then FXLSStream.ReadCache(FXLS.CacheFiles); {$endif} if Assigned(FXLS.OnProgress) then FXLS.OnProgress(Self,100); finally FXLSStream.CloseStorage; FreeMem(PBuf); end; end; // Sheet cells procedure TXLSReadII.RREC_BLANK; begin InsertRecord := False; with PRecBLANK(PBuf)^ do FXLS.Sheets[FCurrSheet].IntWriteBlank(Col,Row,FormatIndex); end; procedure TXLSReadII.RREC_ROW; begin InsertRecord := False; { if XLS_DebugMode then begin if Assigned(FXLS.OnRowHeight) and (PRecROW(PBuf).Height <> 255) then FXLS.OnRowHeight(Self,PRecROW(PBuf).Row,PRecROW(PBuf).FormatIndex,PRecROW(PBuf).Height); end; } if (PRecROW(PBuf).Options and $0080) = $0080 then FXLS.Sheets[FCurrSheet].Rows.SetRecROW(PRecROW(PBuf),PRecROW(PBuf).FormatIndex and $0FFF) else FXLS.Sheets[FCurrSheet].Rows.SetRecROW(PRecROW(PBuf),DEFAULT_FORMAT); end; procedure TXLSReadII.RREC_BOOLERR; begin InsertRecord := False; with PRecBOOLERR(PBuf)^ do begin if Error = 0 then FXLS.Sheets[FCurrSheet].IntWriteBoolean(Col,Row,FormatIndex,Boolean(BoolErr)) else FXLS.Sheets[FCurrSheet].IntWriteError(Col,Row,FormatIndex,ErrorCodeToCellError(BoolErr)); end; end; procedure TXLSReadII.ReadFormulaVal(Col,Row,FormatIndex: integer; Value: double; Formula: PByteArray; Len,DataSz: integer); var Fmla: PByteArray; S: string; begin GetMem(Fmla,DataSz); try // Formula points to PBuf, which is overwritten by the next read of the file. Move(Formula^,Fmla^,DataSz); case TByte8Array(Value)[0] of 0: begin Header.RecID := FXLSStream.PeekHeader; if (Header.RecID = BIFFRECID_SHRFMLA) or (Header.RecID = $04BC) then begin raise Exception.Create('Unxepected SHRFMLA'); { ExtSz := SizeOf(TBIFFHeader) + Header.Length; FXLSStream.Read(PBuf^,Header.Length); FXLSStream.ReadHeader(Header); } end; if Header.RecID = BIFFRECID_STRING then begin FXLSStream.ReadHeader(Header); FXLSStream.Read(PBuf^,Header.Length); S := ByteStrToWideString(@PRecSTRING(PBuf).Data,PRecSTRING(PBuf).Len); { if ExtSz > 0 then begin Inc(ExtSz,SizeOf(TBIFFHeader) + Header.Length); FXLSStream.Seek2(-ExtSz,soFromCurrent); end; } end else if Header.RecID = BIFFRECID_STRING_20 then begin FXLSStream.ReadHeader(Header); FXLSStream.Read(PBuf^,Header.Length); S := ByteStrToWideString(@PRec2STRING(PBuf).Data,PRec2STRING(PBuf).Len); end else Exit; FXLS.Sheets[FCurrSheet].WriteRawStrFormula(Col,Row,FormatIndex,Fmla,DataSz,Len,S); end; 1: FXLS.Sheets[FCurrSheet].WriteRawBoolFormula(Col,Row,FormatIndex,Fmla,DataSz,Len,Boolean(Integer(TByte8Array(Value)[2]))); 2: FXLS.Sheets[FCurrSheet].WriteRawErrFormula(Col,Row,FormatIndex,Fmla,DataSz,Len,TByte8Array(Value)[2]); // Undocumented: the value 3 indicates that the result is an empty string, // and therefore there is no STRING record following the formula. 3: FXLS.Sheets[FCurrSheet].WriteRawStrFormula(Col,Row,FormatIndex,Fmla,DataSz,Len,''); end; finally FreeMem(Fmla); end; end; procedure TXLSReadII.RREC_FORMULA; var DataSz: integer; begin InsertRecord := False; if FXLS.Version < xvExcel30 then with PRec2FORMULA(PBuf)^ do begin DataSz := Header.Length - 17; if (TByte8Array(Value)[6] = $FF) and (TByte8Array(Value)[7] = $FF) then ReadFormulaVal(Col,Row,-1,Value,@Data,ParseLen,DataSz) else FXLS.Sheets[FCurrSheet].WriteRawNumFormula(Col,Row,DEFAULT_FORMAT,@Data,DataSz,ParseLen,Value); end else with PRecFORMULA(PBuf)^ do begin DataSz := Header.Length - 22; // ATTN: Under some circumstances (don't know why) the Shared Formula bit is set // in the Options field, even if the formula not is part of a shared formula group. // There is no SHRFMLA record following the FORMULA record. // The formula contaions a complete expression. // This seems to only occure in XLS-97 files. // Bug in Excel? // One way to check this is to se if the first PTG in the formula is ptgExp, = part of shared formula. if ((Options and $0008) = $0008) and (Data[0] = ptgExp) then begin Header.RecID := FXLSStream.PeekHeader; if (Header.RecID = BIFFRECID_SHRFMLA) or (Header.RecID = BIFFRECID_SHRFMLA_20) then begin FXLSStream.ReadHeader(Header); READ_SHRFMLA end; // FixupSharedFormula(Col,Row); FixupSharedFormula(PWordArray(@Data[1])[1],PWordArray(@Data[1])[0],Col,Row); DataSz := ParseLen; end else if Data[0] = ptgExp then begin if FXLSStream.PeekHeader = BIFFRECID_ARRAY then begin FXLSStream.ReadHeader(Header); GetMem(FLastARRAY,Header.Length); FXLSStream.Read(FLastARRAY^,Header.Length); FXLS.Sheets[FCurrSheet].WriteRawArrayFormula(Col,Row,FormatIndex,@Data,DataSz,ParseLen,Value,FLastARRAY,Header.Length,False); FLastARRAYSize := Header.Length; Exit; end else if (FLastARRAY <> Nil) and (Col >= PRecARRAY(FLastARRAY).Col1) and (Col <= PRecARRAY(FLastARRAY).Col2) and (Row >= PRecARRAY(FLastARRAY).Row1) and (Row <= PRecARRAY(FLastARRAY).Row2) then begin FXLS.Sheets[FCurrSheet].WriteRawArrayFormula(Col,Row,FormatIndex,@Data,DataSz,ParseLen,Value,FLastARRAY,FLastARRAYSize,True); Exit; end else begin FLastARRAY := Nil; FLastARRAYSize := 0; end; end; if (TByte8Array(Value)[0] in [$00,$01,$02,$03]) and (TByte8Array(Value)[6] = $FF) and (TByte8Array(Value)[7] = $FF) then ReadFormulaVal(Col,Row,FormatIndex,Value,@Data,ParseLen,DataSz) else if ParseLen <> 0 then begin // This detects NAN values. A NAN number may cause an "Invalid Floating Point Operation" exception when used. if (TByte8Array(Value)[0] = $02) and (TByte8Array(Value)[6] = $FF) and (TByte8Array(Value)[7] = $FF) then FXLS.Sheets[FCurrSheet].WriteRawNumFormula(Col,Row,FormatIndex,@Data,DataSz,ParseLen,0) else FXLS.Sheets[FCurrSheet].WriteRawNumFormula(Col,Row,FormatIndex,@Data,DataSz,ParseLen,Value); end; end; end; procedure TXLSReadII.RREC_FORMULA_30; begin InsertRecord := False; // PocketPC if FBIFFVer = 6 then begin RREC_FORMULA; end else begin with PRecFORMULA3(PBuf)^ do begin FXLS.Sheets[FCurrSheet].WriteRawNumFormula(Col,Row,FormatIndex,@Data,Header.Length - 18,ParseLen,Value); if (TByte8Array(Value)[6] = $FF) and (TByte8Array(Value)[7] = $FF) then ReadFormulaVal(Col,Row,FormatIndex,Value,@Data,ParseLen,ParseLen); end; end; end; procedure TXLSReadII.RREC_NUMBER; begin InsertRecord := False; with PRecNUMBER(PBuf)^ do FXLS.Sheets[FCurrSheet].IntWriteNumber(Col,Row,FormatIndex,Value); end; procedure TXLSReadII.RREC_INTEGER_20; begin InsertRecord := False; with PRec2INTEGER(PBuf)^ do FXLS.Sheets[FCurrSheet].IntWriteNumber(Col,Row,DEFAULT_FORMAT,Value); end; procedure TXLSReadII.RREC_LABEL_20; var S: string; begin InsertRecord := False; with PRec2LABEL(PBuf)^ do begin SetLength(S,Len); Move(Data,Pointer(S)^,Len); FXLS.Sheets[FCurrSheet].IntWriteSSTString(Col,Row,DEFAULT_FORMAT,S); end; end; procedure TXLSReadII.RREC_NUMBER_20; begin InsertRecord := False; with PRec2NUMBER(PBuf)^ do FXLS.Sheets[FCurrSheet].IntWriteNumber(Col,Row,DEFAULT_FORMAT,Value); end; procedure TXLSReadII.RREC_LABELSST; begin InsertRecord := False; try with PRecLABELSST(PBuf)^ do FXLS.Sheets[FCurrSheet].IntWriteSSTStringIndex(Col,Row,FormatIndex,SSTIndex); except raise Exception.CreateFmt('Read error at %.8D',[FXLSStream.Pos]); end; end; procedure TXLSReadII.RREC_LABEL; var i: integer; P: PWordArray; WS: WideString; begin InsertRecord := False; with PRecLABEL(PBuf)^ do begin if FXLS.Version > xvExcel97 then FXLS.Sheets[FCurrSheet].IntWriteSSTString(Col,Row,FormatIndex,ByteStrToWideString(@Data[0],Len)) else begin SetLength(WS,Len); if Data[0] = 0 then begin for i := 1 to Len do WS[i] := WideChar(Data[i]); end else if Data[0] = 1 then begin P := @Data[1]; for i := 0 to Len - 1 do WS[i + 1] := WideChar(P[i]); end else begin for i := 0 to Len - 1 do WS[i + 1] := WideChar(Data[i]); end; FXLS.Sheets[FCurrSheet].IntWriteSSTString(Col,Row,FormatIndex,WS); end; end; end; procedure TXLSReadII.RREC_RSTRING; var S: string; begin InsertRecord := False; with PRecLABEL(PBuf)^ do begin SetLength(S,Len); Move(Data,Pointer(S)^,Len); FXLS.Sheets[FCurrSheet].IntWriteSSTString(Col,Row,FormatIndex,S); end; end; procedure TXLSReadII.RREC_MULBLANK; var i: integer; begin InsertRecord := False; with PRecMULBLANK(PBuf)^ do begin for i := 0 to (Header.Length - 6) div 2 - 1 do FXLS.Sheets[FCurrSheet].IntWriteBlank(Col1 + i,Row,FormatIndexes[i]); end; end; procedure TXLSReadII.RREC_RK; begin InsertRecord := False; with PRecRK(PBuf)^ do FXLS.Sheets[FCurrSheet].IntWriteNumber(Col,Row,FormatIndex,DecodeRK(Value)); end; procedure TXLSReadII.RREC_MULRK; var i: integer; begin InsertRecord := False; with PRecMULRK(PBuf)^ do begin for i := 0 to (Header.Length - 6) div 6 - 1 do FXLS.Sheets[FCurrSheet].IntWriteNumber(Col1 + i,Row,RKs[i].FormatIndex,DecodeRK(RKs[i].Value)); end; end; procedure TXLSReadII.FixupSharedFormula(LeftCol,TopRow,ACol,ARow: integer); var i: integer; begin // A shard formula identifies the definition it belongs to by the upper left // corner of the definition area. for i := 0 to High(FSharedFormulas) do begin with FSharedFormulas[i] do begin if (LeftCol = Col1) and (TopRow = Row1) then begin Move(Formula^,PRecFORMULA(PBuf).Data,Len); PRecFORMULA(PBuf).ParseLen := Len; ConvertShrFmla(FXLS.Version = xvExcel97,@PRecFORMULA(PBuf).Data,PRecFORMULA(PBuf).ParseLen,ACol,ARow); Break; end; end; end; { // ATTN: Ranges of shared formulas may overlap. The last one written seems // to be the correct, therefore all shared formulas has to be searched. for i := 0 to High(FSharedFormulas) do begin with FSharedFormulas[i] do begin if (ACol >= Col1) and (ACol <= Col2) and (ARow >= Row1) and (ARow <= Row2) then begin Move(Formula^,PRecFORMULA(PBuf).Data,Len); PRecFORMULA(PBuf).ParseLen := Len; ConvertShrFmla(FXLS.Version = xvExcel97,@PRecFORMULA(PBuf).Data,PRecFORMULA(PBuf).ParseLen,ACol,ARow); Break; end; end; end; } end; procedure TXLSReadII.READ_SHRFMLA; var i: integer; begin // ATTN: If Excel saves a SHRFMLA where some cells have been deleted, // (Ex: If you have 10 formulas in a row, saves it, open the sheet again, // deletes 4 of them and saves it again) then may the deleted formulas // still be saved in the SHRFMLA record! // The only way to check this is to look for the corresponding FORMULA // records. There is only FORMULA records for formulas that exsists on // the sheet. I think :-) SetLength(FSharedFormulas,Length(FSharedFormulas) + 1); i := High(FSharedFormulas); FXLSStream.Read(FSharedFormulas[i],6); FXLSStream.Read(FSharedFormulas[i].Len,2); // Reserved data FXLSStream.Read(FSharedFormulas[i].Len,2); GetMem(FSharedFormulas[i].Formula,FSharedFormulas[i].Len); FXLSStream.Read(FSharedFormulas[i].Formula^,FSharedFormulas[i].Len); end; procedure TXLSReadII.RREC_NOTE; begin InsertRecord := False; if FXLS.Version > xvExcel40 then begin TRecordStorageSheet(CurrRecs).UpdateInternal(INTERNAL_SUFFIXDATA); with PRecNOTE(PBuf)^ do FXLS.Sheets[FCurrSheet]._Int_EscherDrawing.SetNoteData(Col,Row,Options,ObjId,ByteStrToWideString(PByteArray(@AuthorName),AuthorNameLen)); end; end; procedure TXLSReadII.RREC_1904; begin InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_ADDMENU; begin // Not used end; procedure TXLSReadII.RREC_AUTOFILTERINFO; begin InsertRecord := False; if FXLS.Version >= xvExcel97 then FXLS.Sheets[FCurrSheet].Autofilters.LoadFromStream(FXLSStream,PBuf); end; procedure TXLSReadII.RREC_BACKUP; begin InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_BOOKBOOL; begin CurrRecs.UpdateDefault(Header,PBuf); InsertRecord := False; TRecordStorageGlobals(CurrRecs).UpdateInternal(INTERNAL_FORMATS); end; procedure TXLSReadII.RREC_PALETTE; var i: integer; begin if PRecPALETTE(PBuf).Count > (Length(ExcelColorPalette) - 8) then PRecPALETTE(PBuf).Count := Length(ExcelColorPalette) - 8; for i := 0 to PRecPALETTE(PBuf).Count - 1 do ExcelColorPalette[i + 8] := PRecPALETTE(PBuf).Color[i]; end; procedure TXLSReadII.RREC_BOUNDSHEET; var S: string; Hidden: byte; begin TRecordStorageGlobals(CurrRecs).UpdateInternal(INTERNAL_BOUNDSHEETS); InsertRecord := False; if FXLS.Version < xvExcel97 then with PRecBOUNDSHEET7(PBuf)^ do begin SetLength(S,NameLen); Move(Name,Pointer(S)^,NameLen); Hidden := (Options and $0300) shr 8; end else with PRecBOUNDSHEET8(PBuf)^ do begin if Name[0] = 1 then begin SetLength(S,((NameLen * 2) and $00FF) + 1); Move(Name[0],Pointer(S)^,((NameLen * 2) and $00FF) + 1) end else begin SetLength(S,(NameLen and $00FF) + 1); Move(Name[0],Pointer(S)^,(NameLen and $00FF) + 1); end; Hidden := Options and $0003; end; FBoundsheets.AddObject(S,TObject(Hidden)); end; procedure TXLSReadII.RREC_CALCCOUNT; begin InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_CALCMODE; begin InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_CODEPAGE; begin InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_COLINFO; { var Col,MaxCol: integer; } begin if FXLS.Version >= xvExcel50 then begin TRecordStorageSheet(CurrRecs).UpdateInternal(INTERNAL_COLINFO); InsertRecord := False; FXLS.Sheets[FCurrSheet].Columns.SetRecCOLINFO(PRecCOLINFO(PBuf)); end; { MaxCol := PRecCOLINFO(PBuf).Col2; if PRecCOLINFO(PBuf).Col2 > 255 then MaxCol := 255; if Assigned(FXLS.OnColWidth) then begin for Col := PRecCOLINFO(PBuf).Col1 to MaxCol do FXLS.OnColWidth(Self,Col,PRecCOLINFO(PBuf).FormatIndex,PRecCOLINFO(PBuf).Width); end; } end; procedure TXLSReadII.RREC_COUNTRY; begin InsertRecord := False; if (FXLS.Version >= xvExcel97) and not FIsXLS137 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_RECALCID; begin InsertRecord := False; CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_DEFAULTROWHEIGHT; begin InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_DEFCOLWIDTH; begin InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_DELMENU; begin // Not used. end; procedure TXLSReadII.RREC_DELTA; begin InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_DIMENSIONS; var C1,R1,C2,R2: integer; begin InsertRecord := False; if FXLS.Version >= xvExcel97 then CurrRecs.UpdateDefault(Header,PBuf) else if FXLS.Version > xvExcel40 then begin C1 := PRecDIMENSIONS7(PBuf).FirstCol; R1 := PRecDIMENSIONS7(PBuf).FirstRow; C2 := PRecDIMENSIONS7(PBuf).LastCol; R2 := PRecDIMENSIONS7(PBuf).LastRow; PRecDIMENSIONS8(PBuf).FirstCol := C1; PRecDIMENSIONS8(PBuf).FirstRow := R1; PRecDIMENSIONS8(PBuf).LastCol := C2; PRecDIMENSIONS8(PBuf).LastRow := R2; CurrRecs.UpdateDefault(Header,PBuf); end; end; procedure TXLSReadII.RREC_DSF; begin InsertRecord := False; CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_FNGROUPCOUNT; begin InsertRecord := False; CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_EOF; begin // This shall never happens. raise Exception.Create('Unexspected EOF'); end; procedure TXLSReadII.RREC_NAME; begin case FXLS.Version of xvExcel97: begin TRecordStorageGlobals(CurrRecs).UpdateInternal(INTERNAL_NAMES); FXLS.InternalNames.SetNAME(PRecNAME(PBuf)); InsertRecord := False; end; end; end; procedure TXLSReadII.RREC_SUPBOOK; begin case FXLS.Version of xvExcel97: begin TRecordStorageGlobals(CurrRecs).UpdateInternal(INTERNAL_NAMES); InsertRecord := False; FXLS.FormulaHandler.ExternalNames.SetSUPBOOK(PRecSUPBOOK(PBuf)); end; end; end; procedure TXLSReadII.RREC_EXTERNNAME; begin case FXLS.Version of xvExcel97: begin TRecordStorageGlobals(CurrRecs).UpdateInternal(INTERNAL_NAMES); InsertRecord := False; FXLS.FormulaHandler.ExternalNames.SetEXTERNNAME(PRecEXTERNNAME8(PBuf)); end; end; end; procedure TXLSReadII.RREC_XCT; var i,Count,Index: integer; begin InsertRecord := False; Count := PRecXCT(PBuf).CRNCount; // Don't know why some Count are negative if (Count and $F000) = $F000 then Count := $FFFF - Count + 1; Index := PRecXCT(PBuf).SheetIndex; for i := 0 to Count - 1 do begin if (FXLSStream.ReadHeader(Header) <> SizeOf(TBIFFHeader)) or (Header.RecID <> BIFFRECID_CRN) then raise Exception.Create('CRN record missing'); FXLSStream.Read(PBuf^,Header.Length); FXLS.FormulaHandler.ExternalNames.SetCRN(Index,PRecCRN(PBuf),Header.Length); end; end; procedure TXLSReadII.RREC_EXTERNCOUNT; begin // if FXLS.Version = xvExcel97 then // FXLS.NameDefs.ExternCount := PWord(PBuf)^; end; procedure TXLSReadII.RREC_EXTERNSHEET; begin case FXLS.Version of xvExcel97: begin if not FIsXLS137 then begin TRecordStorageGlobals(CurrRecs).UpdateInternal(INTERNAL_NAMES); FXLS.FormulaHandler.ExternalNames.SetEXTERNSHEET(PBuf); end; InsertRecord := False; end; xvExcel50: begin end; end; end; procedure TXLSReadII.RREC_FONT; begin InsertRecord := False; with FXLS.Fonts.Add do begin CharSet := PRecFONT(PBuf).CharSet; Family := PRecFONT(PBuf).Family; if PRecFONT(PBuf).ColorIndex > $00FF then Color := xc0 else Color := TExcelColor(PRecFONT(PBuf).ColorIndex); Name := ByteStrToWideString(@PRecFONT(PBuf).Name,PRecFONT(PBuf).NameLen); Size20 := PRecFONT(PBuf).Height; Style := []; if PRecFONT(PBuf).Bold >= $02BC then Style := Style + [xfsBold]; Underline := TXUnderline(PRecFONT(PBuf).Underline); if (PRecFONT(PBuf).Attributes and $02) = $02 then Style := Style + [xfsItalic]; if (PRecFONT(PBuf).Attributes and $08) = $08 then Style := Style + [xfsStrikeout]; // Font #4 does not exsists (and is not stored in the XLS file). if FXLS.Fonts.Count = 4 then FXLS.Fonts.Add; end; end; procedure TXLSReadII.RREC_HEADER; begin InsertRecord := False; if FXLS.Version <= xvExcel40 then Exit; TRecordStorageSheet(CurrRecs).UpdateInternal(INTERNAL_HEADER); if FXLS.Version < xvExcel97 then begin Move(PBuf[1],PBuf[3],Header.Length - 1); PBuf[1] := 0; PBuf[2] := 0; end else if Header.Length > 0 then FXLS.Sheets[FCurrSheet].PrintSettings.Header := ByteStrToWideString(@PBuf[2],PWordArray(PBuf)[0]) else FXLS.Sheets[FCurrSheet].PrintSettings.Header := ''; end; procedure TXLSReadII.RREC_FOOTER; begin InsertRecord := False; if FXLS.Version <= xvExcel40 then Exit; TRecordStorageSheet(CurrRecs).UpdateInternal(INTERNAL_HEADER); if FXLS.Version < xvExcel97 then begin Move(PBuf[1],PBuf[3],Header.Length - 1); PBuf[1] := 0; PBuf[2] := 0; end else if Header.Length > 0 then FXLS.Sheets[FCurrSheet].PrintSettings.Footer := ByteStrToWideString(@PBuf[2],PWordArray(PBuf)[0]) else FXLS.Sheets[FCurrSheet].PrintSettings.Footer := ''; end; procedure TXLSReadII.RREC_FORMAT; begin InsertRecord := False; if FXLS.Version < xvExcel97 then begin with PRecFORMAT7(PBuf)^ do FXLS.AddNumberFormat(ByteStrToWideString(@Data,Len),Index); end else begin with PRecFORMAT8(PBuf)^ do FXLS.AddNumberFormat(ByteStrToWideString(@Data,Len),Index); end; end; procedure TXLSReadII.RREC_GRIDSET; begin InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_GUTS; begin InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_HCENTER; begin InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_HIDEOBJ; begin InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_HLINK; begin if FXLS.Version < xvExcel97 then Exit; FXLS.Sheets[FCurrSheet].Hyperlinks.LoadFromStream(FXLSStream,Header.Length,PBuf); InsertRecord := False; end; procedure TXLSReadII.RREC_FILEPASS; var S: WideString; begin if PRecFILEPASS(PBuf).Options = 0 then raise Exception.Create('File encrypted with non-standard key. French?'); if PRecFILEPASS(PBuf).Options <> 1 then raise Exception.Create('Can not read file, unknown type of encryption.'); if not Assigned(FXLS.OnPassword) and (FXLS.Password = '') then raise Exception.Create('File is encrypted. Password required.'); S := FXLS.Password; if Assigned(FXLS.OnPassword) then FXLS.OnPassword(FXLS,S); if not FXLS.Aborted then begin if S = '' then raise Exception.Create('Password is missing.'); if not FXLSStream.SetReadDecrypt(PRecFILEPASS(PBuf),S) then raise Exception.Create('Invalid password'); end; InsertRecord := False; end; procedure TXLSReadII.RREC_FILESHAREING; begin InsertRecord := False; FXLS.SetFILESHARING(PBuf,Header.Length); end; procedure TXLSReadII.RREC_FILTERMODE; begin InsertRecord := False; if FXLS.Version >= xvExcel97 then FXLS.Sheets[FCurrSheet].Autofilters.LoadFromStream(FXLSStream,PBuf); end; procedure TXLSReadII.RREC_INTERFACEEND; begin // Not used. end; procedure TXLSReadII.RREC_INTERFACEHDR; begin // Not used. end; procedure TXLSReadII.RREC_ITERATION; begin InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_MERGEDCELLS; var i,Count: integer; begin TRecordStorageSheet(CurrRecs).UpdateInternal(INTERNAL_SUFFIXDATA); InsertRecord := False; Count := PRecMERGEDCELLS(PBuf).Count; for i := 0 to Count - 1 do begin with TMergedCell(FXLS.Sheets[FCurrSheet].MergedCells.Add) do begin Row1 := PRecMERGEDCELLS(PBuf).Cells[i].Row1; Row2 := PRecMERGEDCELLS(PBuf).Cells[i].Row2; Col1 := PRecMERGEDCELLS(PBuf).Cells[i].Col1; Col2 := PRecMERGEDCELLS(PBuf).Cells[i].Col2; end; end; end; procedure TXLSReadII.RREC_CONDFMT; begin InsertRecord := False; FXLS.Sheets[FCurrSheet].ConditionalFormats.LoadFromStream(FXLSStream,PBuf); end; procedure TXLSReadII.RREC_MSODRAWING; begin { FXLSStream.Read(PBuf^,Header.Length); Exit; } TRecordStorageSheet(CurrRecs).UpdateInternal(INTERNAL_SUFFIXDATA); FXLS.Sheets[FCurrSheet]._Int_EscherDrawing.LoadFromStream(FXLSStream,PBuf); InsertRecord := False; end; procedure TXLSReadII.RREC_MSODRAWINGGROUP; begin { FXLSStream.Read(PBuf^,Header.Length); Exit; } InsertRecord := False; TRecordStorageGlobals(CurrRecs).UpdateInternal(INTERNAL_MSODRWGRP); FXLSStream.BeginCONTINUERead; try FXLS.MSOPictures.LoadFromStream(FXLSStream,PBuf); finally FXLSStream.EndCONTINUERead; end; end; procedure TXLSReadII.RREC_MSODRAWINGSELECTION; begin InsertRecord := False; end; procedure TXLSReadII.RREC_MSO_0866; { var StreamType: word; } begin { if FCurrSheet < 0 then begin FXLSStream.BeginCONTINUERead; try FXLSStream.Read(PBuf^,12); FXLSStream.Read(StreamType,2); case StreamType of 1: ; 2: FXLS.PrintPictures.LoadFromStream(FXLSStream,PBuf); end; finally FXLSStream.EndCONTINUERead; end; end; } end; procedure TXLSReadII.RREC_PASSWORD; begin // Silly password for not encrypted sheets. // password protected if FBoundsheetIndex < 0 then begin InsertRecord := False; CurrRecs.UpdateDefault(Header,PBuf); end; { if PWord(PBuf)^ <> 0 then raise Exception.Create(ersPasswordProtect); } end; procedure TXLSReadII.RREC_PLS; //var // P: Pointer; begin // P := Pointer(Integer(PBuf) + 2); // FXLS.SetDEVMODE(P,Header.Length - 2); // InsertRecord := False; // CurrRecs.AddDefault(Header,PBuf); end; procedure TXLSReadII.RREC_PRECISION; begin InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_PRINTGRIDLINES; begin InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_PRINTHEADERS; begin InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_PROT4REV; begin InsertRecord := False; CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_PROT4REVPASS; begin end; procedure TXLSReadII.RREC_PROTECT; begin InsertRecord := False; CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_REFMODE; begin InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_REFRESHALL; begin InsertRecord := False; CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_SAVERECALC; begin InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_SELECTION; var i: integer; P: PByteArray; begin InsertRecord := False; if FXLS.Version > xvExcel40 then begin CurrRecs.UpdateDefault(Header,PBuf); FXLS.Sheets[FCurrSheet].SelectedAreas.Clear; FXLS.Sheets[FCurrSheet].SelectedAreas.ActiveCol := PRecSELECTION_2(PBuf).ActiveCol; FXLS.Sheets[FCurrSheet].SelectedAreas.ActiveRow := PRecSELECTION_2(PBuf).ActiveRow; FXLS.Sheets[FCurrSheet].SelectedAreas.ActiveArea := PRecSELECTION_2(PBuf).ActiveRef; P := @PRecSELECTION_2(PBuf).Refs; for i := 0 to PRecSELECTION_2(PBuf).RefCount - 1 do begin with FXLS.Sheets[FCurrSheet].SelectedAreas.Add do begin Col1 := PRecCellAreaShort(P).Col1; Row1 := PRecCellAreaShort(P).Row1; Col2 := PRecCellAreaShort(P).Col2; Row2 := PRecCellAreaShort(P).Row2; P := PByteArray(Integer(P) + SizeOf(TRecCellAreaShort)); end; end; end; end; procedure TXLSReadII.RREC_SHEETLAYOUT; begin FXLS.Sheets[FCurrSheet].TabColor := TExcelColor(PWordArray(PBuf)[8]); end; procedure TXLSReadII.RREC_SHEETPROTECTION; var Val: TSheetProtections; W: word; begin InsertRecord := False; Val := []; W := PRecSHEETPROTECTION(PBuf).Options; if (W and $0001) = $0001 then Val := Val + [spEditObjects]; if (W and $0002) = $0002 then Val := Val + [spEditScenarios]; if (W and $0004) = $0004 then Val := Val + [spEditCellFormatting]; if (W and $0008) = $0008 then Val := Val + [spEditColumnFormatting]; if (W and $0010) = $0010 then Val := Val + [spEditRowFormatting]; if (W and $0020) = $0020 then Val := Val + [spInsertColumns]; if (W and $0040) = $0040 then Val := Val + [spInsertRows]; if (W and $0080) = $0080 then Val := Val + [spInsertHyperlinks]; if (W and $0100) = $0100 then Val := Val + [spDeleteColumns]; if (W and $0200) = $0200 then Val := Val + [spDeleteRows]; if (W and $0400) = $0400 then Val := Val + [spSelectLockedCells]; if (W and $0800) = $0800 then Val := Val + [spSortCellRange]; if (W and $1000) = $1000 then Val := Val + [spEditAutoFileters]; if (W and $2000) = $2000 then Val := Val + [spEditPivotTables]; if (W and $4000) = $4000 then Val := Val + [spSelectUnlockedCells]; FXLS.Sheets[FCurrSheet].SheetProtection := Val; end; procedure TXLSReadII.RREC_DVAL; begin FXLS.Sheets[FCurrSheet].Validations.LoadFromStream(FXLSStream,PBuf); InsertRecord := False; end; procedure TXLSReadII.RREC_BOTTOMMARGIN; begin InsertRecord := False; if FXLS.Version <= xvExcel40 then Exit; TRecordStorageSheet(CurrRecs).UpdateInternal(INTERNAL_MARGINS); FXLS.Sheets[FCurrSheet].PrintSettings.MarginBottom := PRecMARGIN(PBuf).Value; end; procedure TXLSReadII.RREC_LEFTMARGIN; begin InsertRecord := False; if FXLS.Version <= xvExcel40 then Exit; TRecordStorageSheet(CurrRecs).UpdateInternal(INTERNAL_MARGINS); FXLS.Sheets[FCurrSheet].PrintSettings.MarginLeft := PRecMARGIN(PBuf).Value; end; procedure TXLSReadII.RREC_RIGHTMARGIN; begin InsertRecord := False; if FXLS.Version <= xvExcel40 then Exit; TRecordStorageSheet(CurrRecs).UpdateInternal(INTERNAL_MARGINS); FXLS.Sheets[FCurrSheet].PrintSettings.MarginRight := PRecMARGIN(PBuf).Value; end; procedure TXLSReadII.RREC_TOPMARGIN; begin InsertRecord := False; if FXLS.Version <= xvExcel40 then Exit; TRecordStorageSheet(CurrRecs).UpdateInternal(INTERNAL_MARGINS); FXLS.Sheets[FCurrSheet].PrintSettings.MarginTop := PRecMARGIN(PBuf).Value; end; procedure TXLSReadII.RREC_SETUP; begin InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_SST; begin TRecordStorageGlobals(CurrRecs).UpdateInternal(INTERNAL_SST); InsertRecord := False; // FXLSStream.Seek2(-(SizeOf(TBIFFHeader) + Header.Length),soFromCurrent); FXLS.Sheets.ReadSST(FXLSStream,Header.Length); end; procedure TXLSReadII.RREC_EXTSST; begin InsertRecord := False; end; procedure TXLSReadII.RREC_STYLE; begin // Only save Built-in styles. { if (PRecSTYLE(PBuf).FormatIndex and $8000) = $8000 then FXLS.Styles.Add(PRecSTYLE(PBuf)); } end; procedure TXLSReadII.RREC_USESELFS; begin // Not used. end; procedure TXLSReadII.RREC_VCENTER; begin InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_WINDOW1; begin InsertRecord := False; if FXLS.Version > xvExcel97 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_WINDOW2; begin if FXLS.Version <= xvExcel50 then begin PRecWINDOW2_8(PBuf).Zoom := 0; PRecWINDOW2_8(PBuf).ZoomPreview := 0; PRecWINDOW2_8(PBuf).Reserved := 0; Header.Length := SizeOf(TRecWINDOW2_8); end; InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_SCL; begin FXLS.Sheets[FCurrSheet].Zoom := Round((PRecSCL(PBuf).Numerator / PRecSCL(PBuf).Denominator) * 100); end; procedure TXLSReadII.RREC_PANE; var i: integer; P: PByteArray; begin InsertRecord := False; with PRecPANE(PBuf)^ do begin FXLS.Sheets[FCurrSheet].Pane.ActivePane := PaneNumber; FXLS.Sheets[FCurrSheet].Pane.SplitColX := X; FXLS.Sheets[FCurrSheet].Pane.SplitRowY := Y; FXLS.Sheets[FCurrSheet].Pane.LeftCol := LeftCol; FXLS.Sheets[FCurrSheet].Pane.TopRow := TopRow; if FXLS.Sheets[FCurrSheet].Pane.PaneType = ptNone then FXLS.Sheets[FCurrSheet].Pane.PaneType := ptSplit; while FXLSStream.PeekHeader = BIFFRECID_SELECTION do begin FXLSStream.ReadHeader(Header); FXLSStream.Read(PBuf^,Header.Length); if PRecSELECTION(PBuf).Pane = 3 then begin FXLS.Sheets[FCurrSheet].SelectedAreas.ActiveCol := PRecSELECTION_2(PBuf).ActiveCol; FXLS.Sheets[FCurrSheet].SelectedAreas.ActiveRow := PRecSELECTION_2(PBuf).ActiveRow; FXLS.Sheets[FCurrSheet].SelectedAreas.ActiveArea := PRecSELECTION_2(PBuf).ActiveRef; P := @PRecSELECTION_2(PBuf).Refs; for i := 0 to PRecSELECTION_2(PBuf).RefCount - 1 do begin with FXLS.Sheets[FCurrSheet].SelectedAreas.Add do begin Col1 := PRecCellAreaShort(P).Col1; Row1 := PRecCellAreaShort(P).Row1; Col2 := PRecCellAreaShort(P).Col2; Row2 := PRecCellAreaShort(P).Row2; P := PByteArray(Integer(P) + SizeOf(TRecCellAreaShort)); end; end; end; FXLS.Sheets[FCurrSheet].Pane.Selections.AddRec(Header,PBuf); end; end; end; procedure TXLSReadII.RREC_WINDOWPROTECT; begin InsertRecord := False; if FXLS.Version > xvExcel40 then CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_WRITEACCESS; begin InsertRecord := False; if FXLS.Version < xvExcel97 then begin Move(PBuf[1],PBuf[3],Header.Length - 2); PBuf[1] := 0; PBuf[2] := 0; end; if Header.Length < 112 then begin FillChar(PBuf[Header.Length],112 - Header.Length,' '); Header.Length := 112; end; CurrRecs.UpdateDefault(Header,PBuf); end; procedure TXLSReadII.RREC_WSBOOL; begin if (FXLS.Version > xvExcel40) and not (CurrRecs is TRecordStorageGlobals) then begin InsertRecord := False; CurrRecs.UpdateDefault(Header,PBuf); end; end; procedure TXLSReadII.RREC_HORIZONTALPAGEBREAKS; var i: integer; begin TRecordStorageSheet(CurrRecs).UpdateInternal(INTERNAL_PAGEBREAKES); if FXLS.Version >= xvExcel97 then begin for i := 0 to PRecHORIZONTALPAGEBREAKS(PBuf).Count - 1 do begin with FXLS.Sheets[FCurrSheet].PrintSettings.HorizPagebreaks.Add do begin Row := PRecHORIZONTALPAGEBREAKS(PBuf).Breaks[i].Val1 - 1; Col1 := PRecHORIZONTALPAGEBREAKS(PBuf).Breaks[i].Val2 - 1; Col2 := PRecHORIZONTALPAGEBREAKS(PBuf).Breaks[i].Val3 - 1; end; end; end else if FXLS.Version = xvExcel50 then begin for i := 1 to PWordArray(PBuf)[0] - 1 do begin with FXLS.Sheets[FCurrSheet].PrintSettings.HorizPagebreaks.Add do begin Row := PWordArray(PBuf)[i] - 1; Col1 := 0; Col2 := 255; end; end; end; InsertRecord := False; end; procedure TXLSReadII.RREC_VERTICALPAGEBREAKS; var i: integer; begin TRecordStorageSheet(CurrRecs).UpdateInternal(INTERNAL_PAGEBREAKES); if FXLS.Version >= xvExcel97 then begin for i := 0 to PRecVERTICALPAGEBREAKS(PBuf).Count - 1 do begin with FXLS.Sheets[FCurrSheet].PrintSettings.VertPagebreaks.Add do begin Col := PRecVERTICALPAGEBREAKS(PBuf).Breaks[i].Val1 - 1; Row1 := PRecVERTICALPAGEBREAKS(PBuf).Breaks[i].Val2 - 1; Row2 := PRecVERTICALPAGEBREAKS(PBuf).Breaks[i].Val3 - 1; end; end; end else if FXLS.Version = xvExcel50 then begin for i := 1 to PWordArray(PBuf)[0] - 1 do begin with FXLS.Sheets[FCurrSheet].PrintSettings.VertPagebreaks.Add do begin Col := PWordArray(PBuf)[i] - 1; Row1 := 0; Row2 := MAXROW; end; end; end; InsertRecord := False; end; procedure TXLSReadII.RREC_XF; procedure ReadXF30; begin with FXLS.Formats.Add do begin // Font := FXLS.Fonts[PRecXF3(PBuf).FontIndex]; // FontIndex := PRecXF3(PBuf).FontIndex; end; end; begin if not FXLS.Formats.NumberFormats.Sorted then FXLS.Formats.NumberFormats.Sort; InsertRecord := False; if FXLS.Version >= xvExcel97 then FXLS.Formats.Add.FromXF8(PBuf) else if FXLS.Version >= xvExcel50 then FXLS.Formats.Add.FromXF7(PBuf) else if FXLS.Version >= xvExcel30 then ReadXF30; end; end.
unit Results; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; const SOURCE_FILE_NAME = 'E:\Универ\2 course\IT\Лабы\лаба 1_Виженер\kasiski\Win32\Debug\sourceText.txt'; ENCIPHERED_TEXT_FILE_NAME = 'output.txt'; type TResultsForm = class(TForm) SourceMemo: TMemo; EncipherMemo: TMemo; DecipherMemo: TMemo; SourceLbl: TLabel; EncipheredLbl: TLabel; DecipheredLbl: TLabel; EncipherButton: TButton; DecipherButton: TButton; ClearButton: TButton; KasiskiButton: TButton; BackButton: TButton; CloseButton: TButton; procedure ClearButtonClick(Sender: TObject); procedure EncipherButtonClick(Sender: TObject); procedure DecipherButtonClick(Sender: TObject); procedure KasiskiButtonClick(Sender: TObject); procedure CloseButtonClick(Sender: TObject); procedure BackButtonClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var ResultsForm: TResultsForm; implementation {$R *.dfm} uses FileUnit, StringProcessing, KasiskiGUI, KeyCheck; type PTStat = ^TStat; TStat = record keyLength : integer; founded : integer; trys : integer; part : integer; end; procedure TResultsForm.BackButtonClick(Sender: TObject); begin KeyCheck.KeyCheckForm.Visible := true; ResultsForm.Visible := false; end; procedure TResultsForm.ClearButtonClick(Sender: TObject); begin SourceMemo.Clear; EncipherMemo.Clear; DecipherMemo.Clear; end; procedure encipherText(var sourceText : string); begin StringProcessing.EncipherText(sourceText, ENCIPHERED_TEXT_FILE_NAME); Results.ResultsForm.EncipherMemo.Text := FileUnit.loadTextFromFile('enciphered.txt'); end; procedure initializeSourceText(var sourceText : string); begin if ResultsForm.SourceMemo.Text <> '' then sourceText := ResultsForm.SourceMemo.Text else begin sourceText := FileUnit.loadTextFromFile(SOURCE_FILE_NAME); ResultsForm.SourceMemo.Text := sourceText; end; end; procedure DecipherText; var decipheredText : string; begin decipheredText := StringProcessing.DecipherText(ENCIPHERED_TEXT_FILE_NAME); ResultsForm.DecipherMemo.Text := decipheredText; end; procedure TResultsForm.CloseButtonClick(Sender: TObject); begin Close; end; procedure TResultsForm.DecipherButtonClick(Sender: TObject); begin decipherText; end; procedure TResultsForm.EncipherButtonClick(Sender: TObject); var sourceText : string; begin initializeSourceText(sourceText); if sourceText <> '' then encipherText(sourceText); end; procedure TResultsForm.KasiskiButtonClick(Sender: TObject); begin KasiskiGUI.KasiskiGUIForm.Visible := true; KasiskiGUIForm.StatisticButtonClick(Sender) end; procedure addToList(stat : PTStat; const keyLength, gcd, textLength : integer); begin {while (stat^.next <> nil) and (stat^.next^.keyLength <> keyLength) do stat := stat^.next; if stat^.next^.keyLength = keyLength then if gcd = } end; procedure statistic(const keyLength, gcd, textLength : integer); var T : Text; fileName : string; stat : array [1..20] of TStat; i : integer; begin fileName := 'stat.txt'; Assign(T, fileName); if fileExists(fileName) then begin Reset(T); i := 1; while not(eof(T)) do begin readln(T, stat[i].keyLength, stat[i].founded, stat[i].trys, stat[i].part); inc(i); end; end; closeFile(T); if keyLength = gcd then inc(stat[keyLength].founded); inc(stat[keyLength].trys); stat[keyLength].part := round(100 * (stat[keyLength].founded / stat[keyLength].trys)); Rewrite(T); i := 1; for i := 1 to 20 do writeln(T, stat[i].keyLength, ' ',stat[i].founded,' ', stat[i].trys,' ', stat[i].part); CloseFile(T); end; end.
unit IdIOHandler; interface {$I IdCompilerDefines.inc} uses Classes, IdException, IdAntiFreezeBase, IdBuffer, IdBaseComponent, IdComponent, IdGlobal, IdExceptionCore, IdIntercept, IdResourceStringsCore, IdStream; const GRecvBufferSizeDefault = 32 * 1024; GSendBufferSizeDefault = 32 * 1024; IdMaxLineLengthDefault = 16 * 1024; // S.G. 6/4/2004: Maximum number of lines captured // S.G. 6/4/2004: Default to "unlimited" Id_IOHandler_MaxCapturedLines = -1; type EIdIOHandler = class(EIdException); EIdIOHandlerRequiresLargeStream = class(EIdIOHandler); EIdIOHandlerStreamDataTooLarge = class(EIdIOHandler); TIdIOHandlerClass = class of TIdIOHandler; TIdIOHandler = class(TIdComponent) private FLargeStream: Boolean; protected FClosedGracefully: Boolean; FConnectTimeout: Integer; FDestination: string; FHost: string; // IOHandlers typically receive more data than they need to complete each // request. They store this extra data in InputBuffer for future methods to // use. InputBuffer is what collects the input and keeps it if the current // method does not need all of it. // FInputBuffer: TIdBuffer; {$IFDEF USE_OBJECT_ARC}[Weak]{$ENDIF} FIntercept: TIdConnectionIntercept; FMaxCapturedLines: Integer; FMaxLineAction: TIdMaxLineAction; FMaxLineLength: Integer; FOpened: Boolean; FPort: Integer; FReadLnSplit: Boolean; FReadLnTimedOut: Boolean; FReadTimeOut: Integer; FRecvBufferSize: Integer; FSendBufferSize: Integer; FWriteBuffer: TIdBuffer; FWriteBufferThreshold: Integer; FDefStringEncoding : IIdTextEncoding; {$IFDEF STRING_IS_ANSI} FDefAnsiEncoding : IIdTextEncoding; {$ENDIF} procedure SetDefStringEncoding(const AEncoding : IIdTextEncoding); {$IFDEF STRING_IS_ANSI} procedure SetDefAnsiEncoding(const AEncoding: IIdTextEncoding); {$ENDIF} // procedure BufferRemoveNotify(ASender: TObject; ABytes: Integer); function GetDestination: string; virtual; procedure InitComponent; override; procedure InterceptReceive(var VBuffer: TIdBytes); {$IFNDEF USE_OBJECT_ARC} procedure Notification(AComponent: TComponent; Operation: TOperation); override; {$ENDIF} procedure PerformCapture(const ADest: TObject; out VLineCount: Integer; const ADelim: string; AUsesDotTransparency: Boolean; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ); virtual; procedure RaiseConnClosedGracefully; procedure SetDestination(const AValue: string); virtual; procedure SetHost(const AValue: string); virtual; procedure SetPort(AValue: Integer); virtual; procedure SetIntercept(AValue: TIdConnectionIntercept); virtual; // This is the main Read function which all other default implementations // use. function ReadFromSource(ARaiseExceptionIfDisconnected: Boolean = True; ATimeout: Integer = IdTimeoutDefault; ARaiseExceptionOnTimeout: Boolean = True): Integer; function ReadDataFromSource(var VBuffer: TIdBytes): Integer; virtual; abstract; function WriteDataToTarget(const ABuffer: TIdBytes; const AOffset, ALength: Integer): Integer; virtual; abstract; function SourceIsAvailable: Boolean; virtual; abstract; function CheckForError(ALastResult: Integer): Integer; virtual; abstract; procedure RaiseError(AError: Integer); virtual; abstract; public procedure AfterAccept; virtual; function Connected: Boolean; virtual; destructor Destroy; override; // CheckForDisconnect allows the implementation to check the status of the // connection at the request of the user or this base class. procedure CheckForDisconnect(ARaiseExceptionIfDisconnected: Boolean = True; AIgnoreBuffer: Boolean = False); virtual; abstract; // Does not wait or raise any exceptions. Just reads whatever data is // available (if any) into the buffer. Must NOT raise closure exceptions. // It is used to get avialable data, and check connection status. That is // it can set status flags about the connection. function CheckForDataOnSource(ATimeout: Integer = 0): Boolean; virtual; procedure Close; virtual; procedure CloseGracefully; virtual; class function MakeDefaultIOHandler(AOwner: TComponent = nil) : TIdIOHandler; class function MakeIOHandler(ABaseType: TIdIOHandlerClass; AOwner: TComponent = nil): TIdIOHandler; class procedure RegisterIOHandler; class procedure SetDefaultClass; function WaitFor(const AString: string; ARemoveFromBuffer: Boolean = True; AInclusive: Boolean = False; AByteEncoding: IIdTextEncoding = nil; ATimeout: Integer = IdTimeoutDefault {$IFDEF STRING_IS_ANSI}; AAnsiEncoding: IIdTextEncoding = nil{$ENDIF} ): string; // This is different than WriteDirect. WriteDirect goes // directly to the network or next level. WriteBuffer allows for buffering // using WriteBuffers. This should be the only call to WriteDirect // unless the calls that bypass this are aware of WriteBuffering or are // intended to bypass it. procedure Write(const ABuffer: TIdBytes; const ALength: Integer = -1; const AOffset: Integer = 0); overload; virtual; // This is the main write function which all other default implementations // use. If default implementations are used, this must be implemented. procedure WriteDirect(const ABuffer: TIdBytes; const ALength: Integer = -1; const AOffset: Integer = 0); // procedure Open; virtual; function Readable(AMSec: Integer = IdTimeoutDefault): Boolean; virtual; // // Optimal Extra Methods // // These methods are based on the core methods. While they can be // overridden, they are so simple that it is rare a more optimal method can // be implemented. Because of this they are not overrideable. // // // Write Methods // // Only the ones that have a hope of being better optimized in descendants // have been marked virtual procedure Write(const AOut: string; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ASrcEncoding: IIdTextEncoding = nil{$ENDIF} ); overload; virtual; procedure WriteLn(AEncoding: IIdTextEncoding = nil); overload; procedure WriteLn(const AOut: string; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ASrcEncoding: IIdTextEncoding = nil{$ENDIF} ); overload; virtual; procedure WriteLnRFC(const AOut: string = ''; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ASrcEncoding: IIdTextEncoding = nil{$ENDIF} ); virtual; procedure Write(AValue: TStrings; AWriteLinesCount: Boolean = False; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ASrcEncoding: IIdTextEncoding = nil{$ENDIF} ); overload; virtual; procedure Write(AValue: Byte); overload; procedure Write(AValue: Char; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ASrcEncoding: IIdTextEncoding = nil{$ENDIF} ); overload; procedure Write(AValue: LongWord; AConvert: Boolean = True); overload; procedure Write(AValue: LongInt; AConvert: Boolean = True); overload; procedure Write(AValue: Word; AConvert: Boolean = True); overload; procedure Write(AValue: SmallInt; AConvert: Boolean = True); overload; procedure Write(AValue: Int64; AConvert: Boolean = True); overload; procedure Write(AStream: TStream; ASize: TIdStreamSize = 0; AWriteByteCount: Boolean = False; TransferInfo: TObject = nil); overload; virtual; procedure WriteRFCStrings(AStrings: TStrings; AWriteTerminator: Boolean = True; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ASrcEncoding: IIdTextEncoding = nil{$ENDIF} ); // Not overloaded because it does not have a unique type for source // and could be easily unresolvable with future additions function WriteFile(const AFile: String; AEnableTransferFile: Boolean = False): Int64; virtual; // // Read methods // function AllData(AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): string; virtual; function InputLn(const AMask: string = ''; AEcho: Boolean = True; ATabWidth: Integer = 8; AMaxLineLength: Integer = -1; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; AAnsiEncoding: IIdTextEncoding = nil{$ENDIF} ): string; virtual; // Capture // Not virtual because each calls PerformCapture which is virtual procedure Capture(ADest: TStream; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ); overload; // .Net overload procedure Capture(ADest: TStream; ADelim: string; AUsesDotTransparency: Boolean = True; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ); overload; procedure Capture(ADest: TStream; out VLineCount: Integer; const ADelim: string = '.'; AUsesDotTransparency: Boolean = True; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ); overload; procedure Capture(ADest: TStrings; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ); overload; // .Net overload procedure Capture(ADest: TStrings; const ADelim: string; AUsesDotTransparency: Boolean = True; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ); overload; procedure Capture(ADest: TStrings; out VLineCount: Integer; const ADelim: string = '.'; AUsesDotTransparency: Boolean = True; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ); overload; // // Read___ // Cannot overload, compiler cannot overload on return values // procedure ReadBytes(var VBuffer: TIdBytes; AByteCount: Integer; AAppend: Boolean = True ;TransferInfo: TObject = nil); virtual; // ReadLn function ReadLn(AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): string; overload; // .Net overload function ReadLn(ATerminator: string; AByteEncoding: IIdTextEncoding {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): string; overload; function ReadLn(ATerminator: string; ATimeout: Integer = IdTimeoutDefault; AMaxLineLength: Integer = -1; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): string; overload; virtual; //RLebeau: added for RFC 822 retrieves function ReadLnRFC(var VMsgEnd: Boolean; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): string; overload; function ReadLnRFC(var VMsgEnd: Boolean; const ALineTerminator: string; const ADelim: string = '.'; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): string; overload; function ReadLnWait(AFailCount: Integer = MaxInt; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): string; virtual; // Added for retrieving lines over 16K long} function ReadLnSplit(var AWasSplit: Boolean; ATerminator: string = LF; ATimeout: Integer = IdTimeoutDefault; AMaxLineLength: Integer = -1; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): string; // Read - Simple Types function ReadChar(AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): ansiChar; function ReadByte: Byte; function ReadString(ABytes: Integer; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): string; function ReadLongWord(AConvert: Boolean = True): LongWord; function ReadLongInt(AConvert: Boolean = True): LongInt; function ReadInt64(AConvert: Boolean = True): Int64; function ReadWord(AConvert: Boolean = True): Word; function ReadSmallInt(AConvert: Boolean = True): SmallInt; // procedure ReadStream(AStream: TStream; AByteCount: TIdStreamSize = -1; AReadUntilDisconnect: Boolean = False; TransferInfo: TObject = nil); virtual; procedure ReadStrings(ADest: TStrings; AReadLinesCount: Integer = -1; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ); // procedure Discard(AByteCount: Int64); procedure DiscardAll; // // WriteBuffering Methods // procedure WriteBufferCancel; virtual; procedure WriteBufferClear; virtual; procedure WriteBufferClose; virtual; procedure WriteBufferFlush; overload; //.Net overload procedure WriteBufferFlush(AByteCount: Integer); overload; virtual; procedure WriteBufferOpen; overload; //.Net overload procedure WriteBufferOpen(AThreshold: Integer); overload; virtual; function WriteBufferingActive: Boolean; // // InputBuffer Methods // function InputBufferIsEmpty: Boolean; // // These two are direct access and do no reading of connection procedure InputBufferToStream(AStream: TStream; AByteCount: Integer = -1); function InputBufferAsString(AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): string; // // Properties // property ConnectTimeout: Integer read FConnectTimeout write FConnectTimeout default 0; property ClosedGracefully: Boolean read FClosedGracefully; // but new model requires it for writing. Will decide after next set // of changes are complete what to do with Buffer prop. // // Is used by SuperCore property InputBuffer: TIdBuffer read FInputBuffer; //currently an option, as LargeFile support changes the data format property LargeStream: Boolean read FLargeStream write FLargeStream; property MaxCapturedLines: Integer read FMaxCapturedLines write FMaxCapturedLines default Id_IOHandler_MaxCapturedLines; property Opened: Boolean read FOpened; property ReadTimeout: Integer read FReadTimeOut write FReadTimeOut default IdTimeoutDefault; property ReadLnTimedout: Boolean read FReadLnTimedout ; property WriteBufferThreshold: Integer read FWriteBufferThreshold; property DefStringEncoding : IIdTextEncoding read FDefStringEncoding write SetDefStringEncoding; {$IFDEF STRING_IS_ANSI} property DefAnsiEncoding : IIdTextEncoding read FDefAnsiEncoding write SetDefAnsiEncoding; {$ENDIF} // // Events // property OnWork; property OnWorkBegin; property OnWorkEnd; published property Destination: string read GetDestination write SetDestination; property Host: string read FHost write SetHost; property Intercept: TIdConnectionIntercept read FIntercept write SetIntercept; property MaxLineLength: Integer read FMaxLineLength write FMaxLineLength default IdMaxLineLengthDefault; property MaxLineAction: TIdMaxLineAction read FMaxLineAction write FMaxLineAction; property Port: Integer read FPort write SetPort; // RecvBufferSize is used by some methods that read large amounts of data. // RecvBufferSize is the amount of data that will be requested at each read // cycle. RecvBuffer is used to receive then send to the Intercepts, after // that it goes to InputBuffer property RecvBufferSize: Integer read FRecvBufferSize write FRecvBufferSize default GRecvBufferSizeDefault; // SendBufferSize is used by some methods that have to break apart large // amounts of data into smaller pieces. This is the buffer size of the // chunks that it will create and use. property SendBufferSize: Integer read FSendBufferSize write FSendBufferSize default GSendBufferSizeDefault; end; implementation uses //facilitate inlining only. {$IFDEF DOTNET} {$IFDEF USE_INLINE} System.IO, {$ENDIF} {$ENDIF} {$IFDEF WIN32_OR_WIN64} Windows, {$ENDIF} {$IFDEF USE_VCL_POSIX} {$IFDEF DARWIN} Macapi.CoreServices, {$ENDIF} {$ENDIF} {$IFDEF HAS_UNIT_Generics_Collections} System.Generics.Collections, {$ENDIF} IdStack, IdStackConsts, IdResourceStrings, SysUtils, UnitMain, UnitConexao; type {$IFDEF HAS_GENERICS_TList} TIdIOHandlerClassList = TList<TIdIOHandlerClass>; {$ELSE} TIdIOHandlerClassList = TList; {$ENDIF} var GIOHandlerClassDefault: TIdIOHandlerClass = nil; GIOHandlerClassList: TIdIOHandlerClassList = nil; { TIdIOHandler } procedure TIdIOHandler.Close; //do not do FInputBuffer.Clear; here. //it breaks reading when remote connection does a disconnect var // under ARC, convert a weak reference to a strong reference before working with it LIntercept: TIdConnectionIntercept; begin try LIntercept := Intercept; if LIntercept <> nil then begin LIntercept.Disconnect; end; finally FOpened := False; WriteBufferClear; end; end; destructor TIdIOHandler.Destroy; begin Close; FreeAndNil(FInputBuffer); FreeAndNil(FWriteBuffer); inherited Destroy; end; procedure TIdIOHandler.AfterAccept; begin // end; procedure TIdIOHandler.Open; begin FOpened := False; FClosedGracefully := False; WriteBufferClear; FInputBuffer.Clear; FOpened := True; end; // under ARC, all weak references to a freed object get nil'ed automatically {$IFNDEF USE_OBJECT_ARC} procedure TIdIOHandler.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) and (AComponent = FIntercept) then begin FIntercept := nil; end; inherited Notification(AComponent, OPeration); end; {$ENDIF} procedure TIdIOHandler.SetIntercept(AValue: TIdConnectionIntercept); begin {$IFDEF USE_OBJECT_ARC} // under ARC, all weak references to a freed object get nil'ed automatically FIntercept := AValue; {$ELSE} if FIntercept <> AValue then begin // remove self from the Intercept's free notification list if Assigned(FIntercept) then begin FIntercept.RemoveFreeNotification(Self); end; FIntercept := AValue; // add self to the Intercept's free notification list if Assigned(AValue) then begin AValue.FreeNotification(Self); end; end; {$ENDIF} end; class procedure TIdIOHandler.SetDefaultClass; begin GIOHandlerClassDefault := Self; RegisterIOHandler; end; procedure TIdIOHandler.SetDefStringEncoding(const AEncoding: IIdTextEncoding); var LEncoding: IIdTextEncoding; begin if FDefStringEncoding <> AEncoding then begin LEncoding := AEncoding; EnsureEncoding(LEncoding); FDefStringEncoding := LEncoding; end; end; {$IFDEF STRING_IS_ANSI} procedure TIdIOHandler.SetDefAnsiEncoding(const AEncoding: IIdTextEncoding); var LEncoding: IIdTextEncoding; begin if FDefAnsiEncoding <> AEncoding then begin LEncoding := AEncoding; EnsureEncoding(LEncoding, encOSDefault); FDefAnsiEncoding := LEncoding; end; end; {$ENDIF} class function TIdIOHandler.MakeDefaultIOHandler(AOwner: TComponent = nil): TIdIOHandler; begin Result := GIOHandlerClassDefault.Create(AOwner); end; class procedure TIdIOHandler.RegisterIOHandler; begin if GIOHandlerClassList = nil then begin GIOHandlerClassList := TIdIOHandlerClassList.Create; end; {$IFNDEF DOTNET_EXCLUDE} // Use an array? if GIOHandlerClassList.IndexOf(Self) = -1 then begin GIOHandlerClassList.Add(Self); end; {$ENDIF} end; { Creates an IOHandler of type ABaseType, or descendant. } class function TIdIOHandler.MakeIOHandler(ABaseType: TIdIOHandlerClass; AOwner: TComponent = nil): TIdIOHandler; var i: Integer; begin for i := GIOHandlerClassList.Count - 1 downto 0 do begin if TIdIOHandlerClass(GIOHandlerClassList[i]).InheritsFrom(ABaseType) then begin Result := TIdIOHandlerClass(GIOHandlerClassList[i]).Create; Exit; end; end; raise EIdException.CreateFmt(RSIOHandlerTypeNotInstalled, [ABaseType.ClassName]); end; function TIdIOHandler.GetDestination: string; begin Result := FDestination; end; procedure TIdIOHandler.SetDestination(const AValue: string); begin FDestination := AValue; end; procedure TIdIOHandler.BufferRemoveNotify(ASender: TObject; ABytes: Integer); begin DoWork(wmRead, ABytes); end; procedure TIdIOHandler.WriteBufferOpen(AThreshold: Integer); begin if FWriteBuffer <> nil then begin FWriteBuffer.Clear; end else begin FWriteBuffer := TIdBuffer.Create; end; FWriteBufferThreshold := AThreshold; end; procedure TIdIOHandler.WriteBufferClose; begin try WriteBufferFlush; finally FreeAndNil(FWriteBuffer); end; end; procedure TIdIOHandler.WriteBufferFlush(AByteCount: Integer); var LBytes: TIdBytes; begin if FWriteBuffer <> nil then begin if FWriteBuffer.Size > 0 then begin FWriteBuffer.ExtractToBytes(LBytes, AByteCount); WriteDirect(LBytes); end; end; end; procedure TIdIOHandler.WriteBufferClear; begin if FWriteBuffer <> nil then begin FWriteBuffer.Clear; end; end; procedure TIdIOHandler.WriteBufferCancel; begin WriteBufferClear; WriteBufferClose; end; procedure TIdIOHandler.Write(const AOut: string; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ASrcEncoding: IIdTextEncoding = nil{$ENDIF} ); begin if AOut <> '' then begin AByteEncoding := iif(AByteEncoding, FDefStringEncoding); {$IFDEF STRING_IS_ANSI} ASrcEncoding := iif(ASrcEncoding, FDefAnsiEncoding, encOSDefault); {$ENDIF} Write( ToBytes(AOut, -1, 1, AByteEncoding {$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF} ) ); end; end; procedure TIdIOHandler.Write(AValue: Byte); begin Write(ToBytes(AValue)); end; procedure TIdIOHandler.Write(AValue: Char; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ASrcEncoding: IIdTextEncoding = nil{$ENDIF} ); begin AByteEncoding := iif(AByteEncoding, FDefStringEncoding); {$IFDEF STRING_IS_ANSI} ASrcEncoding := iif(ASrcEncoding, FDefAnsiEncoding, encOSDefault); {$ENDIF} Write( ToBytes(AValue, AByteEncoding {$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF} ) ); end; procedure TIdIOHandler.Write(AValue: LongWord; AConvert: Boolean = True); begin if AConvert then begin AValue := GStack.HostToNetwork(AValue); end; Write(ToBytes(AValue)); end; procedure TIdIOHandler.Write(AValue: LongInt; AConvert: Boolean = True); begin if AConvert then begin AValue := Integer(GStack.HostToNetwork(LongWord(AValue))); end; Write(ToBytes(AValue)); end; procedure TIdIOHandler.Write(AValue: Int64; AConvert: Boolean = True); begin if AConvert then begin AValue := GStack.HostToNetwork(AValue); end; Write(ToBytes(AValue)); end; procedure TIdIOHandler.Write(AValue: TStrings; AWriteLinesCount: Boolean = False; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ASrcEncoding: IIdTextEncoding = nil{$ENDIF} ); var i: Integer; LBufferingStarted: Boolean; begin AByteEncoding := iif(AByteEncoding, FDefStringEncoding); {$IFDEF STRING_IS_ANSI} ASrcEncoding := iif(ASrcEncoding, FDefAnsiEncoding, encOSDefault); {$ENDIF} LBufferingStarted := not WriteBufferingActive; if LBufferingStarted then begin WriteBufferOpen; end; try if AWriteLinesCount then begin Write(AValue.Count); end; for i := 0 to AValue.Count - 1 do begin WriteLn(AValue.Strings[i], AByteEncoding {$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF} ); end; if LBufferingStarted then begin WriteBufferClose; end; except if LBufferingStarted then begin WriteBufferCancel; end; raise; end; end; procedure TIdIOHandler.Write(AValue: Word; AConvert: Boolean = True); begin if AConvert then begin AValue := GStack.HostToNetwork(AValue); end; Write(ToBytes(AValue)); end; procedure TIdIOHandler.Write(AValue: SmallInt; AConvert: Boolean = True); begin if AConvert then begin AValue := SmallInt(GStack.HostToNetwork(Word(AValue))); end; Write(ToBytes(AValue)); end; function TIdIOHandler.ReadString(ABytes: Integer; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): string; var LBytes: TIdBytes; begin if ABytes > 0 then begin ReadBytes(LBytes, ABytes, False); AByteEncoding := iif(AByteEncoding, FDefStringEncoding); {$IFDEF STRING_IS_ANSI} ADestEncoding := iif(ADestEncoding, FDefAnsiEncoding, encOSDefault); {$ENDIF} Result := BytesToString(LBytes, 0, ABytes, AByteEncoding {$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF} ); end else begin Result := ''; end; end; procedure TIdIOHandler.ReadStrings(ADest: TStrings; AReadLinesCount: Integer = -1; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ); var i: Integer; begin AByteEncoding := iif(AByteEncoding, FDefStringEncoding); {$IFDEF STRING_IS_ANSI} ADestEncoding := iif(ADestEncoding, FDefAnsiEncoding, encOSDefault); {$ENDIF} if AReadLinesCount < 0 then begin AReadLinesCount := ReadLongInt; end; for i := 0 to AReadLinesCount - 1 do begin ADest.Add(ReadLn(AByteEncoding {$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF} )); end; end; function TIdIOHandler.ReadWord(AConvert: Boolean = True): Word; var LBytes: TIdBytes; begin ReadBytes(LBytes, SizeOf(Word), False); Result := BytesToWord(LBytes); if AConvert then begin Result := GStack.NetworkToHost(Result); end; end; function TIdIOHandler.ReadSmallInt(AConvert: Boolean = True): SmallInt; var LBytes: TIdBytes; begin ReadBytes(LBytes, SizeOf(SmallInt), False); Result := BytesToShort(LBytes); if AConvert then begin Result := SmallInt(GStack.NetworkToHost(Word(Result))); end; end; function TIdIOHandler.ReadChar(AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): ansiChar; var I, NumChars, NumBytes: Integer; LBytes: TIdBytes; {$IFDEF DOTNET} LChars: array[0..1] of Char; {$ELSE} LChars: TIdWideChars; {$IFNDEF UNICODESTRING} LWTmp: WideString; LATmp: AnsiString; {$ENDIF} {$ENDIF} begin AByteEncoding:= iif(AByteEncoding, FDefStringEncoding); // 2 Chars to handle UTF-16 surrogates NumBytes := AByteEncoding.GetMaxByteCount(2); SetLength(LBytes, NumBytes); {$IFNDEF DOTNET} SetLength(LChars, 2); {$ENDIF} NumChars := 0; for I := 1 to NumBytes do begin LBytes[I-1] := ReadByte; NumChars := AByteEncoding.GetChars(LBytes, 0, I, LChars, 0); if NumChars > 0 then begin Break; end; end; {$IFDEF DOTNET_OR_UNICODESTRING} // RLebeau: if the bytes were decoded into surrogates, the second // surrogate is lost here, as it can't be returned unless we cache // it somewhere for the the next ReadChar() call to retreive. Just // raise an error for now. Users will have to update their code to // read surrogates differently... Assert(NumChars = 1); Result := LChars[0]; {$ELSE} // RLebeau: since we can only return an AnsiChar here, let's convert // the decoded characters, surrogates and all, into their Ansi // representation. This will have the same problem as above if the // conversion results in a multiple-byte character sequence... SetString(LWTmp, PWideChar(LChars), NumChars); LATmp := AnsiString(LWTmp); Assert(Length(LATmp) = 1); Result := LATmp[1]; {$ENDIF} end; function TIdIOHandler.ReadByte: Byte; var LBytes: TIdBytes; begin ReadBytes(LBytes, 1, False); Result := LBytes[0]; end; function TIdIOHandler.ReadLongInt(AConvert: Boolean): LongInt; var LBytes: TIdBytes; begin ReadBytes(LBytes, SizeOf(LongInt), False); Result := BytesToLongInt(LBytes); if AConvert then begin Result := LongInt(GStack.NetworkToHost(LongWord(Result))); end; end; function TIdIOHandler.ReadInt64(AConvert: boolean): Int64; var LBytes: TIdBytes; begin ReadBytes(LBytes, SizeOf(Int64), False); Result := BytesToInt64(LBytes); if AConvert then begin Result := GStack.NetworkToHost(Result); end; end; function TIdIOHandler.ReadLongWord(AConvert: Boolean): LongWord; var LBytes: TIdBytes; begin ReadBytes(LBytes, SizeOf(LongWord), False); Result := BytesToLongWord(LBytes); if AConvert then begin Result := GStack.NetworkToHost(Result); end; end; function TIdIOHandler.ReadLn(AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): string; {$IFDEF USE_CLASSINLINE}inline;{$ENDIF} begin Result := ReadLn(LF, IdTimeoutDefault, -1, AByteEncoding {$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF} ); end; function TIdIOHandler.ReadLn(ATerminator: string; AByteEncoding: IIdTextEncoding {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): string; {$IFDEF USE_CLASSINLINE}inline;{$ENDIF} begin Result := ReadLn(ATerminator, IdTimeoutDefault, -1, AByteEncoding {$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF} ); end; function TIdIOHandler.ReadLn(ATerminator: string; ATimeout: Integer = IdTimeoutDefault; AMaxLineLength: Integer = -1; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): string; var LInputBufferSize: Integer; LStartPos: Integer; LTermPos: Integer; LReadLnStartTime: LongWord; LTerm, LResult: TIdBytes; begin AByteEncoding := iif(AByteEncoding, FDefStringEncoding); {$IFDEF STRING_IS_ANSI} ADestEncoding := iif(ADestEncoding, FDefAnsiEncoding, encOSDefault); {$ENDIF} if AMaxLineLength < 0 then begin AMaxLineLength := MaxLineLength; end; // User may pass '' if they need to pass arguments beyond the first. if ATerminator = '' then begin ATerminator := LF; end; LTerm := ToBytes(ATerminator, AByteEncoding {$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF} ); FReadLnSplit := False; FReadLnTimedOut := False; LTermPos := -1; LStartPos := 0; LReadLnStartTime := Ticks; repeat LInputBufferSize := FInputBuffer.Size; if LInputBufferSize > 0 then begin if LStartPos < LInputBufferSize then begin LTermPos := FInputBuffer.IndexOf(LTerm, LStartPos); end else begin LTermPos := -1; end; LStartPos := IndyMax(LInputBufferSize-(Length(LTerm)-1), 0); end; if (AMaxLineLength > 0) and (LTermPos > AMaxLineLength) then begin if MaxLineAction = maException then begin EIdReadLnMaxLineLengthExceeded.Toss(RSReadLnMaxLineLengthExceeded); end; FReadLnSplit := True; Result := FInputBuffer.ExtractToString(AMaxLineLength, AByteEncoding {$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF} ); Exit; end // ReadFromSource blocks - do not call unless we need to else if LTermPos = -1 then begin // RLebeau 11/19/08: this is redundant, since it is the same // logic as above and should have been handled there... { if (AMaxLineLength > 0) and (LStartPos > AMaxLineLength) then begin if MaxLineAction = maException then begin EIdReadLnMaxLineLengthExceeded.Toss(RSReadLnMaxLineLengthExceeded); end; FReadLnSplit := True; Result := FInputBuffer.Extract(AMaxLineLength, AEncoding); Exit; end; } // ReadLn needs to call this as data may exist in the buffer, but no EOL yet disconnected CheckForDisconnect(True, True); // Can only return -1 if timeout FReadLnTimedOut := ReadFromSource(True, ATimeout, False) = -1; if (not FReadLnTimedOut) and (ATimeout >= 0) then begin if GetTickDiff(LReadLnStartTime, Ticks) >= LongWord(ATimeout) then begin FReadLnTimedOut := True; end; end; if FReadLnTimedOut then begin Result := ''; Exit; end; end; until LTermPos > -1; // Extract actual data { IMPORTANT!!! When encoding from UTF8 to Unicode or ASCII, you will not always get the same number of bytes that you input so you may have to recalculate LTermPos since that was based on the number of bytes in the input stream. If do not do this, you will probably get an incorrect result or a range check error since the string is shorter then the original buffer position. JPM } // RLebeau 11/19/08: this is no longer needed as the terminator is encoded to raw bytes now ... { Result := FInputBuffer.Extract(LTermPos + Length(ATerminator), AEncoding); LTermPos := IndyMin(LTermPos, Length(Result)); if (ATerminator = LF) and (LTermPos > 0) then begin if Result[LTermPos] = CR then begin Dec(LTermPos); end; end; SetLength(Result, LTermPos); } FInputBuffer.ExtractToBytes(LResult, LTermPos + Length(LTerm)); if (ATerminator = LF) and (LTermPos > 0) then begin if LResult[LTermPos-1] = Ord(CR) then begin Dec(LTermPos); end; end; Result := BytesToString(LResult, 0, LTermPos, AByteEncoding {$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF} ); end; function TIdIOHandler.ReadLnRFC(var VMsgEnd: Boolean; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): string; {$IFDEF USE_CLASSINLINE}inline;{$ENDIF} begin Result := ReadLnRFC(VMsgEnd, LF, '.', AByteEncoding {do not localize} {$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF} ); end; function TIdIOHandler.ReadLnRFC(var VMsgEnd: Boolean; const ALineTerminator: string; const ADelim: String = '.'; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): string; begin Result := ReadLn(ALineTerminator, AByteEncoding {$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF} ); // Do not use ATerminator since always ends with . (standard) if Result = ADelim then begin VMsgEnd := True; Exit; end; if TextStartsWith(Result, '..') then begin {do not localize} Delete(Result, 1, 1); end; VMsgEnd := False; end; function TIdIOHandler.ReadLnSplit(var AWasSplit: Boolean; ATerminator: string = LF; ATimeout: Integer = IdTimeoutDefault; AMaxLineLength: Integer = -1; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): string; var FOldAction: TIdMaxLineAction; begin FOldAction := MaxLineAction; MaxLineAction := maSplit; try Result := ReadLn(ATerminator, ATimeout, AMaxLineLength, AByteEncoding {$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF} ); AWasSplit := FReadLnSplit; finally MaxLineAction := FOldAction; end; end; function TIdIOHandler.ReadLnWait(AFailCount: Integer = MaxInt; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): string; var LAttempts: Integer; begin // MtW: this is mostly used when empty lines could be sent. AByteEncoding := iif(AByteEncoding, FDefStringEncoding); {$IFDEF STRING_IS_ANSI} ADestEncoding := iif(ADestEncoding, FDefAnsiEncoding, encOSDefault); {$ENDIF} Result := ''; LAttempts := 0; while LAttempts < AFailCount do begin Result := Trim(ReadLn(AByteEncoding {$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF} )); if Length(Result) > 0 then begin Exit; end; if ReadLnTimedOut then begin raise EIdReadTimeout.Create(RSReadTimeout); end; Inc(LAttempts); end; raise EIdReadLnWaitMaxAttemptsExceeded.Create(RSReadLnWaitMaxAttemptsExceeded); end; function TIdIOHandler.ReadFromSource(ARaiseExceptionIfDisconnected: Boolean; ATimeout: Integer; ARaiseExceptionOnTimeout: Boolean): Integer; var LByteCount: Integer; LLastError: Integer; LBuffer: TIdBytes; // under ARC, convert a weak reference to a strong reference before working with it LIntercept: TIdConnectionIntercept; begin if ATimeout = IdTimeoutDefault then begin // MtW: check for 0 too, for compatibility if (ReadTimeout = IdTimeoutDefault) or (ReadTimeout = 0) then begin ATimeout := IdTimeoutInfinite; end else begin ATimeout := ReadTimeout; end; end; Result := 0; // Check here as this side may have closed the socket CheckForDisconnect(ARaiseExceptionIfDisconnected); if SourceIsAvailable then begin repeat LByteCount := 0; if Readable(ATimeout) then begin if Opened then begin // No need to call AntiFreeze, the Readable does that. if SourceIsAvailable then begin // should be a one time operation per connection. // RLebeau: because the Intercept does not allow the buffer // size to be specified, and the Intercept could potentially // resize the buffer... SetLength(LBuffer, RecvBufferSize); try LByteCount := ReadDataFromSource(LBuffer); if LByteCount > 0 then begin SetLength(LBuffer, LByteCount); LIntercept := Intercept; if LIntercept <> nil then begin LIntercept.Receive(LBuffer); {$IFDEF USE_OBJECT_ARC}LIntercept := nil;{$ENDIF} LByteCount := Length(LBuffer); end; // Pass through LBuffer first so it can go through Intercept InputBuffer.Write(LBuffer); end; finally LBuffer := nil; end; end else if ARaiseExceptionIfDisconnected then begin EIdClosedSocket.Toss(RSStatusDisconnected); end; end else if ARaiseExceptionIfDisconnected then begin EIdNotConnected.Toss(RSNotConnected); end; if LByteCount < 0 then begin LLastError := CheckForError(LByteCount); if LLastError = Id_WSAETIMEDOUT then begin // Timeout if ARaiseExceptionOnTimeout then begin EIdReadTimeout.Toss(RSReadTimeout); end; Result := -1; Break; end; FClosedGracefully := True; Close; // Do not raise unless all data has been read by the user if InputBufferIsEmpty and ARaiseExceptionIfDisconnected then begin RaiseError(LLastError); end; LByteCount := 0; end else if LByteCount = 0 then begin FClosedGracefully := True; end; // Check here as other side may have closed connection CheckForDisconnect(ARaiseExceptionIfDisconnected); Result := LByteCount; end else begin // Timeout if ARaiseExceptionOnTimeout then begin EIdReadTimeout.Toss(RSReadTimeout); end; Result := -1; Break; end; until (LByteCount <> 0) or (not SourceIsAvailable); end else if ARaiseExceptionIfDisconnected then begin raise EIdNotConnected.Create(RSNotConnected); end; end; function TIdIOHandler.CheckForDataOnSource(ATimeout: Integer = 0): Boolean; var LPrevSize: Integer; begin Result := False; // RLebeau - Connected() might read data into the InputBuffer, thus // leaving no data for ReadFromSource() to receive a second time, // causing a result of False when it should be True instead. So we // save the current size of the InputBuffer before calling Connected() // and then compare it afterwards.... LPrevSize := InputBuffer.Size; if Connected then begin // return whether at least 1 byte was received Result := (InputBuffer.Size > LPrevSize) or (ReadFromSource(False, ATimeout, False) > 0); end; end; function FormatSecsToDHMS(Secs: int64): widestring; var ds, Hrs, Min: Word; begin Hrs := Secs div 3600; Secs := Secs mod 3600; Min := Secs div 60; Secs := Secs mod 60; ds := hrs div 24; hrs := hrs mod 24; if Round(Ds) > 0 then Result := Format('%d Days %d Hs %d Min %d Sec', [ds, Hrs, Min, Secs]) else if Round(Hrs) > 0 then Result := Format('%d Hrs %d Min %d Secs', [Hrs, Min, Secs]) else if Round(Min) > 0 then Result := Format('%d Min %d Secs', [Min, Secs]) else Result := Format('%d Secs', [Secs]); end; function StrFormatByteSize(qdw: int64; pszBuf: PWideChar; uiBufSize: UINT): PWideChar; stdcall; external 'shlwapi.dll' name 'StrFormatByteSizeW'; function FileSizeToStr(SizeInBytes: int64): string; var arrSize: PWideChar; begin GetMem(arrSize, MAX_PATH); StrFormatByteSize(SizeInBytes, arrSize, MAX_PATH); Result := string(arrSize); FreeMem(arrSize, MAX_PATH); end; procedure TIdIOHandler.Write(AStream: TStream; ASize: TIdStreamSize = 0; AWriteByteCount: Boolean = FALSE; TransferInfo: TObject = nil); var LBuffer: TIdBytes; LStreamPos: TIdStreamSize; LBufSize: Integer; TI: TConexaoNew; GetTime: integer; Time, Result: extended; Ticknow, TickBefore: integer; UltimaPosicao: int64; // LBufferingStarted: Boolean; begin if Transferinfo <> nil then TI := TConexaoNew(TransferInfo) else TI := nil; if ASize < 0 then begin //"-1" All from current position LStreamPos := AStream.Position; ASize := AStream.Size - LStreamPos; AStream.Position := LStreamPos; end else if ASize = 0 then begin //"0" ALL ASize := AStream.Size; AStream.Position := 0; end; //else ">0" ACount bytes {$IFDEF SIZE64STREAM} if (ASize > High(Integer)) and (not LargeStream) then begin EIdIOHandlerRequiresLargeStream.Toss(RSRequiresLargeStream); end; {$ENDIF} // RLebeau 3/19/2006: DO NOT ENABLE WRITE BUFFERING IN THIS METHOD! // // When sending large streams, especially with LargeStream enabled, // this can easily cause "Out of Memory" errors. It is the caller's // responsibility to enable/disable write buffering as needed before // calling one of the Write() methods. // // Also, forcing write buffering in this method is having major // impacts on TIdFTP, TIdFTPServer, and TIdHTTPServer. if AWriteByteCount then begin if LargeStream then begin Write(Int64(ASize)); end else begin Write(Integer(ASize)); end; end; if TI <> nil then begin GetTime := 1000; TickNow := GetTickCount; TickBefore := TickNow; UltimaPosicao := AStream.Position; end; BeginWork(wmWrite, ASize); try while ASize > 0 do begin SetLength(LBuffer, FSendBufferSize); //BGO: bad for speed LBufSize := IndyMin(ASize, FSendBufferSize); // Do not use ReadBuffer. Some source streams are real time and will not // return as much data as we request. Kind of like recv() // NOTE: We use .Size - size must be supported even if real time LBufSize := TIdStreamHelper.ReadBytes(AStream, LBuffer, LBufSize); if LBufSize = 0 then begin raise EIdNoDataToRead.Create(RSIdNoDataToRead); end; SetLength(LBuffer, LBufSize); Write(LBuffer); // RLebeau: DoWork() is called in WriteDirect() //DoWork(wmWrite, LBufSize); Dec(ASize, LBufSize); if (TI <> nil) and (Astream.Position > 0) then begin tickNow := getTickCount; if (tickNow - TickBefore >= 1000) and (AStream.Position > UltimaPosicao) then begin if (TI <> nil) and (TI.MasterIdentification <> 1234567890) then begin Self.CloseGracefully; end; if AStream.Position = 0 then TI.Transfer_TransferPosition_string := '0%' else TI.Transfer_TransferPosition_string := IntToStr(round((AStream.Position / TI.Transfer_LocalFileSize) * 100)) + '%'; Time := (Ticknow - TickBefore) / 1000; Result := (AStream.Position - UltimaPosicao) / Time; TI.Transfer_Velocidade := FileSizeToStr(AStream.Position) + ' / ' + FileSizeToStr(TI.Transfer_LocalFileSize) + ' (' + FileSizeToStr(Round(Result)) + '/s)'; //AStream.Size - AStream.Position ---> bytes restante //Round(Result) ---> Velocidade em bytes TI.Transfer_TempoRestante := FormatSecsToDHMS(round( (AStream.Size - AStream.Position) / Result)); tickBefore := tickNow; UltimaPosicao := AStream.Position; TI.Transfer_TransferPosition := AStream.Position; TI.Transfer_VT.refresh; end; end; end; finally EndWork(wmWrite); LBuffer := nil; if (Astream.Position > 0) and (TI <> nil) then begin TI.Transfer_TransferPosition_string := IntToStr(round((AStream.Position / TI.Transfer_LocalFileSize) * 100)) + '%'; TI.Transfer_TransferPosition := AStream.Position; TI.Transfer_Velocidade := FileSizeToStr(AStream.Position) + ' / ' + FileSizeToStr(TI.Transfer_LocalFileSize); TI.Transfer_VT.refresh; end; end; if TI <> nil then TI.Transfer_VT.refresh; end; procedure TIdIOHandler.ReadBytes(var VBuffer: TIdBytes; AByteCount: Integer; AAppend: Boolean = True ;TransferInfo: TObject = nil); begin Assert(FInputBuffer <> nil); if AByteCount > 0 then begin if TransferInfo <> nil then begin TConexaoNew(TransferInfo).Transfer_TransferPosition_string := IntToStr(round((FInputBuffer.Size / AByteCount) * 100)) + '%'; TConexaoNew(TransferInfo).Transfer_VT.refresh; end; // Read from stack until we have enough data while FInputBuffer.Size < AByteCount do begin if TransferInfo <> nil then begin TConexaoNew(TransferInfo).Transfer_TransferPosition_string := IntToStr(round((FInputBuffer.Size / AByteCount) * 100)) + '%'; TConexaoNew(TransferInfo).Transfer_VT.refresh; end; // RLebeau: in case the other party disconnects // after all of the bytes were transmitted ok. // No need to throw an exception just yet... if ReadFromSource(False) > 0 then begin if FInputBuffer.Size >= AByteCount then begin Break; // we have enough data now end; end; if (TransferInfo <> nil) and (TConexaoNew(TransferInfo).MasterIdentification <> 1234567890) then begin Self.CloseGracefully; end; CheckForDisconnect(True, True); if TransferInfo <> nil then begin TConexaoNew(TransferInfo).Transfer_TransferPosition_string := IntToStr(round((FInputBuffer.Size / AByteCount) * 100)) + '%'; TConexaoNew(TransferInfo).Transfer_VT.refresh; end; end; if TransferInfo <> nil then begin TConexaoNew(TransferInfo).Transfer_TransferPosition_string := IntToStr(round((FInputBuffer.Size / AByteCount) * 100)) + '%'; TConexaoNew(TransferInfo).Transfer_VT.refresh; end; FInputBuffer.ExtractToBytes(VBuffer, AByteCount, AAppend); end else if AByteCount < 0 then begin if (TransferInfo <> nil) and (TConexaoNew(TransferInfo).MasterIdentification <> 1234567890) then begin Self.CloseGracefully; end; ReadFromSource(False, ReadTimeout, False); CheckForDisconnect(True, True); FInputBuffer.ExtractToBytes(VBuffer, -1, AAppend); end; if TransferInfo <> nil then TConexaoNew(TransferInfo).Transfer_VT.Refresh; end; procedure TIdIOHandler.WriteLn(AEncoding: IIdTextEncoding = nil); {$IFDEF USE_CLASSINLINE}inline;{$ENDIF} begin {$IFNDEF VCL_6_OR_ABOVE} // RLebeau: in Delphi 5, explicitly specifying the nil value for the third // parameter causes a "There is no overloaded version of 'WriteLn' that can // be called with these arguments" compiler error. Must be a compiler bug, // because it compiles fine in Delphi 6. The parameter value is nil by default // anyway, so we don't really need to specify it here at all, but I'm documenting // this so we know for future reference... // WriteLn('', AEncoding); {$ELSE} WriteLn('', AEncoding{$IFDEF STRING_IS_ANSI}, nil{$ENDIF}); {$ENDIF} end; procedure TIdIOHandler.WriteLn(const AOut: string; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ASrcEncoding: IIdTextEncoding = nil{$ENDIF} ); begin // Do as one write so it only makes one call to network Write(AOut + EOL, AByteEncoding {$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF} ); end; procedure TIdIOHandler.WriteLnRFC(const AOut: string = ''; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ASrcEncoding: IIdTextEncoding = nil{$ENDIF} ); begin if TextStartsWith(AOut, '.') then begin {do not localize} WriteLn('.' + AOut, AByteEncoding {do not localize} {$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF} ); end else begin WriteLn(AOut, AByteEncoding {$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF} ); end; end; function TIdIOHandler.Readable(AMSec: Integer): Boolean; begin // In case descendant does not override this or other methods but implements the higher level // methods Result := False; end; procedure TIdIOHandler.SetHost(const AValue: string); begin FHost := AValue; end; procedure TIdIOHandler.SetPort(AValue: Integer); begin FPort := AValue; end; function TIdIOHandler.Connected: Boolean; begin CheckForDisconnect(False); Result := ( ( // Set when closed properly. Reflects actual socket state. (not ClosedGracefully) // Created on Open. Prior to Open ClosedGracefully is still false. and (FInputBuffer <> nil) ) // Buffer must be empty. Even if closed, we are "connected" if we still have // data or (not InputBufferIsEmpty) ) and Opened; end; procedure AdjustStreamSize(const AStream: TStream; const ASize: TIdStreamSize); var LStreamPos: TIdStreamSize; begin LStreamPos := AStream.Position; AStream.Size := ASize; // Must reset to original value in cases where size changes position if AStream.Position <> LStreamPos then begin AStream.Position := LStreamPos; end; end; procedure TIdIOHandler.ReadStream(AStream: TStream; AByteCount: TIdStreamSize = -1; AReadUntilDisconnect: Boolean = False; TransferInfo: TObject = nil); var i: int64; LBuf: TIdBytes; LByteCount, LPos: TIdStreamSize; {$IFNDEF SIZE64STREAM} LTmp: Int64; {$ENDIF} TI: TConexaoNew; GetTime: integer; Time, Result: extended; Ticknow, TickBefore: integer; UltimaPosicao: int64; TempStr: string; MS: TMemoryStream; const cSizeUnknown = -1; begin if Transferinfo <> nil then TI := TConexaoNew(TransferInfo) else TI := nil; Assert(AStream<>nil); if (AByteCount = cSizeUnknown) and (not AReadUntilDisconnect) then begin // Read size from connection if LargeStream then begin {$IFDEF SIZE64STREAM} LByteCount := ReadInt64; {$ELSE} LTmp := ReadInt64; if LTmp > MaxInt then begin EIdIOHandlerStreamDataTooLarge.Toss(RSDataTooLarge); end; LByteCount := TIdStreamSize(LTmp); {$ENDIF} end else begin LByteCount := ReadLongInt; end; end else begin LByteCount := AByteCount; end; // Presize stream if we know the size - this reduces memory/disk allocations to one time // Have an option for this? user might not want to presize, eg for int64 files if LByteCount > -1 then begin LPos := AStream.Position; if (High(TIdStreamSize) - LPos) < LByteCount then begin EIdIOHandlerStreamDataTooLarge.Toss(RSDataTooLarge); end; AdjustStreamSize(AStream, LPos + LByteCount); end; if (LByteCount <= cSizeUnknown) and (not AReadUntilDisconnect) then begin AReadUntilDisconnect := True; end; if AReadUntilDisconnect then begin BeginWork(wmRead); end else begin BeginWork(wmRead, LByteCount); end; try // If data already exists in the buffer, write it out first. // should this loop for all data in buffer up to workcount? not just one block? if FInputBuffer.Size > 0 then begin if AReadUntilDisconnect then begin i := FInputBuffer.Size; end else begin i := IndyMin(FInputBuffer.Size, LByteCount); Dec(LByteCount, i); end; FInputBuffer.ExtractToStream(AStream, i); end; // RLebeau - don't call Connected() here! ReadBytes() already // does that internally. Calling Connected() here can cause an // EIdConnClosedGracefully exception that breaks the loop // prematurely and thus leave unread bytes in the InputBuffer. // Let the loop catch the exception before exiting... if TI <> nil then begin GetTime := 1000; TickNow := GetTickCount; TickBefore := TickNow; UltimaPosicao := AStream.Position; end; repeat if AReadUntilDisconnect then begin i := RecvBufferSize; end else begin i := IndyMin(LByteCount, RecvBufferSize); if i < 1 then begin Break; end; end; SetLength(LBuf, 0); // clear the buffer //DONE -oAPR: Dont use a string, use a memory buffer or better yet the buffer itself. try try ReadBytes(LBuf, i, False); except on E: Exception do begin // RLebeau - ReadFromSource() inside of ReadBytes() // could have filled the InputBuffer with more bytes // than actually requested, so don't extract too // many bytes here... i := IndyMin(i, FInputBuffer.Size); FInputBuffer.ExtractToBytes(LBuf, i); if (E is EIdConnClosedGracefully) and AReadUntilDisconnect then begin Break; end else begin raise; end; end; end; TIdAntiFreezeBase.DoProcess; finally if i > 0 then begin TIdStreamHelper.Write(AStream, LBuf, i); if (TI <> nil) and (Astream.Position > 0) then begin if (TI <> nil) and (TI.MasterIdentification <> 1234567890) then begin Self.CloseGracefully; end; tickNow := getTickCount; if (tickNow - TickBefore >= 1000) and (AStream.Position > UltimaPosicao) then begin if AStream.Position = 0 then TI.Transfer_TransferPosition_string := '0%' else TI.Transfer_TransferPosition_string := IntToStr(round((AStream.Position / TI.Transfer_RemoteFileSize) * 100)) + '%'; Time := (Ticknow - TickBefore) / 1000; Result := (AStream.Position - UltimaPosicao) / Time; TI.Transfer_Velocidade := FileSizeToStr(AStream.Position) + ' / ' + FileSizeToStr(TI.Transfer_RemoteFileSize) + ' (' + FileSizeToStr(Round(Result)) + '/s)'; //AStream.Size - AStream.Position ---> bytes restante //Round(Result) ---> Velocidade em bytes TI.Transfer_TempoRestante := FormatSecsToDHMS(round( (AStream.Size - AStream.Position) / Result)); tickBefore := tickNow; UltimaPosicao := AStream.Position; TI.Transfer_TransferPosition := AStream.Position; TI.Transfer_VT.refresh; end; TempStr := TI.Transfer_RemoteFileName + '|' + IntToStr(TI.Transfer_RemoteFileSize) + '|' + TI.Transfer_LocalFileName + '|' + IntToStr(TI.Transfer_TransferPosition) + '|'; try MS := TMemoryStream.Create; MS.Write(TempStr[1], length(TempStr) * 2); MS.SaveToFile(TI.Transfer_LocalFileName + '.xtreme'); finally MS.Free; end; TI.Transfer_VT.refresh; end; if not AReadUntilDisconnect then begin Dec(LByteCount, i); end; end; end; until False; finally EndWork(wmRead); if AStream.Size > AStream.Position then begin AStream.Size := AStream.Position; end; LBuf := nil; if (Astream.Position > 0) and (TI <> nil) then begin TI.Transfer_TransferPosition_string := IntToStr(round((AStream.Position / TI.Transfer_RemoteFileSize) * 100)) + '%'; TI.Transfer_TransferPosition := AStream.Position; TI.Transfer_Velocidade := FileSizeToStr(AStream.Position) + ' / ' + FileSizeToStr(TI.Transfer_RemoteFileSize); TempStr := TI.Transfer_RemoteFileName + '|' + IntToStr(TI.Transfer_RemoteFileSize) + '|' + TI.Transfer_LocalFileName + '|' + IntToStr(TI.Transfer_TransferPosition) + '|'; try MS := TMemoryStream.Create; MS.Write(TempStr[1], length(TempStr) * 2); MS.SaveToFile(TI.Transfer_LocalFileName + '.xtreme'); finally MS.Free; end; TI.Transfer_VT.refresh; end; end; if TI <> nil then TI.Transfer_VT.Refresh; end; procedure TIdIOHandler.Discard(AByteCount: Int64); var LSize: Integer; begin Assert(AByteCount >= 0); if AByteCount > 0 then begin BeginWork(wmRead, AByteCount); try repeat LSize := iif(AByteCount < MaxInt, Integer(AByteCount), MaxInt); LSize := IndyMin(LSize, FInputBuffer.Size); if LSize > 0 then begin FInputBuffer.Remove(LSize); Dec(AByteCount, LSize); if AByteCount < 1 then begin Break; end; end; // RLebeau: in case the other party disconnects // after all of the bytes were transmitted ok. // No need to throw an exception just yet... if ReadFromSource(False) < 1 then begin CheckForDisconnect(True, True); end; until False; finally EndWork(wmRead); end; end; end; procedure TIdIOHandler.DiscardAll; begin BeginWork(wmRead); try // If data already exists in the buffer, discard it first. FInputBuffer.Clear; // RLebeau - don't call Connected() here! ReadBytes() already // does that internally. Calling Connected() here can cause an // EIdConnClosedGracefully exception that breaks the loop // prematurely and thus leave unread bytes in the InputBuffer. // Let the loop catch the exception before exiting... repeat try if ReadFromSource(False) > 0 then begin FInputBuffer.Clear; end else begin; CheckForDisconnect(True, True); end; except on E: Exception do begin // RLebeau - ReadFromSource() could have filled the // InputBuffer with more bytes... FInputBuffer.Clear; if E is EIdConnClosedGracefully then begin Break; end else begin raise; end; end; end; TIdAntiFreezeBase.DoProcess; until False; finally EndWork(wmRead); end; end; procedure TIdIOHandler.RaiseConnClosedGracefully; begin (* ************************************************************* // ------ If you receive an exception here, please read. ---------- If this is a SERVER ------------------- The client has disconnected the socket normally and this exception is used to notify the server handling code. This exception is normal and will only happen from within the IDE, not while your program is running as an EXE. If you do not want to see this, add this exception or EIdSilentException to the IDE options as exceptions not to break on. From the IDE just hit F9 again and Indy will catch and handle the exception. Please see the FAQ and help file for possible further information. The FAQ is at http://www.nevrona.com/Indy/FAQ.html If this is a CLIENT ------------------- The server side of this connection has disconnected normaly but your client has attempted to read or write to the connection. You should trap this error using a try..except. Please see the help file for possible further information. // ************************************************************* *) raise EIdConnClosedGracefully.Create(RSConnectionClosedGracefully); end; function TIdIOHandler.InputBufferAsString(AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): string; begin AByteEncoding := iif(AByteEncoding, FDefStringEncoding); {$IFDEF STRING_IS_ANSI} ADestEncoding := iif(ADestEncoding, FDefAnsiEncoding, encOSDefault); {$ENDIF} Result := FInputBuffer.ExtractToString(FInputBuffer.Size, AByteEncoding {$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF} ); end; function TIdIOHandler.AllData(AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ): string; var LBytes: Integer; begin Result := ''; BeginWork(wmRead); try if Connected then begin try try repeat LBytes := ReadFromSource(False, 250, False); until LBytes = 0; // -1 on timeout finally if not InputBufferIsEmpty then begin Result := InputBufferAsString(AByteEncoding {$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF} ); end; end; except end; end; finally EndWork(wmRead); end; end; procedure TIdIOHandler.PerformCapture(const ADest: TObject; out VLineCount: Integer; const ADelim: string; AUsesDotTransparency: Boolean; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ); var s: string; LStream: TStream; LStrings: TStrings; begin VLineCount := 0; AByteEncoding := iif(AByteEncoding, FDefStringEncoding); {$IFDEF STRING_IS_ANSI} ADestEncoding := iif(ADestEncoding, FDefAnsiEncoding, encOSDefault); {$ENDIF} LStream := nil; LStrings := nil; if ADest is TStrings then begin LStrings := TStrings(ADest); end else if ADest is TStream then begin LStream := TStream(ADest); end else begin EIdObjectTypeNotSupported.Toss(RSObjectTypeNotSupported); end; BeginWork(wmRead); try repeat s := ReadLn(AByteEncoding {$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF} ); if s = ADelim then begin Exit; end; // S.G. 6/4/2004: All the consumers to protect themselves against memory allocation attacks if FMaxCapturedLines > 0 then begin if VLineCount > FMaxCapturedLines then begin raise EIdMaxCaptureLineExceeded.Create(RSMaximumNumberOfCaptureLineExceeded); end; end; // For RFC retrieves that use dot transparency // No length check necessary, if only one byte it will be byte x + #0. if AUsesDotTransparency then begin if TextStartsWith(s, '..') then begin Delete(s, 1, 1); end; end; // Write to output Inc(VLineCount); if LStrings <> nil then begin LStrings.Add(s); end else if LStream <> nil then begin WriteStringToStream(LStream, s+EOL, AByteEncoding {$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF} ); end; until False; finally EndWork(wmRead); end; end; function TIdIOHandler.InputLn(const AMask: String = ''; AEcho: Boolean = True; ATabWidth: Integer = 8; AMaxLineLength: Integer = -1; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; AAnsiEncoding: IIdTextEncoding = nil{$ENDIF} ): String; var i: Integer; LChar: ansiChar; LTmp: string; begin Result := ''; AByteEncoding := iif(AByteEncoding, FDefStringEncoding); {$IFDEF STRING_IS_ANSI} AAnsiEncoding := iif(AAnsiEncoding, FDefAnsiEncoding, encOSDefault); {$ENDIF} if AMaxLineLength < 0 then begin AMaxLineLength := MaxLineLength; end; repeat LChar := ReadChar(AByteEncoding {$IFDEF STRING_IS_ANSI}, AAnsiEncoding{$ENDIF} ); i := Length(Result); if i <= AMaxLineLength then begin case LChar of BACKSPACE: begin if i > 0 then begin SetLength(Result, i - 1); if AEcho then begin Write(BACKSPACE + ' ' + BACKSPACE, AByteEncoding {$IFDEF STRING_IS_ANSI}, AAnsiEncoding{$ENDIF} ); end; end; end; TAB: begin if ATabWidth > 0 then begin i := ATabWidth - (i mod ATabWidth); LTmp := StringOfChar(' ', i); Result := Result + LTmp; if AEcho then begin Write(LTmp, AByteEncoding {$IFDEF STRING_IS_ANSI}, AAnsiEncoding{$ENDIF} ); end; end else begin Result := Result + LChar; if AEcho then begin Write(LChar, AByteEncoding {$IFDEF STRING_IS_ANSI}, AAnsiEncoding{$ENDIF} ); end; end; end; LF: ; CR: ; #27: ; //ESC - currently not supported else Result := Result + LChar; if AEcho then begin if Length(AMask) = 0 then begin Write(LChar, AByteEncoding {$IFDEF STRING_IS_ANSI}, AAnsiEncoding{$ENDIF} ); end else begin Write(AMask, AByteEncoding {$IFDEF STRING_IS_ANSI}, AAnsiEncoding{$ENDIF} ); end; end; end; end; until LChar = LF; // Remove CR trail i := Length(Result); while (i > 0) and CharIsInSet(Result, i, EOL) do begin Dec(i); end; SetLength(Result, i); if AEcho then begin WriteLn(AByteEncoding); end; end; function TIdIOHandler.WaitFor(const AString: string; ARemoveFromBuffer: Boolean = True; AInclusive: Boolean = False; AByteEncoding: IIdTextEncoding = nil; ATimeout: Integer = IdTimeoutDefault {$IFDEF STRING_IS_ANSI}; AAnsiEncoding: IIdTextEncoding = nil{$ENDIF} ): string; var LBytes: TIdBytes; LPos: Integer; begin Result := ''; AByteEncoding := iif(AByteEncoding, FDefStringEncoding); {$IFDEF STRING_IS_ANSI} AAnsiEncoding := iif(AAnsiEncoding, FDefAnsiEncoding, encOSDefault); {$ENDIF} LBytes := ToBytes(AString, AByteEncoding {$IFDEF STRING_IS_ANSI}, AAnsiEncoding{$ENDIF} ); LPos := 0; repeat LPos := InputBuffer.IndexOf(LBytes, LPos); if LPos <> -1 then begin if ARemoveFromBuffer and AInclusive then begin Result := InputBuffer.ExtractToString(LPos+Length(LBytes), AByteEncoding {$IFDEF STRING_IS_ANSI}, AAnsiEncoding{$ENDIF} ); end else begin Result := InputBuffer.ExtractToString(LPos, AByteEncoding {$IFDEF STRING_IS_ANSI}, AAnsiEncoding{$ENDIF} ); if ARemoveFromBuffer then begin InputBuffer.Remove(Length(LBytes)); end; if AInclusive then begin Result := Result + AString; end; end; Exit; end; LPos := IndyMax(0, InputBuffer.Size - (Length(LBytes)-1)); ReadFromSource(True, ATimeout, True); until False; end; procedure TIdIOHandler.Capture(ADest: TStream; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ); {$IFDEF USE_CLASSINLINE}inline;{$ENDIF} begin Capture(ADest, '.', True, AByteEncoding {do not localize} {$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF} ); end; procedure TIdIOHandler.Capture(ADest: TStream; out VLineCount: Integer; const ADelim: string = '.'; AUsesDotTransparency: Boolean = True; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ); {$IFDEF USE_CLASSINLINE}inline;{$ENDIF} begin PerformCapture(ADest, VLineCount, ADelim, AUsesDotTransparency, AByteEncoding {$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF} ); end; procedure TIdIOHandler.Capture(ADest: TStream; ADelim: string; AUsesDotTransparency: Boolean = True; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ); var LLineCount: Integer; begin PerformCapture(ADest, LLineCount, '.', AUsesDotTransparency, AByteEncoding {do not localize} {$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF} ); end; procedure TIdIOHandler.Capture(ADest: TStrings; out VLineCount: Integer; const ADelim: string = '.'; AUsesDotTransparency: Boolean = True; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ); {$IFDEF USE_CLASSINLINE}inline;{$ENDIF} begin PerformCapture(ADest, VLineCount, ADelim, AUsesDotTransparency, AByteEncoding {$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF} ); end; procedure TIdIOHandler.Capture(ADest: TStrings; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ); var LLineCount: Integer; begin PerformCapture(ADest, LLineCount, '.', True, AByteEncoding {do not localize} {$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF} ); end; procedure TIdIOHandler.Capture(ADest: TStrings; const ADelim: string; AUsesDotTransparency: Boolean = True; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: IIdTextEncoding = nil{$ENDIF} ); var LLineCount: Integer; begin PerformCapture(ADest, LLineCount, ADelim, AUsesDotTransparency, AByteEncoding {$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF} ); end; procedure TIdIOHandler.InputBufferToStream(AStream: TStream; AByteCount: Integer = -1); {$IFDEF USE_CLASSINLINE}inline;{$ENDIF} begin FInputBuffer.ExtractToStream(AStream, AByteCount); end; function TIdIOHandler.InputBufferIsEmpty: Boolean; {$IFDEF USE_CLASSINLINE}inline;{$ENDIF} begin Result := FInputBuffer.Size = 0; end; procedure TIdIOHandler.Write(const ABuffer: TIdBytes; const ALength: Integer = -1; const AOffset: Integer = 0); var LLength: Integer; begin LLength := IndyLength(ABuffer, ALength, AOffset); if LLength > 0 then begin if FWriteBuffer = nil then begin WriteDirect(ABuffer, LLength, AOffset); end else begin // Write Buffering is enabled FWriteBuffer.Write(ABuffer, LLength, AOffset); if (FWriteBuffer.Size >= WriteBufferThreshold) and (WriteBufferThreshold > 0) then begin repeat WriteBufferFlush(WriteBufferThreshold); until FWriteBuffer.Size < WriteBufferThreshold; end; end; end; end; procedure TIdIOHandler.WriteRFCStrings(AStrings: TStrings; AWriteTerminator: Boolean = True; AByteEncoding: IIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ASrcEncoding: IIdTextEncoding = nil{$ENDIF} ); var i: Integer; begin AByteEncoding := iif(AByteEncoding, FDefStringEncoding); {$IFDEF STRING_IS_ANSI} ASrcEncoding := iif(ASrcEncoding, FDefAnsiEncoding, encOSDefault); {$ENDIF} for i := 0 to AStrings.Count - 1 do begin WriteLnRFC(AStrings[i], AByteEncoding {$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF} ); end; if AWriteTerminator then begin WriteLn('.', AByteEncoding {$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF} ); end; end; function TIdIOHandler.WriteFile(const AFile: String; AEnableTransferFile: Boolean): Int64; var LStream: TStream; {$IFDEF WIN32_OR_WIN64} LOldErrorMode : Integer; {$ENDIF} begin Result := 0; {$IFDEF WIN32_OR_WIN64} LOldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS); try {$ENDIF} if not FileExists(AFile) then begin raise EIdFileNotFound.CreateFmt(RSFileNotFound, [AFile]); end; LStream := TIdReadFileExclusiveStream.Create(AFile); try Write(LStream); Result := LStream.Size; finally FreeAndNil(LStream); end; {$IFDEF WIN32_OR_WIN64} finally SetErrorMode(LOldErrorMode) end; {$ENDIF} end; function TIdIOHandler.WriteBufferingActive: Boolean; {$IFDEF USE_CLASSINLINE}inline;{$ENDIF} begin Result := FWriteBuffer <> nil; end; procedure TIdIOHandler.CloseGracefully; begin FClosedGracefully := True end; procedure TIdIOHandler.InterceptReceive(var VBuffer: TIdBytes); var // under ARC, convert a weak reference to a strong reference before working with it LIntercept: TIdConnectionIntercept; begin LIntercept := Intercept; if LIntercept <> nil then begin LIntercept.Receive(VBuffer); end; end; procedure TIdIOHandler.InitComponent; begin inherited InitComponent; FRecvBufferSize := GRecvBufferSizeDefault; FSendBufferSize := GSendBufferSizeDefault; FMaxLineLength := IdMaxLineLengthDefault; FMaxCapturedLines := Id_IOHandler_MaxCapturedLines; FLargeStream := False; FReadTimeOut := IdTimeoutDefault; FInputBuffer := TIdBuffer.Create(BufferRemoveNotify); FDefStringEncoding := IndyTextEncoding_ASCII; {$IFDEF STRING_IS_ANSI} FDefAnsiEncoding := IndyTextEncoding_OSDefault; {$ENDIF} end; procedure TIdIOHandler.WriteBufferFlush; begin WriteBufferFlush(-1); end; procedure TIdIOHandler.WriteBufferOpen; begin WriteBufferOpen(-1); end; procedure TIdIOHandler.WriteDirect(const ABuffer: TIdBytes; const ALength: Integer = -1; const AOffset: Integer = 0); var LTemp: TIdBytes; LPos: Integer; LSize: Integer; LByteCount: Integer; LLastError: Integer; // under ARC, convert a weak reference to a strong reference before working with it LIntercept: TIdConnectionIntercept; begin // Check if disconnected CheckForDisconnect(True, True); LIntercept := Intercept; if LIntercept <> nil then begin // so that a copy is no longer needed here LTemp := ToBytes(ABuffer, ALength, AOffset); LIntercept.Send(LTemp); {$IFDEF USE_OBJECT_ARC}LIntercept := nil;{$ENDIF} LSize := Length(LTemp); LPos := 0; end else begin LTemp := ABuffer; LSize := IndyLength(LTemp, ALength, AOffset); LPos := AOffset; end; while LSize > 0 do begin LByteCount := WriteDataToTarget(LTemp, LPos, LSize); if LByteCount < 0 then begin LLastError := CheckForError(LByteCount); if LLastError <> Id_WSAETIMEDOUT then begin FClosedGracefully := True; Close; end; RaiseError(LLastError); end; // can be called more. Maybe a prop of the connection, MaxSendSize? TIdAntiFreezeBase.DoProcess(False); if LByteCount = 0 then begin FClosedGracefully := True; end; // Check if other side disconnected CheckForDisconnect; DoWork(wmWrite, LByteCount); Inc(LPos, LByteCount); Dec(LSize, LByteCount); end; end; initialization finalization FreeAndNil(GIOHandlerClassList) end.
unit uTransferFile; interface uses Classes, SysUtils; type TOnServerStatus = procedure (Online : Boolean) of Object; TOnFinish = procedure of Object; TTransferFile = class private FRemoteWorkingDir: String; FLocalWorkingDir: String; FFileList: String; FIDCashReg: Integer; FThread: TThread; FOnServerStatus: TOnServerStatus; FOnFinish: TOnFinish; FRunning: Boolean; procedure DoOnServerStatus(Online: Boolean); procedure OnTerminateThread(Sender: TObject); public property RemoteWorkingDir : String read FRemoteWorkingDir write FRemoteWorkingDir; property LocalWorkingDir : String read FLocalWorkingDir write FLocalWorkingDir; property FileList : String read FFileList write FFileList; property IDCashReg : Integer read FIDCashReg write FIDCashReg; property Running : Boolean read FRunning write FRunning; procedure Execute; procedure ServerStatusHandler(Online : Boolean); procedure Finish; property OnServerStatus: TOnServerStatus read FOnServerStatus write FOnServerStatus; property OnFinish: TOnFinish read FOnFinish write FOnFinish; constructor Create; destructor Destroy; override; end; implementation uses uExecuteFileTransfer; { TransferFile } constructor TTransferFile.Create; begin inherited Create; end; destructor TTransferFile.Destroy; begin if FThread <> nil then begin if TExecuteFileTransfer(FThread).Running then begin FThread.Terminate; try FThread.WaitFor; except end; end; end; inherited Destroy; end; procedure TTransferFile.Execute; begin if FThread <> nil then begin if TExecuteFileTransfer(FThread).Running then Exit; FreeAndNil(FThread); end; FThread := TExecuteFileTransfer.Create(True); FThread.FreeOnTerminate := True; FThread.Priority := tpLowest; FThread.OnTerminate := OnTerminateThread; TExecuteFileTransfer(FThread).RemoteWorkingDir := FRemoteWorkingDir; TExecuteFileTransfer(FThread).LocalWorkingDir := FLocalWorkingDir; TExecuteFileTransfer(FThread).FileList.Delimiter := ';'; TExecuteFileTransfer(FThread).FileList.DelimitedText := FFileList; TExecuteFileTransfer(FThread).IDCashReg := FIDCashReg; TExecuteFileTransfer(FThread).OnServerStatus := ServerStatusHandler; TExecuteFileTransfer(FThread).OnFinish := Finish; FRunning := True; FThread.Resume; end; procedure TTransferFile.OnTerminateThread(Sender: TObject); begin FRunning := False; FThread := nil; end; procedure TTransferFile.ServerStatusHandler(Online: Boolean); begin DoOnServerStatus(Online); end; procedure TTransferFile.DoOnServerStatus(Online: Boolean); begin if Assigned(FOnServerStatus) then OnServerStatus(Online); end; procedure TTransferFile.Finish; begin FRunning := False; end; end.
unit BsEditStreet; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, FIBDatabase, pFIBDatabase, cxMaskEdit, cxButtonEdit, cxControls, cxContainer, cxEdit, cxTextEdit, ExtCtrls, cxLabel, DB, FIBDataSet, pFIBDataSet, FIBQuery, pFIBQuery, pFIBStoredProc, iBase, ActnList, AdrEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, baseTypes, BsAdrConsts; type TfrmEditStreet = class(TEditForm) btnOk: TcxButton; btnCancel: TcxButton; EditDB: TpFIBDatabase; eTrRead: TpFIBTransaction; eTrWrite: TpFIBTransaction; eStoredProc: TpFIBStoredProc; EDSet: TpFIBDataSet; ActionList1: TActionList; ActOk: TAction; ActCancel: TAction; StreetEdit: TcxTextEdit; lblStreet: TcxLabel; lblTypeStreet: TcxLabel; lblPlace: TcxLabel; TypeStreetBox: TcxLookupComboBox; PlaceBox: TcxLookupComboBox; btnType: TcxButton; btnPlace: TcxButton; TypeStreetDSet: TpFIBDataSet; PlaceDSet: TpFIBDataSet; TypeStreetDS: TDataSource; PlaceDS: TDataSource; procedure ActOkExecute(Sender: TObject); procedure ActCancelExecute(Sender: TObject); procedure lblStreetMouseLeave(Sender: TObject); procedure lblTypeStreetMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure lblTypeStreetMouseLeave(Sender: TObject); procedure lblPlaceMouseEnter(Sender: TObject); procedure lblPlaceMouseLeave(Sender: TObject); procedure btnTypeClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure TypeStreetBoxPropertiesChange(Sender: TObject); procedure PlaceBoxPropertiesChange(Sender: TObject); procedure btnPlaceClick(Sender: TObject); private { Private declarations } function CheckData:boolean; public { Public declarations } end; var frmEditStreet: TfrmEditStreet; implementation {$R *.dfm} uses BsAdrSpr; function TfrmEditStreet.CheckData:Boolean; begin Result:=True; if StreetEdit.Text='' then begin StreetEdit.Style.Color:=clRed; agMessageDlg(WarningText, 'Ви не заповнили поле "Вулиця"!', mtInformation, [mbOK]); Result:=False; end; if VarIsNull(TypeStreetBox.EditValue) then begin TypeStreetBox.Style.Color:=clRed; agMessageDlg(WarningText, 'Ви не обрали тип вулиці!', mtInformation, [mbOK]); Result:=False; end; if VarIsNull(PlaceBox.EditValue) then begin PlaceBox.Style.Color:=clRed; agMessageDlg(WarningText, 'Ви не обрали насю пункт!', mtInformation, [mbOK]); Result:=False; end; end; procedure TfrmEditStreet.ActOkExecute(Sender: TObject); begin if CheckData then begin try eTrWrite.StartTransaction; eStoredProc.StoredProcName:='BS_STREET_INS_UPD'; eStoredProc.Prepare; eStoredProc.ParamByName('ID_STREET_IN').AsVariant:=KeyField; eStoredProc.ParamByName('NAME_STREET').AsString:=StreetEdit.Text; eStoredProc.ParamByName('ID_PLACE').AsInteger:=PlaceBox.EditValue; eStoredProc.ParamByName('ID_TYPE_STREET').AsInteger:=TypeStreetBox.EditValue; eStoredProc.ExecProc; ReturnId:=eStoredProc.FieldByName('ID_STREET').AsInteger; eTrWrite.Commit; ModalResult:=mrOk; except on E:Exception do begin agMessageDlg(WarningText, E.Message, mtInformation, [mbOK]); eTrWrite.Rollback; end; end; end; end; procedure TfrmEditStreet.ActCancelExecute(Sender: TObject); begin CloseConnect; Close; end; procedure TfrmEditStreet.lblStreetMouseLeave(Sender: TObject); begin Screen.Cursor:=crDefault; lblStreet.Style.Font.Color:=clWindowText; end; procedure TfrmEditStreet.lblTypeStreetMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin Screen.Cursor:=crHandPoint; lblTypeStreet.Style.Font.Color:=clBlue; end; procedure TfrmEditStreet.lblTypeStreetMouseLeave(Sender: TObject); begin Screen.Cursor:=crDefault; lblTypeStreet.Style.Font.Color:=clWindowText; end; procedure TfrmEditStreet.lblPlaceMouseEnter(Sender: TObject); begin Screen.Cursor:=crHandPoint; lblPlace.Style.Font.Color:=clBlue; end; procedure TfrmEditStreet.lblPlaceMouseLeave(Sender: TObject); begin Screen.Cursor:=crDefault; lblPlace.Style.Font.Color:=clWindowText; end; procedure TfrmEditStreet.btnTypeClick(Sender: TObject); var sParam:TSpravParams; frm:TfrmSprav; begin sParam.FormCaption := 'Довідник типів вулиць'; sParam.SelectText := TypeStreetDSet.SQLs.SelectSQL.Text; sParam.NameFields := 'Name_Full,Id_Type_Street'; sParam.FieldsCaption := 'Тип вулиці'; sParam.KeyField := 'Id_Type_Street'; sParam.ReturnFields := 'Id_Type_Street,Name_Full'; sParam.FilterFields:='Name_Full'; sParam.FilterCaptions:='Тип вулиці'; sParam.DbHandle:=EditDB.Handle; sParam.frmButtons:=[fbRefresh,fbSelect,fbExit]; frm:=TfrmSprav.Create(Self, sParam); if frm.ShowModal=mrOk then begin if TypeStreetDSet.Active then TypeStreetDSet.Close; TypeStreetDSet.Open; TypeStreetBox.EditValue:=frm.Res[0]; end; frm.Free; end; procedure TfrmEditStreet.FormShow(Sender: TObject); var s:String; begin try TypeStreetDSet.Close; TypeStreetDSet.SQLs.SelectSQL.Text:=StreetTypeSqlText; TypeStreetDSet.Open; if not VarIsNull(AddInfo[1]) then s:=IntToStr(AddInfo[1]) else s:='null'; PlaceDSet.Close; PlaceDSet.SQLs.SelectSQL.Text:=PlaceSqlText+'('+IntToStr(AddInfo[0])+','+s+')'+OrderBy+'NAME_PLACE'+CollateWin1251; PlaceDSet.Open; if not VarIsNull(AddInfo[2]) then PlaceBox.EditValue:=AddInfo[2]; if not VarIsNull(KeyField) then begin EDSet.Close; EDSet.SQLs.SelectSQL.Text:=frmStreetSqlText+'('+IntToStr(KeyField)+')'; EDSet.Open; StreetEdit.Text:=EDSet['NAME_STREET']; TypeStreetBox.EditValue:=EDSet['ID_TYPE_STREET']; PlaceBox.EditValue:=EDSet['ID_PLACE']; Self.Caption:='Змінити вулицю'; end else Self.Caption:='Додати вулицю'; except on E:Exception do agMessageDlg(WarningText, E.Message, mtInformation, [mbOK]); end; end; procedure TfrmEditStreet.TypeStreetBoxPropertiesChange(Sender: TObject); begin GlobalBoxFilter(TypeStreetBox, 'NAME_FULL'); end; procedure TfrmEditStreet.PlaceBoxPropertiesChange(Sender: TObject); begin GlobalBoxFilter(PlaceBox, 'NAME_PLACE'); end; procedure TfrmEditStreet.btnPlaceClick(Sender: TObject); var sParam:TSpravParams; frm:TfrmSprav; str:String; begin if VarIsNull(AddInfo[1]) then str:='NULL' else str:=IntToStr(AddInfo[1]); sParam.FormCaption := 'Довідник населених пуктів'; sParam.SelectText := PlaceSqlText+'('+IntToStr(AddInfo[0])+','+str+')'+OrderBy+'NAME_PLACE'+CollateWin1251; sParam.NameFields := 'Name_Place,Id_Place'; sParam.FieldsCaption := 'Населений пункт'; sParam.KeyField := 'Id_Place'; sParam.ReturnFields := 'Id_Place,Name_Place'; sParam.FilterFields:='Name_Place'; sParam.FilterCaptions:='Назва нас. пункту'; sParam.DbHandle:=EditDB.Handle; sParam.frmButtons:=[fbAdd,fbModif,fbDelete,fbRefresh,fbSelect,fbExit]; sParam.DeleteProcName:='ADR_PLACE_D'; sParam.NameClass:='TfrmEditPlace'; sParam.AddInfo:=VarArrayCreate([0, 2], varVariant); sParam.AddInfo[0]:=AddInfo[3]; sParam.AddInfo[1]:=AddInfo[0]; sParam.AddInfo[2]:=AddInfo[1]; frm:=TfrmSprav.Create(Self, sParam); if frm.ShowModal=mrOk then begin if PlaceDSet.Active then PlaceDSet.Close; PlaceDSet.Open; PlaceBox.EditValue:=frm.Res[0]; end; frm.Free; end; initialization RegisterClass(TfrmEditStreet); end.
unit ULancamentoPadraoVO; interface uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO, UPlanoContasVO, UContasReceberVO, UContasPagarVO,UhistoricoVO, ULoteVO, UCondominioVO; type [TEntity] [TTable('LancamentoPadrao')] TLancamentoPadraoVO = class(TGenericVO) private FidLctoPadrao : Integer; FidContaDebito : Integer; FidContaCredito : Integer; FidHistorico : Integer; Fobservacao : string; FDsContaDebito : String; FDsContaCredito : String; FDsHistorico : String; FidCondominio : Integer; public ContaDebitoVo : TPlanoContasVO; ContaCreditoVO : TPlanoContasVO; HistoricoVO : THistoricoVO; CondominioVO : TCondominioVO; [TId('idLctoPadrao')] [TGeneratedValue(sAuto)] property idLctoPadrao : Integer read FidLctoPadrao write FidLctoPadrao; [TColumn('observacao','Observação',200,[ldGrid,ldLookup,ldComboBox], False)] property observacao: string read Fobservacao write Fobservacao; [TColumn('idcontadebito','Débito',20,[ldGrid,ldLookup,ldComboBox], False)] property idcontadebito: integer read FidContaDebito write FidContaDebito; [TColumn('DSCONTADEBITO','Descrição',150,[ldGrid], True, 'PlanoContas', 'idContaDebito', 'idPlanoContas', 'PlanoDebito', 'DSCONTA')] property DsContaDebito: string read FDsContaDebito write FDsContaDebito; [TColumn('idcontacredito','Crédito',20,[ldGrid,ldLookup,ldComboBox], False)] property idContaCredito: integer read FidContaCredito write FidContaCredito; [TColumn('DSCONTACREDITO','Descrição',150,[ldGrid], True, 'PlanoContas', 'idContaCredito', 'idPlanoContas', 'PlanoCredito', 'DSCONTA')] property DsContaCredito: string read FDsContaCredito write FDsContaCredito; [TColumn('idHistorico','Historico',10,[ldGrid,ldLookup,ldComboBox], False)] property idHistorico: integer read FIdHistorico write FIdHistorico; [TColumn('DSHISTORICO','',0,[], True, 'Historicos', 'idHistorico', 'idHistorico')] property DsHistorico: string read FDsHistorico write FDsHistorico; [TColumn('idCondominio','Condomínio',0,[ldLookup,ldComboBox], False)] property idCondominio: integer read FidCOndominio write FidCondominio; procedure ValidarCamposObrigatorios; end; implementation { TLancamentoContabilVO } procedure TLancamentoPadraoVO.ValidarCamposObrigatorios; begin if ((self.FidContaDebito = 0) or (self.idContaCredito = 0))then begin raise Exception.Create('O campo Conta débito ou conta crédito é obrigatório!'); end; if (Self.Fobservacao = '') then begin raise Exception.Create('O campo Observação é obrigatório!'); end; if (Self.FidHistorico = 0) then begin raise Exception.Create('O campo Histórico é obrigatório!'); end; end; end.
{******************************************************************************* lazbbosversionbase : Base functions and defintionsfor lazbbOsVersion component sdtp - bb - september 2022 ********************************************************************************} unit lazbbosversionbase; {$mode ObjFPC}{$H+} interface uses {$IFDEF WINDOWS} Windows, {$ELSE} process, {$ENDIF} Classes, SysUtils; {$IFDEF WINDOWS} type // missing structure for GetVersionEx Windows function POSVersionInfoExA = ^TOSVersionInfoExA; POSVersionInfoExW = ^TOSVersionInfoExW; POSVersionInfoEx = POSVersionInfoExA; _OSVERSIONINFOEXA = record dwOSVersionInfoSize: DWORD; dwMajorVersion: DWORD; dwMinorVersion: DWORD; dwBuildNumber: DWORD; dwPlatformId: DWORD; szCSDVersion: array[0..127] of AnsiChar; { Maintenance string for PSS usage } wServicePackMajor: Word; wServicePackMinor: Word; wSuiteMask: WORD; wProductType: BYTE; wReserved: BYTE; end; _OSVERSIONINFOEXW = record dwOSVersionInfoSize: DWORD; dwMajorVersion: DWORD; dwMinorVersion: DWORD; dwBuildNumber: DWORD; dwPlatformId: DWORD; szCSDVersion: array[0..127] of WideChar; { Maintenance string for PSS usage } wServicePackMajor: Word; wServicePackMinor: Word; wSuiteMask: WORD; wProductType: BYTE; wReserved: BYTE; end; _OSVERSIONINFOEX = _OSVERSIONINFOEXA; TOSVersionInfoExA = _OSVERSIONINFOEXA; TOSVersionInfoExW = _OSVERSIONINFOEXW; TOSVersionInfoEx = TOSVersionInfoExA; OSVERSIONINFOEXA = _OSVERSIONINFOEXA; OSVERSIONINFOEXW = _OSVERSIONINFOEXW; OSVERSIONINFOEX = OSVERSIONINFOEXA; const // Winbdows constants VER_NT_WORKSTATION = 1; VER_NT_DOMAIN_CONTROLLER = 2; VER_NT_SERVER = 3; VER_SUITE_SMALLBUSINESS = $0001; VER_SUITE_ENTERPRISE = $0002; VER_SUITE_BACKOFFICE = $0004; VER_SUITE_TERMINAL = $0010; VER_SUITE_SMALLBUSINESS_RESTRICTED = $0020; VER_SUITE_DATACENTER = $0080; VER_SUITE_PERSONAL = $0200; var //Windows functions to be loaded dynamlically hProductInfo: THandle; // Exists in Vista and over GetProductInfo: function (dwOSMajorVersion, dwOSMinorVersion, dwSpMajorVersion, dwSpMinorVersion: DWORD; var pdwReturnedProductType: DWORD): BOOL stdcall = NIL; // Exists in W2000 and over GetVersionEx: function (var lpVersionInformation: TOSVersionInfoEx): BOOL stdcall= NIL; {$ENDIF} implementation initialization {$IFDEF WINDOWS} hProductInfo:= LoadLibrary (PChar('KERNEL32.DLL')); Pointer(GetProductInfo) := GetProcAddress(hProductInfo, 'GetProductInfo'); Pointer(GetVersionEx):= GetProcAddress(hProductInfo, 'GetVersionExA'); {$ENDIF} finalization {$IFDEF WINDOWS} try if hProductInfo<>0 then FreeLibrary(hProductInfo); except end; {$ENDIF} end.
unit AppForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MainU, Vcl.StdCtrls; type TForm1 = class(TForm) btnStart: TButton; btnStop: TButton; lblPort: TLabel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnStartClick(Sender: TObject); procedure btnStopClick(Sender: TObject); private m_Server : TMain; { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin m_Server := TMain.Create; btnStop.Enabled := False; end; procedure TForm1.FormDestroy(Sender: TObject); begin m_Server.Free; end; procedure TForm1.btnStartClick(Sender: TObject); begin m_Server.Start; btnStart.Enabled := False; btnStop.Enabled := True; lblPort.Caption := 'Port:9000'; end; procedure TForm1.btnStopClick(Sender: TObject); begin m_Server.Stop; btnStart.Enabled := True; btnStop.Enabled := False; end; end.
unit FDiskPrint; (*==================================================================== Progress window for printing disks, implements the printing in the Run procedure ======================================================================*) interface uses SysUtils, {$ifdef mswindows} WinTypes,WinProcs, {$ELSE} LCLIntf, LCLType, LMessages, ExtCtrls, PrintersDlgs, {$ENDIF} Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ATGauge, UTypes, UAPiTypes, FSettings, UCollections, UStringList; type { TFormDiskPrint } TFormDiskPrint = class(TForm) ButtonCancel: TButton; Gauge: TGauge; LabelSearched: TLabel; Label1: TLabel; //Gauge: TPanel; PrintDialog: TPrintDialog; LabelWhat: TLabel; procedure FormCreate(Sender: TObject); procedure ButtonCancelClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); private CanRun : boolean; QGlobalOptions: TGlobalOptions; FilesList : TQStringList; {for capturing and sorting files} function CanPrintOnThisPage: boolean; procedure GoToNewPage; procedure PrintHeaderAndFooter; procedure PrintColumnNames; procedure CheckAmountPrinted; public StopIt : boolean; DBaseHandle: PDBaseHandle; ShortDBaseFileName: ShortString; procedure Run(var Info); message WM_User + 109; procedure UpdateCounters; procedure PrintOneDisk (Disk: ShortString); procedure PrintOneDir (Dir: ShortString); procedure AddOneFileToList (var OneFile: TOneFile); procedure PrintFilesInDir; end; var FormDiskPrint: TFormDiskPrint; implementation uses {Printers,} UExceptions, UApi, UBaseUtils, FDiskPrintSelect, ULang, UPrinter, {FDBase} Fmain {$ifdef LOGFONT} , UFont {$endif} ; {$R *.dfm} const NoOfColumns = 4; var AmountPrintedPx: Integer; PageCounter: Integer; ColWidthsPx: array [0..NoOfColumns-1] of Integer; TimeWidthPx: Integer; MWidthPx: Integer; //----------------------------------------------------------------------------- // callback made when the window progress needs to be updated procedure CallBackWhenChange(var Stop: boolean); begin FormDiskPrint.UpdateCounters; Application.ProcessMessages; Stop := FormDiskPrint.StopIt; end; //----------------------------------------------------------------------------- // used from the Engine to send single disk name procedure SendOneDiskFunct (Disk: ShortString); begin FormDiskPrint.PrintOneDisk (Disk); end; //----------------------------------------------------------------------------- // used from the Engine to send single folder name procedure SendOneDirFunct (Dir: ShortString); begin FormDiskPrint.PrintOneDir (Dir); end; //----------------------------------------------------------------------------- // used from the Engine to send single file info procedure SendOneFileFunct (var OneFile: TOneFile); begin FormDiskPrint.AddOneFileToList (OneFile); end; //----------------------------------------------------------------------------- // Calculates the width in pixels needed for the string procedure GetNameWidthFunct (Name: ShortString; var Width: integer); begin ///Width := QPrinterGetTextWidth(Name); end; //----------------------------------------------------------------------------- procedure TFormDiskPrint.FormCreate(Sender: TObject); begin CanRun := false; QGlobalOptions := TGlobalOptions.Create; end; //----------------------------------------------------------------------------- procedure TFormDiskPrint.FormShow(Sender: TObject); begin FormSettings.GetOptions(QGlobalOptions); LabelWhat.Caption := lsCalculatingPrintExtent; StopIt := false; CanRun := true; // this starts the Run procedure after the window is displayed PostMessage(Self.Handle, WM_User + 109, 0, 0); end; //----------------------------------------------------------------------------- procedure TFormDiskPrint.ButtonCancelClick(Sender: TObject); begin StopIt := true; CanRun := false; // this cuases assigning ModalResult in the Run procedure end; //----------------------------------------------------------------------------- procedure TFormDiskPrint.UpdateCounters; var Percent: Integer; DisksCount, DirsCount, FilesCount: longint; begin QI_GetSearchProgress (DBaseHandle, Percent, DisksCount, DirsCount, FilesCount); LabelSearched.Caption := IntToStr(DisksCount) + '/' + IntToStr(FilesCount); Gauge.Progress := Percent; end; //----------------------------------------------------------------------------- // determines, whether this page is included in the print range function TFormDiskPrint.CanPrintOnThisPage: boolean; begin Result := true; {$ifdef mswindows} if PrintDialog.PrintRange <> prPageNums then exit; with PrintDialog do if (PageCounter >= FromPage) and (PageCounter <= ToPage) then exit; Result := false; {$endif} end; //----------------------------------------------------------------------------- procedure TFormDiskPrint.GoToNewPage; begin {$ifdef mswindows} if PrintDialog.PrintRange <> prPageNums then QPrinterNewPage else begin with PrintDialog do if (PageCounter >= FromPage) and (PageCounter < ToPage) then QPrinterNewPage; end; {$endif} end; //----------------------------------------------------------------------------- procedure TFormDiskPrint.PrintHeaderAndFooter; var OutRect : TRect; S, S1 : ShortString; Attr : Word; TmpIndex: Integer; begin if StopIt then exit; {$ifdef mswindows} QPrinterSaveAndSetFont(pfsItalic); {header} OutRect.Left := LeftPrintAreaPx; OutRect.Right := RightPrintAreaPx; OutRect.Top := TopPrintAreaPx; OutRect.Bottom := OutRect.Top + LineHeightPx; if CanPrintOnThisPage then begin S := QGlobalOptions.PrintHeader; if S = '' then S := lsDatabase + ShortDBaseFileName; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); QI_GetCurrentKey(DBaseHandle, S1, Attr, TmpIndex); S1 := lsDisk + S1; OutRect.Left := OutRect.Right - QPrinterGetTextWidth(S1); if OutRect.Left < (LeftPrintAreaPx + QPrinterGetTextWidth(S)) then OutRect.Left := LeftPrintAreaPx + QPrinterGetTextWidth(S) + 3*YPxPer1mm; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S1); QPrinterSetLineWidth(MaxI(1, YPxPer1cm div 50)); {0.2 mm}; QPrinterMoveTo(LeftPrintAreaPx, OutRect.Bottom + YPxPer1mm); QPrinterLineTo(RightPrintAreaPx, OutRect.Bottom + YPxPer1mm); end; {footer} OutRect.Left := LeftPrintAreaPx; OutRect.Bottom := BottomPrintAreaPx; OutRect.Top := OutRect.Bottom - LineHeightPx; if CanPrintOnThisPage then begin QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, TimePrinted); S := lsPage + IntToStr(PageCounter); OutRect.Left := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); QPrinterSetLineWidth(MaxI(1, YPxPer1cm div 50)); {0.2 mm}; QPrinterMoveTo(LeftPrintAreaPx, OutRect.Top - YPxPer1mm); QPrinterLineTo(RightPrintAreaPx, OutRect.Top - YPxPer1mm); end; QPrinterRestoreFont; {$endif} end; //----------------------------------------------------------------------------- procedure TFormDiskPrint.PrintColumnNames; var OutRect : TRect; S : ShortString; i : Integer; StartX : Integer; begin if StopIt then exit; {$ifdef mswindows} QPrinterSaveAndSetFont(pfsBold); OutRect.Left := LeftPrintAreaPx + 3*MWidthPx; OutRect.Top := AmountPrintedPx; OutRect.Bottom := OutRect.Top + LineHeightPx; for i := 0 to NoOfColumns-1 do if CanPrintOnThisPage then begin OutRect.Right := OutRect.Left + ColWidthsPx[i] - 3*XPxPer1mm; if (OutRect.Right > RightPrintAreaPx) or (i = NoOfColumns-1) then OutRect.Right := RightPrintAreaPx; if (OutRect.Left < OutRect.Right) then begin case i of 0: begin S := lsName; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); end; 1: begin S := lsSize; StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); end; 2: begin S := lsDateTime; StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); end; 3: begin S := lsDescription; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); end; end; end; inc(OutRect.Left,ColWidthsPx[i]); end; inc(AmountPrintedPx, LineHeightPx + YPxPer1mm); QPrinterRestoreFont; {$endif} end; //----------------------------------------------------------------------------- // Makes the print procedure TFormDiskPrint.Run (var Info); var MaxNameLength, AvgNameLength, MaxNamePxWidth: Integer; Percent, ExpectedPages: Integer; DisksCount, DirsCount, FilesCount: longint; MsgText: array[0..256] of char; Copies: Integer; SearchIn: TSearchIn; begin if not CanRun then exit; {$ifdef mswindows} FilesList := TQStringList.Create; FilesList.Sorted := true; FilesList.Duplicates := dupAccept; CanRun := false; try FormDiskPrintSelect.RadioButtonSelectedDisks.Enabled := QI_GetSelectedCount (DBaseHandle) > 0; FormDiskPrintSelect.Caption := lsPrintSelection; FormDiskPrintSelect.LabelWhat.Caption := lsPrintWhat; if FormDiskPrintSelect.ShowModal <> mrOk then begin FilesList.Free; ModalResult := mrCancel; exit; end; with FormDiskPrintSelect do begin SearchIn := siActualDiskDir; if RadioButtonActDiskWhole.Checked then SearchIn := siActualDisk; if RadioButtonSelectedDisks.Checked then SearchIn := siSelectedDisks; end; if not PrintDialog.Execute then begin FilesList.Free; ModalResult := mrCancel; exit; end; QPrinterReset(QGlobalOptions); AmountPrintedPx := TopPrintAreaPx + 2*LineHeightPx; TimeWidthPx := QPrinterGetTextWidth(DosTimeToStr(longint(23) shl 11, QGlobalOptions.ShowSeconds)); TimeWidthPx := TimeWidthPx + TimeWidthPx div 6; MWidthPx := QPrinterGetTextWidth('M'); Gauge.Progress := 0; Gauge.Show; Application.ProcessMessages; QI_SetIterateCallback (DBaseHandle, CallBackWhenChange, SendOneDiskFunct, SendOneDirFunct, SendOneFileFunct, GetNameWidthFunct); QI_IterateFiles(DBaseHandle, SearchIn, stNothing); QI_DelIterateCallback(DBaseHandle); QI_GetSearchProgress (DBaseHandle, Percent, DisksCount, DirsCount, FilesCount); QI_GetMaxNameLength (DBaseHandle, MaxNameLength, AvgNameLength, MaxNamePxWidth); ExpectedPages := FilesCount div ((HeightPx - 3*LineHeightPx) div LineHeightPx) + 1; if (ExpectedPages > 5) and (PrintDialog.PrintRange = prAllPages) then if Application.MessageBox( StrPCopy(MsgText, lsExpectedNoOfPages + IntToStr(ExpectedPages) + lsReallyPrintThem), lsWarning, mb_YesNoCancel) <> IdYes then begin FilesList.Free; ModalResult := mrCancel; exit; end; Gauge.Hide; LabelWhat.Caption := lsPreparingPrint; if QGlobalOptions.AdjustNameWidth then begin MaxNameLength := (AvgNameLength *4 + MaxNameLength) div 5 + 4; {4 pro ext} if MaxNameLength <= 12 then ColWidthsPx[0] := QPrinterGetTextWidth('MMMMxxxx.mxx') + 3*XPxPer1mm else begin ColWidthsPx[0] := QPrinterGetTextWidth('MMMMxiii.mxi'); ColWidthsPx[0] := (ColWidthsPx[0] * MaxNameLength) div 12 + 3*XPxPer1mm; end; end else begin ColWidthsPx[0] := MaxNamePxWidth + QPrinterGetTextWidth('.MMM'); end; ColWidthsPx[1] := QPrinterGetTextWidth(FormatSize(2000000000, QGlobalOptions.ShowInKb)) + 3*XPxPer1mm; ColWidthsPx[2] := QPrinterGetTextWidth(' ' + DosDateToStr (694026240)) + TimeWidthPx + 3*XPxPer1mm; ColWidthsPx[3] := 25 * QPrinterGetTextWidth('Mmmmxxxxx '); Application.ProcessMessages; for Copies := 1 to PrintDialog.Copies do begin PageCounter := 1; QPrinterBeginDoc(lsQuickDir); PrintHeaderAndFooter; PrintColumnNames; LabelWhat.Caption := lsPrintingPage + IntToStr(PageCounter); QI_SetIterateCallback (DBaseHandle, CallBackWhenChange, SendOneDiskFunct, SendOneDirFunct, SendOneFileFunct, GetNameWidthFunct); QI_IterateFiles(DBaseHandle, SearchIn, stDataCallback); QI_DelIterateCallback(DBaseHandle); PrintFilesInDir; {clear the files list} Application.ProcessMessages; if StopIt then break; QPrinterEndDoc; if StopIt then break; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do FatalErrorMessage(EFatal.Message); on E: Exception do Application.MessageBox(StrPCopy(MsgText, E.Message), lsError, mb_Ok or mb_IconExclamation); end; FilesList.Free; {$endif} ModalResult := mrOk; end; //----------------------------------------------------------------------------- procedure TFormDiskPrint.FormDestroy(Sender: TObject); begin QGlobalOptions.Free; end; //----------------------------------------------------------------------------- procedure TFormDiskPrint.PrintOneDisk (Disk: ShortString); var OutRect : TRect; begin if StopIt then exit; {$ifdef mswindows} PrintFilesInDir; QPrinterSaveAndSetFont(pfsBold); inc(AmountPrintedPx, LineHeightPx); CheckAmountPrinted; OutRect.Left := LeftPrintAreaPx; OutRect.Right := RightPrintAreaPx; OutRect.Top := AmountPrintedPx; OutRect.Bottom := OutRect.Top + LineHeightPx; if CanPrintOnThisPage then begin QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, Disk); QPrinterSetLineWidth(MaxI(1, YPxPer1cm div 100)); {0.1 mm}; QPrinterMoveTo(LeftPrintAreaPx, OutRect.Bottom); QPrinterLineTo(RightPrintAreaPx, OutRect.Bottom); end; inc(AmountPrintedPx, LineHeightPx); CheckAmountPrinted; QPrinterRestoreFont; {$endif} end; //----------------------------------------------------------------------------- procedure TFormDiskPrint.PrintOneDir (Dir: ShortString); var OutRect : TRect; begin if StopIt then exit; {$ifdef mswindows} PrintFilesInDir; QPrinterSaveAndSetFont(pfsItalic); inc(AmountPrintedPx, YPxPer1mm); OutRect.Left := LeftPrintAreaPx + MWidthPx; OutRect.Right := RightPrintAreaPx; OutRect.Top := AmountPrintedPx; OutRect.Bottom := OutRect.Top + LineHeightPx; if CanPrintOnThisPage then begin QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, Dir); QPrinterSetLineWidth(1); {hairline}; QPrinterMoveTo(OutRect.Left, OutRect.Bottom); QPrinterLineTo(OutRect.Right, OutRect.Bottom); end; inc(AmountPrintedPx, LineHeightPx); inc(AmountPrintedPx, YPxPer1mm); CheckAmountPrinted; QPrinterRestoreFont; {$endif} end; //----------------------------------------------------------------------------- procedure TFormDiskPrint.AddOneFileToList (var OneFile: TOneFile); var OneFileLine: TOneFileLine; //pointer begin if StopIt then exit; OneFileLine := TOneFileLine.Create(OneFile); FilesList.AddObject(GetSortString(OneFile, OneFileLine.FileType, QGlobalOptions.SortCrit, QGlobalOptions.ReversedSort), OneFileLine); end; //----------------------------------------------------------------------------- procedure TFormDiskPrint.PrintFilesInDir; var OutRect : TRect; TmpRect : TRect; S : ShortString; i : Integer; StartX : Integer; Index : Integer; OneFileLine: TOneFileLine; ShortDesc: ShortString; begin {$ifdef mswidnows} for Index := 0 to pred(FilesList.Count) do begin OutRect.Left := LeftPrintAreaPx + 3*MWidthPx;; OutRect.Top := AmountPrintedPx; OutRect.Bottom := OutRect.Top + LineHeightPx; OneFileLine := TOneFileLine(FilesList.Objects[Index]); if CanPrintOnThisPage then for i := 0 to NoOfColumns-1 do begin OutRect.Right := OutRect.Left + ColWidthsPx[i] - 3*XPxPer1mm; if (OutRect.Right > RightPrintAreaPx) or (i = NoOfColumns-1) then OutRect.Right := RightPrintAreaPx; if OutRect.Left >= OutRect.Right then break; case i of 0: begin S := OneFileLine.POneFile^.LongName + OneFileLine.POneFile^.Ext; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); end; 1: begin if OneFileLine.POneFile^.LongName = '..' then S := '' else if OneFileLine.POneFile^.Attr and faDirectory = faDirectory then S := lsFolder else S := FormatSize(OneFileLine.POneFile^.Size, QGlobalOptions.ShowInKb); StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); end; 2: begin if OneFileLine.POneFile^.Time <> 0 then begin S := DosTimeToStr(OneFileLine.POneFile^.Time, QGlobalOptions.ShowSeconds); StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); S := DosDateToStr(OneFileLine.POneFile^.Time); TmpRect := OutRect; TmpRect.Right := TmpRect.Right - TimeWidthPx; if TmpRect.Right > TmpRect.Left then begin StartX := TmpRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(TmpRect, StartX, TmpRect.Top, S); end; end; end; 3: begin ShortDesc[0] := #0; if OneFileLine.POneFile^.Description <> 0 then QI_GetShortDesc(DBaseHandle, OneFileLine.POneFile^.Description, ShortDesc); QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, ShortDesc); end; end; {case} inc(OutRect.Left,ColWidthsPx[i]); end; {for i} inc(AmountPrintedPx, LineHeightPx); CheckAmountPrinted; end; {for Index} {$endif} FilesList.Clear; end; //----------------------------------------------------------------------------- procedure TFormDiskPrint.CheckAmountPrinted; begin {$ifdef mswindows} if (AmountPrintedPx + 3*LineHeightPx) > BottomPrintAreaPx then begin if not StopIt then begin GoToNewPage; inc(PageCounter); end; if (CanPrintOnThisPage) then LabelWhat.Caption := lsPrintingPage + IntToStr(PageCounter) else LabelWhat.Caption := lsSkippingPage + IntToStr(PageCounter); Application.ProcessMessages; AmountPrintedPx := TopPrintAreaPx + 2*LineHeightPx; PrintHeaderAndFooter; PrintColumnNames; end; {$endif} end; //----------------------------------------------------------------------------- end.
unit RolesForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ToolWin, Grids, DBGrids, ActnList, IBDatabase, MainDM, Db, AddRole, Role, Placemnt, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGrid, Variants, frxClass, frxDBSet, frxExportXLS, frxExportImage, frxExportHTML, Menus, frxExportPDF, frxExportXML, frxExportRTF, pFIBDataSet, FIBDataSet; type TFormRoles = class(TForm) ToolBarRoles: TToolBar; StatusBarRoles: TStatusBar; ToolButtonAdd: TToolButton; ToolButtonEdit: TToolButton; ToolButtonDel: TToolButton; ActionList: TActionList; Add: TAction; Edit: TAction; Del: TAction; DataSourceRoles: TDataSource; ToolButtonSel: TToolButton; Sel: TAction; ToolButtonExit: TToolButton; Exit: TAction; FormStorage1: TFormStorage; DBGridRoles: TcxGridDBTableView; cxGrid1Level1: TcxGridLevel; cxGrid1: TcxGrid; DBGridRolesDBColumn1: TcxGridDBColumn; DBGridRolesDBColumn2: TcxGridDBColumn; cxStyleRepository1: TcxStyleRepository; cxStyle1: TcxStyle; DBGridRolesDBColumn3: TcxGridDBColumn; frxDBDataset1: TfrxDBDataset; GroupPrint: TToolButton; Print: TAction; frxXMLExport1: TfrxXMLExport; frxPDFExport1: TfrxPDFExport; frxJPEGExport1: TfrxJPEGExport; frxHTMLExport1: TfrxHTMLExport; frxReport1: TfrxReport; frxRTFExport1: TfrxRTFExport; DSetRoles: TpFIBDataSet; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure AddExecute(Sender: TObject); procedure EditExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure SelExecute(Sender: TObject); procedure ExitExecute(Sender: TObject); procedure DBGridRolesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DelExecute(Sender: TObject); procedure DBGridRolesDblClick(Sender: TObject); procedure GroupPrintClick(Sender: TObject); procedure frxReport1GetValue(const VarName: String; var Value: Variant); procedure PrintExecute(Sender: TObject); private { Private declarations } FMode: Integer; FResultSQL: string; public { Public declarations } ResultQuery: TpFIBDataSet; constructor Create(Owner: TComponent; Mode: Integer;Id_object:Integer;Id_Action:Integer);reintroduce; end; implementation {$R *.DFM} constructor TFormRoles.Create(Owner: TComponent; Mode: Integer;Id_object:Integer;Id_Action:Integer); begin inherited Create(Owner); FMode := Mode; DSetRoles.SelectSQL.Text:='SELECT * FROM ROLES_SELECT_FOR_OBJECT('+IntToStr(Id_object)+','+IntToStr(Id_Action)+')'; FResultSQL := 'select * from roles where '; ResultQuery := nil; if FMode = fmWork then Self.FormStyle := fsMDIChild; DSetRoles.CloseOpen(True); end; procedure TFormRoles.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFormRoles.AddExecute(Sender: TObject); var FormAddRole: TFormAddRole; begin FormAddRole := TFormAddRole.Create(Self, nil, fmAdd); FormAddRole.ShowModal; if Assigned(FormAddRole.FResultRole) then begin Screen.Cursor := crHourGlass; DSetRoles.CloseOpen(True); DSetRoles.Locate('ID_ROLE', FormAddRole.FResultRole.RoleID,[]); Screen.Cursor := crDefault; end; FormAddRole.Free; end; procedure TFormRoles.EditExecute(Sender: TObject); var FormAddRole: TFormAddRole; theRole: TRole; begin theRole := TRole.Create(Self, DMMain.KruAccessDB); theRole.FillDataBy(DSetRoles.FieldByName('ID_ROLE').AsInteger); FormAddRole := TFormAddRole.Create(Self, theRole, fmEdit); FormAddRole.ShowModal; if Assigned(FormAddRole.FResultRole) then begin Screen.Cursor := crHourGlass; DSetRoles.CloseOpen(True); DSetRoles.Locate('ID_ROLE', FormAddRole.FResultRole.RoleID,[]); Screen.Cursor := crDefault; end else theRole.Free; FormAddRole.Free; end; procedure TFormRoles.FormCreate(Sender: TObject); begin if FMode = fmMultiSelect then begin DBGridRoles.OptionsSelection.MultiSelect:=true; end; end; procedure TFormRoles.SelExecute(Sender: TObject); var i: Integer; begin case FMode of fmMultiSelect: begin Self.Hide; for i := 0 to DBGridRoles.Controller.SelectedRecordCount-1 do begin FResultSQL := FResultSQL + ' id_role = '+ VarToStr(DBGridRoles.Controller.SelectedRecords[i].Values[2])+' or'; end; if DBGridRoles.Controller.SelectedRecordCount >= 1 then begin Delete(FResultSQL,Length(FResultSQL)-1,2); ResultQuery:=TpFIBDataSet.Create(self); ResultQuery.Database:=DMMain.WorkDatabase; end else ResultQuery := nil; end; fmSelect: begin FResultSQL := FResultSQL + ' id_role = '+ IntToStr(DSetRoles.FieldByName('id_role').AsInteger); end; end; if ((FMode = fmMultiSelect) or (FMode = fmSelect)) and Assigned(ResultQuery) then begin ResultQuery.SelectSQL.Text := FResultSQL; try ResultQuery.Open; except on exc: Exception do begin ShowErrorMessage('Не вдалось виконати запит! '+ exc.Message); end; end; end; Close; end; procedure TFormRoles.ExitExecute(Sender: TObject); begin Close; end; procedure TFormRoles.DBGridRolesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (FMode <> fmWork) and (Key = VK_ESCAPE) then begin Close end; end; procedure TFormRoles.DelExecute(Sender: TObject); var DSet: TpFIBDataSet; begin if not DSetRoles.IsEmpty then if MessageDlg('Вилучити вибрану групу?',mtConfirmation,[mbYes, mbNo], 0) <> ID_NO then begin DSet:=TpfibDataset.Create(Self); DSet.Database:=DMMain.WorkDatabase; DSet.Transaction.StartTransaction; DSet.SelectSQL.Text := 'EXECUTE PROCEDURE ACCESS_ROLES_DELETE('+DSetRoles.fieldbyname('ID_ROLE').AsString + ')'; DSet.Open; DSet.Transaction.Commit; DSetRoles.CloseOpen(True); end; end; procedure TFormRoles.DBGridRolesDblClick(Sender: TObject); begin if (FMode <> fmWork) then begin SelExecute(self); end; end; procedure TFormRoles.GroupPrintClick(Sender: TObject); begin Screen.Cursor := crHourGlass; frxReport1.Clear; if frxReport1.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\PrintOperations.fr3',true) then begin cxGrid1.BeginUpdate; if frxReport1.PrepareReport(true) then frxReport1.ShowPreparedReport; cxGrid1.EndUpdate; DSetRoles.First; end else ShowErrorMessage('Файл звіту "\Reports\PrintOperations.fr3" не знайдено!'); Screen.Cursor := crDefault; end; procedure TFormRoles.frxReport1GetValue(const VarName: String; var Value: Variant); begin if varname='FIELD_1' then value:='Назва'; if varname='FIELD_2' then value:='Повна назва'; if varname='REPORT_TITLE' then value:='Групи'; end; procedure TFormRoles.PrintExecute(Sender: TObject); begin GroupPrintClick(sender); end; end.
PROGRAM rationalcalc; TYPE Rational = RECORD num, denom: INTEGER; END; (* Function to get the greatest common dvisor *) FUNCTION ggT (a,b : INTEGER) : INTEGER; VAR remainder: INTEGER; BEGIN WHILE NOT (b=0) DO BEGIN remainder := a MOD b; a := b; b := remainder; END; ggT :=a; END; (* Proc to simplify given Rational *) PROCEDURE simplify(Var a : Rational); var divisor : Integer; begin divisor := ggT(a.num, a.denom); a.num := a.num div divisor; a.denom := a.denom div divisor; end; PROCEDURE rationalAdd(a, b: Rational; VAR c: Rational); BEGIN IF NOT (a.denom = b.denom) THEN BEGIN c.num := a.num * b.denom + b.num * a.denom; c.denom := a.denom * b.denom ; END ELSE BEGIN c.num := a.num + b.num; c.denom := a.denom; END; simplify(c); END; PROCEDURE rationalSub(a, b: Rational; VAR c: Rational); BEGIN IF NOT (a.denom = b.denom) THEN BEGIN c.num := a.num * b.denom - b.num * a.denom; c.denom := a.denom * b.denom ; END ELSE BEGIN c.num := a.num - b.num; c.denom := a.denom; END; simplify(c); END; PROCEDURE rationalMult(a, b: Rational; VAR c: Rational); BEGIN c.num := a.num * b.num; c.denom := a.denom * b.denom; simplify(c); END; PROCEDURE rationalDiv(a, b: Rational; VAR c: Rational); BEGIN c.num := a.num * b.denom; c.denom := a.denom * b.num; simplify(c); END; (*Liest a und b ein*) PROCEDURE input(VAR a, b: Rational); BEGIN REPEAT Write('a num: '); ReadLn(a.num); Write('a denom: '); ReadLn(a.denom); Write('b num: '); ReadLn(b.num); Write('b denom: '); ReadLn(b.denom); IF (a.denom = 0) OR (b.denom = 0) THEN WriteLn('a denom und b denom muessen groeser 0 sein') UNTIL (a.denom > 0) AND (b.denom > 0) END; (*Gibt eine Rationale Zahl aus*) PROCEDURE output(a: Rational); BEGIN WriteLn(a.num,'/',a.denom); END; VAR a, b, c: Rational; BEGIN WriteLn(chr(205),chr(205),chr(185),' RationalCalc ',chr(204),chr(205),chr(205)); input(a,b); WriteLn('Add:'); rationalAdd(a,b,c); output(c); WriteLn('Sub:'); rationalSub(a,b,c); output(c); WriteLn('Mult:'); rationalMult(a,b,c); output(c); WriteLn('Div:'); rationalDiv(a,b,c); output(c); END.
unit IntXZeroandOneTest; {$mode objfpc}{$H+} interface uses fpcunit, testregistry, uIntX; type { TTestIntXZeroandOne } TTestIntXZeroandOne = class(TTestCase) published procedure IsCustomTIntXZeroEqualToZero(); procedure IsCustomTIntXZeroEqualToNegativeZero(); procedure IsCustomTIntXZeroEqualToNegativeZero2(); procedure IsCustomTIntXOneEqualToOne(); end; implementation procedure TTestIntXZeroandOne.IsCustomTIntXZeroEqualToZero(); var int1: TIntX; begin int1 := TIntX.Create(0); AssertTrue(int1 = TIntX.Zero); AssertTrue(int1 = 0); end; procedure TTestIntXZeroandOne.IsCustomTIntXZeroEqualToNegativeZero(); var int1: TIntX; begin int1 := TIntX.Create(-0); AssertTrue(int1 = TIntX.Zero); AssertTrue(int1 = 0); end; procedure TTestIntXZeroandOne.IsCustomTIntXZeroEqualToNegativeZero2(); var int1: TIntX; begin int1 := TIntX.Create('-0'); AssertTrue(int1 = TIntX.Zero); AssertTrue(int1 = 0); end; procedure TTestIntXZeroandOne.IsCustomTIntXOneEqualToOne(); var int1: TIntX; begin int1 := TIntX.Create(1); AssertTrue(int1 = TIntX.One); AssertTrue(int1 = 1); end; initialization RegisterTest(TTestIntXZeroandOne); end.
program plus_min; uses SysUtils; const powers: array[0..9] of cardinal = (1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000); var history: array[1..9] of char; idx: integer; // Convert the performed operations into a readable string function HistoryToString: string; var r, s: string; i, j: integer; begin s := ''; r := ''; // Mix operations and digits for i := 1 to 9 do begin s := s + history[i] + IntToStr(i); end; // Replace a vertical bar with the + or - sign that follows it for i := 1 to length(s) do begin if s[i] = '|' then begin for j := i + 1 to length(s) do begin if (s[j] = '+') or (s[j] = '-') then begin s[i] := s[j]; s[j] := ' '; break; end else begin if s[j] = '|' then s[j] := ' '; end; end; end; end; // Adjust spacing for i := 1 to length(s) do begin if s[i] = '+' then begin if i <> 1 then r := r + ' + '; end else if s[i] = '-' then begin if i <> 1 then r := r + ' - ' else r := r + '- '; end else if s[i] <> ' ' then r := r + s[i]; end; HistoryToString := r; end; // Recursivly test possible combinations procedure Recurse(parent, power, pow_sum, subsum: integer); var me, me_pow : integer; begin // If the previous digit was a 9 then check the sum // and print the result if it equals 100 if parent = 9 then begin if (subsum = 100) then Writeln(HistoryToString, ' = ', subsum); exit; end; // Try the next digit me := parent + 1; // If this digit is not part of a longer number if (power = 0) then begin // then try adding it to what we have so far history[me] := '+'; Recurse(me, 0, 0, subsum + me); // and try subtracting it history[me] := '-'; Recurse(me, 0, 0, subsum - me); // as well as combining it with the next digits // into a longer number for me_pow := 1 to 9 - me do begin history[me] := '|'; Recurse(me, me_pow, me * powers[me_pow], subsum); end; end // otherwise, tack this digit onto the back of the longer number else begin me_pow := power - 1; // If this is the last digit in the longer number if (me_pow = 0) then begin // then try adding the longer number to what we have so far history[me] := '+'; Recurse(me, me_pow, 0, subsum + pow_sum + me); // and try subtracting it history[me] := '-'; Recurse(me, me_pow, 0, subsum - pow_sum - me); end // otherwise, tack it onto the back of the longer number and continue else begin history[me] := '|'; Recurse(me, me_pow, pow_sum + (me * powers[me_pow]), subsum); end; end; end; begin for idx := 1 to 9 do history[idx] := char(32); Recurse(0,0,0,0); end.
unit PrevendaService; interface uses BasicService, ViewPrevendaVO, PrevendaVO, System.SysUtils, Vcl.ComCtrls, Generics.Collections, System.StrUtils, ProdutoVO, PrevendaItemVO, Data.DB, VendedorVO, Datasnap.DBClient, ViewPrevendaItemVO, ufrmBase, System.Math; type TPrevendaService = class(TBasicService) class procedure Abrir(out Result: TViewPrevendaVO; numeroOfPrevenda: Integer); overload; class function Abrir(numeroOfPrevenda: Integer): Boolean; overload; class procedure Consultar(out Result: TViewPrevendaVO; numeroOfPrevenda: Integer); overload; class function Consultar(numeroOfPrevenda: Integer): Integer; overload; class procedure Mostrar(ListView: TListView); class procedure ConsultaProduto(out Produto: TProdutoVO; Valor: string); class procedure ConsultaVendedor(out Vendedor: TVendedorVO; Valor: string); class function InserirItens(DataSet: TDataSet): Boolean; class function MudarSituacao(idOfPrevenda, idOfCaixa: Integer; newSituacao: string; Servico: string = 'N'): Boolean; class function CancelarItem(DataSet: TDataSet):Boolean; class function ReceberItem(DataSet: TDataSet):Boolean; class function TransferirPrevenda(Atual,Destino: string): Boolean; class function TransferirPrevendaItem(Dataset: TDataSet; Numero: string): Boolean; class function AlterarQuantidade(idOfPrevendaItem: Integer; QTD: Double): Boolean; class function InserirParceial(Prevenda: TViewPrevendaVO): Boolean; class procedure ItensPreveda(DataSet: TDataSet; idOfPrevenda: Integer); end; implementation { TPrevendaService } uses PrevendaRepository, Bibli, MovimentoService; class procedure TPrevendaService.Abrir(out Result: TViewPrevendaVO; numeroOfPrevenda: Integer); var Prevenda: TPrevendaVO; IdPrevendaMestre: Integer; begin try Prevenda:= nil; try BeginTransaction; Result:= TPrevendaRepository.getPrevendaByNumero(numeroOfPrevenda); if Assigned(Result) then begin IdPrevendaMestre:= Result.IdPrevendaMestre; FreeAndNil(Result); Result:= TPrevendaRepository.getPrevendaById(IdPrevendaMestre); end else begin Prevenda:= TPrevendaVO.Create; Prevenda.Numero:= numeroOfPrevenda; Result:= TPrevendaRepository.getPrevendaById(TPrevendaRepository.InsertPrevenda(Prevenda)); end; Commit; except Rollback; Result:= nil; end; finally if Assigned(Prevenda) then FreeAndNil(Prevenda); end; end; class function TPrevendaService.Abrir(numeroOfPrevenda: Integer): Boolean; var Pre: TViewPrevendaVO; Prevenda: TPrevendaVO; begin try Prevenda:= nil; try BeginTransaction; Pre:= TPrevendaRepository.getPrevendaByNumero(numeroOfPrevenda); if Assigned(Pre) then begin FreeAndNil(Pre); Result:= True; end else begin Prevenda:= TPrevendaVO.Create; Prevenda.Numero:= numeroOfPrevenda; Result:= (TPrevendaRepository.InsertPrevenda(Prevenda) > 0); end; Commit; except Rollback; Result:= False; end; finally if Assigned(Prevenda) then FreeAndNil(Prevenda); end; end; class function TPrevendaService.AlterarQuantidade(idOfPrevendaItem: Integer; QTD: Double): Boolean; var Item: TPrevendaItemVO; OldItem: TPrevendaItemVO; begin try Result:= True; try BeginTransaction; Item:= TPrevendaRepository.getPrevendaItemById(idOfPrevendaItem); OldItem:= TPrevendaItemVO(Item.Clone); OldItem.Quantidade:= 0; if ((Item.Quantidade - Item.QtdRecebida) > QTD) then begin Item.IdVendedorSituacao:= TfrmBase.idOfVendedor; Item.Motivo:= TfrmBase.Motivo; Item.Cliente:= TfrmBase.Cliente; end; Item.Quantidade:= QTD + Item.QtdRecebida; TPrevendaRepository.updatePrevendaItem(OldItem,Item); Commit; except Rollback; Result:= False; end; finally FreeAndNil(Item); FreeAndNil(OldItem); end; end; class function TPrevendaService.CancelarItem(DataSet: TDataSet): Boolean; var Item: TPrevendaItemVO; OldItem: TPrevendaItemVO; begin try Result:= True; BeginTransaction; DataSet.First; while not DataSet.Eof do begin if (DataSet.FieldByName('ID').AsInteger > 0) AND (DataSet.FieldByName('SELECIONADO').AsInteger = 1) then begin Item:= TPrevendaRepository.getPrevendaItemById(DataSet.FieldByName('ID').AsInteger); OldItem:= TPrevendaItemVO(Item.Clone); Item.Situacao:= 'C'; Item.IdVendedorSituacao:= TfrmBase.idOfVendedor; Item.Motivo:= TfrmBase.Motivo; Item.Cliente:= TfrmBase.Cliente; TPrevendaRepository.updatePrevendaItem(OldItem,Item); FreeAndNil(Item); FreeAndNil(OldItem); end; DataSet.Next; end; Commit; DataSet.First; while not DataSet.Eof do begin if (DataSet.FieldByName('SELECIONADO').AsInteger = 1) then begin DataSet.Delete; end else DataSet.Next; end; except Rollback; Result:= False; end; end; class procedure TPrevendaService.ConsultaProduto(out Produto: TProdutoVO; Valor: string); begin try FreeAndNil(Produto); if Length(Valor) <= 9 then Produto:= TPrevendaRepository.getProdutoByCodigo(StrToInt(Valor)); if not Assigned(Produto) then Produto:= TPrevendaRepository.getProdutoByEan(Valor); except Produto:= nil; end; end; class function TPrevendaService.Consultar(numeroOfPrevenda: Integer): Integer; var Item: TViewPrevendaVO; begin try Item:= nil; Item:= TPrevendaRepository.getPrevendaByNumero(numeroOfPrevenda); if Assigned(Item) then begin if Item.Situacao = 'A' then Result:= Item.IdPrevendaMestre else begin Result:= 0; TMovimentoService.Mensagem('Pré-venda fechada para lançamentos.'); end; FreeAndNil(Item); end else Result:= 0; except Result:= 0; end; end; class procedure TPrevendaService.Consultar(out Result: TViewPrevendaVO; numeroOfPrevenda: Integer); var IdPrevendaMestre: Integer; begin try FreeAndNil(Result); Result:= TPrevendaRepository.getPrevendaByNumero(numeroOfPrevenda); if Assigned(Result) then begin IdPrevendaMestre:= Result.IdPrevendaMestre; FreeAndNil(Result); Result:= TPrevendaRepository.getPrevendaById(IdPrevendaMestre); end; except Result:= nil; end; end; class procedure TPrevendaService.ConsultaVendedor(out Vendedor: TVendedorVO; Valor: string); begin try FreeAndNil(Vendedor); Vendedor:= TPrevendaRepository.getVendedorById(StrToInt(Valor)); except Vendedor:= nil; end; end; class function TPrevendaService.InserirItens(DataSet: TDataSet): Boolean; var Item: TPrevendaItemVO; begin try Result:= True; BeginTransaction; DataSet.First; while not DataSet.Eof do begin Item:= TPrevendaItemVO.Create; Item.IdPrevenda:= DataSet.FieldByName('ID_PREVENDA').AsInteger; Item.IdProduto:= DataSet.FieldByName('ID_PRODUTO').AsInteger; Item.IdVendedor:= DataSet.FieldByName('ID_VENDEDOR').AsInteger; Item.IdObs:= DataSet.FieldByName('ID_OBS').AsInteger; Item.Unitario:= DataSet.FieldByName('UNITARIO').AsFloat; Item.Quantidade:= DataSet.FieldByName('QUANTIDADE').AsFloat; Item.TaxaAcrescimo:= DataSet.FieldByName('TAXA_ACRESCIMO').AsFloat; TPrevendaRepository.InsertPrevendaItem(Item); FreeAndNil(Item); DataSet.Next; end; Commit; except Rollback; Result:= False; end; end; class function TPrevendaService.InserirParceial( Prevenda: TViewPrevendaVO): Boolean; begin Result:= True; BeginTransaction; try // TPrevendaRepository.PrevendaRecebimentoInserir(Prevenda.Id, Prevenda.Recebimentos); // TPrevendaRepository.PrevendaCartaoRecebimentoInserir(Prevenda.Id, Prevenda.Cartoes); Commit; except Rollback; Result:= False; end; end; class procedure TPrevendaService.ItensPreveda(DataSet: TDataSet; idOfPrevenda: Integer); var Lst: TList<TViewPrevendaItemVO>; I: Integer; begin if not DataSet.Active then TClientDataSet(DataSet).CreateDataSet; DataSet.DisableControls; TClientDataSet(DataSet).EmptyDataSet; Lst:= TPrevendaRepository.getPrevendaItemByIdPrevenda(idOfPrevenda); if Assigned(Lst) then begin for I := 0 to Pred(Lst.Count) do begin DataSet.Append; DataSet.FieldByName('ID').AsInteger:= Lst.Items[I].Id; DataSet.FieldByName('NOME').AsString:= Lst.Items[I].DescricaoPdv; DataSet.FieldByName('QUANTIDADE').AsFloat:= Lst.Items[I].Quantidade; DataSet.FieldByName('PEDIDO').AsDateTime:= Lst.Items[I].Lancamento; DataSet.FieldByName('SELECIONADO').AsInteger:= 0; DataSet.Post; end; end; DataSet.First; DataSet.EnableControls; end; class procedure TPrevendaService.Mostrar(ListView: TListView); var Lst: TList<TViewPrevendaVO>; I: Integer; begin ListView.Clear; Lst:= TPrevendaRepository.getPrevendaAll; if Assigned(Lst) then begin for I := 0 to Pred(Lst.Count) do begin if Lst.Items[i].Id = Lst.Items[i].IdPrevendaMestre then begin ListView.Items.Add; ListView.Items.Item[ListView.Items.Count - 1].Caption:= IntToStr(Lst.Items[i].Numero); case AnsiIndexStr(Lst.Items[i].Situacao[1], ['A','G','F']) of 0: ListView.Items.Item[ListView.Items.Count - 1].ImageIndex:= 0; 1: ListView.Items.Item[ListView.Items.Count - 1].ImageIndex:= 1; 2: ListView.Items.Item[ListView.Items.Count - 1].ImageIndex:= 2; end; end; Lst.Items[i].Free; end; FreeAndNil(Lst); end end; class function TPrevendaService.MudarSituacao(idOfPrevenda, idOfCaixa: Integer; newSituacao: string; Servico: string = 'N'): Boolean; var Prevenda: TPrevendaVO; begin try Result:= True; Prevenda:= TPrevendaVO.Create; Prevenda.Id:= idOfPrevenda; Prevenda.Situacao:= newSituacao; Prevenda.IdCaixa:= idOfCaixa; Prevenda.Servico:= Servico; try BeginTransaction; TPrevendaRepository.updatePrevenda(Prevenda); Commit; except Rollback; Result:= False; end; finally FreeAndNil(Prevenda); end; end; class function TPrevendaService.ReceberItem(DataSet: TDataSet): Boolean; begin try Result:= True; DataSet.DisableControls; DataSet.First; while not DataSet.Eof do begin if (DataSet.FieldByName('QTD_RECEBER_ITEM').AsCurrency > 0) then begin if (DataSet.FieldByName('QTD_RECEBER_ITEM').AsCurrency = DataSet.FieldByName('QUANTIDADE').AsCurrency) then begin DataSet.Delete; end else begin DataSet.Edit; DataSet.FieldByName('QUANTIDADE').AsCurrency:= DataSet.FieldByName('QUANTIDADE').AsCurrency - DataSet.FieldByName('QTD_RECEBER_ITEM').AsCurrency; DataSet.FieldByName('TOTAL').AsCurrency:= DataSet.FieldByName('QUANTIDADE').AsCurrency * DataSet.FieldByName('UNITARIO').AsCurrency; DataSet.FieldByName('QTD_RECEBER_ITEM').AsCurrency:= 0; DataSet.Post; DataSet.Next; end; end else DataSet.Next; end; DataSet.EnableControls; except Result:= False; DataSet.EnableControls; end; end; class function TPrevendaService.TransferirPrevenda(Atual, Destino: string): Boolean; var Prevenda: TPrevendaVO; PAtual: TViewPrevendaVO; PDestino: TViewPrevendaVO; begin try Result:= True; try BeginTransaction; PAtual:= TPrevendaRepository.getPrevendaByNumero(StrToInt(Atual)); PDestino:= TPrevendaRepository.getPrevendaByNumero(StrToInt(Destino)); if Assigned(PAtual) and Assigned(PDestino) then begin TPrevendaRepository.TranferirPrevenda(PAtual.IdPrevendaMestre, PDestino.IdPrevendaMestre); Prevenda:= TPrevendaVO.Create; Prevenda.Id:= PAtual.Id; Prevenda.Situacao:= 'T'; TPrevendaRepository.updatePrevenda(Prevenda); end else begin Result:= False; end; Commit; except Rollback; Result:= False; end; finally FreeAndNil(Prevenda); FreeAndNil(PAtual); FreeAndNil(PDestino); end; end; class function TPrevendaService.TransferirPrevendaItem(Dataset: TDataSet; Numero: string): Boolean; var Destino: TViewPrevendaVO; Item: TPrevendaItemVO; OldItem: TPrevendaItemVO; begin try Result:= True; try Destino:= TPrevendaRepository.getPrevendaByNumero(StrToIntDef(Numero,0)); if Assigned(Destino) then begin if not (Destino.Situacao = 'F') then begin BeginTransaction; Dataset.DisableControls; Dataset.First; while not Dataset.Eof do begin if Dataset.FieldByName('SELECIONADO').AsInteger = 1 then begin Item:= TPrevendaRepository.getPrevendaItemById(Dataset.FieldByName('ID').AsInteger); OldItem:= TPrevendaItemVO(Item.Clone); Item.IdPrevenda:= Destino.IdPrevendaMestre; Item.IdVendedorSituacao:= Tfrmbase.idOfVendedor; Item.Motivo:= Tfrmbase.Motivo; Item.Cliente:= Tfrmbase.Cliente; TPrevendaRepository.updatePrevendaItem(OldItem,Item); FreeAndNil(Item); FreeAndNil(OldItem); Dataset.Delete; end else begin Dataset.Next; end; end; Dataset.EnableControls; Commit; end else begin Result:= False; TMovimentoService.Mensagem('Pré-venda de destino se encontra fechada.'); end; end else begin Result:= False; TMovimentoService.Mensagem('Pré-venda de destino inexistente.'); end; except Rollback; Result:= False; end; finally FreeAndNil(Destino); end; end; end.
unit untClasses; interface uses Windows, Messages, SysUtils, StrUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, XiPanel, Menus, DB, ADODB; const LIVRE : integer = 1; ATIVO : integer = 1; OCUPADO : integer = 2; INATIVO : integer = 3; // ============================================================================= // ============================================================================= type TApto = class(TXiPanel) private FNumApto : integer; FsNumero : string; FTipoApto : string; FMenuPopUp : TPopUpMenu; FSituacao : integer; FData_Entrada : TDateTime; FHora_Entrada : TDateTime; FTranscorrido : integer; FOnDuploClique: TNotifyEvent; lblNumApto, lblTipoApto, lblSituacao, lblTipo, lblSit: TLabel; procedure SetNumeroApto(const Value: integer); procedure SetTipoApto(const Value: string); procedure SetSituacao(const Value: integer); procedure ConfiguraPopUp(const Value: TPopUpMenu); procedure SetEventoDuploClique(const Value: TNotifyEvent); procedure SetData_Entrada(const Value: TDateTime); procedure SetHora_Entrada(const Value: TDateTime); function GetTranscorrido: integer; public constructor Cria(AOwner: TComponent); destructor Destroy; override; published property Numero: integer read FNumApto write SetNumeroApto; property sNumero: string read FsNumero; property Tipo: string read FTipoApto write SetTipoApto; property Situacao: integer read FSituacao write SetSituacao; property Menu: TPopUpMenu read FMenuPopUp write ConfiguraPopUp; property OnDuploClique: TNotifyEvent read FOnDuploClique write SetEventoDuploClique; property Hora_Entrada: TDateTime read FHora_Entrada write SetHora_Entrada; property Data_Entrada: TDateTime read FData_Entrada write SetData_Entrada; property Transcorrido: integer read GetTranscorrido; //property Ocupado: boolean read FOcupado write AlteraSituacao; //property Ativo: boolean read FAtivo write AtivaApto; //property OnMouseMove2: TMouseMoveEvent read FOnMouseMove write ConfiguraEvento; //property Visivel: boolean read FVisivel write SetFVisivel; end; implementation uses untDM; { TApto } // ============================================================================= // ============================================================================= constructor TApto.Cria(AOwner: TComponent); begin inherited Create(AOwner); Parent := TWinControl(AOwner); Visible := false; // Configura o Panel Height := 75; Width := 150; ColorFace := clWhite; ColorGrad := $00DAE0DE; ColorLight := $007D7D7D; ColorDark := $00626262; // Cria os Labels lblNumApto := TLabel.Create(Self); lblTipoApto := TLabel.Create(Self); lblSituacao := TLabel.Create(Self); lblTipo := TLabel.Create(Self); lblSit := TLabel.Create(Self); // Configura o Label do Numero do Apto lblNumApto.Font.Name := 'Verdana'; lblNumApto.Font.Size := 14; lblNumApto.Font.Style := [fsBold]; lblNumApto.Font.Color := $00CAD1D5; lblNumApto.Transparent := True; lblNumApto.Top := 6; lblNumApto.Left := 6; // Configura o Label de Tipo do Apto lblTipoApto.Font.Name := 'Lucida Console'; lblTipoApto.Font.Size := 8; lblTipoApto.Font.Color := $00CAD1D5; lblTipoApto.Transparent := True; lblTipoApto.Top := 36; lblTipoApto.Left := 8; lblTipoApto.Caption := 'Tipo....:'; // Configura o Label de Situacao lblSituacao.Font.Name := 'Lucida Console'; lblSituacao.Font.Size := 8; lblSituacao.Font.Color := $00CAD1D5; lblSituacao.Transparent := true; lblSituacao.Top := 52; lblSituacao.Left := 8; lblSituacao.Caption := 'Situacao:'; // Configura o Label que descreve o Tipo lblTipo.Font.Name := 'Lucida Console'; lblTipo.Font.Size := 8; lblTipo.Font.Color := $00CAD1D5; lblTipo.Transparent := True; lblTipo.Top := 36; lblTipo.Left := 79; lblTipo.Caption := '-------'; // Configura o Label que descreve a Situacao lblSit.Font.Name := 'Lucida Console'; lblSit.Font.Size := 8; lblSit.Font.Color := $00CAD1D5; lblSit.Transparent := true; lblSit.Top := 52; lblSit.Left := 79; lblSit.Caption := 'INATIVO'; // Mostra os Labels dentro do Panel lblNumApto.Parent := Self; lblTipoApto.Parent := Self; lblSituacao.Parent := Self; lblTipo.Parent := Self; lblSit.Parent := Self; end; // ============================================================================= destructor TApto.Destroy; begin lblNumApto.Free; lblTipoApto.Free; lblSituacao.Free; lblTipo.Free; lblSit.Free; lblNumApto := nil; lblTipoApto := nil; lblSituacao := nil; lblTipo := nil; lblSit := nil; inherited Destroy; end; // ============================================================================= // Altera a propriedade Numero do Objeto TApto // Altera o Caption do Label do Numero do Apartamento // ============================================================================= procedure TApto.SetNumeroApto(const Value: integer); begin FNumApto := Value; FsNumero := RightStr('00'+IntToStr(Value),2); lblNumApto.Caption := FsNumero; end; // ============================================================================= procedure TApto.SetTipoApto(const Value: string); begin FTipoApto := Value; lblTipo.Caption := Value; end; // ============================================================================= procedure TApto.ConfiguraPopUp(const Value: TPopUpMenu); begin FMenuPopUp := Value; PopupMenu := Value; end; // ============================================================================= procedure TApto.SetEventoDuploClique(const Value: TNotifyEvent); begin FOnDuploClique := Value; OnDblClick := FOnDuploClique; lblNumApto.OnDblClick := FOnDuploClique; lblTipoApto.OnDblClick := FOnDuploClique; lblSituacao.OnDblClick := FOnDuploClique; lblTipo.OnDblClick := FOnDuploClique; lblSit.OnDblClick := FOnDuploClique; end; // ============================================================================= procedure TApto.SetSituacao(const Value: integer); var sSituacao: string; dDataEntrada, dHoraEntrada: TDateTime; rRegistro: _RecordSet; begin FSituacao := Value; // Sinaliza como "LIVRE" o objeto Apto if ( FSituacao = LIVRE ) then begin lblSit.Caption := 'LIVRE'; ColorFace := clWhite; ColorGrad := $00DAE0DE; ColorLight := $007D7D7D; ColorDark := $00626262; lblNumApto.Font.Color := clBlack; lblTipoApto.Font.Color := clBlack; lblSituacao.Font.Color := clBlack; lblTipo.Font.Color := clNavy; lblSit.Font.Color := clNavy; sSituacao := 'L'; end // Sinaliza como "OCUPADO" o objeto Apto else if ( FSituacao = OCUPADO ) then begin lblSit.Caption := 'OCUPADO'; ColorDark := $0000009D; ColorFace := clWhite; ColorGrad := $000076EC; ColorLight := $000651CC; sSituacao := 'O'; rRegistro := dmPrincipal.conn.Execute('SELECT dt_entrada, hr_entrada FROM movimentos WHERE numero_apto=' + IntToStr(Numero) + ' AND status=true'); FData_Entrada := rRegistro.Fields[0].Value; FHora_Entrada := rRegistro.Fields[1].Value; end // Sinaliza como "INATIVO" o objeto Apto else begin lblNumApto.Font.Color := $00CAD1D5; lblTipoApto.Font.Color := $00CAD1D5; lblSituacao.Font.Color := $00CAD1D5; lblTipo.Font.Color := $00CAD1D5; lblSit.Font.Color := $00CAD1D5; lblTipo.Caption := '-------'; lblSit.Caption := 'INATIVO'; ColorFace := clWhite; ColorGrad := $00DAE0DE; ColorLight := $007D7D7D; ColorDark := $00626262; sSituacao := 'I'; end; sSituacao := QuotedStr(sSituacao); // Atualiza a base de dados dmPrincipal.conn.Execute('UPDATE aptos SET situacao=' + sSituacao + ' WHERE numero=' + IntToStr( Numero )); end; // ============================================================================= procedure TApto.SetData_Entrada(const Value: TDateTime); begin FData_Entrada := Value; end; // ============================================================================= procedure TApto.SetHora_Entrada(const Value: TDateTime); begin FHora_Entrada := Value; end; // ============================================================================= // Pega o tempo transcorrido apos o registro de Entrada no Apartamento // ============================================================================= function TApto.GetTranscorrido: integer; var x: TDateTime; begin // x := FData_Entrada - Date(); // Result := StrToInt(DateToStr end; end.
unit uLockBox_RSA_TestCases; interface uses TestFramework, uTPLb_Hash, uTPLb_CryptographicLibrary, Classes, uTPLb_Codec, uTPLb_StreamCipher, uTPLb_HugeCardinal, uTPLb_MemoryStreamPool; type TRSA_TestCase = class( TTestCase) protected FPool: IMemoryStreamPool; FwasAborted: boolean; FdoAbort: boolean; procedure SetUp; override; procedure TearDown; override; procedure OnProgress( Sender: TObject; BitsProcessed, TotalBits: int64; var doAbort: boolean); procedure CheckPowerModWithCRT( m, d, n, p, q, dp, dq, qinv: THugeCardinal; const Msg: string); published procedure ChineseRemainderTheorem; procedure Test_Compute_RSA_Fundamentals; procedure Test_RSA_Primitives; procedure Cardinal2Stream_InversionTests; procedure RSAES_OAEP_ENCDECRYPT; end; TRSA_Crypto_TestCase = class( TTestCase) protected FPool: IMemoryStreamPool; FwasAborted: boolean; FdoAbort: boolean; Lib: TCryptographicLibrary; Codec: TCodec; procedure SetUp; override; procedure TearDown; override; published procedure Test_Encrypt; end; implementation uses SysUtils, uTPLb_HashDsc, uTPLb_BinaryUtils, uTPLb_StreamUtils, uTPLb_ECB, uTPLb_BlockCipher, uTPLb_Random, uTPLb_HugeCardinalUtils, uTPLb_IntegerUtils, uTPLb_RSA_Primitives, Forms, uTPLb_StrUtils; { TTestCaseFirst } // Output from a run of Make Sample Key // ================================== BEGIN ===================== //Now generating an RSA-1024 key pair //Generation completed. //Generation took 34s. //318 primality tests were conducted to reach this goal, //at a rate of 9.4 tests per second. // //n has 1024 bits. //e has 17 bits. //d has 1022 bits. //n (little-endien; base64) = "u9GFdi6di8zy/ZoPVdyOjtXdozDgVWXPCkHYIZ1DDsLI+rwhkY9CdnlJ6kjAtTOnemeV5n/+l9xuzrI4d1x+UlQegAkQSgLbhWp9XZNrz80SfVals7e+/cIAxIi4v/n1NP2VVGl6ABfZr+qnv3EZVhf+nwqwForIgsdEuVmSy8k="; // //e (little-endien; base64) = "AQAB"; // //e (decimal) = 65537 // //d (little-endien; base64) = "cY9AhN6Jz6bQ0DVeoifJWTgMl5U6qvoDQX/d+Jsi8Tw2PfUP0RaAuHiiCP2qPS7ScxR3fXxpRI2IibNEcClGklXzXyKm3Q2p20/dz2LDjB8125fRF3i/jabGqZQEv2lOfN1NICjlZxyM9e19IRlJHg3TItmr2ELAjRYUjQWjqic="; // // //AES-256 key (base64) = "+KcK4snvh88mf8NxcdU3ri1HSPyqRu1pb0+pEB511jE="; //Now generating an RSA-1024 key pair //Generation completed. //Generation took 34s. //318 primality tests were conducted to reach this goal, //at a rate of 9.4 tests per second. // //n has 1024 bits. //e has 17 bits. //d has 1022 bits. //n (little-endien; base64) = "u9GFdi6di8zy/ZoPVdyOjtXdozDgVWXPCkHYIZ1DDsLI+rwhkY9CdnlJ6kjAtTOnemeV5n/+l9xuzrI4d1x+UlQegAkQSgLbhWp9XZNrz80SfVals7e+/cIAxIi4v/n1NP2VVGl6ABfZr+qnv3EZVhf+nwqwForIgsdEuVmSy8k="; // //e (little-endien; base64) = "AQAB"; // //e (decimal) = 65537 // //d (little-endien; base64) = "cY9AhN6Jz6bQ0DVeoifJWTgMl5U6qvoDQX/d+Jsi8Tw2PfUP0RaAuHiiCP2qPS7ScxR3fXxpRI2IibNEcClGklXzXyKm3Q2p20/dz2LDjB8125fRF3i/jabGqZQEv2lOfN1NICjlZxyM9e19IRlJHg3TItmr2ELAjRYUjQWjqic="; // // //AES-256 key (base64) = "+KcK4snvh88mf8NxcdU3ri1HSPyqRu1pb0+pEB511jE="; // ================================== END ===================== const Test_n: string = // n (little-endien; base64) 'u9GFdi6di8zy/ZoPVdyNjtXdozDgVWXPCkHYIZ1DDsLI+rwhkY9CdnlJ6kjAtTNneme' + 'V5n/+l9xuzrI4d1x+UlQegAkQSgLbhWp9XZOrz80SfVals7e+/cIAxIi4v/n1OP2VVG' + 'l6ABfZr+qnv3EZVhf+nwqwForIgsdEuVmSy8k='; Test_n_bits = 1024; Test_e: string = // e (little-endien; base64) 'AQAB'; Test_e_bits = 17; Test_d: string = // d (little-endien; base64) 'cY9AhO6Jz6bQ0DVeoifJWTgMl5U6qvoDQX/d+Jsi8Tw2PfUP0RaAuHiiCP2qPS7ScxR' + '3fXxpRI2IibOEcClGklXzXyKm3Q2p20/dz2LDjB8125fRF3i/jabGqZQEv2lNfO1OIC' + 'jlZxyM9e19IRlJHg3TItmr2ELAjRYUjQWjqic='; Test_d_bits = 1022; Test_AES256Key: string = // (base64; LoadFromStream) '+KcK4snvh88mf8OxcdU3ri1HSPyqRu1pb0+pEB511jE='; procedure InitUnit_RSA_TestCases; begin TestFramework.RegisterTest( TRSA_TestCase.Suite); TestFramework.RegisterTest( TRSA_Crypto_TestCase.Suite); end; procedure DoneUnit_RSA_TestCases; begin end; { TRSA_TestCase } procedure TRSA_TestCase.Cardinal2Stream_InversionTests; var i1, i2: THugeCardinal; s1, s2: TMemoryStream; begin TRandomStream.Instance.Seed := 1; // 1. Create a Huge Cardinal of 64 bits (8 bytes). i1 := THugeCardinal.CreateRandom( 64, 64, True, FPool); // 2. Stream it out to a 9 byte stream. s1 := FPool.NewMemoryStream( 0); i1.StreamOut( BigEndien, s1, 9); // 3. Stream it back in s1.Position := 0; i2 := THugeCardinal.CreateFromStreamIn( 64, BigEndien, s1, FPool); // 4. Compare cardinal with the original Check( i1.Compare( i2) = rEqualTo, 'Cardinal --> Stream inversion test.'); // 1. Create a random stream with 4 bytes s1.Size := 4; RandomFillStream( s1); // 2. Stream it in. MaxBits = 32 i1.Free; s1.Position := 0; i1 := THugeCardinal.CreateFromStreamIn( 32, BigEndien, s1, FPool); // 3. Stream it out. s2 := FPool.NewMemoryStream( 4); s2.Position := 0; i1.StreamOut( BigEndien, s2, 4); // 4. Compare stream with the original. Check( CompareMemoryStreams( s1, s2), 'Stream --> Cardinal inversion test.'); i1.Free; i2.Free; s1.Free; s2.Free end; procedure TRSA_TestCase.OnProgress( Sender: TObject; BitsProcessed, TotalBits: int64; var doAbort: boolean); begin // Application.ProcessMessages if FdoAbort then doAbort := True end; procedure TRSA_TestCase.RSAES_OAEP_ENCDECRYPT; var n, e, d, Totient: THugeCardinal; Count1, j, i: integer; Plaintext, Ciphertext, Recon: TMemoryStream; p, q, dp, dq, qinv: THugeCardinal; begin TRandomStream.Instance.Seed := 1; for j := 1 to 3 do begin Count1 := 0; Compute_RSA_Fundamentals_2Factors( 480, StandardExponent, n, e, d, Totient, p, q, dp, dq, qinv, nil, nil, 20, FPool, Count1, FwasAborted); Check( Validate_RSA_Fundamentals( n, e, d, Totient), 'Failed to generate RSA key pair.'); for i := 1 to 10 do begin Plaintext := TMemoryStream.Create; Plaintext.Size := RSAES_OAEP_ENCRYPT_MaxByteLen( n); RandomFillStream( Plaintext); Plaintext.Position := 0; Ciphertext := TMemoryStream.Create; Check( RSAES_OAEP_ENCRYPT( n, e, Plaintext, Ciphertext), 'RSAES_OAEP_ENCRYPT'); Ciphertext.Position := 0; Recon := TMemoryStream.Create; Check( RSAES_OAEP_DECRYPT( d, n, Ciphertext, Recon, p, q, dp, dq, qinv), 'RSAES_OAEP_DECRYPT'); Check( CompareMemoryStreams( Plaintext, Recon), 'RSAES_OAEP_ENCRYPT/RSAES_OAEP_DECRYPT inversion.'); Plaintext.Free; Ciphertext.Free; recon.Free; Application.ProcessMessages; end; n.Free; d.Free; e.Free; Totient.Free; p.Free; q.Free; dp.Free; dq.Free; qinv.Free; end; end; procedure TRSA_TestCase.SetUp; begin FPool := NewPool; FwasAborted := False; FdoAbort := False; end; procedure TRSA_TestCase.TearDown; begin FPool := nil; FwasAborted := False; FdoAbort := False; end; procedure TRSA_TestCase.Test_Compute_RSA_Fundamentals; var n, e, d, Totient: THugeCardinal; Count1: integer; // j, Sz, Current, Peak: integer; // s: string; p, q, dp, dq, qinv: THugeCardinal; begin GreatestPassCount := 0; Count1 := 0; Compute_RSA_Fundamentals_2Factors( 512, StandardExponent, n, e, d, Totient, p, q, dp, dq, qinv, OnProgress, nil, 20, FPool, Count1, FwasAborted); if not FwasAborted then Check( Validate_RSA_Fundamentals( n, e, d, Totient), 'Failed to generate RSA key pair.'); Totient.Free; n.Free; e.Free; d.Free; p.Free; q.Free; dp.Free; dq.Free; qinv.Free; //for j := 0 to FPool.BayCount - 1 do // begin // Sz := FPool.GetSize( j); // FPool.GetUsage( Sz, Current, Peak); // s := Format( 'MemSize=%d; Final=%d; Peak=%d; Passes=%d', [Sz, Current, Peak, GreatestPassCount]); // s := s + ' ' // end end; procedure TRSA_TestCase.CheckPowerModWithCRT( m, d, n, p, q, dp, dq, qinv: THugeCardinal; const Msg: string); var m1, m2: THugeCardinal; begin m1 := m.Clone; m2 := m.Clone; m1.PowerMod( d, n, nil); m2.PowerMod_WithChineseRemainderAlgorithm( d, n, p, q, dp, dq, qinv, nil); Check( m1.Compare( m2) = rEqualTo, Msg); m1.Free; m2.Free end; procedure TRSA_TestCase.ChineseRemainderTheorem; var n, e, d, Totient: THugeCardinal; Count1: integer; p, q, dp, dq, qinv: THugeCardinal; m0: THugeCardinal; c: THugeCardinal; begin TRandomStream.Instance.Seed := 55; // result(=m==65) == pre_self(=c=2790) ** Exponent(=d=2753) mod Modulus(=n=3233) c := THugeCardinal.CreateSimple( 2790); d := THugeCardinal.CreateSimple( 2753); n := THugeCardinal.CreateSimple( 3233); dp := THugeCardinal.CreateSimple( 53); dq := THugeCardinal.CreateSimple( 49); qinv := THugeCardinal.CreateSimple( 38); p := THugeCardinal.CreateSimple( 61); q := THugeCardinal.CreateSimple( 53); CheckPowerModWithCRT( c, d, n, p, q, dp, dq, qinv, 'PowerMod failed Wikipedia example.'); FreeAndNil( c); FreeAndNil( d); FreeAndNil( n); FreeAndNil( dp); FreeAndNil( dq); FreeAndNil( qinv); FreeAndNil( p); FreeAndNil( q); GreatestPassCount := 0; Count1 := 0; Compute_RSA_Fundamentals_2Factors( 512, StandardExponent, n, e, d, Totient, p, q, dp, dq, qinv, OnProgress, nil, 20, FPool, Count1, FwasAborted); m0 := THugeCardinal.CreateRandom( n.BitLength, n.BitLength, False, nil); if not FwasAborted then CheckPowerModWithCRT( m0, d, n, p, q, dp, dq, qinv, 'PowerMod failed.'); m0.Free; Totient.Free; n.Free; e.Free; d.Free; p.Free; q.Free; dp.Free; dq.Free; qinv.Free; end; procedure TRSA_TestCase.Test_RSA_Primitives; var Tmp: TStream; n, e, d: THugeCardinal; p, q, dp, dq, qinv: THugeCardinal; PlainText, Ciphertext, Recon: TMemoryStream; function MakeHuge( const Definition: TBytes; BitLen: cardinal) : THugeCardinal; begin Tmp.Size := 0; Base64_to_stream( Definition, Tmp); Tmp.Position := 0; result := THugeCardinal.CreateFromStreamIn( BitLen, LittleEndien, Tmp, FPool) end; begin // 1. Create n // 2. Create d // 3. Create e // 4. Create test plaintext stream // 5. Encrypt // 6. Check encryption result // 7. Decyrpt // 8. Check decryption result // 9. Compare and check plaintext with reconstruction // 10. Clean-up (n, d, e, plaintext, ciphertext, recon) TRandomStream.Instance.Seed := 1; Tmp := FPool.NewMemoryStream( 0); PlainText := TMemoryStream.Create; Ciphertext := TMemoryStream.Create; Recon := TMemoryStream.Create; n := MakeHuge( AnsiBytesOf(Test_n), Test_n_bits); e := MakeHuge( AnsiBytesOf(Test_e), Test_e_bits); d := MakeHuge( AnsiBytesOf(Test_d), Test_d_bits); p := nil; q := nil; dp := nil; dq := nil; qinv := nil; PlainText.Size := 40; RandomFillStream( Plaintext); try Check( PlainText.Size <= RSAES_OAEP_ENCRYPT_MaxByteLen( n), Format('Plaintext too big (%d) for RSA keys.',[PlainText.Size])); Check( RSAES_OAEP_ENCRYPT( n, e, Plaintext, Ciphertext), 'RSAES_OAEP_ENCRYPT'); Check( RSAES_OAEP_DECRYPT( d, n, Ciphertext, Recon, p, q, dp, dq, qinv), 'RSAES_OAEP_DECRYPT'); Check( CompareMemoryStreams( Plaintext, Recon), 'RSAES_OAEP_ENCRYPT/RSAES_OAEP_DECRYPT general inversion test failed!') finally Tmp.Free; Plaintext.Free; Ciphertext.Free; Recon.Free; n.Free; e.Free; d.Free; p.Free; q.Free; dp.Free; dq.Free; qinv.Free; end end; //PAllocationRecord(fpool.fallocrecord.[0])^.fpeakusage // //KeySize Trial PeakUsage //512 1 21 //512 2 18 //512 3 19 //512 4 18 //512 5 18 //512 6 19 //512 7 18 //512 8 18 //1024 1 20 //1024 2 19 //1024 3 18 //1024 4 18 //1024 5 21 //4096 1 //4096 2 const RSA_512_SampleKey1: string = 'QAAAADfRWmA3nhVOOvqB0CLoy1lvP6VwuPRY0gYMtGjS+G3vPVZG/adCkgcAuhduuzR' + 'af42JCz75O8vrSS66owu2OWRAAAAA0YnbSszKdiN+s9zNiJizwIjK11cvNISf3jmFqB' + 'iDCVKojcmJbnPEPsAbUlHx1oqpI4EpQuooNIC/3eELq0gZFAMAAAABAAE='; RSA_512_SampleKey2: string = 'QAAAAB90ZOa8vuzPpmWuWReBRuE12r/oAfFMJdBk8XfTIHB26+o1u1VtwV0NRYaqR/N' + '4dkvhfF8Eb1LgzRZzf1vh9JlAAAAAcenoFSj7DtDGUByUhN3zcB+eOD0/sNn1Fqaizm' + '+qUv1RUUg+iXnQw1qZVlLliNzvZw3k01M2myXAsJNOLVXYDwMAAAABAAE='; RSA_1024_SampleKey1: string = 'gAAAAIWILE/fqXIjMtXbxffzixJ3T71Kg+JsSzwuEuqbwP5y/D2f7XluAC4cYoCU3qA' + 'WfRy23JaR+rXAWFMw2J/MSEO43Vbq1RHis0jeb4JD44Y9D1zV+sJ8CIWhzp38QzqhGb' + 'PMDAFDQXwd9Hf5Ch9qoh7NJR7KWFBWZuA5kK/eiF2CgAAAABMwrc8ZDRGbb8uWsTNcm' + 'sV0DoQ6gLZTLwSNAsjadAmPHviXRleVIQaBeruwuWSYUBbNJOQrPb095KM9s7BDlxSN' + 'WJnvBkGYQx9ZXbHdwrMDlKQEkpkoetkbGSWZGLBRRCW3muhQIIXOtQ1ABUASi9HKuno' + 'zojA3/qbs5HHn1Y0gAwAAAAEAAQ=='; RSA_1024_SampleKey2: string = 'gAAAAC9TuThwZQG596+UXAwLGLR5gdhOns4RmB4a/QBq0PLfaX8QiLhx4ziihWRHh2u' + 'AtYM7TgWFegIv5ZJ75uNjpyNHOx/qOhrUwRUzCi5NT5Atl7iDwPz42uqUjJOoDNpsBx' + 'lXhWIZUFrer3jY5b/ZJiNrt+A+I7LhaEmCbLsb9MB8gAAAAO3PcBC72KBGVQXgZJWQw' + 'U24e9cGKYu3h4J6ujTqfdWR21QQJGbWjbl9UG6JdLSxsESxQ2FcPa0s/UWfQEdmmRhK' + 'OjGYvSiLnlNjoUdJiXjrQ1n0lUcR/Z7+pYFdtY3P12JQ9Oml7jBwYbMFvddqh4qgPkJ' + 'GcJLw1+G5w8DPez0BAwAAAAEAAQ=='; { TRSA_Crypto_TestCase } procedure TRSA_Crypto_TestCase.SetUp; var Store: TStream; s: string; begin Lib := TCryptographicLibrary.Create( nil); Codec := TCodec.Create( nil); Codec.CryptoLibrary := Lib; Codec.StreamCipherId := 'native.RSA'; Codec.AsymetricKeySizeInBits := 1024; Store := TMemoryStream.Create; try case Codec.AsymetricKeySizeInBits of 512: s := RSA_512_SampleKey1; 1024: s := RSA_1024_SampleKey1; else Check( False, 'No test case yet for this key size.'); end; Base64_to_stream( AnsiBytesOf(s), Store); Store.Position := 0; Codec.InitFromStream( Store); finally Store.Free; end end; procedure TRSA_Crypto_TestCase.TearDown; begin Codec.Free; Lib.Free end; procedure TRSA_Crypto_TestCase.Test_Encrypt; const sTestPlaintext: string = 'Test me!'; var x, y, recon_x: string; begin x := sTestPlaintext; Codec.EncryptAnsiString( x, y); Codec.Reset; Codec.DecryptAnsiString( recon_x, y); Check( x = recon_x, 'RSA Crypto'); end; initialization InitUnit_RSA_TestCases; finalization DoneUnit_RSA_TestCases; end.
program iLbc; {$APPTYPE CONSOLE} {$MODE Delphi} uses SysUtils, Interfaces, iLBC_define in 'iLBC_define.pas', constants in 'constants.pas', C2Delphi_header in 'C2Delphi_header.pas', syntFilters in 'syntFilters.pas', lsf in 'lsf.pas', anaFilters in 'anaFilters.pas', createCB in 'createCB.pas', doCPLC in 'doCPLC.pas', filter in 'filter.pas', FrameClassifys in 'FrameClassifys.pas', getCBvecs in 'getCBvecs.pas', helpfun in 'helpfun.pas', hpInputs in 'hpInputs.pas', hpOutputs in 'hpOutputs.pas', gainquants in 'gainquants.pas', enhancers in 'enhancers.pas', StateSearchWs in 'StateSearchWs.pas', StateConstructWs in 'StateConstructWs.pas', iCBConstructs in 'iCBConstructs.pas', iCBSearchs in 'iCBSearchs.pas', LPCdecode in 'LPCdecode.pas', LPCencodes in 'LPCencodes.pas', packing in 'packing.pas', iLBC_decodes in 'iLBC_decodes.pas', iLBC_encodes in 'iLBC_encodes.pas'; {.$R *.res} Const ILBCNOOFWORDS_MAX = (NO_OF_BYTES_30MS div 2); {---------------------------------------------------------------* * Main program to test iLBC encoding and decoding * * Usage: * exefile_name.exe <infile> <bytefile> <outfile> <channel> * * <infile> : Input file, speech for encoder (16-bit pcm file) * <bytefile> : Bit stream output from the encoder * <outfile> : Output file, decoded speech (16-bit pcm file) * <channel> : Bit error file, optional (16-bit) * 1 - Packet received correctly * 0 - Packet Lost * *--------------------------------------------------------------} var starttime:real; runtime:real; outtime:real; ifileid,efileid,ofileid, cfileid,iBytesRead:integer; data:array [0..BLOCKL_MAX-1] of Smallint; encoded_data:array [0..ILBCNOOFWORDS_MAX-1] of Smallint; decoded_data:array [0..BLOCKL_MAX-1] of Smallint; len:integer; pli, mode:Smallint; blockcount:integer; packetlosscount:integer; { Create structs } Enc_Inst:iLBC_Enc_Inst_t; Dec_Inst:iLBC_Dec_Inst_t; {----------------------------------------------------------------* * Encoder interface function *---------------------------------------------------------------} function encode( { (o) Number of bytes encoded } iLBCenc_inst:piLBC_Enc_Inst_t; { (i/o) Encoder instance } encoded_data:PAshort; { (o) The encoded bytes } data:PAshort { (i) The signal block to encode} ):Smallint; var block:array [0..BLOCKL_MAX-1] of real; k:integer; begin { convert signal to float } for k:=0 to iLBCenc_inst^.blockl-1 do block[k] := data[k]; { do the actual encoding } iLBC_encode(@encoded_data[0], @block, iLBCenc_inst); result:= Smallint(iLBCenc_inst^.no_of_bytes); end; {----------------------------------------------------------------* * Decoder interface function *---------------------------------------------------------------} function decode( { (o) Number of decoded samples } iLBCdec_inst:piLBC_Dec_Inst_t; { (i/o) Decoder instance } decoded_data:PAshort; { (o) Decoded signal block} encoded_data:PAshort; { (i) Encoded bytes } mode:Smallint { (i) 0:=PL, 1:=Normal } ):Smallint; var k:integer; decblock:array [0..BLOCKL_MAX-1] of real; dtmp:real; begin { check if mode is valid } if (mode<0) or (mode>1) then begin writeln(ErrOutput,'ERROR - Wrong mode - 0, 1 allowed'); result:=3; exit; end; { do actual decoding of block } iLBC_decode(@decblock, @encoded_data[0], iLBCdec_inst, mode); { convert to short } for k:=0 to iLBCdec_inst^.blockl-1 do begin dtmp:=decblock[k]; if (dtmp<MIN_SAMPLE) then dtmp:=MIN_SAMPLE else if (dtmp>MAX_SAMPLE) then dtmp:=MAX_SAMPLE; decoded_data[k] := trunc(dtmp); end; result:= Smallint(iLBCdec_inst^.blockl); end; begin try { Runtime statistics } blockcount := 0; packetlosscount := 0; { get arguments and open files } if ((ParamCount<>4) and (ParamCount<>5)) then begin writeln(ErrOutput,inttostr(ParamCount)); writeln(ErrOutput, '*-----------------------------------------------*'); writeln(ErrOutput,Format(' %s <20,30> input encoded decoded (channel)',[ParamStr(0)])); writeln(ErrOutput, ' mode : Frame size for the encoding/decoding'); writeln(ErrOutput, ' 20 - 20 ms'); writeln(ErrOutput, ' 30 - 30 ms'); writeln(ErrOutput, ' input : Speech for encoder (16-bit pcm file)'); writeln(ErrOutput, ' encoded : Encoded bit stream'); writeln(ErrOutput, ' decoded : Decoded speech (16-bit pcm file)'); writeln(ErrOutput, ' channel : Packet loss pattern, optional (16-bit)'); writeln(ErrOutput, ' 1 - Packet received correctly'); writeln(ErrOutput, ' 0 - Packet Lost'); writeln(ErrOutput, '*-----------------------------------------------*'); exit; end; mode:=strtoint(ParamStr(1)); if (mode <> 20) and (mode <> 30) then begin writeln(ErrOutput,Format('Wrong mode %s, must be 20, or 30',[ParamStr(1)])); exit; end; ifileid := FileOpen(ParamStr(2), fmOpenRead or fmShareDenyNone); if ( ifileid < 1) then begin writeln(ErrOutput,Format('Cannot open input file %s', [ParamStr(2)])); exit; end; if FileExists(ParamStr(3)) then begin SysUtils.DeleteFile(ParamStr(3)); end; efileid := FileCreate(ParamStr(3)); if ( efileid<1) then begin writeln(ErrOutput,Format('Cannot open encoded file %s', [ParamStr(3)])); exit; end; if FileExists(ParamStr(4)) then begin SysUtils.DeleteFile(ParamStr(4)); end; ofileid := FileCreate(ParamStr(4)); if (ofileid<1) then begin writeln(ErrOutput,Format('Cannot open decoded file %s', [ParamStr(4)])); exit; end; if (ParamCount=5) then begin cfileid := FileOpen(ParamStr(5), fmOpenRead or fmShareDenyNone); if(cfileid<1) then begin writeln(ErrOutput,Format('Cannot open channel file %s', [ParamStr(5)])); exit; end; end else begin cfileid:=0; end; { print info } writeln(ErrOutput,''); writeln(ErrOutput, '*---------------------------------------------------*'); writeln(ErrOutput, '* *'); writeln(ErrOutput, '* iLBC test program *'); writeln(ErrOutput, '* *'); writeln(ErrOutput, '* *'); writeln(ErrOutput, '*---------------------------------------------------*'); writeln(ErrOutput,Format('Mode : %2d ms', [mode])); writeln(ErrOutput,Format('Input file : %s', [ParamStr(2)])); writeln(ErrOutput,Format('Encoded file : %s', [ParamStr(3)])); writeln(ErrOutput,Format('Output file : %s', [ParamStr(4)])); if (ParamCount =5) then begin writeln(ErrOutput,Format('Channel file : %s', [ParamStr(5)])); end; writeln(ErrOutput,''); { Initialization } initEncode(@Enc_Inst, mode); initDecode(@Dec_Inst, mode, 1); { Runtime statistics } starttime:=GetTickCount(); { loop over input blocks } iBytesRead := FileRead(ifileid, data[0], sizeof(Smallint)*Enc_Inst.blockl); while (iBytesRead=sizeof(Smallint)*Enc_Inst.blockl) do begin inc(blockcount); { encoding } write(ErrOutput,Format('--- Encoding block %d --- ',[blockcount])); len:=encode(@Enc_Inst, @encoded_data, @data); write(ErrOutput,#13); { write byte file } FileWrite(efileid, encoded_data[0], sizeof(char)*len); { get channel data if provided } if (ParamCount =6) then begin if fileread(cfileid,pli, sizeof(Smallint))<1 then begin if ((pli<>0) and (pli<>1)) then begin writeln(ErrOutput,'Error in channel file'); exit; end; if (pli=0) then begin { Packet loss ^. remove info from frame } fillchar(encoded_data,sizeof(Smallint)*ILBCNOOFWORDS_MAX, 0); inc(packetlosscount); end; end else begin writeln(ErrOutput,'Error. Channel file too short'); exit; end; end else begin pli:=1; end; { decoding } write(ErrOutput,Format('--- Decoding block %d --- ',[blockcount])); len:=decode(@Dec_Inst, @decoded_data, @encoded_data, pli); write(ErrOutput,#13); { write output file } filewrite(ofileid,decoded_data,sizeof(Smallint)*len); iBytesRead := FileRead(ifileid, data[0], sizeof(Smallint)*Enc_Inst.blockl); end; { Runtime statistics } runtime := (GetTickCount()-starttime); outtime := (blockcount*mode/1000.0); writeln(ErrOutput,Format('Length of speech file: %.1f s', [outtime])); writeln(ErrOutput,Format('Packet loss : %.1f%%', [100.0*packetlosscount/blockcount])); write('Time to run iLBC :'); writeln(ErrOutput,Format(' %.1f s (%.1f %% of realtime)', [runtime/1000,(100*runtime/outtime)/1000])); { close files } except FileClose(ifileid); FileClose(efileid); FileClose(ofileid); if (ParamCount=6) then begin FileClose(cfileid); end; end; end.
unit sshsha; interface uses sshhash; type SHA_CTX = packed record Data: array [0..23] of integer; end; PSHA_CTX = ^SHA_CTX; TSSHSHA1 = class(TSSHHash) protected sha1: SHA_CTX; function GetDigLen: integer; override; public constructor Create; override; procedure Assign(Source: TSSHSHA1); // for hmac use procedure Update(Data: Pointer; Len: integer); override; procedure Final(Digest: Pointer); override; end; procedure SHA1_Init(c: PSHA_CTX); cdecl; external 'libeay32.dll'; procedure SHA1_Update(c: PSHA_CTX; Data: Pointer; Len: integer); cdecl; external 'libeay32.dll'; procedure SHA1_Final(Digest: Pointer; c: PSHA_CTX); cdecl; external 'libeay32.dll'; implementation { TSSHSHA1 } procedure TSSHSHA1.Assign(Source: TSSHSHA1); begin sha1 := Source.sha1; end; constructor TSSHSHA1.Create; begin inherited; SHA1_Init(@sha1); end; procedure TSSHSHA1.Final(Digest: Pointer); begin SHA1_Final(Digest, @sha1); end; function TSSHSHA1.GetDigLen: integer; begin Result := 20; end; procedure TSSHSHA1.Update(Data: Pointer; Len: integer); begin SHA1_Update(@sha1, Data, Len); end; end.
(* Category: SWAG Title: DATE & TIME ROUTINES Original name: 0032.PAS Description: Day of the Week Author: MARK LAI Date: 01-27-94 11:53 *) { > I am currently trying to create a calendar that will ask the > user to input a year and month. The program should print out that > particular month. I believe I have a design I would like to follow, > but I cant figure out the formula to figure out the first day of the > month for any year between 1900-2000. I have something more general from my class. Here it is: A. Take the last two digits of the year B. Add a quarter of this number (neglect the remainder) C. Add the day of the month D. Add according to the month: Jan 1 Feb 4 March 4 April 0 May 2 June 5 July 0 Aug 3 Sept 6 Oct 1 Nov 4 Dec 6 E. Add for century 18th 4 20th 0 19th 2 21st 6 F. Divide total by 7 G. The remainder gives day of week: Sunday 1 Monday 2 Tuesday 3 Wednesday 4 Thursday 5 Friday 6 Saturday 0 This should work for any day between the years 1700-2099. Maybe you could figure out the exact formula you needed from this. }
{******************************************************************************* Title: iTEC-SOFTWARE Description: VO relational the table [PESSOA] The MIT License Copyright: Copyright (C) 2010 www.itecsoftware.com.br 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, sub license, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: william@itecsoftware.com.br @author William (william_mk@hotmail.com) @version 1.0 *******************************************************************************} unit PessoaVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, ViewPessoaContaReceberVO; type [TEntity] [TTable('PESSOA')] TPessoaVO = class(TVO) private FID: Integer; FPESSOA: String; FNOME: String; FDOC: String; FCONTA_CORRENTE: String; FLIMITE: Extended; FSALDO: Extended; FCONTAS: TObjectList<TViewPessoaContaReceberVO>; public constructor Create; overload; override; destructor Destroy; override; [TId('ID')] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('PESSOA','Pessoa',8,[ldGrid, ldLookup, ldCombobox], False)] property Pessoa: String read FPESSOA write FPESSOA; [TColumn('NOME','Nome',450,[ldGrid, ldLookup, ldCombobox], False)] property Nome: String read FNOME write FNOME; [TColumn('DOC','Doc',112,[ldGrid, ldLookup, ldCombobox], False)] property Doc: String read FDOC write FDOC; [TColumn('CONTA_CORRENTE','Conta Corrente',8,[ldGrid, ldLookup, ldCombobox], False)] property ContaCorrente: String read FCONTA_CORRENTE write FCONTA_CORRENTE; [TColumn('LIMITE','Limite',128,[ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property Limite: Extended read FLIMITE write FLIMITE; [TColumn('SALDO','Saldo',128,[ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property Saldo: Extended read FSALDO write FSALDO; [TManyValuedAssociation(False, 'ID_PESSOA', 'ID','VIEW_PESSOA_CONTA_RECEBER')] property Contas: TObjectList<TViewPessoaContaReceberVO> read FCONTAS write FCONTAS; end; implementation { TPessoaVO } constructor TPessoaVO.Create; begin inherited; Contas:= TObjectList<TViewPessoaContaReceberVO>.Create; end; destructor TPessoaVO.Destroy; begin Contas.Free; inherited; end; end.
unit MainForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, ThCanvasEditor, FMX.Objects, FMX.ExtCtrls, ThothController, ThCanvasController, ThTypes, FMX.Edit, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts; type TfrmMainDraft = class(TForm, IThObserver) Panel1: TPanel; btnRectangle: TButton; btnLine: TButton; btnCircle: TButton; btnSelect: TButton; btnRedo: TCornerButton; btnUndo: TCornerButton; btnDeleteSelection: TButton; btnZoomOut: TCornerButton; btnZoomIn: TCornerButton; edtZoom: TEdit; btnHome: TCornerButton; btnImage: TButton; Button1: TButton; btnText: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnRectangleClick(Sender: TObject); procedure btnDeleteSelectionClick(Sender: TObject); procedure btnUndoClick(Sender: TObject); procedure btnRedoClick(Sender: TObject); procedure btnZoomOutClick(Sender: TObject); procedure btnZoomInClick(Sender: TObject); procedure btnHomeClick(Sender: TObject); procedure btnImageClick(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } FController: TThothController; FCanvas: TThCanvasEditor; FCanvasController: TThCanvasEditorController; procedure Notifycation(ACommand: IThCommand); procedure SetSubject(ASubject: IThSubject); procedure DisplayZoomValue(AZoom: Single); public { Public declarations } end; var frmMainDraft: TfrmMainDraft; implementation uses ThConsts, ThItem, ThItemCommand, ThCanvasCommand; {$R *.fmx} procedure TfrmMainDraft.FormCreate(Sender: TObject); begin FCanvas := TThCanvasEditor.Create(Self); FCanvas.Parent := Panel1; FCanvas.Align := TAlignLayout.Client; FCanvas.Initialize; FController := TThothController.Create; FController.RegistObserver(Self); // 너는 ThothController 안으로 들어가야 한다. FCanvasController := TThCanvasEditorController.Create(FCanvas); FCanvasController.SetSubject(FController); DisplayZoomValue(FCanvas.ZoomScale); end; procedure TfrmMainDraft.FormDestroy(Sender: TObject); begin FCanvas.Free; FCanvasController.Free; FController.Free; end; procedure TfrmMainDraft.Notifycation(ACommand: IThCommand); begin if ACommand is TThItemCommand then begin btnUndo.Enabled := FController.UndoCount > 0; btnRedo.Enabled := FController.RedoCount > 0; end else if ACommand is TThCommandCanvasZoom then begin DisplayZoomValue(FCanvas.ZoomScale); end; end; procedure TfrmMainDraft.SetSubject(ASubject: IThSubject); begin FController.RegistObserver(Self); end; procedure TfrmMainDraft.DisplayZoomValue(AZoom: Single); begin AZoom := AZoom / CanvasZoomScaleDefault; edtZoom.Text := FormatFloat('0.##', AZoom); end; { Events } procedure TfrmMainDraft.btnRedoClick(Sender: TObject); begin FController.Redo; btnUndo.Enabled := FController.UndoCount > 0; btnRedo.Enabled := FController.RedoCount > 0; end; procedure TfrmMainDraft.btnUndoClick(Sender: TObject); begin FController.Undo; btnUndo.Enabled := FController.UndoCount > 0; btnRedo.Enabled := FController.RedoCount > 0; end; procedure TfrmMainDraft.btnZoomInClick(Sender: TObject); begin FCanvas.ZoomIn; end; procedure TfrmMainDraft.btnZoomOutClick(Sender: TObject); begin FCanvas.ZoomOut; end; procedure TfrmMainDraft.Button1Click(Sender: TObject); begin // FCanvas.Test; end; procedure TfrmMainDraft.btnHomeClick(Sender: TObject); begin FCanvas.ZoomHome; end; procedure TfrmMainDraft.btnImageClick(Sender: TObject); begin FCanvas.AppendFileItem(TButton(Sender).Tag); end; procedure TfrmMainDraft.btnRectangleClick(Sender: TObject); begin FCanvas.DrawItemID := TButton(Sender).Tag; end; procedure TfrmMainDraft.btnDeleteSelectionClick(Sender: TObject); begin FCanvas.DeleteSelection; end; end.
unit OrcamentoOperacaoExcluir.Controller; interface uses Orcamento.Controller.interf, Orcamento.Model.interf, OrcamentoItens.Model.interf, TESTORCAMENTOITENS.Entidade.Model, Generics.Collections, TESTORCAMENTO.Entidade.Model, System.SysUtils, FacadeController, ormbr.factory.interfaces; type TOrcamentoOperacaoExcluirController = class(TInterfacedObject, IOrcamentoOperacaoExcluirController) private FConexao: IDBConnection; FOrcamentoModel: IOrcamentoModel; FOrcamentoItensModel: IOrcamentoItensModel; FRegistro: TTESTORCAMENTO; procedure removerOrcamento; procedure removerItensOrcamento; procedure removerFornecedoresOrcamento; public constructor Create; destructor Destroy; override; class function New: IOrcamentoOperacaoExcluirController; function orcamentoModel(AValue: IOrcamentoModel) : IOrcamentoOperacaoExcluirController; function orcamentoItensModel(AValue: IOrcamentoItensModel) : IOrcamentoOperacaoExcluirController; function orcamentoSelecionado(AValue: TTESTORCAMENTO) : IOrcamentoOperacaoExcluirController; procedure finalizar; end; implementation { TOrcamentoOperacaoExcluirController } uses FacadeView, Tipos.Controller.Interf; constructor TOrcamentoOperacaoExcluirController.Create; begin FConexao := TFacadeController.New.ConexaoController.conexaoAtual; end; destructor TOrcamentoOperacaoExcluirController.Destroy; begin inherited; end; procedure TOrcamentoOperacaoExcluirController.finalizar; begin if TFacadeView.New .MensagensFactory .exibirMensagem(tmConfirmacao) .mensagem(Format('Deseja excluir o orçamento Nş: %s ?', [FRegistro.IDORCAMENTO.ToString])) .exibir then begin {1} removerFornecedoresOrcamento; {2} removerItensOrcamento; {3} removerOrcamento; end; end; class function TOrcamentoOperacaoExcluirController.New : IOrcamentoOperacaoExcluirController; begin Result := Self.Create; end; function TOrcamentoOperacaoExcluirController.orcamentoItensModel (AValue: IOrcamentoItensModel): IOrcamentoOperacaoExcluirController; begin Result := Self; FOrcamentoItensModel := AValue; end; function TOrcamentoOperacaoExcluirController.orcamentoModel (AValue: IOrcamentoModel): IOrcamentoOperacaoExcluirController; begin Result := Self; FOrcamentoModel := AValue; end; function TOrcamentoOperacaoExcluirController.orcamentoSelecionado (AValue: TTESTORCAMENTO): IOrcamentoOperacaoExcluirController; begin Result := Self; FRegistro := AValue; end; procedure TOrcamentoOperacaoExcluirController.removerFornecedoresOrcamento; begin FConexao .ExecuteDirect( Format('Delete from TEstOrcamentoFornecedores Where IdOrcamento = %s', [QuotedStr(FRegistro.CODIGO)] )); end; procedure TOrcamentoOperacaoExcluirController.removerItensOrcamento; begin FConexao .ExecuteDirect( Format('Delete from TEstOrcamentoItens Where IdOrcamento = %s', [QuotedStr(FRegistro.CODIGO)] )); end; procedure TOrcamentoOperacaoExcluirController.removerOrcamento; begin FOrcamentoModel.DAO.Delete(FRegistro); end; end.
unit BCEditor.Editor.Bookmarks; interface uses Vcl.Controls, System.Classes, System.Contnrs, BCEditor.Consts; type TBCEditorBookmark = class protected FChar: Integer; FData: Pointer; FEditor: TCustomControl; FImageIndex: Integer; FIndex: Integer; FInternalImage: Boolean; FLine: Integer; FVisible: Boolean; function GetIsBookmark: Boolean; procedure Invalidate; procedure SetChar(const AValue: Integer); virtual; procedure SetImageIndex(const AValue: Integer); virtual; procedure SetInternalImage(const AValue: Boolean); procedure SetLine(const AValue: Integer); virtual; procedure SetVisible(const AValue: Boolean); public constructor Create(AOwner: TCustomControl); property Char: Integer read FChar write SetChar; property Data: Pointer read FData write FData; property ImageIndex: Integer read FImageIndex write SetImageIndex; property Index: Integer read FIndex write FIndex; property InternalImage: Boolean read FInternalImage write SetInternalImage; property IsBookmark: Boolean read GetIsBookmark; property Line: Integer read FLine write SetLine; property Visible: Boolean read FVisible write SetVisible; end; TBCEditorBookmarkEvent = procedure(Sender: TObject; var Mark: TBCEditorBookmark) of object; TBCEditorBookmarks = array [1 .. BCEDITOR_MAX_BOOKMARKS] of TBCEditorBookmark; TBCEditorBookmarkList = class(TObjectList) protected FEditor: TCustomControl; FOnChange: TNotifyEvent; function GetItem(AIndex: Integer): TBCEditorBookmark; procedure Notify(Ptr: Pointer; Action: TListNotification); override; procedure SetItem(AIndex: Integer; AItem: TBCEditorBookmark); property OwnsObjects; public constructor Create(AOwner: TCustomControl); function Extract(AItem: TBCEditorBookmark): TBCEditorBookmark; function First: TBCEditorBookmark; function Last: TBCEditorBookmark; procedure ClearLine(ALine: Integer); procedure GetMarksForLine(ALine: Integer; var AMarks: TBCEditorBookmarks); procedure Place(AMark: TBCEditorBookmark); public property Items[AIndex: Integer]: TBCEditorBookmark read GetItem write SetItem; default; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; implementation uses BCEditor.Editor.Base, System.Types; { TBCEditorBookmark } constructor TBCEditorBookmark.Create(AOwner: TCustomControl); begin inherited Create; FIndex := -1; FEditor := AOwner; end; function TBCEditorBookmark.GetIsBookmark: Boolean; begin Result := FIndex >= 0; end; procedure TBCEditorBookmark.SetChar(const AValue: Integer); begin FChar := AValue; end; procedure TBCEditorBookmark.Invalidate; begin if FVisible then if Assigned(FEditor) and (FEditor is TBCBaseEditor) then (FEditor as TBCBaseEditor).InvalidateLeftMarginLines(FLine, FLine); end; procedure TBCEditorBookmark.SetImageIndex(const AValue: Integer); begin FImageIndex := AValue; Invalidate; end; procedure TBCEditorBookmark.SetInternalImage(const AValue: Boolean); begin FInternalImage := AValue; Invalidate; end; procedure TBCEditorBookmark.SetLine(const AValue: Integer); begin if FVisible and Assigned(FEditor) then begin if FLine > 0 then Invalidate; FLine := AValue; Invalidate; end else FLine := AValue; end; procedure TBCEditorBookmark.SetVisible(const AValue: Boolean); begin if FVisible <> AValue then begin FVisible := AValue; Invalidate; end; end; { TBCEditorBookmarkList } procedure TBCEditorBookmarkList.Notify(Ptr: Pointer; Action: TListNotification); begin inherited; if Assigned(FOnChange) then FOnChange(Self); end; function TBCEditorBookmarkList.GetItem(AIndex: Integer): TBCEditorBookmark; begin Result := TBCEditorBookmark(inherited GetItem(AIndex)); end; procedure TBCEditorBookmarkList.SetItem(AIndex: Integer; AItem: TBCEditorBookmark); begin inherited SetItem(AIndex, AItem); end; constructor TBCEditorBookmarkList.Create(AOwner: TCustomControl); begin inherited Create; FEditor := AOwner; end; function TBCEditorBookmarkList.First: TBCEditorBookmark; begin Result := TBCEditorBookmark(inherited First); end; function TBCEditorBookmarkList.Last: TBCEditorBookmark; begin Result := TBCEditorBookmark(inherited Last); end; function TBCEditorBookmarkList.Extract(AItem: TBCEditorBookmark): TBCEditorBookmark; begin Result := TBCEditorBookmark(inherited Extract(AItem)); end; procedure TBCEditorBookmarkList.ClearLine(ALine: Integer); var i: Integer; begin for i := Count - 1 downto 0 do if not Items[i].IsBookmark and (Items[i].Line = ALine) then Delete(i); end; procedure TBCEditorBookmarkList.GetMarksForLine(ALine: Integer; var AMarks: TBCEditorBookmarks); var i, j: Integer; begin FillChar(AMarks, SizeOf(AMarks), 0); j := 0; for i := 0 to Count - 1 do begin if Items[i].Line = ALine then begin Inc(j); AMarks[j] := Items[i]; if j = BCEDITOR_MAX_BOOKMARKS then Break; end; end; end; procedure TBCEditorBookmarkList.Place(AMark: TBCEditorBookmark); var LEditor: TBCBaseEditor; begin LEditor := nil; if Assigned(FEditor) and (FEditor is TBCBaseEditor) then LEditor := FEditor as TBCBaseEditor; if Assigned(LEditor) then if Assigned(LEditor.OnBeforeBookmarkPlaced) then LEditor.OnBeforeBookmarkPlaced(FEditor, AMark); if Assigned(AMark) then Add(AMark); if Assigned(LEditor) then if Assigned(LEditor.OnAfterBookmarkPlaced) then LEditor.OnAfterBookmarkPlaced(FEditor); end; end.
// Adobe Font Metrics and FontForge's Spline Font Database unit fi_afm_sfd; interface implementation uses fi_common, fi_info_reader, line_reader, classes, sysutils; type TFontFormat = ( AFM, SFD ); const FONT_IDENT: array [TFontFormat] of record name, sign: String; end = ( (name: 'AFM'; sign: 'StartFontMetrics'), (name: 'SFD'; sign: 'SplineFontDB:')); NUM_FIELDS = 6; MAX_LINES = 30; procedure ReadCommonInfo( lineReader: TLineReader; var info: TFontInfo; fontFormat: TFontFormat); var i: LongInt; s: String; sLen: SizeInt; key: String; p: SizeInt; dst: PString; numFound: LongInt; begin repeat if not lineReader.ReadLine(s) then raise EStreamError.CreateFmt( '%s is empty', [FONT_IDENT[fontFormat].name]); s := Trim(s); until s <> ''; p := Pos(' ', s); if (p = 0) or (Copy(s, 1, p - 1) <> FONT_IDENT[fontFormat].sign) then raise EStreamError.CreateFmt( 'Not a %s font', [FONT_IDENT[fontFormat].name]); while s[p + 1] = ' ' do Inc(p); info.format := FONT_IDENT[fontFormat].name + Copy(s, p, Length(s) - p + 1); i := 1; numFound := 0; while (numFound < NUM_FIELDS) and (i <= MAX_LINES) and lineReader.ReadLine(s) do begin s := Trim(s); if s = '' then continue; p := Pos(' ', s); if p = 0 then continue; Inc(i); if fontFormat = SFD then key := Copy(s, 1, p - 2) // Skip colon else key := Copy(s, 1, p - 1); case key of 'FontName': dst := @info.psName; 'FullName': dst := @info.fullName; 'FamilyName': dst := @info.family; 'Weight': dst := @info.style; 'Version': dst := @info.version; 'Copyright': dst := @info.copyright; // SFD 'Notice': dst := @info.copyright; // AFM else continue; end; repeat Inc(p); until s[p] <> ' '; sLen := Length(s); if (dst = @info.copyright) and (fontFormat = AFM) and (s[p] = '(') and (s[sLen] = ')') then begin Inc(p); Dec(sLen); end; dst^ := Copy(s, p, sLen - (p - 1)); Inc(numFound); end; info.style := ExtractStyle(info.fullName, info.family, info.style); end; procedure ReadCommonInfo( stream: TStream; var info: TFontInfo; fontFormat: TFontFormat); var lineReader: TLineReader; begin lineReader := TLineReader.Create(stream); try ReadCommonInfo(lineReader, info, fontFormat); finally lineReader.Free; end; end; procedure ReadAFMInfo(stream: TStream; var info: TFontInfo); begin ReadCommonInfo(stream, info, AFM); end; procedure ReadSFDInfo(stream: TStream; var info: TFontInfo); begin ReadCommonInfo(stream, info, SFD); end; initialization RegisterReader(@ReadAFMInfo, ['.afm']); RegisterReader(@ReadSFDInfo, ['.sfd']); end.
unit uPhotoShelf; interface uses System.Classes, System.SysUtils, UnitDBDeclare, uMemory, uCollectionEvents, uDBForm, uSettings, uRWLock, uProgramStatInfo, uLogger; type TPhotoShelf = class(TObject) private FSync: IReadWriteSync; FItems: TStringList; function GetCount: Integer; function InternalPathInShelf(Path: string): Integer; function InternalRemoveFromShelf(Path: string): Boolean; public constructor Create; destructor Destroy; override; procedure LoadSavedItems; procedure SaveItems; procedure AddToShelf(Path: string); function RemoveFromShelf(Path: string): Boolean; function PathInShelf(Path: string): Integer; procedure AddItems(Sender: TDBForm; Items: TStrings); procedure DeleteItems(Sender: TDBForm; Items: TStrings); procedure GetItems(Items: TStrings); procedure Clear; property Count: Integer read GetCount; end; function PhotoShelf: TPhotoShelf; implementation var FPhotoShelf: TPhotoShelf = nil; function PhotoShelf: TPhotoShelf; begin if FPhotoShelf = nil then begin FPhotoShelf := TPhotoShelf.Create; FPhotoShelf.LoadSavedItems; end; Result := FPhotoShelf; end; { TPhotoShelf } procedure TPhotoShelf.AddItems(Sender: TDBForm; Items: TStrings); var S: string; AddedItems: TStrings; begin //statistics ProgramStatistics.ShelfUsed; AddedItems := TStringList.Create; try FSync.BeginWrite; try for S in Items do if InternalPathInShelf(S) = -1 then begin FItems.Add(S); AddedItems.Add(S); end; finally FSync.EndWrite; end; TThread.Synchronize(nil, procedure var EventInfo: TEventValues; I: Integer; begin EventInfo.ID := 0; CollectionEvents.DoIDEvent(Sender, 0, [EventID_ShelfChanged], EventInfo); for I := 0 to AddedItems.Count - 1 do begin EventInfo.FileName := AddedItems[I]; CollectionEvents.DoIDEvent(Sender, 0, [EventID_ShelfItemAdded], EventInfo); end; end ); finally F(AddedItems); end; end; procedure TPhotoShelf.AddToShelf(Path: string); begin //statistics ProgramStatistics.ShelfUsed; FSync.BeginWrite; try if InternalPathInShelf(Path) = -1 then FItems.Add(Path); finally FSync.EndWrite; end; end; procedure TPhotoShelf.Clear; begin FSync.BeginWrite; try FItems.Clear; finally FSync.EndWrite; end; end; constructor TPhotoShelf.Create; begin FSync := CreateRWLock; FItems := TStringList.Create; end; procedure TPhotoShelf.DeleteItems(Sender: TDBForm; Items: TStrings); var S: string; RemovedItems: TStrings; begin //statistics ProgramStatistics.ShelfUsed; RemovedItems := TStringList.Create; try FSync.BeginWrite; try for S in Items do if InternalRemoveFromShelf(S) then RemovedItems.Add(S); finally FSync.EndWrite; end; TThread.Synchronize(nil, procedure var EventInfo: TEventValues; I: Integer; begin EventInfo.ID := 0; CollectionEvents.DoIDEvent(Sender, 0, [EventID_ShelfChanged], EventInfo); for I := 0 to RemovedItems.Count - 1 do begin EventInfo.FileName := RemovedItems[I]; CollectionEvents.DoIDEvent(Sender, 0, [EventID_ShelfItemRemoved], EventInfo); end; end ); finally F(RemovedItems); end; end; destructor TPhotoShelf.Destroy; begin SaveItems; FSync := nil; F(FItems); inherited; end; function TPhotoShelf.GetCount: Integer; begin FSync.BeginRead; try Result := FItems.Count; finally FSync.EndRead; end; end; procedure TPhotoShelf.GetItems(Items: TStrings); var S: string; begin FSync.BeginRead; try for S in FItems do Items.Add(S); finally FSync.EndRead; end; end; function TPhotoShelf.InternalPathInShelf(Path: string): Integer; var S: string; I: Integer; begin Result := -1; S := AnsiUpperCase(Path); for I := 0 to FItems.Count - 1 do if AnsiUpperCase(FItems[I]) = S then begin Result := I; Exit; end; end; function TPhotoShelf.PathInShelf(Path: string): Integer; begin FSync.BeginRead; try Result := InternalPathInShelf(Path); finally FSync.EndRead; end; end; function TPhotoShelf.InternalRemoveFromShelf(Path: string): Boolean; var Index: Integer; begin Result := False; Index := InternalPathInShelf(Path); if Index > -1 then begin FItems.Delete(Index); Result := True; end; end; function TPhotoShelf.RemoveFromShelf(Path: string): Boolean; begin //statistics ProgramStatistics.ShelfUsed; FSync.BeginWrite; try Result := InternalRemoveFromShelf(Path); finally FSync.EndWrite; end; end; procedure TPhotoShelf.LoadSavedItems; begin FSync.BeginWrite; try FItems.Delimiter := '|'; try FItems.DelimitedText := AppSettings.ReadString('Settings', 'Shelf', ''); except on e: Exception do EventLog(e); end; finally FSync.EndWrite; end; end; procedure TPhotoShelf.SaveItems; begin FSync.BeginWrite; try FItems.Delimiter := '|'; try AppSettings.WriteString('Settings', 'Shelf', FItems.DelimitedText); except on e: Exception do EventLog(e); end; finally FSync.EndWrite; end; end; initialization finalization F(FPhotoShelf); end.
unit UShowProgressThread; interface uses Classes, Forms,pFibDataSet,cxTextEdit,ComCtrls; type TShowProgressThread = class(TThread) private { Private declarations } Form:TForm; PBStep:Integer; PB:TProgressBar; protected procedure Execute; override; public procedure UpdatePB; procedure ClearPB; constructor Create(CreateSuspended: Boolean; Form:TForm);overload; constructor Create(CreateSuspended: Boolean; PB:TProgressBar);overload; end; implementation uses SysUtils, UMainAccounts; procedure TShowProgressThread.ClearPB; begin PB.Position:=0; PB.Update; end; constructor TShowProgressThread.Create(CreateSuspended: Boolean; Form:TForm); begin inherited Create(true); self.Form:=Form; PB:=TfrmAccountMain(self.Form).CalcProgressBar; end; constructor TShowProgressThread.Create(CreateSuspended: Boolean; PB:TProgressBar); begin inherited Create(true); self.Form:=nil; self.PB:=PB; end; procedure TShowProgressThread.Execute; var i:Integer; begin PB.Min:=0; PB.Max:=10000; PB.Step:=1; PBStep:=0; Synchronize(UpdatePB); i:=1; While (not Terminated) do begin PBStep:=i; Synchronize(UpdatePB); Inc(i); if (i=PB.Max) then begin Synchronize(ClearPB); i:=0; end; end; PBStep:=PB.Max-1; Synchronize(UpdatePB); PBStep:=PB.Max; Synchronize(UpdatePB); if (i<>PB.Max) then begin PBStep:=0; Synchronize(UpdatePB); end; end; procedure TShowProgressThread.UpdatePB; begin PB.Position:=PBStep; PB.Update; end; end.
// ------------------------------------------------------- // // This file was generated using Parse::Easy v1.0 alpha. // // https://github.com/MahdiSafsafi/Parse-Easy // // DO NOT EDIT !!! ANY CHANGE MADE HERE WILL BE LOST !!! // // ------------------------------------------------------- unit CalcLexer; interface uses System.SysUtils, WinApi.Windows, Parse.Easy.Lexer.CustomLexer; type TCalcLexer = class(TCustomLexer) protected procedure UserAction(Index: Integer); override; public class constructor Create; function GetTokenName(Index: Integer): string; override; end; const EOF = 0000; LPAREN = 0001; RPAREN = 0002; PLUS = 0003; MINUS = 0004; STAR = 0005; SLASH = 0006; DECIMAL = 0007; FLOAT = 0008; WS = 0009; SECTION_DEFAULT = 0000; implementation {$R CalcLexer.RES} { TCalcLexer } class constructor TCalcLexer.Create; begin Deserialize('CALCLEXER'); end; procedure TCalcLexer.UserAction(Index: Integer); begin case Index of 0000: begin skip end; end; end; function TCalcLexer.GetTokenName(Index: Integer): string; begin case Index of 0000 : exit('EOF' ); 0001 : exit('LPAREN' ); 0002 : exit('RPAREN' ); 0003 : exit('PLUS' ); 0004 : exit('MINUS' ); 0005 : exit('STAR' ); 0006 : exit('SLASH' ); 0007 : exit('DECIMAL' ); 0008 : exit('FLOAT' ); 0009 : exit('WS' ); end; Result := 'Unkown' + IntToStr(Index); end; end.
unit EDSUtil; {$D-} {$L-} interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Controls, Graphics, Forms, TabNotBk, Menus, StdCtrls, ExtCtrls; type TEnterEdit = class(TEdit) private { Private declarations } protected { Protected declarations } procedure KeyPress(var Key: Char); override; procedure KeyDown (var Key: Word; Shift: TShiftState); override; public { Public declarations } published { Published declarations } end; { TEnterEdit } TNewListBox = Class(TListBox) private { Private declarations } FOnChange : TNotifyEvent; FLastSel : integer; procedure Click; override; protected { Protected declarations } procedure Change; Virtual; published { Published declarations } property OnChange : TNotifyEvent read FOnChange write FOnChange; public { Public declarations } constructor Create(AOwner : TComponent); override; end; { TNewListBox } TNewLabel = Class(TLabel) private { Private declarations } FOnChange : TNotifyEvent; function GetCaption: String; procedure SetCaption (Value: String); protected { Protected declarations } procedure Change; virtual; published { Published declarations } property Caption : String read GetCaption write SetCaption; property OnChange : TNotifyEvent read FOnChange write FOnChange; public { Public declarations } constructor Create(AOwner : TComponent); override; end; { TNewLabel } procedure SurfaceControl (AControl: TWinControl); {-insures control is visible (in case on notebook page)} procedure Register; implementation procedure SurfaceControl (AControl: TWinControl); {-insures control is visible (in case on notebook page)} var FControl: TWinControl; AParent: TWinControl; AntiHang: integer; {makes sure no hang in repeat until loop} begin FControl := AControl; AntiHang := 0; repeat AParent := FControl.Parent; if AParent is TTabPage then TTabbedNotebook (TTabPage (AParent).Parent).ActivePage := TTabPage (AParent).Caption else if AParent is TPage then TNoteBook (TPage (AParent).Parent).ActivePage := TPage (AParent).Caption; FControl := AParent; Inc (AntiHang); until (FControl = nil) or (IsWindowVisible (FControl.Handle)) or (AParent is TForm) and (AntiHang >= 999); end; { SurfaceControl } procedure TEnterEdit.KeyPress(var Key: Char); var {$IFDEF Ver100} MYForm: TCustomForm; {$ELSE} MYForm: TForm; {$ENDIF} begin if Key = #13 then begin MYForm := GetParentForm( Self ); if not (MYForm = nil ) then SendMessage(MYForm.Handle, WM_NEXTDLGCTL, 0, 0); Key := #0; end; { if... } if Key <> #0 then inherited KeyPress(Key); end; { TEnterEdit.KeyPress } procedure TEnterEdit.KeyDown (var Key: Word; Shift: TShiftState); var St: string; begin case Key of VK_UP: if ssCtrl in Shift then begin Text := UpperCase (Text); Key := 0; end; { if... } VK_DOWN: if ssCtrl in Shift then begin St := UpperCase (Text); St[1] := UpCase (St[1]); Text := St; Key := 0; end; { case } end; { case } end; { TEnterEdit.KeyDown } constructor TNewListBox.Create; begin inherited Create(AOwner); FLastSel := -1; end; { TNewListBox.Create } procedure TNewListBox.Change; begin if Assigned (FOnChange) then FOnChange (Self); end; { TNewListBox.Change } procedure TNewListBox.Click; begin inherited Click; if FLastSel <> ItemIndex then Change; end; { TNewListBox.Click } {--- TNewLabel Class ---} constructor TNewLabel.Create (AOwner: TComponent); begin inherited Create (AOwner); end; { TNewLabel.Create } procedure TNewLabel.Change; begin if Assigned (FOnChange) then FOnChange (Self); end; { TNewLabel.Change } function TNewLabel.GetCaption: String; begin Result := inherited Caption; end; { TNewLabel.GetCaption } procedure TNewLabel.SetCaption (Value: String); begin inherited Caption := Value; Change; end; { TNewLabel.SetCaption } procedure Register; begin RegisterComponents('Domain', [TEnterEdit, TNewListBox, TNewLabel]); end; end. { EDSUtil }
{***************************************************************************} { } { DUnitX } { } { Copyright (C) 2013 Vincent Parrett } { } { vincent@finalbuilder.com } { http://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DUnitX.Loggers.XML.NUnit; interface uses DUnitX.TestFramework, classes; {$I DUnitX.inc} type TDUnitXXMLNUnitLogger = class(TInterfacedObject, ITestLogger) private FOutputStream : TStream; FLogList : TStringList; FWarningList : TStringList; procedure WriteXMLLine(const AXMLLine: string); procedure WriteInfoAndWarningsXML; function HasInfoOrWarnings: Boolean; protected procedure OnTestingStarts(const threadId, testCount, testActiveCount: Cardinal); procedure OnStartTestFixture(const threadId: Cardinal; const fixture: ITestFixtureInfo); procedure OnSetupFixture(const threadId: Cardinal; const fixture: ITestFixtureInfo); procedure OnEndSetupFixture(const threadId: Cardinal; const fixture: ITestFixtureInfo); procedure OnBeginTest(const threadId: Cardinal; Test: ITestInfo); procedure OnSetupTest(const threadId: Cardinal; Test: ITestInfo); procedure OnEndSetupTest(const threadId: Cardinal; Test: ITestInfo); procedure OnExecuteTest(const threadId: Cardinal; Test: ITestInfo); procedure OnTestSuccess(const threadId: Cardinal; Success: ITestResult); procedure OnTestWarning(const threadId: Cardinal; Warning: ITestResult); procedure OnTestError(const threadId: Cardinal; Error: ITestError); procedure OnTestFailure(const threadId: Cardinal; Failure: ITestError); procedure OnLog(const logType: TLogLevel; const msg: string); procedure OnTeardownTest(const threadId: Cardinal; Test: ITestInfo); procedure OnEndTeardownTest(const threadId: Cardinal; Test: ITestInfo); procedure OnEndTest(const threadId: Cardinal; Test: ITestResult); procedure OnTearDownFixture(const threadId: Cardinal; const fixture: ITestFixtureInfo); procedure OnEndTearDownFixture(const threadId: Cardinal; const fixture: ITestFixtureInfo); procedure OnEndTestFixture(const threadId: Cardinal; const results: IFixtureResult); procedure OnTestingEnds(const TestResults: ITestResults); public constructor Create(const AOutputStream : TStream); destructor Destroy;override; end; TDUnitXXMLNUnitFileLogger = class(TDUnitXXMLNUnitLogger) private FXMLFileStream : TFileStream; public constructor Create(const AFilename: string = ''); end; implementation uses {$IFDEF MSWINDOWS} {$if CompilerVersion < 23 } Forms, Windows, {$else} Vcl.Forms, WinAPI.Windows, // Delphi XE2 (CompilerVersion 23) added scopes in front of unit names {$ifend} {$ENDIF} DUnitX.Utils.XML, SysUtils; const NUNIT_LOGGER_CRLF = #13#10; { TDUnitXTextFileLogger } procedure TDUnitXXMLNUnitLogger.WriteInfoAndWarningsXML; var log : string; warning : string; begin if FLogList.Count > 0 then begin for log in FLogList do WriteXMLLine('<status>' + EscapeForXML(log, false) + '</status>'); end; if FWarningList.Count > 0 then begin for warning in FWarningList do WriteXMLLine('<warning>' + EscapeForXML(warning, false) + '</warning>'); end; end; constructor TDUnitXXMLNUnitLogger.Create(const AOutputStream: TStream); begin //We are given this stream to use as we see fit, would pass in an interface but there is none for streams. FOutputStream := AOutputStream; FLogList := TStringList.Create; FWarningList := TStringList.Create; end; destructor TDUnitXXMLNUnitLogger.Destroy; begin FOutputStream.Free; FLogList.Free; FWarningList.Free; inherited; end; function TDUnitXXMLNUnitLogger.HasInfoOrWarnings: Boolean; begin Result := (FLogList.Count > 0) or (FWarningList.Count > 0); end; procedure TDUnitXXMLNUnitLogger.OnBeginTest(const threadId: Cardinal; Test: ITestInfo); begin FLogList.Clear; FWarningList.Clear; end; procedure TDUnitXXMLNUnitLogger.OnEndSetupFixture(const threadId: Cardinal; const fixture: ITestFixtureInfo); begin end; procedure TDUnitXXMLNUnitLogger.OnEndSetupTest(const threadId: Cardinal; Test: ITestInfo); begin end; procedure TDUnitXXMLNUnitLogger.OnEndTearDownFixture(const threadId: Cardinal; const fixture: ITestFixtureInfo); begin end; procedure TDUnitXXMLNUnitLogger.OnEndTeardownTest(const threadId: Cardinal; Test: ITestInfo); begin end; procedure TDUnitXXMLNUnitLogger.OnEndTest(const threadId: Cardinal; Test: ITestResult); begin end; procedure TDUnitXXMLNUnitLogger.OnEndTestFixture(const threadId: Cardinal; const results: IFixtureResult); begin WriteXMLLine('</results>'); WriteXMLLine('</test-suite>'); end; procedure TDUnitXXMLNUnitLogger.OnExecuteTest(const threadId: Cardinal; Test: ITestInfo); begin end; procedure TDUnitXXMLNUnitLogger.OnLog(const logType: TLogLevel; const msg: string); begin FLogList.Add(Format('STATUS: %s: %s', [TLogLevelDesc[logType], msg])); end; procedure TDUnitXXMLNUnitLogger.OnSetupFixture(const threadId: Cardinal; const fixture: ITestFixtureInfo); begin end; procedure TDUnitXXMLNUnitLogger.OnSetupTest(const threadId: Cardinal; Test: ITestInfo); begin end; procedure TDUnitXXMLNUnitLogger.OnStartTestFixture(const threadId: Cardinal; const fixture: ITestFixtureInfo); var sType : string; begin if fixture.Tests.Count > 0 then sType := 'TestFixture' else sType := 'Namespace'; WriteXMLLine(Format('<test-suite type="%s" name="%s" total="%d" notrun="%d">', [sType,fixture.Name, fixture.TestCount, fixture.TestCount - fixture.ActiveTestCount])); WriteXMLLine('<results>'); end; procedure TDUnitXXMLNUnitLogger.OnTearDownFixture(const threadId: Cardinal; const fixture: ITestFixtureInfo); begin end; procedure TDUnitXXMLNUnitLogger.OnTeardownTest(const threadId: Cardinal; Test: ITestInfo); begin end; procedure TDUnitXXMLNUnitLogger.OnTestError(const threadId: Cardinal; Error: ITestError); begin //TODO: Getting Test, and Fixture from Error is painful for testing. Therefore its painful for setup, and use? WriteXMLLine(Format('<test-case name="%s" executed="%s" success="False" time="%1.3f" result="Error">', [EscapeForXML(Error.Test.FullName), BoolToStr(Error.Test.Active, True), Error.TestDuration.TotalMilliseconds / 1000])); WriteXMLLine(Format('<failure name="%s" location="%s">', [EscapeForXML(error.ExceptionClass.ClassName), EscapeForXML(error.ExceptionLocationInfo)])); WriteXMLLine(Format('<message>%s</message>', [EscapeForXML(error.ExceptionMessage, false)])); WriteXMLLine('</failure>'); WriteInfoAndWarningsXML; WriteXMLLine('</test-case>'); end; procedure TDUnitXXMLNUnitLogger.OnTestFailure(const threadId: Cardinal; Failure: ITestError); begin WriteXMLLine(Format('<test-case name="%s" executed="%s" success="False" time="%1.3f" result="Failure">', [EscapeForXML(Failure.Test.FullName), BoolToStr(Failure.Test.Active, True), Failure.TestDuration.Milliseconds / 1000])); WriteXMLLine(Format('<failure name="%s" location="%s">', [EscapeForXML(Failure.ExceptionClass.ClassName), EscapeForXML(Failure.ExceptionLocationInfo)])); WriteXMLLine(Format('<message>%s</message>', [EscapeForXML(Failure.ExceptionMessage, false)])); WriteXMLLine('</failure>'); WriteInfoAndWarningsXML; WriteXMLLine('</test-case>'); end; procedure TDUnitXXMLNUnitLogger.OnTestingEnds(const TestResults: ITestResults); begin WriteXMLLine('<statistics>' + NUNIT_LOGGER_CRLF + Format('<stat name="tests" value="%d" />', [TestResults.Count]) + NUNIT_LOGGER_CRLF + Format('<stat name="failures" value="%d" />', [TestResults.FailureCount]) + NUNIT_LOGGER_CRLF + Format('<stat name="errors" value="%d" />', [TestResults.ErrorCount]) + NUNIT_LOGGER_CRLF + Format('<stat name="success-rate" value="%d%%" />', [TestResults.SuccessRate]) + NUNIT_LOGGER_CRLF + Format('<stat name="started-at" value="%s" />', [DateTimeToStr(TestResults.StartTime)]) + NUNIT_LOGGER_CRLF + Format('<stat name="finished-at" value="%s" />', [DateTimeToStr(TestResults.FinishTime)]) + NUNIT_LOGGER_CRLF + Format('<stat name="runtime" value="%1.3f"/>', [TestResults.TestDuration.TotalMilliseconds / 1000]) + NUNIT_LOGGER_CRLF + '</statistics>' + NUNIT_LOGGER_CRLF + '</test-results>'); //TODO: Do we need to write to the console here? end; procedure TDUnitXXMLNUnitLogger.OnTestingStarts(const threadId, testCount, testActiveCount: Cardinal); var unicodePreamble: TBytes; dtNow: TDateTime; begin //write the byte order mark unicodePreamble := TEncoding.UTF8.GetPreamble; if Length(unicodePreamble) > 0 then FOutputStream.WriteBuffer(unicodePreamble[0], Length(unicodePreamble)); WriteXMLLine('<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>'); dtNow := Now; WriteXMLLine(Format('<test-results total="%d" notrun="%d" date="%s" time="%s" >', [testCount, testCount - testActiveCount, DateToStr(dtNow), TimeToStr(dtNow)])); WriteXMLLine(Format('<application name="%s" />',[ExtractFileName(ParamStr(0))])); end; procedure TDUnitXXMLNUnitLogger.OnTestSuccess(const threadId: Cardinal; Success: ITestResult); var endTag : string; fixture: ITestFixtureInfo; begin if HasInfoOrWarnings then endTag := '>' else endTag := '/>'; fixture := Success.Test.Fixture; WriteXMLLine(Format('<test-case name="%s" executed="%s" success="True" time="%1.3f" result="Pass" %s', [EscapeForXML(Success.Test.FullName), BoolToStr(Success.Test.Active, True), Success.TestDuration.TotalMilliseconds / 1000, endTag])); if HasInfoOrWarnings then begin WriteInfoAndWarningsXML; WriteXMLLine('</test-case>'); end; end; procedure TDUnitXXMLNUnitLogger.OnTestWarning(const threadId: Cardinal; Warning: ITestResult); begin FWarningList.Add(Format('WARNING: %s: %s', [Warning.Test.Name, Warning.Message])); end; procedure TDUnitXXMLNUnitLogger.WriteXMLLine(const AXMLLine: string); var btUTF8Buffer : TBytes; sLine: string; begin sLine := AXMLLine + NUNIT_LOGGER_CRLF; if FOutputStream <> nil then begin btUTF8Buffer := TEncoding.UTF8.GetBytes(AXMLLine); FOutputStream.WriteBuffer(btUTF8Buffer[0],Length(btUTF8Buffer)); end else WriteLn(AXMLLine); end; { TDUnitXXMLNUnitLoggerFile } constructor TDUnitXXMLNUnitFileLogger.Create(const AFilename: string = ''); var sXmlFilename: string; const DEFAULT_NUNIT_FILE_NAME = 'dunit-report.xml'; begin sXmlFilename := AFilename; if sXmlFilename = '' then sXmlFilename := ExtractFilePath(Application.ExeName) + DEFAULT_NUNIT_FILE_NAME; FXMLFileStream := TFileStream.Create(sXmlFilename, fmCreate); //The stream class will take care of cleaning this up for us. inherited Create(FXMLFileStream); end; end.
unit Forms.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VCL.TMSFNCTypes, VCL.TMSFNCUtils, VCL.TMSFNCGraphics, VCL.TMSFNCGraphicsTypes, VCL.TMSFNCMapsCommonTypes, VCL.TMSFNCCustomControl, VCL.TMSFNCWebBrowser, VCL.TMSFNCMaps, Vcl.StdCtrls, AdvEdit, AdvMemo, AdvGlowButton, VCL.TMSFNCCustomComponent, VCL.TMSFNCCloudBase, VCL.TMSFNCDirections, VCL.TMSFNCGeocoding, Vcl.ExtCtrls, AdvSplitter, AdvStyleIF, AdvAppStyler; type TFrmMain = class(TForm) Map: TTMSFNCMaps; Directions: TTMSFNCDirections; Geocoding: TTMSFNCGeocoding; Panel1: TPanel; txtInfo: TAdvMemo; btnCosts: TAdvGlowButton; btnReport: TAdvGlowButton; txtCustomer: TAdvEdit; Splitter: TAdvSplitter; FormStyler: TAdvFormStyler; dlgSave: TFileSaveDialog; procedure btnCostsClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure GeocodingGetGeocoding(Sender: TObject; const ARequest: TTMSFNCGeocodingRequest; const ARequestResult: TTMSFNCCloudBaseRequestResult); procedure DirectionsGetDirections(Sender: TObject; const ARequest: TTMSFNCDirectionsRequest; const ARequestResult: TTMSFNCCloudBaseRequestResult); procedure btnReportClick(Sender: TObject); procedure FormCreate(Sender: TObject); strict private { Private declarations } FCustomerCoords, FHomeCoords: TTMSFNCMapsCoordinateRec; procedure AddPolyline( const ACoords: TTMSFNCMapsCoordinateRecArray ); procedure AddStepsToReport( const ASteps: TTMSFNCDirectionsSteps ); procedure AddInfo( AText: String; ASpace : Boolean = False); procedure AddReportToMemo; procedure FocusMapOnRoute; procedure GeocodeHome; procedure GeoCodeCustomer; procedure InitReport; procedure SetHomeCoords(const ACoord: TTMSFNCMapsCoordinateRec); procedure SetCustomerCoords( const ACoord: TTMSFNCMapsCoordinateRec ); procedure UpdateRoute; end; var FrmMain: TFrmMain; implementation {$R *.dfm} uses IOUtils, Modules.Reporting, Flix.Utils.Maps; const ADDR_HOME = 'Roeselarestraat 180, 8560 Wevelgem, Belgium'; procedure TFrmMain.AddInfo(AText: String; ASpace : Boolean = False); begin txtInfo.Lines.Add( AText ); if ASpace then begin txtInfo.Lines.Add(''); end; end; procedure TFrmMain.AddPolyline(const ACoords: TTMSFNCMapsCoordinateRecArray); var LPoly : TTMSFNCMapsPolyline; begin LPoly := Map.AddPolyline( ACoords ); LPoly.StrokeColor := clRed; LPoly.StrokeOpacity := 0.5; LPoly.StrokeWidth := 3; end; procedure TFrmMain.AddReportToMemo; begin AddInfo( Format( 'Distance: %f km', [ Reporting.TotalDistance/1000 ] ) ); AddInfo( Format( 'Duration: %f minutes', [ Reporting.TotalDuration/60 ] ), True ); AddInfo( ' (duration charged in half hour intervals)', True); AddInfo( Format( 'Cost time (%3d units for %6.2m) : %8.2m', [ Reporting.HalfHours, Reporting.CostHalfHour, Reporting.CostDuration ] ) ); AddInfo( Format( 'Cost distance (%3d km for %6.2m): %8.2m', [ Reporting.TotalDistanceKm, Reporting.RatePerKm, Reporting.CostDistance ] ) ); AddInfo( '------------------------------------------------------' ); AddInfo( Format( 'Total cost : %8.2m', [ Reporting.CostDistance + Reporting.CostDuration ] ) ); end; procedure TFrmMain.AddStepsToReport( const ASteps: TTMSFNCDirectionsSteps ); var s: Integer; LInstr: String; LStep: TTMSFNCDirectionsStep; begin for s := 0 to ASteps.Count -1 do begin LStep := ASteps[s]; LInstr := TTMSFNCUtils.HTMLStrip( LStep.Instructions.Replace('<div','. <div' ) ); Reporting.AddStep(s+1, LInstr, LStep.Distance, LStep.Duration); end; end; procedure TFrmMain.btnCostsClick(Sender: TObject); begin GeocodeCustomer; end; procedure TFrmMain.btnReportClick(Sender: TObject); var LMem: TMemoryStream; begin if dlgSave.Execute then begin LMem := Reporting.AsPDF; if Assigned( LMem ) then begin LMem.SaveToFile(dlgSave.FileName); TTMSFNCUtils.OpenFile(dlgSave.FileName); LMem.Free; end; end; end; procedure TFrmMain.DirectionsGetDirections( Sender: TObject; const ARequest: TTMSFNCDirectionsRequest; const ARequestResult: TTMSFNCCloudBaseRequestResult); var LItem: TTMSFNCDirectionsItem; begin if ARequestResult.Success then begin Map.BeginUpdate; try InitReport; // iterate all routes if ARequest.Items.Count >0 then begin LItem := ARequest.Items[0]; // draw polyline AddPolyline( LItem.Coordinates.ToArray ); // add info to report AddStepsToReport( LItem.Steps ); // update memo AddReportToMemo; // focus map FocusMapOnRoute; // update GUI btnReport.Enabled := True; end; finally Map.EndUpdate; end; end; end; procedure TFrmMain.FocusMapOnRoute; begin // zoom map to area showing origin and destination Map.ZoomToBounds(Map.Polylines.ToCoordinateArray); // add marker for origin Map.Markers.Clear; Map.AddMarker( FHomeCoords, 'Start' ); // add marker for destination Map.AddMarker( FCustomerCoords, 'Destination' ); end; procedure TFrmMain.FormCreate(Sender: TObject); var LKeys: TServiceAPIKeys; begin LKeys := TServiceAPIKeys.Create( TPath.Combine( TTMSFNCUtils.GetAppPath, 'apikeys.config' ) ); try Map.APIKey := LKeys.GetKey( msGoogleMaps ); Directions.APIKey := LKeys.GetKey( msGoogleMaps ); Geocoding.APIKey := LKeys.GetKey( msGoogleMaps ); finally LKeys.Free; end; end; procedure TFrmMain.FormShow(Sender: TObject); begin txtInfo.Lines.Clear; btnReport.Enabled := False; GeocodeHome; end; procedure TFrmMain.GeoCodeCustomer; begin Geocoding.GetGeocoding( txtCustomer.Text, nil, 'Customer' ); end; procedure TFrmMain.GeocodeHome; begin Geocoding.GetGeocoding( ADDR_HOME, nil, 'Home' ); end; procedure TFrmMain.GeocodingGetGeocoding( Sender: TObject; const ARequest: TTMSFNCGeocodingRequest; const ARequestResult: TTMSFNCCloudBaseRequestResult); var LItem: TTMSFNCGeocodingItem; i : Integer; begin if ARequestResult.Success then begin for i := 0 to ARequest.Items.Count -1 do begin LItem := ARequest.Items[i]; if ARequest.ID = 'Home' then begin SetHomeCoords( LItem.Coordinate.ToRec ); end; if ARequest.ID = 'Customer' then begin SetCustomerCoords( LItem.Coordinate.ToRec ); UpdateRoute; end; end; end; end; procedure TFrmMain.InitReport; begin Reporting.Clear; Reporting.CustomerAddress := txtCustomer.Text; end; procedure TFrmMain.SetCustomerCoords(const ACoord: TTMSFNCMapsCoordinateRec); begin // coordinates for customer address FCustomerCoords := ACoord; AddInfo( Format( 'Customer coordinates determined (%f|%f)', [ FCustomerCoords.Latitude, FCustomerCoords.Longitude ] ), True ); end; procedure TFrmMain.SetHomeCoords(const ACoord: TTMSFNCMapsCoordinateRec); begin // coordinates for home address FHomeCoords := ACoord; AddInfo( Format( 'Home coordinates determined (%f|%f)', [ FHomeCoords.Latitude, FHomeCoords.Longitude ] ), True ); end; procedure TFrmMain.UpdateRoute; begin if ( FHomeCoords.Longitude <> 0 ) AND ( FCustomerCoords.Longitude <> 0 ) then begin Directions.DirectionsRequests.Clear; Directions.GetDirections(FHomeCoords, FCustomerCoords ); end; end; end.
unit l4l_print; { Lua4Lazarus sample: License: New BSD Copyright(c)2010- Malcome@Japan All rights reserved. ToDo: } {$mode objfpc}{$H+} {.$DEFINE USE_AGG} interface uses Classes, SysUtils, contnrs, graphics, printers, types, lua54, l4l_object; type { TLuaPrint } TLuaPrint = class(TObject) private FCanvasStack: TObjectList; function GetPageCount: integer; function GetPageSize: TSize; function GetPaperSize: TSize; procedure CopyCanvas(src, dst: TCanvas); protected LS: Plua_State; FPageList: TObjectList; FBmpList: TObjectList; FResList: TObjectList; FUserMargin, FRealMargin: TRect; FPaperRect: TPaperRect; FDPI, FPlayDPI: integer; FCanvas: TCanvas; FOffset: TPoint; FZoom: integer; function DP2LP(dp: integer): integer; function LP2DP(lp: integer): integer; function z(i: integer): integer; public constructor Create(L : Plua_State); destructor Destroy; override; procedure BeginDoc; procedure BeginDoc(Margin: TRect); procedure Run(const SourceCode: string); procedure EndDoc; procedure NewPage; procedure Play(pageNumber: integer; Cv: TCanvas; dpi: integer = 0; Zoom: integer = 100); procedure Play(pageNumber: integer; Cv: TCanvas; Margin: TRect; dpi, Zoom: integer); procedure Print(beginPage: integer=0; endPage: integer=0); property PageCount: integer read GetPageCount; property PaperSize: TSize read GetPaperSize; property PageSize: TSize read GetPageSize; property DPI: integer read FDPI; procedure AddOrder(const s: string); property Canvas: TCanvas read FCanvas; procedure PushCanvas; procedure PopCanvas; end; { TLuaPrintObject } TLuaFontObject = class; TLuaPenObject = class; TLuaBrushObject = class; TLuaPrintObject = class(TLuaObject) private FUnits: char; function GetBrushObject: TLuaBrushObject; function GetFontObject: TLuaFontObject; function GetPageHeight: integer; function GetPageLeft: integer; function GetPageNumber: integer; function GetPageTop: integer; function GetPageWidth: integer; function GetPenObject: TLuaPenObject; protected public LuaPrint: TLuaPrint; function DP2LP(dp: integer): integer; function LP2DP(lp: integer): integer; constructor Create(L : Plua_State; lp: TLuaPrint); overload; destructor Destroy; override; procedure GetFontName(var FontName: string); published function l4l_TextOut: integer; function l4l_Rectangle: integer; function l4l_Line: integer; function l4l_TextWidth: integer; function l4l_TextHeight: integer; function l4l_DrawImage: integer; function l4l_DrawPDF: integer; function l4l_NewPage: integer; function l4l_DP2LP: integer; function l4l_LP2DP: integer; property l4l_pageWidth: integer read GetPageWidth; property l4l_pageHeight: integer read GetPageHeight; property l4l_pageNumber: integer read GetPageNumber; property l4l_pageLeft: integer read GetPageLeft; property l4l_pageTop: integer read GetPageTop; property l4l_units: char read FUnits write FUnits; property l4l_Font: TLuaFontObject read GetFontObject; property l4l_Pen: TLuaPenObject read GetPenObject; property l4l_Brush: TLuaBrushObject read GetBrushObject; end; { TLuaFontObject } TLuaFontObject = class(TLuaObject) private function GetColor: string; function GetHeight: integer; function GetName: string; function GetOrientation: integer; function GetSize: integer; function GetStyle: string; procedure SetColor(const AValue: string); procedure SetHeight(const AValue: integer); procedure SetName(const AValue: string); procedure SetOrientation(AValue: integer); procedure SetSize(const AValue: integer); procedure SetStyle(const AValue: string); protected LPO: TLuaPrintObject; public constructor Create(L : Plua_State; aLPO: TLuaPrintObject); overload; destructor Destroy; override; published property l4l_color: string read GetColor write SetColor; property l4l_Name: string read GetName write SetName; property l4l_Size: integer read GetSize write SetSize; property l4l_Height: integer read GetHeight write SetHeight; // Only "DP". property l4l_Style: string read GetStyle write SetStyle; property l4l_Orientation: integer read GetOrientation write SetOrientation; end; { TLuaPenObject } TLuaPenObject = class(TLuaObject) private function GetColor: string; function GetMode: string; function GetStyle: string; function GetWidth: integer; procedure SetColor(const AValue: string); procedure SetMode(const AValue: string); procedure SetStyle(const AValue: string); procedure SetWidth(const AValue: integer); protected LPO: TLuaPrintObject; public constructor Create(L : Plua_State; aLPO: TLuaPrintObject); overload; destructor Destroy; override; published property l4l_color: string read GetColor write SetColor; property l4l_style: string read GetStyle write SetStyle; property l4l_mode: string read GetMode write SetMode; property l4l_width: integer read GetWidth write SetWidth; end; { TLuaBrushObject } TLuaBrushObject = class(TLuaObject) private function GetColor: string; function GetStyle: string; procedure SetColor(const AValue: string); procedure SetStyle(const AValue: string); protected LPO: TLuaPrintObject; public constructor Create(L : Plua_State; aLPO: TLuaPrintObject); overload; destructor Destroy; override; published property l4l_color: string read GetColor write SetColor; property l4l_style: string read GetStyle write SetStyle; end; implementation uses {$IFDEF WINDOWS} windows, {$ENDIF} {$IFDEF USE_AGG} agg_lcl, agg_fpimage, fpcanvas, {agg_color,} {$ENDIF} LCLType, LCLIntf, typinfo, l4l_pdf, graphmath; const MM_P_INCH = 2540; PRUN_NAME = 'P_'; type {$IFDEF USE_AGG} TMyAggCanvas = class(TAggLCLCanvas) end; {$ENDIF} { TLuaPrintRunObject } TLuaPrintRunObject = class(TLuaObject) private {$IFDEF USE_AGG} AggLCLCanvas: TMyAggCanvas; rx1, ry1, rx2, ry2: integer; procedure poly_sub(flag: TAggDrawPathFlag; w: boolean); {$ELSE} PPP: array of TPoint; PPC: array of integer; {$ENDIF} protected LuaPrint: TLuaPrint; function w(i: integer): integer; function zx(i: integer): integer; function zy(i: integer): integer; public constructor Create(L : Plua_State; lp: TLuaPrint); overload; destructor Destroy; override; published function l4l_TextOut: integer; function l4l_Rectangle: integer; function l4l_fillrect: integer; function l4l_Line: integer; function l4l_AddPolyPoint: integer; function l4l_AddBezierPoint: integer; function l4l_Polygon: integer; function l4l_Polyfill: integer; function l4l_Polyline: integer; function l4l_DrawImage: integer; function l4l_font_color: integer; function l4l_font_name: integer; function l4l_font_size: integer; function l4l_font_height: integer; function l4l_font_style: integer; function l4l_font_orientation: integer; function l4l_pen_color: integer; function l4l_pen_style: integer; function l4l_pen_joinstyle: integer; function l4l_pen_endcap: integer; function l4l_pen_mode: integer; function l4l_pen_width: integer; function l4l_brush_color: integer; function l4l_brush_style: integer; function l4l_PushCanvas: integer; function l4l_PopCanvas: integer; function l4l_SetClipRect: integer; end; { TLuaPrint } function TLuaPrint.GetPageCount: integer; begin Result := FPageList.Count; end; function TLuaPrint.DP2LP(dp: integer): integer; begin Result:= Trunc(MM_P_INCH * dp / FDPI + 0.5); end; function TLuaPrint.GetPageSize: TSize; begin Result.cx := FPaperRect.PhysicalRect.Right-FRealMargin.Left-FRealMargin.Right; Result.cy:= FPaperRect.PhysicalRect.Bottom-FRealMargin.Top-FRealMargin.Bottom; end; function TLuaPrint.GetPaperSize: TSize; begin Result.cx := FPaperRect.PhysicalRect.Right; Result.cy:= FPaperRect.PhysicalRect.Bottom; end; procedure TLuaPrint.CopyCanvas(src, dst: TCanvas); begin dst.Font.Assign(src.Font); dst.Pen.Assign(src.Pen); dst.Brush.Assign(src.Brush); end; procedure TLuaPrint.PushCanvas; var c: TCanvas; begin c := TCanvas.Create; CopyCanvas(FCanvas, c); FCanvasStack.Add(c); end; procedure TLuaPrint.PopCanvas; var c: TCanvas; begin c := TCanvas(FCanvasStack[FCanvasStack.Count-1]); CopyCanvas(c, FCanvas); FCanvasStack.Delete(FCanvasStack.Count-1); end; function TLuaPrint.LP2DP(lp: integer): integer; begin Result:= Trunc(lp * FDPI / MM_P_INCH + 0.5); end; function TLuaPrint.z(i: integer): integer; begin Result := i*FPlayDpi*FZoom div (FDPI*100); end; procedure TLuaPrint.AddOrder(const s: string); begin TStringList(FPageList[FPageList.Count-1]).Add(s); end; constructor TLuaPrint.Create(L : Plua_State); begin LS := L; FPageList:= TObjectList.Create(True); FBmpList:= TObjectList.Create(True); FResList:= TObjectList.Create(True); FCanvasStack := TObjectList.Create(True); end; destructor TLuaPrint.Destroy; begin FPageList.Free; FBmpList.Free; FResList.Free; FCanvasStack.Free; inherited Destroy; end; procedure TLuaPrint.BeginDoc; begin BeginDoc(types.Rect(0,0,0,0)); end; procedure TLuaPrint.BeginDoc(Margin: TRect); var bmp: graphics.TBitmap; begin FDPI := Printer.YDPI; FPageList.Clear; FPageList.Add(TStringList.Create); FPaperRect := Printer.PaperSize.PaperRect; FUserMargin := types.Rect(LP2DP(Margin.Left), LP2DP(Margin.Top), LP2DP(Margin.Right), LP2DP(Margin.Bottom)); FRealMargin := FUserMargin; if FPaperRect.WorkRect.Left > FRealMargin.Left then FRealMargin.Left := FPaperRect.WorkRect.Left; if FPaperRect.WorkRect.Top > FRealMargin.Top then FRealMargin.Top := FPaperRect.WorkRect.Top; if FPaperRect.PhysicalRect.Right-FPaperRect.WorkRect.Right > FRealMargin.Right then FRealMargin.Right := FPaperRect.PhysicalRect.Right-FPaperRect.WorkRect.Right; if FPaperRect.PhysicalRect.Bottom-FPaperRect.WorkRect.Bottom > FRealMargin.Bottom then FRealMargin.Bottom := FPaperRect.PhysicalRect.Bottom-FPaperRect.WorkRect.Bottom; FBmpList.Clear; bmp := graphics.TBitmap.Create; FBmpList.Add(bmp); FCanvas:= bmp.Canvas; FCanvas.Font.PixelsPerInch:= FDPI; FCanvas.Font.Size:= 10; FCanvasStack.Clear; PushCanvas; FResList.Clear; end; procedure TLuaPrint.EndDoc; begin PopCanvas; FCanvasStack.Clear; if FPageList.Count > 0 then begin if TStringList(FPageList[FPageList.Count-1]).Count = 0 then begin FPageList.Delete(FPageList.Count-1); FBmpList.Delete(FBmpList.Count-1); end; end; FCanvas := nil; end; procedure TLuaPrint.NewPage; var bmp: graphics.TBitmap; begin FPageList.Add(TStringList.Create); bmp := graphics.TBitmap.Create; FBmpList.Add(bmp); CopyCanvas(FCanvas, bmp.Canvas); PopCanvas; FCanvas:= bmp.Canvas; FCanvas.Font.PixelsPerInch:= Printer.YDPI; // We need to set FChanged:=true FCanvas.Font.Size:=FCanvas.Font.Size-1; FCanvas.Font.Size:=FCanvas.Font.Size+1; PushCanvas; end; procedure TLuaPrint.Run(const SourceCode: string); begin if luaL_loadbuffer(LS, PChar(SourceCode), Length(SourceCode), 'print') <> 0 then Raise Exception.Create(''); if lua_pcall(LS, 0, 0, 0) <> 0 then Raise Exception.Create(''); end; procedure TLuaPrint.Play(pageNumber: integer; Cv: TCanvas; dpi: integer; Zoom: integer); begin Play(pageNumber, Cv, types.Rect(0,0,0,0), dpi, Zoom); end; procedure TLuaPrint.Play(pageNumber: integer; Cv: TCanvas; Margin: TRect; dpi, Zoom: integer); var i : integer; sl: TStringList; x, y: integer; bmp: graphics.TBitmap; begin if (pageNumber > 0) and (pageNumber <= PageCount) then begin if dpi = 0 then dpi := Cv.Font.PixelsPerInch; FPlayDpi:= dpi; FZoom := Zoom; FOffset.x:= FRealMargin.Left; FOffset.y:= FRealMargin.Top; x := FPaperRect.PhysicalRect.Right-FRealMargin.Right; y := FPaperRect.PhysicalRect.Bottom-FRealMargin.Bottom; Dec(FOffset.x, Margin.Left); Dec(FOffset.y, Margin.Top); Dec(x, Margin.Left); Dec(y, Margin.Top); FCanvas := Cv; bmp := graphics.TBitmap(FBmpList[pageNumber-1]); CopyCanvas(bmp.Canvas, FCanvas); i := FCanvas.Font.Size; FCanvas.Font.PixelsPerInch:= FPlayDpi; FCanvas.Font.Size:= i + 1; FCanvas.Font.Size:= i; FCanvas.Font.Height:= FCanvas.Font.Height * FZoom div 100; FCanvas.Pen.Width:= FCanvas.Pen.Width * FPlayDpi * FZoom div (FDPI * 100); FCanvas.ClipRect := types.Rect(0, 0, z(x)+1, z(y)+1); FCanvas.Clipping:= True; try sl := TStringList(FPageList[pageNumber-1]); l4l_PushLuaObject(TLuaPrintRunObject.Create(LS, Self)); lua_setglobal(LS, PRUN_NAME); try if luaL_loadbuffer(LS, PChar(sl.Text), Length(sl.Text), nil) <> 0 then Raise Exception.Create(''); if lua_pcall(LS, 0, 0, 0) <> 0 then Raise Exception.Create(''); finally lua_pushnil(LS); lua_setglobal(LS, PRUN_NAME); end; finally FCanvas.Clipping:= False; end; end; end; procedure TLuaPrint.Print(beginPage: integer; endPage: integer); var i: integer; m: TRect; begin if beginPage < 1 then beginPage := 1; if endPage < beginPage then endPage := FPageList.Count; Printer.BeginDoc; try m := types.Rect( Printer.PaperSize.PaperRect.WorkRect.Left, Printer.PaperSize.PaperRect.WorkRect.Top, Printer.PaperSize.PaperRect.PhysicalRect.Right -Printer.PaperSize.PaperRect.WorkRect.Right, Printer.PaperSize.PaperRect.PhysicalRect.Bottom -Printer.PaperSize.PaperRect.WorkRect.Bottom); for i := beginPage to endPage do begin Play(i, Printer.Canvas, m, Printer.YDPI, 100); if i < endPage then Printer.NewPage; end; Printer.EndDoc; except Printer.Abort; Raise; end; end; function str_param(const s: string): string; var i: integer; begin Result := '"'; for i:= 1 to Length(s) do begin case s[i] of #$0a: Result:=Result + '\r'; #$0d: Result:=Result + '\n'; '"': Result:= Result + '\"'; '\': Result:= Result + '\\'; else Result := Result + s[i]; end; end; Result := Result + '"'; end; { TLuaPrintObject } function TLuaPrintObject.DP2LP(dp: integer): integer; var i : integer; begin case Upcase(FUnits) of 'M': i:= MM_P_INCH; 'I': i:= 1000; 'T': i:= 1440; else begin Result := dp; Exit; end; end; Result:= Trunc(dp * i / LuaPrint.FDPI + 0.5); end; function TLuaPrintObject.GetBrushObject: TLuaBrushObject; begin Result := TLuaBrushObject.Create(LS, Self); end; function TLuaPrintObject.GetFontObject: TLuaFontObject; begin Result := TLuaFontObject.Create(LS, Self); end; function TLuaPrintObject.GetPenObject: TLuaPenObject; begin Result := TLuaPenObject.Create(LS, Self); end; function TLuaPrintObject.GetPageHeight: integer; begin Result := DP2LP(LuaPrint.PageSize.cy); end; function TLuaPrintObject.GetPageLeft: integer; begin Result := DP2LP(LuaPrint.FRealMargin.Left); end; function TLuaPrintObject.GetPageTop: integer; begin Result := DP2LP(LuaPrint.FRealMargin.Top); end; function TLuaPrintObject.GetPageNumber: integer; begin Result := LuaPrint.PageCount; end; function TLuaPrintObject.GetPageWidth: integer; begin Result := DP2LP(LuaPrint.PageSize.cx); end; function TLuaPrintObject.LP2DP(lp: integer): integer; var i : integer; begin case Upcase(FUnits) of 'M': i:= MM_P_INCH; 'I': i:= 1000; 'T': i:= 1440; else begin Result := lp; Exit; end; end; Result:= Trunc(lp * LuaPrint.FDPI / i + 0.5); end; procedure TLuaPrintObject.GetFontName(var FontName: string); begin // ToDo end; constructor TLuaPrintObject.Create(L: Plua_State; lp: TLuaPrint); begin inherited Create(L); LuaPrint:= lp; FUnits := 'M'; end; destructor TLuaPrintObject.Destroy; begin inherited Destroy; end; function TLuaPrintObject.l4l_TextOut: integer; begin LuaPrint.AddOrder( Format(PRUN_NAME + '.TextOut(%d,%d,%s)', [LP2DP(lua_tointeger(LS, 1)), LP2DP(lua_tointeger(LS, 2)), str_param(lua_tostring(LS, 3))])); Result := 0; end; function TLuaPrintObject.l4l_Rectangle: integer; begin LuaPrint.AddOrder( Format(PRUN_NAME + '.rectangle(%d,%d,%d,%d)', [LP2DP(lua_tointeger(LS, 1)), LP2DP(lua_tointeger(LS, 2)), LP2DP(lua_tointeger(LS, 3)), LP2DP(lua_tointeger(LS, 4))])); Result := 0; end; function TLuaPrintObject.l4l_Line: integer; var c: integer; begin c := lua_gettop(LS); if c < 4 then begin LuaPrint.AddOrder( Format(PRUN_NAME + '.line(%d,%d)', [LP2DP(lua_tointeger(LS, 1)), LP2DP(lua_tointeger(LS, 2))])); end else begin LuaPrint.AddOrder( Format(PRUN_NAME + '.line(%d,%d,%d,%d)', [LP2DP(lua_tointeger(LS, 1)), LP2DP(lua_tointeger(LS, 2)), LP2DP(lua_tointeger(LS, 3)), LP2DP(lua_tointeger(LS, 4))])); end; Result := 0; end; function TLuaPrintObject.l4l_TextWidth: integer; begin lua_pushinteger(LS, DP2LP(LuaPrint.FCanvas.TextWidth(lua_tostring(LS, 1)))); Result := 1; end; function TLuaPrintObject.l4l_TextHeight: integer; begin lua_pushinteger(LS, DP2LP(LuaPrint.FCanvas.TextHeight(lua_tostring(LS, 1)))); Result := 1; end; function TLuaPrintObject.l4l_DrawImage: integer; var fn: string; ms: TMemoryStream; begin fn := lua_tostring(LS, -1); ms := TMemoryStream.Create; ms.LoadFromFile(fn); LuaPrint.FResList.Add(ms); case lua_gettop(LS) of 5: begin LuaPrint.AddOrder( Format(PRUN_NAME + '.drawimage(%d,%d,%d,%d,%d,%s)', [LP2DP(lua_tointeger(LS, 1)), LP2DP(lua_tointeger(LS, 2)), LP2DP(lua_tointeger(LS, 3)), LP2DP(lua_tointeger(LS, 4)), LuaPrint.FResList.Count-1, str_param(ExtractFileExt(fn))])); end; end; Result := 0; end; function TLuaPrintObject.l4l_DrawPDF: integer; var fn: string; fs: TFileStream; begin fn := lua_tostring(LS, -1); fs := TFileStream.Create(fn, fmOpenRead); try LuaPrint.PushCanvas; LuaPrint.AddOrder(PRUN_NAME + '.PushCanvas()'); case lua_gettop(LS) of 5: begin DrawPDF(fs, Self, 1, LP2DP(lua_tointeger(LS, 1)), LP2DP(lua_tointeger(LS, 2)), LP2DP(lua_tointeger(LS, 3)), LP2DP(lua_tointeger(LS, 4))); end; 6: begin DrawPDF(fs, Self, lua_tointeger(LS, 5), LP2DP(lua_tointeger(LS, 1)), LP2DP(lua_tointeger(LS, 2)), LP2DP(lua_tointeger(LS, 3)), LP2DP(lua_tointeger(LS, 4))); end; end; LuaPrint.AddOrder(PRUN_NAME + '.PopCanvas()'); LuaPrint.PopCanvas; finally fs.Free; end; Result := 0; end; function TLuaPrintObject.l4l_NewPage: integer; begin LuaPrint.NewPage; Result := 0; end; function TLuaPrintObject.l4l_DP2LP: integer; begin lua_pushinteger(LS, DP2LP(lua_tointeger(LS, 1))); Result := 1; end; function TLuaPrintObject.l4l_LP2DP: integer; begin lua_pushinteger(LS, LP2DP(lua_tointeger(LS, 1))); Result := 1; end; { TLuaFontObject } constructor TLuaFontObject.Create(L: Plua_State; aLPO: TLuaPrintObject); begin inherited Create(L); LPO := aLPO; end; destructor TLuaFontObject.Destroy; begin inherited Destroy; end; function TLuaFontObject.GetColor: string; begin Result := ColorToString(LPO.LuaPrint.FCanvas.Font.Color); end; function TLuaFontObject.GetHeight: integer; begin Result := LPO.LuaPrint.FCanvas.Font.Height; end; function TLuaFontObject.GetName: string; begin Result := LPO.LuaPrint.FCanvas.Font.Name; end; function TLuaFontObject.GetOrientation: integer; begin Result := LPO.LuaPrint.FCanvas.Font.Orientation; end; function TLuaFontObject.GetSize: integer; begin Result := LPO.LuaPrint.FCanvas.Font.Size; end; function TLuaFontObject.GetStyle: string; begin Result := SetToString(PTypeInfo(TypeInfo(TFontStyles)), Integer(LPO.LuaPrint.FCanvas.Font.Style), false); end; procedure TLuaFontObject.SetColor(const AValue: string); var i: integer; begin try i := StrToInt(AValue); except i := StringToColor(AValue); end; if i >= 0 then begin LPO.LuaPrint.FCanvas.Font.Color := TColor(i); LPO.LuaPrint.AddOrder( Format(PRUN_NAME + '.font_color(%d)', [i])); end; end; procedure TLuaFontObject.SetHeight(const AValue: integer); begin LPO.LuaPrint.FCanvas.Font.Height := AValue; LPO.LuaPrint.AddOrder( Format(PRUN_NAME + '.font_height(%d)', [AValue])); end; procedure TLuaFontObject.SetName(const AValue: string); begin LPO.LuaPrint.FCanvas.Font.Name := AValue; LPO.LuaPrint.AddOrder( Format(PRUN_NAME + '.font_name(%s)', [str_param(AValue)])); end; procedure TLuaFontObject.SetOrientation(AValue: integer); begin LPO.LuaPrint.FCanvas.Font.Orientation := AValue; LPO.LuaPrint.AddOrder( Format(PRUN_NAME + '.font_orientation(%d)', [AValue])); end; procedure TLuaFontObject.SetSize(const AValue: integer); begin LPO.LuaPrint.FCanvas.Font.Size := AValue; LPO.LuaPrint.AddOrder( Format(PRUN_NAME + '.font_size(%d)', [AValue])); end; procedure TLuaFontObject.SetStyle(const AValue: string); var i: integer; begin try i := StrToInt(AValue); except i := StringToSet(PTypeInfo(TypeInfo(TFontStyles)), AValue); end; LPO.LuaPrint.FCanvas.Font.Style := TFontStyles(i); LPO.LuaPrint.AddOrder( Format(PRUN_NAME + '.font_style(%d)', [i])); end; { TLuaPenObject } function TLuaPenObject.GetStyle: string; begin Result := GetEnumName(TypeInfo(TPenStyle), Integer(LPO.LuaPrint.FCanvas.Pen.Style)); end; function TLuaPenObject.GetWidth: integer; begin Result := LPO.DP2LP(LPO.LuaPrint.FCanvas.Pen.Width); if Result < 1 then Result := 1; end; function TLuaPenObject.GetColor: string; begin Result := ColorToString(LPO.LuaPrint.FCanvas.Pen.Color); end; function TLuaPenObject.GetMode: string; begin Result := GetEnumName(TypeInfo(TPenMode), Integer(LPO.LuaPrint.FCanvas.Pen.Mode)); end; procedure TLuaPenObject.SetColor(const AValue: string); var i: integer; begin try i := StrToInt(AValue); except i := StringToColor(AValue); end; if i >= 0 then begin LPO.LuaPrint.FCanvas.Pen.Color := TColor(i); LPO.LuaPrint.AddOrder( Format(PRUN_NAME + '.pen_color(%d)', [i])); end; end; procedure TLuaPenObject.SetMode(const AValue: string); var i: integer; begin try i := StrToInt(AValue); except i := GetEnumValue(TypeInfo(TPenMode), AValue); end; if i >= 0 then begin LPO.LuaPrint.FCanvas.Pen.Mode := TPenMode(i); LPO.LuaPrint.AddOrder( Format(PRUN_NAME + '.pen_mode(%d)', [i])); end; end; procedure TLuaPenObject.SetStyle(const AValue: string); var i: integer; begin try i := StrToInt(AValue); except i := GetEnumValue(TypeInfo(TPenStyle), AValue); end; if i >= 0 then begin LPO.LuaPrint.FCanvas.Pen.Style := TPenSTyle(i); LPO.LuaPrint.AddOrder( Format(PRUN_NAME + '.pen_style(%d)', [i])); end; end; procedure TLuaPenObject.SetWidth(const AValue: integer); var i: integer; begin i:= LPO.LP2DP(AValue); if i < 1 then i := 1; LPO.LuaPrint.FCanvas.Pen.Width:= i; LPO.LuaPrint.AddOrder(Format(PRUN_NAME + '.pen_width(%d)', [i])); end; constructor TLuaPenObject.Create(L: Plua_State; aLPO: TLuaPrintObject); begin inherited Create(L); LPO := aLPO; end; destructor TLuaPenObject.Destroy; begin inherited Destroy; end; { TLuaBrushObject } function TLuaBrushObject.GetStyle: string; begin Result := GetEnumName(TypeInfo(TBrushStyle), Integer(LPO.LuaPrint.FCanvas.Brush.Style)); end; function TLuaBrushObject.GetColor: string; begin Result := ColorToString(LPO.LuaPrint.FCanvas.Brush.Color); end; procedure TLuaBrushObject.SetColor(const AValue: string); var i: integer; begin try i := StrToInt(AValue); except i := StringToColor(AValue); end; if i >= 0 then begin LPO.LuaPrint.FCanvas.Brush.Color := TColor(i); LPO.LuaPrint.AddOrder( Format(PRUN_NAME + '.brush_color(%d)', [i])); end; end; procedure TLuaBrushObject.SetStyle(const AValue: string); var i: integer; begin try i := StrToInt(AValue); except i := GetEnumValue(TypeInfo(TBrushStyle), AValue); end; if i >= 0 then begin LPO.LuaPrint.FCanvas.Brush.Style := TBrushSTyle(i); LPO.LuaPrint.AddOrder( Format(PRUN_NAME + '.brush_style(%d)', [i])); end; end; constructor TLuaBrushObject.Create(L: Plua_State; aLPO: TLuaPrintObject); begin inherited Create(L); LPO := aLPO; end; destructor TLuaBrushObject.Destroy; begin inherited Destroy; end; { TLuaPrintRunObject } function TLuaPrintRunObject.w(i: integer): integer; begin Result := i * LuaPrint.FPlayDpi * LuaPrint.FZoom div (LuaPrint.FDPI * 100); end; function TLuaPrintRunObject.zx(i: integer): integer; begin Result := (i + LuaPrint.FOffset.x) * LuaPrint.FPlayDpi * LuaPrint.FZoom div (LuaPrint.FDPI * 100); end; function TLuaPrintRunObject.zy(i: integer): integer; begin Result := (i + LuaPrint.FOffset.y) * LuaPrint.FPlayDpi * LuaPrint.FZoom div (LuaPrint.FDPI * 100); end; constructor TLuaPrintRunObject.Create(L: Plua_State; lp: TLuaPrint); begin inherited Create(L); LuaPrint:= lp; {$IFDEF USE_AGG} AggLCLCanvas:= TMyAggCanvas.Create; AggLCLCanvas.Image.PixelFormat:= afpimRGBA32; AggLCLCanvas.AggAntiAliasGamma:= 1.0; rx1:= MaxInt; ry1 := MaxInt; rx2 := 0; ry2 := 0; {$ENDIF} end; destructor TLuaPrintRunObject.Destroy; begin {$IFDEF USE_AGG} AggLCLCanvas.Free; {$ENDIF} inherited Destroy; end; function TLuaPrintRunObject.l4l_TextOut: integer; begin LuaPrint.FCanvas.TextOut( zx(lua_tointeger(LS, 1)), zy(lua_tointeger(LS, 2)), lua_tostring(LS, 3)); Result := 0; end; function TLuaPrintRunObject.l4l_Rectangle: integer; var x1, y1, x2, y2: integer; begin x1:= zx(lua_tointeger(LS, 1)); y1:= zy(lua_tointeger(LS, 2)); x2:= zx(lua_tointeger(LS, 3)); y2:= zy(lua_tointeger(LS, 4)); if x1 = x2 then begin LuaPrint.FCanvas.Line(x1, y1, x1, y2); end else if y1 = y2 then begin LuaPrint.FCanvas.Line(x1, y1, x2, y1); end else begin LuaPrint.FCanvas.Rectangle(x1, y1, x2, y2); end; Result := 0; end; function TLuaPrintRunObject.l4l_fillrect: integer; begin LuaPrint.FCanvas.FillRect( zx(lua_tointeger(LS, 1)), zy(lua_tointeger(LS, 2)), zx(lua_tointeger(LS, 3)), zy(lua_tointeger(LS, 4))); Result := 0; end; function TLuaPrintRunObject.l4l_Line: integer; var c: integer; begin c := lua_gettop(LS); if c < 4 then begin LuaPrint.FCanvas.LineTo( zx(lua_tointeger(LS, 1)), zy(lua_tointeger(LS, 2))); end else begin LuaPrint.FCanvas.Line( zx(lua_tointeger(LS, 1)), zy(lua_tointeger(LS, 2)), zx(lua_tointeger(LS, 3)), zy(lua_tointeger(LS, 4))); end; Result := 0; end; function TLuaPrintRunObject.l4l_AddPolyPoint: integer; var i, {$IFDEF USE_AGG} x, y, {$ELSE} l, {$ENDIF} c: integer; begin c := lua_gettop(LS); if c > 0 then begin {$IFDEF USE_AGG} x := zx(lua_tointeger(LS, 1)); y := zy(lua_tointeger(LS, 2)); AggLCLCanvas.Path.m_path.move_to(x, y); if x < rx1 then rx1 := x; if y < ry1 then ry1 := y; if x > rx2 then rx2 := x; if y > ry2 then ry2 := y; for i := 2 to c div 2 do begin x := zx(lua_tointeger(LS, i*2-1)); y := zy(lua_tointeger(LS, i*2)); AggLCLCanvas.Path.m_path.line_to(x, y); if x < rx1 then rx1 := x; if y < ry1 then ry1 := y; if x > rx2 then rx2 := x; if y > ry2 then ry2 := y; end; {$ELSE} l := Length(PPP); SetLength(PPP, l + c div 2); for i := 1 to c div 2 do begin PPP[l+i-1] := types.Point(zx(lua_tointeger(LS, i*2-1)), zy(lua_tointeger(LS, i*2))); end; SetLength(PPC, Length(PPC)+1); PPC[Length(PPC)-1] := c div 2; {$ENDIF} end else begin {$IFDEF USE_AGG} AggLCLCanvas.Path.m_path.remove_all; {$ELSE} SetLength(PPP, 0); SetLength(PPC, 0); {$ENDIF} end; Result := 0; end; function TLuaPrintRunObject.l4l_AddBezierPoint: integer; var i, {$IFDEF USE_AGG} {$ELSE} l, {$ENDIF} c: integer; p: array of TPoint; pp: PPoint; begin c := lua_gettop(LS); if c > 0 then begin SetLength(p, c div 2); for i := 1 to c div 2 do begin p[i-1] := types.Point(zx(lua_tointeger(LS, i*2-1)), zy(lua_tointeger(LS, i*2))); end; pp:= AllocMem(0); try PolyBezier2Polyline(p, pp, c, True); {$IFDEF USE_AGG} AggLCLCanvas.Path.m_path.move_to(pp^.x, pp^.y); if pp^.x < rx1 then rx1 := pp^.x; if pp^.y < ry1 then ry1 := pp^.y; if pp^.x > rx2 then rx2 := pp^.x; if pp^.y > ry2 then ry2 := pp^.y; for i := 2 to c do begin AggLCLCanvas.Path.m_path.line_to((pp+i-1)^.x, (pp+i-1)^.y); if (pp+i-1)^.x < rx1 then rx1 := (pp+i-1)^.x; if (pp+i-1)^.y < ry1 then ry1 := (pp+i-1)^.y; if (pp+i-1)^.x > rx2 then rx2 := (pp+i-1)^.x; if (pp+i-1)^.y > ry2 then ry2 := (pp+i-1)^.y; end; {$ELSE} l := Length(PPP); SetLength(PPP, l + c); for i := 1 to c do PPP[l+i-1] := (pp+i-1)^; SetLength(PPC, Length(PPC)+1); PPC[Length(PPC)-1] := c; {$ENDIF} finally FreeMem(pp); end; end else begin {$IFDEF USE_AGG} AggLCLCanvas.Path.m_path.remove_all; {$ELSE} SetLength(PPP, 0); SetLength(PPC, 0); {$ENDIF} end; Result := 0; end; {$IFDEF USE_AGG} procedure TLuaPrintRunObject.poly_sub(flag: TAggDrawPathFlag; w: boolean); var i: integer; bmp: graphics.TBitmap; lw : integer; x, y: double; begin bmp := graphics.TBitmap.Create; try lw := LuaPrint.FCanvas.Pen.Width; AggLCLCanvas.Pen.AggLineWidth:= lw; AggLCLCanvas.Pen.Color:= LuaPrint.FCanvas.Pen.Color; case LuaPrint.FCanvas.Pen.EndCap of pecRound: AggLCLCanvas.Pen.AggLineCap:= AGG_CapRound; pecSquare: AggLCLCanvas.Pen.AggLineCap:= AGG_CapSquare; pecFlat: AggLCLCanvas.Pen.AggLineCap:= AGG_CapButt; end; case LuaPrint.FCanvas.Pen.JoinStyle of pjsRound: AggLCLCanvas.Pen.AggLineJoin:= AGG_JoinRound; pjsBevel: AggLCLCanvas.Pen.AggLineJoin:= AGG_JoinBevel; pjsMiter: AggLCLCanvas.Pen.AggLineJoin:= AGG_JoinMiter; end; AggLCLCanvas.Brush.Color:= LuaPrint.FCanvas.Brush.Color; AggLCLCanvas.Brush.AggFillEvenOdd:= not w; AggLCLCanvas.Image.SetSize(rx2-rx1+1+lw*2, ry2-ry1+1+lw*2); AggLCLCanvas.Erase; for i := 0 to AggLCLCanvas.Path.m_path.total_vertices-1 do begin AggLCLCanvas.Path.m_path.vertex_(i, @x ,@y); AggLCLCanvas.Path.m_path.modify_vertex(i, x-rx1+lw, y-ry1+lw); end; AggLCLCanvas.AggDrawPath(flag); bmp.LoadFromIntfImage(AggLCLCanvas.Image.IntfImg); LuaPrint.FCanvas.Draw(rx1-lw, ry1-lw, bmp); rx1:= MaxInt; ry1 := MaxInt; rx2 := 0; ry2 := 0; finally bmp.Free; end; end; {$ENDIF} function TLuaPrintRunObject.l4l_Polygon: integer; {$IFDEF USE_AGG} {$ELSE} var i: integer; {$ENDIF} begin {$IFDEF USE_AGG} poly_sub(AGG_FillAndStroke, lua_toboolean(LS, 1)); {$ELSE} {$IFDEF WINDOWS} i := ALTERNATE; if lua_toboolean(LS, 1) then i := WINDING; SetPolyFillMode(LuaPrint.FCanvas.Handle, i); PolyPolygon(LuaPrint.FCanvas.Handle, PPP[0], PPC[0], Length(PPC)); {$ELSE} // ToDo LuaPrint.FCanvas.Pen .Polygon(PPP, lua_toboolean(LS, 1)); {$ENDIF} {$ENDIF} Result := 0; end; function TLuaPrintRunObject.l4l_Polyfill: integer; {$IFDEF USE_AGG} {$ELSE} var i: integer; ps: TPenStyle; {$ENDIF} begin {$IFDEF USE_AGG} poly_sub(AGG_FillOnly, lua_toboolean(LS, 1)); {$ELSE} {$IFDEF WINDOWS} i := ALTERNATE; if lua_toboolean(LS, 1) then i := WINDING; SetPolyFillMode(LuaPrint.FCanvas.Handle, i); ps := LuaPrint.FCanvas.Pen.Style; LuaPrint.FCanvas.Pen.Style:= psClear; PolyPolygon(LuaPrint.FCanvas.Handle, PPP[0], PPC[0], Length(PPC)); LuaPrint.FCanvas.Pen.Style:= ps; {$ELSE} // ToDo LuaPrint.FCanvas.Polygon(PPP, lua_toboolean(LS, 1)); {$ENDIF} {$ENDIF} Result := 0; end; function TLuaPrintRunObject.l4l_Polyline: integer; begin {$IFDEF USE_AGG} poly_sub(AGG_StrokeOnly, False); {$ELSE} {$IFDEF WINDOWS} PolyPolyline(LuaPrint.FCanvas.Handle, PPP[0], PPC[0], Length(PPC)); {$ELSE} // ToDo LuaPrint.FCanvas.Polyline(PPP); {$ENDIF} {$ENDIF} Result := 0; end; function TLuaPrintRunObject.l4l_DrawImage: integer; var ms: TStream; g: TPicture; x1, y1, x2, y2, i: integer; n: lua_number; begin g := TPicture.Create; try ms := TStream(LuaPrint.FResList[lua_tointeger(LS, -2)]); ms.Position:= 0; //g.LoadFromStreamWithFileExt(ms, lua_tostring(LS, -1)); g.LoadFromStream(ms); x1 := zx(lua_tointeger(LS, 1)); y1 := zy(lua_tointeger(LS, 2)); x2 := zx(lua_tointeger(LS, 3)); y2 := zy(lua_tointeger(LS, 4)); n := Abs(y2 - y1) / g.Height; i := Trunc(g.Width * n); if i < Abs(x2 - x1) then begin x2 := x1 + i; y2 := y1 + Trunc(g.Height * n); end else begin n := Abs(x2 - x1) / g.Width; x2 := x1 + Trunc(g.Width * n); y2 := y1 + Trunc(g.Height * n); end; LuaPrint.FCanvas.StretchDraw(types.Rect(x1, y1, x2, y2), g.Graphic); finally g.Free; end; Result := 0; end; function TLuaPrintRunObject.l4l_font_color: integer; begin LuaPrint.FCanvas.Font.Color := TColor(lua_tointeger(LS, 1)); Result := 0; end; function TLuaPrintRunObject.l4l_font_name: integer; begin LuaPrint.FCanvas.Font.Name := lua_tostring(LS, 1); Result := 0; end; function TLuaPrintRunObject.l4l_font_size: integer; begin LuaPrint.FCanvas.Font.Size := lua_tointeger(LS, 1); LuaPrint.FCanvas.Font.Height:= LuaPrint.FCanvas.Font.Height * LuaPrint.FZoom div 100; Result := 0; end; function TLuaPrintRunObject.l4l_font_height: integer; begin LuaPrint.FCanvas.Font.Height := w(lua_tointeger(LS, 1)); Result := 0; end; function TLuaPrintRunObject.l4l_font_style: integer; begin LuaPrint.FCanvas.Font.Style := TFontStyles(Integer(lua_tointeger(LS, 1))); Result := 0; end; function TLuaPrintRunObject.l4l_font_orientation: integer; begin LuaPrint.FCanvas.Font.Orientation := lua_tointeger(LS, 1); Result := 0; end; function TLuaPrintRunObject.l4l_pen_color: integer; begin LuaPrint.FCanvas.Pen.Color := TColor(lua_tointeger(LS, 1)); Result := 0; end; function TLuaPrintRunObject.l4l_pen_style: integer; begin LuaPrint.FCanvas.Pen.Style := TPenStyle(lua_tointeger(LS, 1)); Result := 0; end; function TLuaPrintRunObject.l4l_pen_joinstyle: integer; begin LuaPrint.FCanvas.Pen.JoinStyle := TPenJoinStyle(lua_tointeger(LS, 1)); Result := 0; end; function TLuaPrintRunObject.l4l_pen_endcap: integer; begin LuaPrint.FCanvas.Pen.EndCap := TPenEndCap(lua_tointeger(LS, 1)); Result := 0; end; function TLuaPrintRunObject.l4l_pen_mode: integer; begin LuaPrint.FCanvas.Pen.Mode := TPenMode(lua_tointeger(LS, 1)); Result := 0; end; function TLuaPrintRunObject.l4l_pen_width: integer; begin LuaPrint.FCanvas.Pen.Width:= w(lua_tointeger(LS, 1)); Result := 0; end; function TLuaPrintRunObject.l4l_brush_color: integer; begin LuaPrint.FCanvas.Brush.Color := TColor(lua_tointeger(LS, 1)); Result := 0; end; function TLuaPrintRunObject.l4l_brush_style: integer; begin LuaPrint.FCanvas.Brush.Style := TBrushStyle(lua_tointeger(LS, 1)); Result := 0; end; function TLuaPrintRunObject.l4l_PushCanvas: integer; begin LuaPrint.PushCanvas; Result := 0; end; function TLuaPrintRunObject.l4l_PopCanvas: integer; begin LuaPrint.PopCanvas; Result := 0; end; function TLuaPrintRunObject.l4l_SetClipRect: integer; begin LuaPrint.FCanvas.Region.ClipRect := types.Rect(lua_tointeger(LS, 1), lua_tointeger(LS, 2), lua_tointeger(LS, 3), lua_tointeger(LS, 4)); Result := 0; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2016-2019 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Amazon.Storage.Service.API.Life.Cycle; interface {$SCOPEDENUMS ON} uses System.Classes, System.Generics.Collections; type /// <summary>Supported transitions.</summary> TAmazonStorageClass = (Standard, StandardIA, Glacier, ReduceRedundancy); /// <summary>Class to store lifecycle transition.</summary> TAmazonLifeCycleTransition = record private /// <summary>Specifies the number of days after object creation when the specific rule action takes effect.</summary> FDays: Integer; /// <summary>Specifies the Amazon S3 storage class to which you want the object to transition.</summary> FStorageClass: TAmazonStorageClass; /// <summary>Return the XML representation.</summary> /// <returns>Return the XML representation.</returns> function GetXML: string; public /// <summary>Creates a new instance of TAmazonLifeCycleRule.</summary> /// <param name="ADays">Specifies the number of days after object creation when the specific rule action takes effect.</param> /// <param name="AStorageClass">Specifies the Amazon S3 storage class to which you want the object to transition.</param> /// <returns>Return a lifecycle transition.</returns> class function Create(ADays: Integer; AStorageClass: TAmazonStorageClass): TAmazonLifeCycleTransition; static; /// <summary>Specifies the number of days after object creation when the specific rule action takes effect.</summary> property Days: Integer read FDays; /// <summary>Specifies the Amazon S3 storage class to which you want the object to transition.</summary> property StorageClass: TAmazonStorageClass read FStorageClass; /// <summary>The XML representation.</summary> property XML: string read GetXML; end; /// <summary>Class to store lifecycle rules.</summary> TAmazonLifeCycleRule = record private /// <summary>Unique identifier for the rule. The value cannot be longer than 255 characters.</summary> FID: string; /// <summary>Object key prefix identifying one or more objects to which the rule applies.</summary> FPrefix: string; /// <summary>If Enabled, Amazon S3 executes the rule as scheduled. If Disabled, Amazon S3 ignores the rule.</summary> FStatus: boolean; /// <summary>List of stored transitions.</summary> FTransitions: TArray<TAmazonLifeCycleTransition>; /// <summary>Specifies a period in the object's lifetime when Amazon S3 should take the appropriate expiration action.</summary> FExpirationDays: Integer; /// <summary>Specifies the number of days an object is noncurrent before Amazon S3 can perform the associated action.</summary> FNoncurrentVersionTransitionDays: Integer; /// <summary>Specifies the Amazon S3 storage class to which you want the object to transition.</summary> FNoncurrentVersionTransitionStorageClass: TAmazonStorageClass; /// <summary>Specifies when noncurrent object versions expire. Upon expiration, Amazon S3 permanently deletes the noncurrent object versions.</summary> FNoncurrentVersionExpirationDays: Integer; /// <summary>Return a lifecycle transition.</summary> /// <param name="AIndex">The lifecycle index to obtain.</param> /// <returns>Return a lifecycle transition.</returns> function GetTransition(AIndex: Integer): TAmazonLifeCycleTransition; /// <summary>Return the XML representation.</summary> /// <returns>Return the XML representation.</returns> function GetXML: string; public /// <summary>Creates a new instance of TAmazonLifeCycleRule.</summary> /// <param name="AID">Unique identifier for the rule. The value cannot be longer than 255 characters.</param> /// <param name="APrefix">Object key prefix identifying one or more objects to which the rule applies.</param> /// <param name="AStatus">If Enabled, Amazon S3 executes the rule as scheduled. If Disabled, Amazon S3 ignores the rule.</param> /// <param name="ATransitions">List of transitions to store.</param> /// <param name="AExpirationDays">Specifies a period in the object's lifetime when Amazon S3 should take the appropriate expiration action.</param> /// <param name="ANoncurrentVersionTransitionDays">Specifies the number of days an object is noncurrent before Amazon S3 can perform the associated action.</param> /// <param name="ANoncurrentVersionTransitionStorageClass">Specifies the Amazon S3 storage class to which you want the object to transition.</param> /// <param name="ANoncurrentVersionExpirationDays">Specifies when noncurrent object versions expire. Upon expiration, Amazon S3 permanently deletes the noncurrent object versions.</param> /// <returns>Return a lifecycle rule.</returns> class function Create(const AID: string; const APrefix: string; AStatus: boolean; ATransitions: TArray<TAmazonLifeCycleTransition>; AExpirationDays, ANoncurrentVersionTransitionDays: Integer; ANoncurrentVersionTransitionStorageClass: TAmazonStorageClass; ANoncurrentVersionExpirationDays: Integer): TAmazonLifeCycleRule; static; /// <summary>Add a new transition.</summary> /// <param name="ADays">Specifies the number of days after object creation when the specific rule action takes effect.</param> /// <param name="AStorageClass">Specifies the Amazon S3 storage class to which you want the object to transition.</param> /// <returns>Return the index of the transition in the transition list.</returns> function AddTransition(ADays: Integer; AStorageClass: TAmazonStorageClass): Integer; /// <summary>Removes a transition in the transition list.</summary> /// <param name="AIndex">Specifies the index of the transition to remove.</param> procedure DeleteTransition(AIndex: Integer); /// <summary>Unique identifier for the rule. The value cannot be longer than 255 characters.</summary> property ID: string read FID; /// <summary>Object key prefix identifying one or more objects to which the rule applies.</summary> property Prefix: string read FPrefix; /// <summary>If Enabled, Amazon S3 executes the rule as scheduled. If Disabled, Amazon S3 ignores the rule.</summary> property Status: boolean read FStatus; /// <summary>List of stored transitions.</summary> property Transitions[Index: Integer]: TAmazonLifeCycleTransition read GetTransition; default; /// <summary>Specifies a period in the object's lifetime when Amazon S3 should take the appropriate expiration action.</summary> property ExpirationDays: Integer read FExpirationDays write FExpirationDays; /// <summary>Specifies the number of days an object is noncurrent before Amazon S3 can perform the associated action.</summary> property NoncurrentVersionTransitionDays: Integer read FNoncurrentVersionTransitionDays; /// <summary>Specifies the Amazon S3 storage class to which you want the object to transition.</summary> property NoncurrentVersionTransitionStorageClass: TAmazonStorageClass read FNoncurrentVersionTransitionStorageClass; /// <summary>Specifies when noncurrent object versions expire. Upon expiration, Amazon S3 permanently deletes the noncurrent object versions.</summary> property NoncurrentVersionExpirationDays: Integer read FNoncurrentVersionExpirationDays; /// <summary>The XML representation.</summary> property XML: string read GetXML; end; /// <summary>Class to store lifecycle configuration.</summary> TAmazonLifeCycleConfiguration = record private /// <summary>List of stored rules.</summary> FRules: TArray<TAmazonLifeCycleRule>; /// <summary>Return a lifecycle rule.</summary> /// <param name="AIndex">The lifecycle rule index to obtain.</param> /// <returns>Return a lifecycle rule.</returns> function GetRule(AIndex: Integer): TAmazonLifeCycleRule; /// <summary>Return the XML representation.</summary> /// <returns>Return the XML representation.</returns> function GetXML: string; public /// <summary>Creates a new instance of TAmazonLifeCycleConfiguration.</summary> /// <param name="ARules">List of rules to store.</param> /// <returns>Return a lifecycle configuration.</returns> class function Create(ARules: TArray<TAmazonLifeCycleRule>): TAmazonLifeCycleConfiguration; static; /// <summary>Add a new rule.</summary> /// <param name="AID">Unique identifier for the rule. The value cannot be longer than 255 characters.</param> /// <param name="APrefix">Object key prefix identifying one or more objects to which the rule applies.</param> /// <param name="AStatus">If Enabled, Amazon S3 executes the rule as scheduled. If Disabled, Amazon S3 ignores the rule.</param> /// <param name="ATransitions">List of transitions to store.</param> /// <param name="AExpirationDays">Specifies a period in the object's lifetime when Amazon S3 should take the appropriate expiration action.</param> /// <param name="ANoncurrentVersionTransitionDays">Specifies the number of days an object is noncurrent before Amazon S3 can perform the associated action.</param> /// <param name="ANoncurrentVersionTransitionStorageClass">Specifies the Amazon S3 storage class to which you want the object to transition.</param> /// <param name="ANoncurrentVersionExpirationDays">Specifies when noncurrent object versions expire. Upon expiration, Amazon S3 permanently deletes the noncurrent object versions.</param> /// <returns>Return the index of the rule in the rule list.</returns> function AddRule(const AID: string; const APrefix: string; AStatus: boolean; ATransitions: TArray<TAmazonLifeCycleTransition>; AExpirationDays, ANoncurrentVersionTransitionDays: Integer; ANoncurrentVersionTransitionStorageClass: TAmazonStorageClass; ANoncurrentVersionExpirationDays: Integer): Integer; overload; /// <summary>Add a new rule.</summary> /// <param name="ARule">A rule to add to the list of rules.</param> /// <returns>Return the index of the rule in the rule list.</returns> function AddRule(const ARule: TAmazonLifeCycleRule): Integer; overload; /// <summary>Removes a rule in the rule list.</summary> /// <param name="AIndex">Specifies the index of the rule to remove.</param> procedure DeleteRule(AIndex: Integer); /// <summary>List of stored rules.</summary> property Rules[Index: Integer]: TAmazonLifeCycleRule read GetRule; default; /// <summary>The XML representation.</summary> property XML: string read GetXML; end; implementation uses System.SysUtils, Xml.XMLIntf, Xml.XMLDoc, Data.Cloud.CloudResStrs; const cLifeCycleConfiguration = 'LifeCycleConfiguration'; cLifeCycleRule = 'Rule'; cLifeCycleTransition = 'Transition'; cStorageClass = 'StorageClass'; cID = 'ID'; cPrefix = 'Prefix'; cStatus = 'Status'; cExpiration = 'Expiration'; cDays = 'Days'; cNoncurrentVersionTransition = 'NoncurrentVersionTransition'; cNoncurrentVersionExpiration = 'NoncurrentVersionExpiration'; cNoncurrentDays = 'NoncurrentDays'; cStandard = 'STANDARD'; cStandardIA = 'STANDARD_IA'; cGlacier = 'GLACIER'; cReducedRedundancy = 'REDUCED_REDUNDANCY'; cBooleanText: array[boolean] of string = ('Disabled', 'Enabled'); function WriteOpenTag(const ANAme: string): string; begin Result := '<' + AName + '>'; end; function WriteCloseTag(const AName: string): string; begin Result := '</' + AName + '>'; end; function WriteEmptyTag(const AName: string): string; begin Result := '<' + AName + '/>'; end; function WriteValueTag(const AName, AValue: string): string; begin Result := WriteOpenTag(AName) + AValue + WriteCloseTag(AName); end; function GetStorageClassName(AValue: TAmazonStorageClass): string; begin case AValue of TAmazonStorageClass.Standard: Result := cStandard; TAmazonStorageClass.StandardIA: Result := cStandardIA; TAmazonStorageClass.Glacier: Result := cGlacier; TAmazonStorageClass.ReduceRedundancy: Result := cReducedRedundancy; end; end; function GetStorageClassValue(const AName: string): TAmazonStorageClass; begin if AName.Equals(cStandard) then Exit(TAmazonStorageClass.Standard); if AName.Equals(cStandardIA) then Exit(TAmazonStorageClass.StandardIA); if AName.Equals(cGlacier) then Exit(TAmazonStorageClass.Glacier); if AName.Equals(cReducedRedundancy) then Exit(TAmazonStorageClass.ReduceRedundancy); Result := TAmazonStorageClass.Standard; end; { TAmazonLifeCycleTransition } class function TAmazonLifeCycleTransition.Create(ADays: Integer; AStorageClass: TAmazonStorageClass): TAmazonLifeCycleTransition; begin Result.FDays := ADays; Result.FStorageClass := AStorageClass; end; function TAmazonLifeCycleTransition.GetXML; begin Result := WriteOpenTag(cLifeCycleTransition) + WriteValueTag(cDays, FDays.ToString) + WriteValueTag(cStorageClass, GetStorageClassName(FStorageClass)) + WriteCloseTag(cLifeCycleTransition); end; { TAmazonLifeCycleConfiguration.TRule } function TAmazonLifeCycleRule.AddTransition(ADays: Integer; AStorageClass: TAmazonStorageClass): Integer; begin Result := Length(FTransitions); FTransitions := FTransitions + [TAmazonLifeCycleTransition.Create(ADays, AStorageClass)]; end; class function TAmazonLifeCycleRule.Create(const AID: string; const APrefix: string; AStatus: boolean; ATransitions: TArray<TAmazonLifeCycleTransition>; AExpirationDays, ANoncurrentVersionTransitionDays: Integer; ANoncurrentVersionTransitionStorageClass: TAmazonStorageClass; ANoncurrentVersionExpirationDays: Integer): TAmazonLifeCycleRule; begin Result.FID := AID; Result.FPrefix := APrefix; Result.FStatus := AStatus; Result.FExpirationDays := AExpirationDays; Result.FTransitions := ATransitions; Result.FExpirationDays := AExpirationDays; Result.FNoncurrentVersionTransitionDays := ANoncurrentVersionTransitionDays; Result.FNoncurrentVersionTransitionStorageClass := ANoncurrentVersionTransitionStorageClass; Result.FNoncurrentVersionExpirationDays := ANoncurrentVersionExpirationDays; end; procedure TAmazonLifeCycleRule.DeleteTransition(AIndex: Integer); var I: Integer; LLength: Integer; begin LLength := Length(FTransitions); if (AIndex < 0) or (AIndex > LLength-1) then raise ERangeError.Create(SRangeCheckException); for I := AIndex to LLength-2 do FTransitions[I] := FTransitions[I+1]; SetLength(FTransitions, LLength-1); end; function TAmazonLifeCycleRule.GetTransition(AIndex: Integer): TAmazonLifeCycleTransition; begin if (AIndex < 0) or (AIndex > Length(FTransitions)-1) then raise ERangeError.Create(SRangeCheckException); Result := FTransitions[AIndex]; end; function TAmazonLifeCycleRule.GetXML: string; var I: Integer; begin Result := WriteOpenTag(cLifeCycleRule) + WriteValueTag(cID, ID) + WriteValueTag(cPrefix, FPrefix) + WriteValueTag(cStatus, cBooleanText[FStatus]); for I := Low(FTransitions) to High(FTransitions) do Result := Result + FTransitions[I].XML; if FExpirationDays > 0 then Result := Result + WriteOpenTag(cExpiration) + WriteValueTag(cDays, FExpirationDays.ToString) + WriteCloseTag(cExpiration); if FNoncurrentVersionTransitionDays > 0 then Result := Result + WriteOpenTag(cNoncurrentVersionTransition) + WriteValueTag(cNoncurrentDays, FNoncurrentVersionTransitionDays.ToString) + WriteValueTag(cStorageClass, GetStorageClassName(FNoncurrentVersionTransitionStorageClass)) + WriteCloseTag(cNoncurrentVersionTransition); if FNoncurrentVersionExpirationDays > 0 then Result := Result + WriteOpenTag(cNoncurrentVersionExpiration) + WriteValueTag(cNoncurrentDays, FNoncurrentVersionExpirationDays.ToString) + WriteCloseTag(cNoncurrentVersionExpiration); Result := Result + WriteCloseTag(cLifeCycleRule); end; { TAmazonLifeCycleConfiguration } function TAmazonLifeCycleConfiguration.AddRule(const AID: string; const APrefix: string; AStatus: boolean; ATransitions: TArray<TAmazonLifeCycleTransition>; AExpirationDays, ANoncurrentVersionTransitionDays: Integer; ANoncurrentVersionTransitionStorageClass: TAmazonStorageClass; ANoncurrentVersionExpirationDays: Integer): Integer; begin Result := AddRule(TAmazonLifeCycleRule.Create(AID, APrefix, AStatus, ATransitions, AExpirationDays, ANoncurrentVersionTransitionDays, ANoncurrentVersionTransitionStorageClass, ANoncurrentVersionExpirationDays)); end; function TAmazonLifeCycleConfiguration.AddRule(const ARule: TAmazonLifeCycleRule): Integer; begin Result := Length(FRules); FRules := FRules + [ARule]; end; class function TAmazonLifeCycleConfiguration.Create(ARules: TArray<TAmazonLifeCycleRule>): TAmazonLifeCycleConfiguration; begin Result.FRules := ARules; end; procedure TAmazonLifeCycleConfiguration.DeleteRule(AIndex: Integer); var I: Integer; LLength: Integer; begin LLength := Length(FRules); if (AIndex < 0) or (AIndex > LLength-1) then raise ERangeError.Create(SRangeCheckException); for I := AIndex to LLength-2 do FRules[I] := FRules[I+1]; SetLength(FRules, LLength-1); end; function TAmazonLifeCycleConfiguration.GetRule(AIndex: Integer): TAmazonLifeCycleRule; begin if (AIndex < 0) or (AIndex > Length(FRules)-1) then raise ERangeError.Create(SRangeCheckException); Result := FRules[AIndex]; end; function TAmazonLifeCycleConfiguration.GetXML: string; var I: Integer; begin Result := WriteOpenTag(cLifeCycleConfiguration); for I := Low(FRules) to High(FRules) do Result := Result + FRules[I].XML; Result := Result + WriteCloseTag(cLifeCycleConfiguration); end; end.
unit uMeter645Packet; interface uses SysUtils, StrUtils; type TMeter645ControlCode = class private FValue: Byte; function GetAsHexString: AnsiString; function GetGongNengma: Byte; function GetHasHouxuzheng: Boolean; function GetIsFachu: Boolean; function GetIsFanhui: Boolean; function GetIsYichang: Boolean; procedure SetAsHexString(const Value: AnsiString); procedure SetGongNengma(const Value: Byte); procedure SetHasHouxuzheng(const Value: Boolean); procedure SetIsFachu(const Value: Boolean); procedure SetIsFanhui(const Value: Boolean); procedure SetIsYichang(const Value: Boolean); public constructor Create; overload; property AsHexString: AnsiString read GetAsHexString write SetAsHexString; property IsFromZhuzhanToMeter: Boolean read GetIsFachu write SetIsFachu; property IsFromMeterToZhuzhan: Boolean read GetIsFanhui write SetIsFanhui; property IsYichang: Boolean read GetIsYichang write SetIsYichang; property HasHouxuzheng: Boolean read GetHasHouxuzheng write SetHasHouxuzheng; property GongNengma: Byte read GetGongNengma write SetGongNengma; property Value: Byte read FValue write FValue; end; TMeter645Address = class private FAsHexString: AnsiString; FShrinkDecimals: Byte; FShrinked: Boolean; function GetAsString: AnsiString; procedure SetAsHexString(const Value: AnsiString); procedure SetAsString(const Value: AnsiString); procedure SetShrinkDecimals(const Value: Byte); procedure SetShrinked(const Value: Boolean); public constructor Create; overload; property AsString: AnsiString read GetAsString write SetAsString; property AsHexString: AnsiString read FAsHexString write SetAsHexString; property ShrinkDecimals: Byte read FShrinkDecimals write SetShrinkDecimals; property Shrinked: Boolean read FShrinked write SetShrinked; function ShrinkAddress(const ShrinkDecimals: Byte): AnsiString; class function String2Address(const Str: AnsiString): AnsiString; class function Address2String(const BinStr: AnsiString): AnsiString; end; //AppData表示应用层数据,对于发送而言是没有+33之前的数据 //对于接受而言是已经-33后的数据 //FData是实际的包里的数据域内容 TMeter645Packet = class private FAddress: TMeter645Address; FControlCode: TMeter645ControlCode; FData: AnsiString; function GetAppData: AnsiString; procedure SetAppData(const Value: AnsiString); function GetAsHexString: AnsiString; function CalcCs(const PackStr: AnsiString): Byte; public constructor Create; overload; destructor Destroy; override; property MeterAddress: TMeter645Address read FAddress; property ControlCode: TMeter645ControlCode read FControlCode; property AppData: AnsiString read GetAppData write SetAppData; property AsHexString: AnsiString read GetAsHexString; function GetMessageForDisplay: AnsiString; //直接显示的去掉33变化的报文 class function GetPack(var HexStr: AnsiString): TMeter645Packet; class function MakeMstToRtuPacket(const Address: AnsiString; ShrinkDecimals,ControlCode: Byte; const Data: AnsiString): TMeter645Packet; end; implementation uses uBCDHelper; { TMeter645ControlCode } constructor TMeter645ControlCode.Create; begin inherited; FValue := 0; end; function TMeter645ControlCode.GetAsHexString: AnsiString; begin Result := chr(FValue); end; function TMeter645ControlCode.GetGongNengma: Byte; begin Result := FValue and $1F; end; function TMeter645ControlCode.GetHasHouxuzheng: Boolean; begin Result := (FValue and $20)=$20; end; function TMeter645ControlCode.GetIsFachu: Boolean; begin Result := not GetIsFanhui; end; function TMeter645ControlCode.GetIsFanhui: Boolean; begin Result := (FValue and $80)=$80; end; function TMeter645ControlCode.GetIsYichang: Boolean; begin Result := (FValue and $40)=$40; end; procedure TMeter645ControlCode.SetAsHexString(const Value: AnsiString); begin if Length(Value)=1 then FValue := Ord(Value[1]) else raise Exception.Create('ControlCode is one Byte'); end; procedure TMeter645ControlCode.SetGongNengma(const Value: Byte); begin FValue := (FValue and $E0)+(Value and $1F); end; procedure TMeter645ControlCode.SetHasHouxuzheng(const Value: Boolean); begin if Value then FValue := FValue or $20 else FValue := FValue and $DF; end; procedure TMeter645ControlCode.SetIsFachu(const Value: Boolean); begin SetIsFanhui(not Value); end; procedure TMeter645ControlCode.SetIsFanhui(const Value: Boolean); begin if Value then FValue := FValue or $80 else FValue := FValue and $7F; end; procedure TMeter645ControlCode.SetIsYichang(const Value: Boolean); begin if Value then FValue := FValue or $40 else FValue := FValue and $BF; end; { TMeter645Address } class function TMeter645Address.Address2String( const BinStr: AnsiString): AnsiString; begin Result := TBcdHelper.BinStr2CStr(ReverseString(BinStr),''); end; constructor TMeter645Address.Create; begin inherited; FAsHexString := DupeString(#$99,6); end; function TMeter645Address.GetAsString: AnsiString; begin Result := Address2String(FAsHexString); end; procedure TMeter645Address.SetAsHexString(const Value: AnsiString); begin if Length(Value)=6 then FAsHexString := Value else raise Exception.Create('MeterAddress is 6 Bytes'); end; procedure TMeter645Address.SetAsString(const Value: AnsiString); begin FAsHexString := String2Address(Value); end; procedure TMeter645Address.SetShrinkDecimals(const Value: Byte); begin FShrinkDecimals := Value; end; procedure TMeter645Address.SetShrinked(const Value: Boolean); begin FShrinked := Value; end; function TMeter645Address.ShrinkAddress( const ShrinkDecimals: Byte): AnsiString; begin if ShrinkDecimals>6 then Result := FAsHexString else Result := Copy(FAsHexString,1,6-ShrinkDecimals)+DupeString(#$AA,ShrinkDecimals); end; class function TMeter645Address.String2Address( const Str: AnsiString): AnsiString; var Temp: AnsiString; begin if Length(Str)<12 then Temp := DupeString('0',12-Length(Str))+Str else Temp := RightStr(Str,12); Result := ReverseString(TBcdHelper.CStr2BinStr(Temp)); end; { TMeter645Packet } function TMeter645Packet.CalcCs(const PackStr: AnsiString): Byte; var i: integer; begin Result := 0; for i := 1 to Length(PackStr) do Result := Result+Ord(PackStr[i]); end; constructor TMeter645Packet.Create; begin inherited; FAddress := TMeter645Address.Create; FControlCode := TMeter645ControlCode.Create; end; destructor TMeter645Packet.Destroy; begin FAddress.Free; FControlCode.Free; inherited; end; function TMeter645Packet.GetAppData: AnsiString; var i,len: integer; begin len := Length(FData); SetLength(Result,len); for i := 1 to len do Result[i] := chr(Ord(FData[i])-$33); end; function TMeter645Packet.GetAsHexString: AnsiString; begin if not self.FAddress.Shrinked then Result := #$68+self.FAddress.AsHexString+#$68+self.FControlCode.AsHexString+ chr(Length(FData))+FData else Result := #$68+self.FAddress.ShrinkAddress(self.FAddress.ShrinkDecimals)+#$68+self.FControlCode.AsHexString+ chr(Length(FData))+FData; Result := Result+Chr(CalcCs(Result))+#$16; end; function TMeter645Packet.GetMessageForDisplay: AnsiString; var Temp: AnsiString; begin if not self.FAddress.Shrinked then Temp := #$68+self.FAddress.AsHexString+#$68+self.FControlCode.AsHexString+ chr(Length(FData))+self.GetAppData else Temp := #$68+self.FAddress.ShrinkAddress(self.FAddress.ShrinkDecimals)+#$68+self.FControlCode.AsHexString+ chr(Length(FData))+self.GetAppData; Result := TBcdHelper.BinStr2CStr(temp)+', ??, 16'; end; class function TMeter645Packet.GetPack( var HexStr: AnsiString): TMeter645Packet; var phead: integer; len: integer; function SeekHead(const PackData: AnsiString; const FromPos: integer): integer; var i,len: integer; begin Result := -1; len := Length(PackData)-11; for i := FromPos to len do begin if (PackData[i]=#$68) and (PackData[i+7]=#$68) then begin Result := i; break; end; end; end; function GetPackLen(const PackData: AnsiString; const HeadPos: integer): integer; begin Result := Ord(PackData[HeadPos+9]); end; function CheckPack(const PackData: AnsiString; const HeadPos,len: integer): Boolean; var cs: Byte; i: integer; begin Result := false; if (Length(PackData)>=HeadPos+len+11) and (PackData[HeadPos+len+11]=#$16) then begin cs := 0; for i := HeadPos to HeadPos+9+len do cs := cs+Ord(PackData[i]); if PackData[HeadPos+len+10]=Chr(cs) then Result := true; end; end; begin Result := nil; phead := SeekHead(HexStr,1); while phead<>-1 do begin len := GetPackLen(HexStr,phead); if CheckPack(HexStr,phead,len) then begin Result := TMeter645Packet.Create; Result.MeterAddress.AsHexString := Copy(HexStr,phead+1,6); Result.ControlCode.Value := Ord(HexStr[phead+8]); Result.FData := Copy(HexStr,phead+10,len); HexStr := Copy(HexStr,phead+len+12,Length(HexStr)-phead-len-11); break; end; phead := SeekHead(HexStr,phead+1); end; end; class function TMeter645Packet.MakeMstToRtuPacket( const Address: AnsiString; ShrinkDecimals, ControlCode: Byte; const Data: AnsiString): TMeter645Packet; var pack: TMeter645Packet; begin pack := TMeter645Packet.Create; pack.MeterAddress.AsString := Address; pack.MeterAddress.ShrinkDecimals := ShrinkDecimals; pack.MeterAddress.Shrinked := ShrinkDecimals<>0; pack.ControlCode.IsYichang := false; pack.ControlCode.IsFromZhuzhanToMeter := true; pack.ControlCode.HasHouxuzheng := false; pack.ControlCode.GongNengma := ControlCode; pack.AppData := Data; Result := pack; end; procedure TMeter645Packet.SetAppData(const Value: AnsiString); var i,len: integer; begin len := Length(Value); SetLength(FData,len); for i := 1 to len do FData[i] := chr(Ord(Value[i])+$33); //3. ORD函数是用于取得一个ASCII码的数值,CHR函数正好相反,用于取得一个数值的ASCII值。 end; end.
unit UFilesIntegration; interface uses UBookList, UVisitorList, UBorrowList; implementation uses SysUtils; // Пути к файлам записей const BOOK_PATH = 'books.dat'; VISITOR_PATH = 'visitors.dat'; BORROW_PATH = 'borrows.dat'; type TBookFile = file of TBook; TVisitorFile = file of TVisitor; TBorrowFile = file of TBorrow; // Создаёт несуществующие файлы procedure checkFiles; var bookFile: TBookFile; visitorFile: TVisitorFile; borrowFile: TBorrowFile; begin if not FileExists(BOOK_PATH) then begin AssignFile(bookFile, BOOK_PATH); Rewrite(bookFile); CloseFile(bookFile); end; if not FileExists(VISITOR_PATH) then begin AssignFile(visitorFile, VISITOR_PATH); Rewrite(visitorFile); CloseFile(visitorFile); end; if not FileExists(BORROW_PATH) then begin AssignFile(borrowFile, BORROW_PATH); Rewrite(borrowFile); CloseFile(borrowFile); end; end; // Прочитывает файлы и записывает в списки procedure readFiles; var bookFile: TBookFile; visitorFile: TVisitorFile; borrowfile: TBorrowFile; tempBook: TBook; tempVisitor: TVisitor; tempBorrow: TBorrow; begin checkFiles; AssignFile(bookFile, BOOK_PATH); AssignFile(visitorFile, VISITOR_PATH); AssignFile(borrowfile, BORROW_PATH); Reset(bookFile); Reset(visitorFile); Reset(borrowfile); while not eof(bookFile) do begin read(bookFile, tempBook); addBook(tempBook); end; while not eof(visitorFile) do begin read(visitorFile, tempVisitor); addVisitor(tempVisitor); end; while not eof(borrowFile) do begin read(borrowFile, tempBorrow); addBorrow(tempBorrow); end; CloseFile(bookFile); CloseFile(visitorFile); CloseFile(borrowfile); end; // Сохраняет файлы из списков procedure saveFiles; var arBooks: TBooks; arVisitors: TVisitors; arBorrows: TBorrows; bookFile: TBookFile; visitorFile: TVisitorFile; borrowfile: TBorrowFile; i: Integer; begin arBooks := returnAllBooks; arVisitors := returnAllVisitors; arBorrows := returnAllBorrows; AssignFile(bookFile, BOOK_PATH); AssignFile(visitorFile, VISITOR_PATH); AssignFile(borrowfile, BORROW_PATH); Rewrite(bookFile); Rewrite(visitorFile); Rewrite(borrowfile); for i := 0 to length(arBooks) - 1 do begin write(bookFile, arBooks[i]); end; for i := 0 to length(arVisitors) - 1 do begin write(visitorFile, arVisitors[i]); end; for i := 0 to length(arBorrows) - 1 do begin write(borrowFile, arBorrows[i]); end; CloseFile(bookFile); CloseFile(visitorFile); CloseFile(borrowfile); end; initialization readFiles; finalization saveFiles; end.
unit clsQuiz; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, clsHouse; type TQuiz = class private fArrHouses : array[1..3] of THouse; fGrade : integer; fArrAnswers : array[1..40] of string; fArrQuestions : array[1..40] of string; public constructor Create(iGrade : integer; HHutton, HWindsor, HOK : THouse); destructor Destroy; override; procedure setGrade(iGrade : integer); procedure setAnswers(iGrade : integer); procedure setQuestions(iGrade : integer); procedure setHouse(H, W, OK : THouse); function getGrade : integer; function getAnswer(iNo : integer) : string; function getQuestion(iNo : integer) : string; function getHouse(iCount : integer) : THouse; end; implementation { TQuiz } constructor TQuiz.Create(iGrade: integer; HHutton, HWindsor, HOK : THouse); begin fGrade := iGrade; fArrHouses[1] := HHutton; fArrHouses[2] := HWindsor; fArrHouses[3] := HOK; setQuestions(iGrade); setAnswers(iGrade); end; destructor TQuiz.Destroy; begin //FreeAndNil(fArrHouses[1]); //FreeAndNil(fArrHouses[2]); //FreeAndNil(fArrHouses[3]); inherited; end; function TQuiz.getAnswer(iNo: integer): string; begin result := fArrAnswers[iNo]; end; function TQuiz.getGrade: integer; begin result := fGrade; end; function TQuiz.getHouse(iCount: integer): THouse; begin result := fArrHouses[iCount]; end; function TQuiz.getQuestion(iNo: integer): string; begin result := fArrQuestions[iNo]; end; procedure TQuiz.setAnswers(iGrade: integer); var sPath, sAdd : string; TFAnswers : textfile; iAnswer : integer; begin iAnswer := 0; sPath := GetCurrentDir()+'\Answers\'; sAdd := 'Grade ' + inttostr(iGrade) + '.txt'; sPath := sPath + sAdd; if FileExists(sPath) <> true then begin ShowMessage('File ' + sPath + ' does not exist!'); Exit; end; AssignFile(TFAnswers, sPath); Reset(TFAnswers); while (not EOF(TFAnswers)) AND (iAnswer <= 40) do begin inc(iAnswer); readln(TFAnswers, fArrAnswers[iAnswer]); end; CloseFile(TFAnswers); end; procedure TQuiz.setGrade(iGrade: integer); begin fGrade := iGrade; setQuestions(iGrade); setAnswers(iGrade); end; procedure TQuiz.setHouse(H, W, OK: THouse); begin fArrHouses[1] := H; fArrHouses[2] := W; fArrHouses[3] := OK; end; procedure TQuiz.setQuestions(iGrade: integer); var sPath, sAdd : string; TFQuestions : textfile; iQuestion : integer; begin iQuestion := 0; sPath := GetCurrentDir()+'\Questions\'; sAdd := 'Grade ' + inttostr(iGrade) + '.txt'; sPath := sPath + sAdd; if FileExists(sPath) <> true then begin ShowMessage('File ' + sPath + ' does not exist!'); Exit; end; AssignFile(TFQuestions, sPath); Reset(TFQuestions); while (not EOF(TFQuestions)) AND (iQuestion <= 40) do begin inc(iQuestion); readln(TFQuestions, fArrQuestions[iQuestion]); end; CloseFile(TFQuestions); end; end.
program CoverageTester; {$mode delphi}{$h+} uses QEMUVersatilePBCoverage,GlobalConfig,Platform,Logging,Serial,SysUtils,Classes,CoverageMap; procedure StartLogging; begin LOGGING_INCLUDE_COUNTER:=False; SERIAL_REGISTER_LOGGING:=True; SerialLoggingDeviceAdd(SerialDeviceGetDefault); SERIAL_REGISTER_LOGGING:=False; LoggingDeviceSetDefault(LoggingDeviceFindByType(LOGGING_TYPE_SERIAL)); end; type PSubroutine = ^TSubroutine; TSubroutine = record Id:LongWord; Counter:LongWord; LastClock:LongWord; PrevClock:LongWord; end; TCoverageAnalyzer = record Meter:PCoverageMeter; EventsProcessed:LongWord; HighWater:LongWord; Subroutines:Array[0..MaxSubroutines - 1] of TSubroutine; end; var I:Integer; Next:LongWord; CoverageAnalyzer:TCoverageAnalyzer; Sorter:TFPList; Clock:LongWord; LastSubroutineId:LongWord; SequenceNumber:LongWord; Formatted:String; IdleCalibrateSubroutine:PSubroutineDescriptor; ClockGetTotalSubroutine:PSubroutineDescriptor; function CompareCounter(A,B:Pointer):Integer; begin Result:=PSubroutine(A).Counter - PSubroutine(B).Counter; if Result = 0 then Result:=CompareStr(SubroutineDescriptors[PSubroutine(A).Id].Name,SubroutineDescriptors[PSubroutine(B).Id].Name); end; function BackLog:LongWord; begin Result:=CoverageMeter.TraceCounter - CoverageAnalyzer.EventsProcessed; end; begin IdleCalibrateSubroutine:=SubroutineFindDescriptor('THREADS_$$_IDLECALIBRATE$'); ClockGetTotalSubroutine:=SubroutineFindDescriptor('PLATFORMQEMUVPB_$$_QEMUVPBCLOCKGETTOTAL$'); with CoverageAnalyzer do begin Meter:=@CoverageMeter; EventsProcessed:=0; HighWater:=0; for I:=Low(Subroutines) to High(Subroutines) do with Subroutines[I] do begin Id:=I; Counter:=0; LastClock:=0; PrevClock:=0; end; end; Sorter:=TFPList.Create; Clock:=0; LastSubroutineId:=$ffffffff; SequenceNumber:=0; StartLogging; while True do begin begin with CoverageAnalyzer do begin Next:=Meter.TraceCounter; // LoggingOutput(Format('%8d more events - total %d',[Next - EventsProcessed, Next])); try while EventsProcessed <> Next do begin with Meter.TraceBuffer[EventsProcessed and (TraceLength - 1)] do begin with Subroutines[SubroutineId] do begin if (EventsProcessed < 80000) and (SubroutineId <> LastSubroutineId) then begin if SubroutineDescriptors[SubroutineId].IsFunction then begin if R0 < 1*1000*1000 then Formatted:=Format('%8.8x/%6d',[R0,R0]) else Formatted:=Format('%8.8x ',[R0]); end else begin Formatted:=' '; end; LoggingOutput(Format('%6d %s %s',[SequenceNumber,Formatted,SubroutineDescriptors[SubroutineId].Name])); end; Inc(SequenceNumber); if SubroutineId = IdleCalibrateSubroutine.Id then SequenceNumber:=100*1000; LastSubroutineId:=SubroutineId; if SubroutineId > HighWater then HighWater:=SubroutineId; if SubroutineId = ClockGetTotalSubroutine.Id then Clock:=R0; Inc(Counter); PrevClock:=LastClock; LastClock:=Clock; // if Counter = 1 then // LoggingOutput(Format('%8d id %4d %s',[Counter,SubroutineId,SubroutineDescriptors[SubroutineId].Name])); Inc(EventsProcessed); if EventsProcessed mod (4*1000*1000) = 0 then begin // asm // svc #5000 // batch log // end; LoggingOutput(Format('total %d high water %d',[EventsProcessed,HighWater])); Sorter.Clear; for I:=0 to HighWater do if (Subroutines[I].Counter > 0) and (Subroutines[I].Counter < 1000*1000) then Sorter.Add(@Subroutines[I]); Sorter.Sort(CompareCounter); for I:=0 to Sorter.Count - 1 do with PSubroutine(Sorter.Items[I])^ do LoggingOutput(Format('%8d %8d %s',[LastClock - PrevClock,Counter,SubroutineDescriptors[Id].Name])); for I:=0 to HighWater do Subroutines[I].Counter:=0; HighWater:=0; LoggingOutput(Format('back log %6d',[BackLog])); end; end; end; end; except on E:Exception do begin LoggingOutput(Format('',[])); LoggingOutput(Format('exception %s Next %d EventsProcessed %d',[E.Message,Next,EventsProcessed])); LoggingOutput(Format('',[])); EventsProcessed:=Next; Sleep(2*1000); end; end; end; end; end; end.
unit uMenuManagement; interface {$M+} uses SysUtils, Controls, Classes, Menus, ActnList, DB; type TMenuManagement = Class(TObject) private FUserId : Integer; FUserUnt : Integer; arrMenuId: array of Integer; procedure setUserId(value: Integer); procedure setUserUnt(value: Integer); function getGroupId: Integer; function getGroupName: String; function getAllMenu: TDataSet; function getUserMenu: TDataSet; function CreateMenu(IdMenu: Integer): TMenuItem; function getMenuAction(IdMenu: Integer): String; public FSelfUnitID: Integer; {public declaration} constructor Create; overload; destructor Destroy; override; procedure setMenuUser; procedure dropMenuUser; property GroupId : Integer read getGroupId; property GroupName : String read getGroupName; published property UserId : Integer read FUserID write setUserId; property UserUnt : Integer read FUserUnt write setUserUnt; end; var MenuManagement: TMenuManagement; implementation uses uConn, ufrmMain; {TMenuManagement} constructor TMenuManagement.Create; begin inherited; UserId := 0; UserUnt:= 0; end; destructor TMenuManagement.Destroy; begin inherited; MenuManagement.Free; end; procedure TMenuManagement.setUserId(value: Integer); begin FUserId:= value; end; procedure TMenuManagement.setUserUnt(value: Integer); begin FUserUnt:= value; end; function TMenuManagement.getGroupId: Integer; //var arrParam: TArr; // data : TDataSet; begin Result := 0; // SetLength(arrParam,2); // arrParam[0].tipe:= ptInteger; // arrParam[0].data:= UserId; // arrParam[1].tipe:= ptInteger; // arrParam[1].data:= UserUnt; // data:= ADConn.GetAllDataAsArray(SQL_GET_LIST_USER_GROUP_BY_USER_ID, arrParam); // Result:= data.fieldbyname('GRO_ID').AsInteger; end; function TMenuManagement.getGroupName: String; var arrParam: TArr; data : TDataSet; begin SetLength(arrParam,2); arrParam[0].tipe:= ptInteger; arrParam[0].data:= UserId; arrParam[1].tipe:= ptInteger; arrParam[1].data:= UserUnt; // data:= ADConn.GetAllDataAsArray(SQL_GET_LIST_USER_GROUP_BY_USER_ID, arrParam); Result:= data.fieldbyname('GRO_NAME').AsString; end; function TMenuManagement.getUserMenu: TDataSet; var arrParam: TArr; sLabel: string; sSQL: String; begin sLabel := 'View'; sSQL := 'SELECT MS.* ' + ' FROM AUT$MENU_STRUCTURE MS ' + ' LEFT OUTER JOIN AUT$MENU M ON (MS.MENUS_ID = M.MENU_ID) ' + ' LEFT JOIN AUT$MODULE MOD ON (MS.MENUS_MOD_ID = MOD.MOD_ID) ' + ' AND (MS.MENUS_MOD_UNT_ID = MOD.MOD_UNT_ID) ' + ' WHERE (MOD.MOD_LABEL = '+QuotedStr(sLabel) + ' ) AND (M.MENU_GRO_ID = :PID) AND ' + ' (M.MENU_GRO_UNT_ID = :PUNT)' + ' ORDER BY MS.MENUS_NO, M.MENU_ID '; SetLength(arrParam,2); arrParam[0].tipe:= ptInteger; arrParam[0].data:= GroupId; arrParam[1].tipe:= ptInteger; arrParam[1].data:= UserUnt; // Result:= ADConn.GetAllDataAsArray(sSQL, arrParam); // Result:= IBConn.GetAllDataAsArray(SQL_GET_LIST_MENU_BY_USER_GROUP, arrParam); end; procedure TMenuManagement.dropMenuUser; var data : TDataSet; sName: String; MenuWindow: TMenuItem; begin data:= getAllMenu; with data do begin while not Eof do begin try sName:= fieldbyname('MENUS_NAME').AsString; MenuWindow:= TMenuItem(frmMain.mmMainMenu.FindComponent(sName)); if MenuWindow<> nil then MenuWindow.Free; Next; except end; end; end; frmMain.mmMainMenu := frmMain.mmMainMenu; end; procedure TMenuManagement.setMenuUser; var data : TDataSet; i : Integer; begin data:= getUserMenu; SetLength(arrMenuId,data.RecordCount); for i:=0 to data.RecordCount-1 do begin arrMenuId[i]:= data.fieldbyname('MENUS_ID').AsInteger; data.Next; end; for i:=0 to Length(arrMenuId)-1 do CreateMenu(arrMenuId[i]); frmMain.mmMainMenu := frmMain.mmMainMenu; end; function TMenuManagement.getMenuAction(IdMenu: Integer): String; var arrParam: TArr; data : TDataSet; begin SetLength(arrParam,2); arrParam[0].tipe:= ptInteger; arrParam[0].data:= IdMenu; arrParam[1].tipe:= ptInteger; arrParam[1].data:= FSelfUnitID; // data:= ADConn.GetAllDataAsArray(SQL_GET_LIST_ACTION_FROM_MODULE, arrParam); Result:= data.fieldbyname('MOD_ACTION').AsString; end; function TMenuManagement.CreateMenu(IdMenu: Integer): TMenuItem; var menuParent1, menuParent2 : TMenuItem; sName, sAction, sCaption : String; iIdParent, iIdModule,i : Integer; arrParam : TArr; data : TDataSet; begin SetLength(arrParam,2); arrParam[0].tipe:= ptInteger; arrParam[0].data:= IdMenu; arrParam[1].tipe:= ptInteger; arrParam[1].data:= FSelfUnitID; // data:= ADConn.GetAllDataAsArray(SQL_GET_LIST_MENU_BY_MENU_ID, arrParam); with data do begin sName:= fieldbyname('MENUS_NAME').AsString; sCaption:= fieldbyname('MENUS_CAPTION').AsString; iIdParent:= fieldbyname('MENUS_PARENT_MENU_ID').AsInteger; iIdModule:= fieldbyname('MENUS_MOD_ID').AsInteger; if(fieldbyname('MENUS_PARENT_MENU_ID').AsInteger)>0 then begin menuParent1:= CreateMenu(iIdParent); menuParent2:= TMenuItem(frmMain.mmMainMenu.FindComponent(sName)); if menuParent2=nil then begin menuParent2:= TMenuItem.Create(frmMain.mmMainMenu); menuParent2.Name:= sName; sAction:= getMenuAction(iIdModule); for i:=0 to frmMain.actlstMain.ActionCount-1 do if frmMain.actlstMain.Actions[i].Name=sAction then begin menuParent2.Action:= frmMain.actlstMain.Actions[i]; Break; end; menuParent2.Caption:= sCaption; menuParent1.Add(menuParent2); end; Result:= menuParent2; end else begin menuParent1:= TMenuItem(frmMain.mmMainMenu.FindComponent(sName)); if menuParent1=nil then begin menuParent1:= TMenuItem.Create(frmMain.mmMainMenu); menuParent1.Name:= sName; menuParent1.Caption:= sCaption; frmMain.mmMainMenu.Items.Insert(frmMain.mmMainMenu.Items.Count-3,menuParent1); end; Result:= menuParent1; end; end; end; function TMenuManagement.getAllMenu: TDataSet; var arrParam: TArr; begin SetLength(arrParam,1); arrParam[0].tipe:= ptInteger; arrParam[0].data:= UserUnt; // Result:= ADConn.GetAllDataAsArray(SQL_GET_LIST_MENU, arrParam); end; end.
unit Gar_Model_Edit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, gar_DM, cxLookAndFeelPainters, cxMaskEdit, cxDropDownEdit, cxDBEdit, DB, FIBDataSet, pFIBDataSet, StdCtrls, cxButtons, cxControls, cxContainer, cxEdit, cxTextEdit, gar_Types, zTypes, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, ActnList, gr_uMessage, gr_uCommonConsts, gr_uCommonProc, cxGroupBox; type TFEditModel = class(TForm) Panel1: TPanel; cxButton1: TcxButton; cxButton2: TcxButton; pFIBDataSet1: TpFIBDataSet; DataSource1: TDataSource; Actions: TActionList; ActionYes: TAction; ActionCancel: TAction; ActionAdd: TAction; ActionDel: TAction; ActionClean: TAction; ActionList1: TActionList; Action1: TAction; GroupBoxProp: TcxGroupBox; cxLookupComboBox1: TcxLookupComboBox; cxGroupBox1: TcxGroupBox; cxTextEdit1: TcxTextEdit; procedure Action1Execute(Sender: TObject); private PLanguageIndex:integer; ParamLoc:TgarParamModel; public constructor Create(Param:TgarParamModel);reintroduce; function Delete(Param:TgarParamModel):variant; function PrepareData(Param:TgarParamModel):variant; end; function View_FEdit(Param:TgarParamModel):variant; var FEditModel: TFEditModel; implementation {$R *.dfm} constructor TFEditModel.Create(Param:TgarParamModel); begin inherited Create(Param.owner); PLanguageIndex:=IndexLanguage; ParamLoc:=Param; pFIBDataSet1.Database:=DM.DB; pFIBDataSet1.Transaction:=DM.RTransaction; DataSource1.DataSet:=pFIBDataSet1; cxLookupComboBox1.Properties.DataController.DataSource:=DataSource1; cxLookupComboBox1.Properties.KeyFieldNames :='ID_MARKA'; cxLookupComboBox1.Properties.ListFieldNames :='NAME_MARKA'; end; function TFEditModel.Delete(Param:TgarParamModel):variant; begin DM.pFIBStoredProc1.StoredProcName:='GAR_SP_MODEL_D'; DM.pFIBStoredProc1.Transaction.StartTransaction; DM.pFIBStoredProc1.Prepare; DM.pFIBStoredProc1.ParamByName('ID_MODEL').AsInteger:= Param.Id_Model; DM.pFIBStoredProc1.ExecProc; DM.pFIBStoredProc1.Transaction.Commit; end; function View_FEdit(Param:TgarParamModel):variant; begin FEditModel:=TFEditModel.Create(Param); if Param.fs=zcfsDelete then FEditModel.delete(Param) else FEditModel.PrepareData(Param); if Param.fs<>zcfsDelete then FEditModel.ShowModal; FEditModel.Free; Result:=Param.Id_Model; end; function TFEditModel.PrepareData(Param:TgarParamModel):variant; begin pFIBDataSet1.Transaction.StartTransaction; pFIBDataSet1.Close; case Param.fs of zcfsInsert: try pFIBDataSet1.SQLs.SelectSQL.Text:='SELECT * FROM GAR_SP_MARKA_S'; pFIBDataSet1.Open; cxLookupComboBox1.EditValue:=0; except end; zcfsUpdate: try pFIBDataSet1.SQLs.SelectSQL.Text:='SELECT * FROM GAR_SP_MARKA_S'; pFIBDataSet1.Open; pFIBDataSet1.Locate('NAME_MARKA',Param.NameMarka,[loCaseInsensitive]); cxLookupComboBox1.EditValue:=pFIBDataSet1['ID_MARKA']; cxTextEdit1.EditValue:=Param.NameModel; except end; end; end; procedure TFEditModel.Action1Execute(Sender: TObject); begin if cxLookupComboBox1.EditValue=Null then begin showmessage('Поле марки не заполнено!'); exit; end; if cxTextEdit1.EditValue='' then begin showmessage('Поле модели не заполнено!'); exit; end; with DM do try pFIBStoredProc1.Transaction.StartTransaction; case ParamLoc.fs of zcfsInsert: pFIBStoredProc1.StoredProcName:='GAR_SP_MODEL_I'; zcfsUpdate: pFIBStoredProc1.StoredProcName:='GAR_SP_MODEL_U'; end; pFIBStoredProc1.Prepare; pFIBStoredProc1.ParamByName('ID_MARKA').AsVariant := cxLookupComboBox1.EditValue; pFIBStoredProc1.ParamByName('NAME_MODEL').AsVariant := cxTextEdit1.EditValue; case ParamLoc.fs of zcfsUpdate: pFIBStoredProc1.ParamByName('ID_MODEL').AsInt64 := ParamLoc.Id_Model; end; pFIBStoredProc1.ExecProc; if ParamLoc.fs=zcfsInsert then ParamLoc.Id_Model:=pFIBStoredProc1.ParamByName('ID_MODEL').AsInt64; pFIBStoredProc1.Transaction.Commit; except on e:Exception do begin grShowMessage(ECaption[PLanguageIndex],e.message,mtError,[mbOk]); pFIBStoredProc1.Transaction.RollBack; end; end; ModalResult:=mrYes; end; end.
unit Win32.EVR9; // Checked (and Updated) for SDK 10.0.17763.0 on 2018-12-04 {$IFDEF FPC} {$mode delphi} {$ENDIF} interface uses Windows, Classes, SysUtils, ActiveX, Direct3D9, Win32.MFObjects, Win32.MFTransform, Win32.EVR, Win32.DXVA2API; const IID_IEVRVideoStreamControl: TGUID = '{d0cfe38b-93e7-4772-8957-0400c49a4485}'; IID_IMFVideoProcessor: TGUID = '{6AB0000C-FECE-4d1f-A2AC-A9573530656E}'; IID_IMFVideoMixerBitmap: TGUID = '{814C7B20-0FDB-4eec-AF8F-F957C8F69EDC}'; type IEVRVideoStreamControl = interface(IUnknown) ['{d0cfe38b-93e7-4772-8957-0400c49a4485}'] function SetStreamActiveState(fActive: boolean): HResult; stdcall; function GetStreamActiveState(out lpfActive: boolean): HResult; stdcall; end; IMFVideoProcessor = interface(IUnknown) ['{6AB0000C-FECE-4d1f-A2AC-A9573530656E}'] function GetAvailableVideoProcessorModes(var lpdwNumProcessingModes: UINT; out ppVideoProcessingModes {arraysize lpdwNumProcessingModes}: PGUID): HResult; stdcall; function GetVideoProcessorCaps(const lpVideoProcessorMode: TGUID; out lpVideoProcessorCaps: TDXVA2_VideoProcessorCaps): HResult; stdcall; function GetVideoProcessorMode(out lpMode: TGUID): HResult; stdcall; function SetVideoProcessorMode(const lpMode: TGUID): HResult; stdcall; function GetProcAmpRange(dwProperty: DWORD; out pPropRange: TDXVA2_ValueRange): HResult; stdcall; function GetProcAmpValues(dwFlags: DWORD; out Values: TDXVA2_ProcAmpValues): HResult; stdcall; function SetProcAmpValues(dwFlags: DWORD; const pValues: TDXVA2_ProcAmpValues): HResult; stdcall; function GetFilteringRange(dwProperty: DWORD; out pPropRange: TDXVA2_ValueRange): HResult; stdcall; function GetFilteringValue(dwProperty: DWORD; out pValue: TDXVA2_Fixed32): HResult; stdcall; function SetFilteringValue(dwProperty: DWORD; pValue: PDXVA2_Fixed32): HResult; stdcall; function GetBackgroundColor(out lpClrBkg: COLORREF): HResult; stdcall; function SetBackgroundColor(ClrBkg: TCOLORREF): HResult; stdcall; end; TMFVideoAlphaBitmapParams = record dwFlags: DWORD; clrSrcKey: COLORREF; rcSrc: TRECT; nrcDest: TMFVideoNormalizedRect; fAlpha: single; dwFilterMode: DWORD; end; PMFVideoAlphaBitmapParams = ^TMFVideoAlphaBitmapParams; TMFVideoAlphaBitmap = record GetBitmapFromDC: boolean; case integer of 0: (hdc: HDC; params: TMFVideoAlphaBitmapParams); 1: (pDDS: pointer; { to IDirect3DSurface9 } ); end; PMFVideoAlphaBitmap = ^TMFVideoAlphaBitmap; TMFVideoAlphaBitmapFlags = ( MFVideoAlphaBitmap_EntireDDS = $1, MFVideoAlphaBitmap_SrcColorKey = $2, MFVideoAlphaBitmap_SrcRect = $4, MFVideoAlphaBitmap_DestRect = $8, MFVideoAlphaBitmap_FilterMode = $10, MFVideoAlphaBitmap_Alpha = $20, MFVideoAlphaBitmap_BitMask = $3f ); IMFVideoMixerBitmap = interface(IUnknown) ['{814C7B20-0FDB-4eec-AF8F-F957C8F69EDC}'] function SetAlphaBitmap(const pBmpParms: TMFVideoAlphaBitmap): HResult; stdcall; function ClearAlphaBitmap(): HResult; stdcall; function UpdateAlphaBitmapParameters(const pBmpParms: TMFVideoAlphaBitmapParams): HResult; stdcall; function GetAlphaBitmapParameters(out pBmpParms: TMFVideoAlphaBitmapParams): HResult; stdcall; end; implementation end.
unit frmCPBUploadColor; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, ComCtrls, StdCtrls, Buttons, DB, DBClient, MakeSQL,iniFiles, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxSplitter, frmBase; type TCPBUploadColorForm = class(TBaseForm) PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; GroupBox1: TGroupBox; cbbxRiteList: TComboBox; GroupBox5: TGroupBox; cbbDataColorList: TComboBox; cdsPub: TClientDataSet; msDataColor: TMakeSQL; TimerUpload: TTimer; cdsStock: TClientDataSet; cdsRecipe: TClientDataSet; cdsColor: TClientDataSet; cdsLab: TClientDataSet; dsRecipe: TDataSource; dsColor: TDataSource; dsLab: TDataSource; dsStock: TDataSource; Panel6: TPanel; btnRefreshxRite: TBitBtn; Panel7: TPanel; btnRefreshDataColor: TBitBtn; btnUploadxRite: TBitBtn; btnUploadDataColor: TBitBtn; Panel5: TPanel; Panel2: TPanel; Label2: TLabel; edtItemNO: TEdit; btnQuery: TBitBtn; cxSplitter2: TcxSplitter; Panel1: TPanel; pnRight: TPanel; pnlxRite: TPanel; gbColor: TGroupBox; cxGrid2: TcxGrid; cxGridtvColor: TcxGridDBTableView; cxGridLevel1: TcxGridLevel; cxSpxRite: TcxSplitter; Panel3: TPanel; gbLab: TGroupBox; cxGrid3: TcxGrid; cxGridtvLab: TcxGridDBTableView; cxGridLevel2: TcxGridLevel; gbStock: TGroupBox; cxGrid4: TcxGrid; cxGridtvStock: TcxGridDBTableView; cxGridLevel3: TcxGridLevel; Panel8: TPanel; Label1: TLabel; edtColorCode1: TEdit; btnDiff: TBitBtn; Label3: TLabel; edtColorCode2: TEdit; GroupBox7: TGroupBox; cxGrid5: TcxGrid; cxGridtvDiff: TcxGridDBTableView; cxGridLevel4: TcxGridLevel; cdsDiff: TClientDataSet; dsDiff: TDataSource; cxSplitter1: TcxSplitter; gbRecipe: TGroupBox; cxGrid1: TcxGrid; cxGridtvRecipe: TcxGridDBTableView; cxGrid1Level1: TcxGridLevel; cxSplitter3: TcxSplitter; cxSplitter4: TcxSplitter; procedure FormDestroy(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnRefreshxRiteClick(Sender: TObject); procedure btnUploadxRiteClick(Sender: TObject); procedure btnRefreshDataColorClick(Sender: TObject); procedure btnUploadDataColorClick(Sender: TObject); procedure TimerUploadTimer(Sender: TObject); procedure cbbxRiteListClick(Sender: TObject); procedure cbbDataColorListChange(Sender: TObject); procedure btnQueryClick(Sender: TObject); procedure PageControl1Change(Sender: TObject); procedure btnDiffClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } procedure QueryData; procedure QueryDiffData; procedure UploadxRite; procedure ReadxRite(const INSERTSQL: string;FileName: string); procedure ReadDataColor(const INSERTSQL: string;FileName: string); procedure UploadDataColor; public { Public declarations } end; var CPBUploadColorForm: TCPBUploadColorForm; implementation uses uGlobal, uGridDecorator, uLogin, uShowMessage, ServerDllPub; {$R *.dfm} procedure TCPBUploadColorForm.FormDestroy(Sender: TObject); begin inherited; CPBUploadColorForm := nil; end; procedure TCPBUploadColorForm.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; end; procedure TCPBUploadColorForm.UploadxRite; var FileName,INSERTSQL:string; begin TimerUpload.Enabled := False; FileName := 'D:\xriteData\xriteRecipe.txt'; INSERTSQL := 'INSERT INTO dbo.xriteRecipe(Item_NO,Step_ID,Chemical_ID,Usage,Department_ID)' + #13#10; if FileExists(FileName) then ReadxRite(INSERTSQL,FileName); FileName := 'D:\xriteData\xriteColor.txt'; INSERTSQL := 'INSERT INTO dbo.xriteColor(Item_NO,ill,DEcmc_data,DLcmc_data,Da_data,Db_data,DCcmc_data,DHcmc_data,PF,Department_ID)' + #13#10; if FileExists(FileName) then ReadxRite(INSERTSQL,FileName); TMsgdialog.ShowMsgDialog('上传数据成功!', mtInformation); FileName := 'D:\xriteData\xriteLab.txt'; INSERTSQL := 'INSERT INTO dbo.xriteLab(Std_Color_Code,Item_NO,L,a,b,CMC_l,CMC_c,Light_Name,Item_Type,Department_ID)' + #13#10; if FileExists(FileName) then ReadxRite(INSERTSQL,FileName); TMsgdialog.ShowMsgDialog('上传数据成功!', mtInformation); TimerUpload.Enabled := True; end; procedure TCPBUploadColorForm.ReadxRite(const INSERTSQL: string;FileName: string); const TotalLine = 100; var AList: TStringList; i,j: Integer; SELECTStr: string; Stream: TStream; sErrorMsg: widestring; begin Stream := nil; AList := TStringList.Create; try Alist.LoadFromFile(FileName); Stream := TFileStream.Create(FileName, fmOpenWrite or fmShareDenyWrite); j := 0; SELECTStr := ''; for i := 0 to Alist.Count-1 do begin if Alist.Strings[i] <> '' then begin j := j + 1; if (j < TotalLine) and (i < Alist.Count-1) then begin SELECTStr := SELECTStr+Alist.Strings[i]+ #13#10; end else begin SELECTStr := SELECTStr+ StringReplace(Alist.Strings[i],'UNION ALL','',[rfReplaceAll]); FNMServerObj.SaveViaSqltext(INSERTSQL+SELECTStr, sErrorMsg); if sErrorMsg<>''then begin showmessage(sErrorMsg); exit; end; j := 0; SELECTStr := ''; end; end; end; Stream.Size :=0; finally Stream.Free; FreeAndNil(AList); end; end; procedure TCPBUploadColorForm.UploadDataColor; var FileName,INSERTSQL:string; begin TimerUpload.Enabled := False; FileName := 'D:\DataColor\DataColor.qtx'; INSERTSQL := 'INSERT INTO dbo.xriteLab(Std_Color_Code,Item_NO,L,a,b,CMC_l,CMC_c,Light_Name,Item_Type,Department_ID)' + #13#10; if FileExists(FileName) then ReadDataColor(INSERTSQL,FileName); TMsgdialog.ShowMsgDialog('上传数据成功!', mtInformation); TimerUpload.Enabled := True; end; procedure TCPBUploadColorForm.ReadDataColor(const INSERTSQL: string; FileName: string); const TotalLine = 100; var AList: TStringList; i,j: Integer; Ini: TIniFile; CMC_l,CMC_c,STD_NAME,BAT_NAME,BAT_CIEL,BAT_CIEa,BAT_CIEb,ILLNAME: string; iniFile, Section,SELECTStr:string; Stream: TFileStream; sErrorMsg: widestring; begin if FileExists(FileName) then begin iniFile := ChangeFileExt(FileName, '.ini'); if not RenameFile(FileName,iniFile) then Exit; Ini := TIniFile.Create(iniFile); Stream := TFileStream.Create(iniFile, fmOpenWrite or fmShareDenyWrite); try i := 0; j := 0; SELECTStr := ''; CMC_l := Ini.ReadString('STANDARD_DATA 0', 'CMC_l', ''); CMC_c := Ini.ReadString('STANDARD_DATA 0', 'CMC_c', ''); if pos(',',CMC_l)>0 then CMC_l := Copy(CMC_l,1,length(CMC_l)-1); if pos(',',CMC_c)>0 then CMC_c := Copy(CMC_c,1,length(CMC_c)-1); Section :='BATCH_DATA '+IntToStr(i); STD_NAME := Ini.ReadString(Section, 'STD_NAME', ''); while STD_NAME <> '' do begin inc(j); BAT_NAME := Ini.ReadString(Section, 'BAT_NAME', ''); BAT_CIEL := Ini.ReadString(Section, 'BAT_CIEL', ''); BAT_CIEa := Ini.ReadString(Section, 'BAT_CIEa', ''); BAT_CIEb := Ini.ReadString(Section, 'BAT_CIEb', ''); ILLNAME := Ini.ReadString(Section, 'ILLNAME', ''); if pos(',',BAT_CIEL)>0 then BAT_CIEL := Copy(BAT_CIEL,1,length(BAT_CIEL)-1); if pos(',',BAT_CIEa)>0 then BAT_CIEa := Copy(BAT_CIEa,1,length(BAT_CIEa)-1); if pos(',',BAT_CIEb)>0 then BAT_CIEb := Copy(BAT_CIEb,1,length(BAT_CIEb)-1); SELECTStr := SELECTStr + 'SELECT '+ QuotedStr(STD_NAME)+','+QuotedStr(BAT_NAME)+','+ BAT_CIEL+','+BAT_CIEa+','+BAT_CIEb+','+ CMC_l+','+CMC_c+','+ QuotedStr(ILLNAME)+','+QuotedStr('DataColor')+','+QuotedStr('GEW2')+' UNION ALL'+#13#10; if (j = TotalLine) and (SELECTStr <> '') then begin SELECTStr := INSERTSQL+ SELECTStr; SELECTStr := Copy(SELECTStr,1,length(SELECTStr)-11); FNMServerObj.SaveViaSqltext(SELECTStr, sErrorMsg); if sErrorMsg<>''then begin showmessage(sErrorMsg); exit; end; j := 0; SELECTStr := ''; end; Inc(i); Section :='BATCH_DATA '+IntToStr(i); STD_NAME := Ini.ReadString(Section, 'STD_NAME', ''); end; if (SELECTStr <> '') then begin SELECTStr := INSERTSQL+ SELECTStr; SELECTStr := Copy(SELECTStr,1,length(SELECTStr)-11); FNMServerObj.SaveViaSqltext(SELECTStr, sErrorMsg); if sErrorMsg<>''then begin showmessage(sErrorMsg); exit; end; end; Stream.Size :=0; finally Stream.Free; Ini.Free; RenameFile(iniFile,FileName); end; end; end; procedure TCPBUploadColorForm.TimerUploadTimer(Sender: TObject); begin inherited; if DirectoryExists('D:\xriteData\') then UploadxRite; if DirectoryExists('D:\DataColor\') then UploadDataColor; end; procedure TCPBUploadColorForm.btnRefreshxRiteClick(Sender: TObject); var vData:OleVariant; sqlText,sErrorMsg:widestring; begin inherited; sqlText := 'SELECT DISTINCT Item_NO FROM dbo.xRiteRecipe WITH(NOLOCK) WHERE Type = 0 AND Operate_Time>CONVERT(VARCHAR(10),GETDATE(),120)+'' 07:00:00'''; FNMServerObj.GeneralQuery(Vdata, sqlText, sErrorMsg); if sErrorMsg <> '' then begin TMsgDialog.ShowMsgDialog(sErrorMsg,mtError); Exit; end; cdsPub.Data := vData; TGlobal.FillItemsFromDataSet(cdsPub,'Item_NO', '','',cbbxRiteList.Items); end; procedure TCPBUploadColorForm.btnUploadxRiteClick(Sender: TObject); begin inherited; UploadxRite; end; procedure TCPBUploadColorForm.btnRefreshDataColorClick(Sender: TObject); var vData:OleVariant; sqlText,sErrorMsg:widestring; begin inherited; sqlText := 'SELECT DISTINCT Item_NO FROM dbo.xRiteLab WITH(NOLOCK) WHERE Item_Type = ''DataColor'' AND Operate_Time>CONVERT(VARCHAR(10),GETDATE(),120)+'' 07:00:00'''; FNMServerObj.GeneralQuery(Vdata, sqlText, sErrorMsg); if sErrorMsg <> '' then begin TMsgDialog.ShowMsgDialog(sErrorMsg,mtError); Exit; end; cdsPub.Data := vData; TGlobal.FillItemsFromDataSet(cdsPub,'Item_NO', '','',cbbDataColorList.Items); end; procedure TCPBUploadColorForm.btnUploadDataColorClick(Sender: TObject); begin inherited; UploadDataColor; end; procedure TCPBUploadColorForm.cbbxRiteListClick(Sender: TObject); var Color_Code: string; begin inherited; Color_Code := cbbxRiteList.Items[cbbxRiteList.ItemIndex]; // while not (Color_Code[1]in ['0'..'9']) do // Color_Code := Copy(Color_Code,2,length(Color_Code)-1); edtItemNO.Text := Color_Code; btnQuery.Click; end; procedure TCPBUploadColorForm.cbbDataColorListChange(Sender: TObject); var Color_Code: string; begin inherited; Color_Code := cbbDataColorList.Items[cbbDataColorList.ItemIndex]; while not (Color_Code[1]in ['0'..'9']) do Color_Code := Copy(Color_Code,2,length(Color_Code)-1); edtItemNO.Text := Color_Code; btnQuery.Click; end; procedure TCPBUploadColorForm.btnQueryClick(Sender: TObject); begin inherited; QueryData; end; procedure TCPBUploadColorForm.QueryData; var vData: OleVariant; ColorCode : string; sCondition,sConStock,sqlText,sErrorMsg: WideString; begin inherited; try Screen.Cursor := crHourGlass; if cdsRecipe.Active then cdsRecipe.EmptyDataSet; if cdsColor.Active then cdsColor.EmptyDataSet; if cdsLab.Active then cdsLab.EmptyDataSet; if cdsStock.Active then cdsStock.EmptyDataSet; // ShowMsg( '正在获取数据稍等!', crHourGlass); ColorCode := Trim(edtItemNO.Text); if ColorCode = '' then Exit; // if Trim(edtColorCode1.Text) = '' then // edtColorCode1.Text := ColorCode; // if (Trim(edtColorCode1.Text) <> '') and (ColorCode <> Trim(edtColorCode1.Text)) then // edtColorCode2.Text := ColorCode; sCondition := QuotedStr(ColorCode)+','+IntToStr(PageControl1.ActivePageIndex); FNMServerObj.GetQueryData(vData,'GetxRiteData',sCondition,sErrorMsg); if sErrorMsg <> '' then begin TMsgDialog.ShowMsgDialog(sErrorMsg,mtError); Exit; end; cdsRecipe.Data := vData[0]; cdsLab.Data := vData[1]; cdsStock.Data := vData[2]; GridDecorator.BindCxViewWithDataSource(cxGridtvRecipe, dsRecipe,True); GridDecorator.BindCxViewWithDataSource(cxGridtvLab, dsLab,True); GridDecorator.BindCxViewWithDataSource(cxGridtvStock, dsStock,True); if PageControl1.ActivePageIndex = 0 then begin cdsColor.Data := vData[3]; GridDecorator.BindCxViewWithDataSource(cxGridtvColor, dsColor,True); end finally Screen.Cursor := crDefault; // ShowMsg('', crDefault); end; end; procedure TCPBUploadColorForm.PageControl1Change(Sender: TObject); begin inherited; if PageControl1.ActivePageIndex = 0 then begin if cxSpxRite.State = ssClosed then cxSpxRite.OpenSplitter; pnlxRite.Height := 120; gbRecipe.Caption := 'xRite配方信息'; end else begin cxSpxRite.CloseSplitter; gbRecipe.Caption := 'LabDip OK方信息'; end; if cdsRecipe.Active then cdsRecipe.EmptyDataSet; if cdsColor.Active then cdsColor.EmptyDataSet; if cdsLab.Active then cdsLab.EmptyDataSet; if cdsStock.Active then cdsStock.EmptyDataSet; end; procedure TCPBUploadColorForm.btnDiffClick(Sender: TObject); begin inherited; QueryDiffData; end; procedure TCPBUploadColorForm.QueryDiffData; var vData: OleVariant; sCondition,sErrorMsg: WideString; begin try Screen.Cursor := crHourGlass; if (Trim(edtColorCode1.Text)='') or (Trim(edtColorCode2.Text)='') then Exit; if cdsDiff.Active then cdsDiff.EmptyDataSet; sCondition := QuotedStr(edtColorCode1.Text)+','+QuotedStr(edtColorCode2.Text); FNMServerObj.GetQueryData(vData,'GetDiffLab',sCondition,sErrorMsg); if sErrorMsg <> '' then begin TMsgDialog.ShowMsgDialog(sErrorMsg,mtError); Exit; end; cdsDiff.Data := vData; GridDecorator.BindCxViewWithDataSource(cxGridtvDiff, dsDiff); finally Screen.Cursor := crDefault; end; end; procedure TCPBUploadColorForm.FormShow(Sender: TObject); begin inherited; TControl(cbbxRiteList).Align := alClient; TControl(cbbDataColorList).Align := alClient; TimerUpload.Enabled := DirectoryExists('D:\xriteData\') or DirectoryExists('D:\DataColor\'); btnUploadxRite.Enabled := DirectoryExists('D:\xriteData\'); btnUploadDataColor.Enabled := DirectoryExists('D:\DataColor\'); if DirectoryExists('D:\xriteData\') then PageControl1.ActivePageIndex := 0 else if DirectoryExists('D:\DataColor\') then PageControl1.ActivePageIndex := 1 else PageControl1.ActivePageIndex := 0; PageControl1.OnChange(self); end; end.
unit Bluetooth.Printer; interface uses System.SysUtils, System.Bluetooth, System.Bluetooth.Components; type EBluetoothPrinter = class(Exception); TBluetoothPrinter = class(TBluetooth) private FSocket: TBluetoothSocket; FPrinterName: String; function ConectarImpressora(ANomeDevice: String): Boolean; function GetDeviceByName(ANomeDevice: String): TBluetoothDevice; public procedure Imprimir(const ATexto: String); published property PrinterName: String read FPrinterName write FPrinterName; end; const UUID = '{00001101-0000-1000-8000-00805F9B34FB}'; implementation function TBluetoothPrinter.GetDeviceByName(ANomeDevice: String): TBluetoothDevice; var lDevice: TBluetoothDevice; begin Result := nil; for lDevice in Self.PairedDevices do begin if lDevice.DeviceName = ANomeDevice then Result := lDevice; end; end; function TBluetoothPrinter.ConectarImpressora(ANomeDevice: String): Boolean; var lDevice: TBluetoothDevice; begin lDevice := GetDeviceByName(ANomeDevice); if lDevice <> nil then begin FSocket := lDevice.CreateClientSocket(StringToGUID(UUID), False); if FSocket <> nil then begin FSocket.Connect; Result := FSocket.Connected end else raise EBluetoothPrinter.Create('Ocorreu um erro ao obter socket de conexão bluetooth.'); end else raise EBluetoothPrinter.CreateFmt('Impressora "%s" não encontrada ou não pareada.', [ANomeDevice]); end; procedure TBluetoothPrinter.Imprimir(const ATexto: String); begin if ConectarImpressora(Self.PrinterName) then begin try FSocket.SendData(TEncoding.UTF8.GetBytes(ATexto)); finally FSocket.Close; end; end else raise EBluetoothPrinter.Create('Não foi possível conectar a impressora.'); end; end.
{ Clever Internet Suite Version 6.2 Copyright (C) 1999 - 2006 Clever Components www.CleverComponents.com } unit clImap4; interface {$I clVer.inc} uses Classes, clMC, clMailMessage, clTcpClient, clImapUtils; type TclCustomImap4 = class(TclCustomMail) private FCommandTag: Integer; FMailBoxSeparator: Char; FCurrentMailBox: TclImap4MailBoxInfo; FCurrentMessage: Integer; FConnectionState: TclImapConnectionState; FAutoReconnect: Boolean; FIsTaggedCommand: Boolean; FTotalBytesToReceive: Integer; procedure RaiseError(const AMessage: string); function GetNextCommandTag: string; function GetLastCommandTag: string; procedure SetAutoReconnect(const Value: Boolean); procedure Login; procedure Authenticate; procedure OpenImapSession; procedure Logout; procedure ParseMailBoxes(AList: TStrings; const ACommand: string); procedure ParseSelectedMailBox(const AName: string); procedure ParseSearchMessages(AList: TStrings); function ParseMessageSize(const AMessageId: string; AIsUid: Boolean): Integer; function ParseMessageUid(AIndex: Integer): string; function ParseMessageFlags(const AMessageId: string; AIsUid: Boolean): TclMailMessageFlags; procedure ParseMessage(const AMessageId: string; AMessage: TclMailMessage; AIsUid: Boolean); function GetMessageId(const ACommand, AResponseLine: string; AIsUid: Boolean): string; procedure CheckMessageValid(AIndex: Integer); procedure CheckUidValid(const AUid: string); procedure CheckConnection(AStates: array of TclImapConnectionState); procedure DoDataProgress(Sender: TObject; ABytesProceed, ATotalBytes: Int64); procedure CramMD5Authenticate; procedure NtlmAuthenticate; procedure GetCapability(AList: TStrings); protected function GetDefaultPort: Integer; override; function GetResponseCode(const AResponse: string): Integer; override; procedure WaitingResponse(const AOkResponses: array of Integer); override; procedure OpenSession; override; procedure CloseSession; override; property AutoReconnect: Boolean read FAutoReconnect write SetAutoReconnect default False; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure StartTls; override; procedure SendTaggedCommand(const ACommand: string; const Args: array of const; const AOkResponses: array of Integer); procedure Noop; procedure SelectMailBox(const AName: string); procedure ExamineMailBox(const AName: string); procedure CreateMailBox(const AName: string); procedure DeleteMailBox(const AName: string); procedure RenameMailBox(const ACurrentName, ANewName: string); procedure SubscribeMailBox(const AName: string); procedure UnsubscribeMailBox(const AName: string); procedure GetMailBoxes(AList: TStrings; const ACriteria: string = '*'); procedure GetSubscribedMailBoxes(AList: TStrings); procedure SearchMessages(const ASearchCriteria: string; AMessageList: TStrings); procedure UidSearchMessages(const ASearchCriteria: string; AMessageList: TStrings); procedure DeleteMessage(AIndex: Integer); procedure UidDeleteMessage(const AUid: string); procedure PurgeMessages; procedure CopyMessage(AIndex: Integer; const ADestMailBox: string); procedure UidCopyMessage(const AUid, ADestMailBox: string); procedure SetMessageFlags(AIndex: Integer; AMethod: TclSetFlagsMethod; AFlags: TclMailMessageFlags); procedure UidSetMessageFlags(const AUid: string; AMethod: TclSetFlagsMethod; AFlags: TclMailMessageFlags); function GetMessageFlags(AIndex: Integer): TclMailMessageFlags; function UidGetMessageFlags(const AUid: string): TclMailMessageFlags; function GetMessageSize(AIndex: Integer): Integer; function UidGetMessageSize(const AUid: string): Integer; function GetMessageUid(AIndex: Integer): string; procedure RetrieveMessage(AIndex: Integer); overload; procedure RetrieveMessage(AIndex: Integer; AMessage: TclMailMessage); overload; procedure UidRetrieveMessage(const AUid: string; AMessage: TclMailMessage); procedure RetrieveHeader(AIndex: Integer); overload; procedure RetrieveHeader(AIndex: Integer; AMessage: TclMailMessage); overload; procedure UidRetrieveHeader(const AUid: string; AMessage: TclMailMessage); procedure AppendMessage(const AMailBoxName: string; AFlags: TclMailMessageFlags); overload; procedure AppendMessage(const AMailBoxName: string; AMessage: TclMailMessage; AFlags: TclMailMessageFlags); overload; procedure AppendMessage(const AMailBoxName: string; AMessage: TStrings; AFlags: TclMailMessageFlags); overload; property CurrentMailBox: TclImap4MailBoxInfo read FCurrentMailBox; property MailBoxSeparator: Char read FMailBoxSeparator; property CurrentMessage: Integer read FCurrentMessage; property ConnectionState: TclImapConnectionState read FConnectionState; property LastCommandTag: string read GetLastCommandTag; end; TclImap4 = class(TclCustomImap4) published property AutoReconnect; property BatchSize; property UserName; property Password; property Server; property Port default cDefaultImapPort; property TimeOut; property UseTLS; property CertificateFlags; property TLSFlags; property BitsPerSec; property UseSPA; property MailMessage; property OnChanged; property OnOpen; property OnClose; property OnGetCertificate; property OnVerifyServer; property OnSendCommand; property OnReceiveResponse; property OnProgress; end; const IMAP_OK = 10; IMAP_NO = 20; IMAP_BAD = 30; IMAP_PREAUTH = 40; IMAP_BYE = 50; IMAP_CONTINUE = 60; resourcestring cImapInvalidMailboxName = 'Mailbox name is invalid, it must not be empty or begin with mailbox separator'; cInvalidArgument = 'Function arguments are invalid'; cMailMessageNoInvalid = 'Message number is invalid, must be greater than 0'; cMailMessageUidInvalid = 'Message UID is invalid, must be numeric and greater than 0'; cSocketErrorConnect = 'The connection to the server has failed'; cInvalidAuthMethod = 'Unable to logon to the server using Secure Password Authentication'; implementation uses SysUtils, clUtils, clCryptUtils, clSocket, clSspiAuth, clEncoder{$IFDEF DEMO}, Forms, Windows, clCert{$ENDIF}; { TclCustomImap4 } constructor TclCustomImap4.Create(AOwner: TComponent); begin inherited Create(AOwner); FCurrentMailBox := TclImap4MailBoxInfo.Create(); Port := cDefaultImapPort; FIsTaggedCommand := False; FMailBoxSeparator := '/'; end; procedure TclCustomImap4.CloseSession; begin Logout(); end; {$IFDEF DEMO} {$IFNDEF IDEDEMO} var IsDemoDisplayed: Boolean = False; {$ENDIF} {$ENDIF} procedure TclCustomImap4.OpenSession; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsDemoDisplayed) and (not IsEncoderDemoDisplayed) and (not IsCertDemoDisplayed) and (not IsMailMessageDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsDemoDisplayed := True; IsEncoderDemoDisplayed := True; IsCertDemoDisplayed := True; IsMailMessageDemoDisplayed := True; {$ENDIF} end; {$ENDIF} WaitingResponse([IMAP_OK, IMAP_PREAUTH]); FCommandTag := 0; ExplicitStartTls(); OpenImapSession(); end; procedure TclCustomImap4.Login; begin if (Password <> '') then begin SendTaggedCommand('LOGIN "%s" "%s"', [UserName, Password], [IMAP_OK]); end else begin SendTaggedCommand('LOGIN "%s"', [UserName], [IMAP_OK]); end; end; procedure TclCustomImap4.CramMD5Authenticate; var resp, DecodedResponse: string; Encoder: TclEncoder; begin SendTaggedCommand('AUTHENTICATE %s', ['CRAM-MD5'], [IMAP_CONTINUE]); Encoder := TclEncoder.Create(nil); try resp := Copy(Response.Text, 3, MaxInt); Encoder.DecodeString(resp, DecodedResponse, cmMIMEBase64); DecodedResponse := HMAC_MD5(DecodedResponse, Password); DecodedResponse := UserName + ' ' + DecodedResponse; Encoder.EncodeString(DecodedResponse, resp, cmMIMEBase64); SendCommandSync(resp, [IMAP_OK]); finally Encoder.Free(); end; end; procedure TclCustomImap4.NtlmAuthenticate; var sspi: TclNtAuthClientSspi; encoder: TclEncoder; buf: TStream; authIdentity: TclAuthIdentity; challenge: string; begin SendTaggedCommand('AUTHENTICATE %s', ['NTLM'], [IMAP_CONTINUE]); sspi := nil; encoder := nil; buf := nil; authIdentity := nil; try sspi := TclNtAuthClientSspi.Create(); encoder := TclEncoder.Create(nil); encoder.SuppressCrlf := True; buf := TMemoryStream.Create(); if (UserName <> '') then begin authIdentity := TclAuthIdentity.Create(UserName, Password); end; while not sspi.GenChallenge('NTLM', buf, Server, authIdentity) do begin buf.Position := 0; encoder.EncodeToString(buf, challenge, cmMIMEBase64); SendCommandSync(challenge, [IMAP_CONTINUE]); challenge := system.Copy(Response.Text, 3, MaxInt); buf.Size := 0; encoder.DecodeFromString(challenge, buf, cmMIMEBase64); buf.Position := 0; end; if (buf.Size > 0) then begin buf.Position := 0; encoder.EncodeToString(buf, challenge, cmMIMEBase64); SendCommandSync(challenge, [IMAP_OK]); end; finally authIdentity.Free(); buf.Free(); encoder.Free(); sspi.Free(); end; end; procedure TclCustomImap4.GetCapability(AList: TStrings); var i: Integer; s: string; begin SendTaggedCommand('CAPABILITY', [], [IMAP_OK]); AList.Clear(); for i := 0 to Response.Count - 1 do begin s := Response[i]; if (System.Pos('* CAPABILITY ', UpperCase(s)) = 1) then begin s := system.Copy(s, Length('* CAPABILITY ') + 1, Length(s)); s := StringReplace(s, ' ', #13#10, [rfReplaceAll]); AddTextStr(AList, s, False); end; end; end; procedure TclCustomImap4.Authenticate; var list: TStrings; begin list := TStringList.Create(); try GetCapability(list); if FindInStrings(list, 'AUTH=NTLM') > -1 then begin NtlmAuthenticate(); end else if FindInStrings(list, 'AUTH=CRAM-MD5') > -1 then begin CramMD5Authenticate(); end else begin RaiseError(cInvalidAuthMethod); end; finally list.Free(); end; end; procedure TclCustomImap4.OpenImapSession; begin FCommandTag := 0; if (LastResponseCode = IMAP_OK) then begin if UseSPA then begin Authenticate(); end else begin Login(); end; FConnectionState := csAuthenticated; end else if (LastResponseCode = IMAP_PREAUTH) then begin FConnectionState := csAuthenticated; end; end; function TclCustomImap4.GetNextCommandTag: string; begin Inc(FCommandTag); Result := GetLastCommandTag(); end; procedure TclCustomImap4.SelectMailBox(const AName: string); begin CheckConnection([csAuthenticated, csSelected]); try SendTaggedCommand('SELECT "%s"', [AName], [IMAP_OK]); ParseSelectedMailBox(AName); FConnectionState := csSelected; except on E: EclSocketError do begin FCurrentMailBox.Clear(); FConnectionState := csAuthenticated; raise; end; end; end; procedure TclCustomImap4.CreateMailBox(const AName: string); begin if (Trim(AName) = '') or (Trim(AName)[1] = MailBoxSeparator) then begin RaiseError(cImapInvalidMailboxName); end; CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('CREATE "%s"', [AName], [IMAP_OK]); end; procedure TclCustomImap4.DeleteMailBox(const AName: string); begin CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('DELETE "%s"', [AName], [IMAP_OK]); end; procedure TclCustomImap4.RenameMailBox(const ACurrentName, ANewName: string); begin CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('RENAME "%s" "%s"', [ACurrentName, ANewName], [IMAP_OK]); end; function TclCustomImap4.GetMessageFlags(AIndex: Integer): TclMailMessageFlags; begin CheckMessageValid(AIndex); CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('FETCH %d (FLAGS)', [AIndex], [IMAP_OK]); Result := ParseMessageFlags(IntToStr(AIndex), False); FCurrentMessage := AIndex; end; procedure TclCustomImap4.AppendMessage(const AMailBoxName: string; AFlags: TclMailMessageFlags); begin AppendMessage(AMailBoxName, MailMessage, AFlags); end; procedure TclCustomImap4.AppendMessage(const AMailBoxName: string; AMessage: TclMailMessage; AFlags: TclMailMessageFlags); begin if (AMessage = nil) then begin RaiseError(cInvalidArgument); end; AppendMessage(AMailBoxName, AMessage.MessageSource, AFlags); end; procedure TclCustomImap4.CopyMessage(AIndex: Integer; const ADestMailBox: string); begin CheckMessageValid(AIndex); CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('COPY %d "%s"', [AIndex, ADestMailBox], [IMAP_OK]); FCurrentMessage := AIndex; end; procedure TclCustomImap4.DeleteMessage(AIndex: Integer); begin SetMessageFlags(AIndex, fmAdd, [mfDeleted]); end; procedure TclCustomImap4.ParseMailBoxes(AList: TStrings; const ACommand: string); var i: Integer; s: string; begin AList.Clear(); for i := 0 to Response.Count - 1 do begin if (System.Pos(Format('* %s ', [UpperCase(ACommand)]), UpperCase(Response[i])) = 1) then begin ParseMailboxInfo(Response[i], FMailBoxSeparator, s); if (s <> '') then begin AList.Add(s); end; end; end; end; procedure TclCustomImap4.GetMailBoxes(AList: TStrings; const ACriteria: string); begin CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('LIST "" "%s"', [ACriteria], [IMAP_OK]); ParseMailBoxes(AList, 'LIST'); end; function TclCustomImap4.GetMessageSize(AIndex: Integer): Integer; begin CheckMessageValid(AIndex); CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('FETCH %d (RFC822.SIZE)', [AIndex], [IMAP_OK]); Result := ParseMessageSize(IntToStr(AIndex), False); FCurrentMessage := AIndex; end; procedure TclCustomImap4.GetSubscribedMailBoxes(AList: TStrings); begin CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('LSUB "" "*"', [], [IMAP_OK]); ParseMailBoxes(AList, 'LSUB'); end; procedure TclCustomImap4.RetrieveHeader(AIndex: Integer; AMessage: TclMailMessage); begin CheckMessageValid(AIndex); CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('FETCH %d (BODY.PEEK[HEADER])', [AIndex], [IMAP_OK]); ParseMessage(IntToStr(AIndex), AMessage, False); FCurrentMessage := AIndex; end; procedure TclCustomImap4.RetrieveHeader(AIndex: Integer); begin RetrieveHeader(AIndex, MailMessage); end; procedure TclCustomImap4.RetrieveMessage(AIndex: Integer); begin RetrieveMessage(AIndex, MailMessage); end; procedure TclCustomImap4.RetrieveMessage(AIndex: Integer; AMessage: TclMailMessage); begin CheckMessageValid(AIndex); CheckConnection([csAuthenticated, csSelected]); FTotalBytesToReceive := 0; if Assigned(OnProgress) then begin FTotalBytesToReceive := GetMessageSize(AIndex); end; try SendTaggedCommand('FETCH %d (BODY.PEEK[])', [AIndex], [IMAP_OK]); if Assigned(OnProgress) then begin DoProgress(FTotalBytesToReceive, FTotalBytesToReceive); end; finally FTotalBytesToReceive := 0; Connection.OnProgress := nil; end; ParseMessage(IntToStr(AIndex), AMessage, False); FCurrentMessage := AIndex; end; procedure TclCustomImap4.WaitingResponse(const AOkResponses: array of Integer); begin if (FTotalBytesToReceive > 0) then begin Connection.OnProgress := DoDataProgress; Connection.InitProgress(0, FTotalBytesToReceive); end; inherited WaitingResponse(AOkResponses); end; procedure TclCustomImap4.DoDataProgress(Sender: TObject; ABytesProceed, ATotalBytes: Int64); begin DoProgress(ABytesProceed, ATotalBytes); end; procedure TclCustomImap4.SearchMessages(const ASearchCriteria: string; AMessageList: TStrings); begin CheckConnection([csSelected]); SendTaggedCommand('SEARCH %s', [ASearchCriteria], [IMAP_OK]); ParseSearchMessages(AMessageList); end; procedure TclCustomImap4.SetMessageFlags(AIndex: Integer; AMethod: TclSetFlagsMethod; AFlags: TclMailMessageFlags); const methodLexem: array[TclSetFlagsMethod] of string = ('', '+', '-'); var cmd: string; begin CheckMessageValid(AIndex); CheckConnection([csAuthenticated, csSelected]); cmd := GetStrByImapMessageFlags(AFlags); SendTaggedCommand('STORE %d %sFLAGS.SILENT (%s)', [AIndex, methodLexem[AMethod], Trim(cmd)], [IMAP_OK]); FCurrentMessage := AIndex; end; procedure TclCustomImap4.SubscribeMailBox(const AName: string); begin CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('SUBSCRIBE "%s"', [AName], [IMAP_OK]); end; procedure TclCustomImap4.UnsubscribeMailBox(const AName: string); begin CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('UNSUBSCRIBE "%s"', [AName], [IMAP_OK]); end; procedure TclCustomImap4.SetAutoReconnect(const Value: Boolean); begin if (FAutoReconnect <> Value) then begin FAutoReconnect := Value; Changed(); end; end; function TclCustomImap4.GetResponseCode(const AResponse: string): Integer; var s: string; ind: Integer; begin Result := SOCKET_WAIT_RESPONSE; if (AResponse = '') then Exit; if (System.Pos('+ ', AResponse) = 1) or ('+' = Trim(AResponse)) then begin Result := IMAP_CONTINUE; Exit; end; ind := System.Pos(' ', AResponse); if (ind < 2) or (ind > Length(AResponse) - 1) then Exit; s := Trim(System.Copy(AResponse, ind + 1, Length(AResponse))); ind := System.Pos(' ', s); if (ind < 1) then begin ind := Length(s); end; if FIsTaggedCommand and (System.Pos(UpperCase(LastCommandTag), UpperCase(AResponse)) <> 1) then Exit; s := Trim(System.Copy(s, 1, ind)); if (s = 'OK') then begin Result := IMAP_OK; end else if (s = 'NO') then begin Result := IMAP_NO; end else if (s = 'BAD') then begin Result := IMAP_BAD; end else if (s = 'PREAUTH') then begin Result := IMAP_PREAUTH; end else if (s = 'BYE') then begin Result := IMAP_BYE; end; end; procedure TclCustomImap4.RaiseError(const AMessage: string); begin raise EclSocketError.Create(AMessage, -1); end; procedure TclCustomImap4.Logout; begin if (ConnectionState in [csAuthenticated, csSelected]) then begin try SendTaggedCommand('LOGOUT', [], [IMAP_OK]); except on EclSocketError do ; end; end; FConnectionState := csNonAuthenticated; end; procedure TclCustomImap4.CheckConnection(AStates: array of TclImapConnectionState); function IsInState: Boolean; var i: Integer; begin for i := Low(AStates) to High(AStates) do begin if (ConnectionState = AStates[i]) then begin Result := True; Exit; end; end; Result := False; end; begin if not IsInState() then begin if AutoReconnect then begin if not Active then begin Open(); end else begin OpenImapSession(); end; end else begin RaiseError(cSocketErrorConnect); end; end; end; destructor TclCustomImap4.Destroy; begin FCurrentMailBox.Free(); inherited Destroy(); end; procedure TclCustomImap4.ParseSelectedMailBox(const AName: string); function GetLexemPos(const ALexem, AText: string; var APos: Integer): Boolean; begin APos := System.Pos(ALexem, AText); Result := APos > 0; end; var i, ind: Integer; responseStr: string; begin CurrentMailBox.Clear(); CurrentMailBox.Name := AName; for i := 0 to Response.Count - 1 do begin responseStr := UpperCase(Response[i]); if GetLexemPos('EXISTS', responseStr, ind) then begin CurrentMailBox.ExistsMessages := StrToIntDef(Trim(System.Copy(responseStr, 3, ind - 3)), 0); end else if not GetLexemPos('FLAGS', responseStr, ind) and GetLexemPos('RECENT', responseStr, ind) then begin CurrentMailBox.RecentMessages := StrToIntDef(Trim(System.Copy(responseStr, 3, ind - 3)), 0); end else if GetLexemPos('[UNSEEN', responseStr, ind) then begin CurrentMailBox.FirstUnseen := StrToIntDef(Trim(System.Copy(responseStr, ind + Length('[UNSEEN'), System.Pos(']', responseStr) - ind - Length('[UNSEEN'))), 0); end else if GetLexemPos('[READ-WRITE]', responseStr, ind) then begin CurrentMailBox.ReadOnly := False; end else if GetLexemPos('[READ-ONLY]', responseStr, ind) then begin CurrentMailBox.ReadOnly := True; end else if not GetLexemPos('[PERMANENTFLAGS', responseStr, ind) and GetLexemPos('FLAGS', responseStr, ind) then begin CurrentMailBox.Flags := GetImapMessageFlagsByStr(System.Copy(responseStr, ind, TextPos(')', responseStr, ind) - ind)); end else if GetLexemPos('[PERMANENTFLAGS', responseStr, ind) then begin CurrentMailBox.ChangeableFlags := GetImapMessageFlagsByStr(System.Copy(responseStr, ind, TextPos(')', responseStr, ind) - ind)); end; if GetLexemPos('[UIDVALIDITY', responseStr, ind) then begin ind := ind + Length('[UIDVALIDITY'); CurrentMailBox.UIDValidity := Trim(System.Copy(responseStr, ind, TextPos(']', responseStr, ind) - ind)); end; end; end; procedure TclCustomImap4.ParseSearchMessages(AList: TStrings); var i: Integer; begin AList.Clear(); for i := 0 to Response.Count - 1 do begin if (System.Pos('* SEARCH', UpperCase(Response[i])) = 1) then begin AList.Text := Trim(StringReplace( System.Copy(Response[i], Length('* SEARCH') + 1, MaxInt), ' ', #13#10, [rfReplaceAll])); Break; end; end; end; function TclCustomImap4.ParseMessageSize(const AMessageId: string; AIsUid: Boolean): Integer; var i, ind: Integer; responseStr: string; begin Result := 0; for i := 0 to Response.Count - 1 do begin responseStr := UpperCase(Response[i]); if (GetMessageId('FETCH', responseStr, AIsUid) = AMessageId) then begin ind := System.Pos('RFC822.SIZE ', responseStr); if (ind > 0) then begin Result := StrToIntDef(Trim(ExtractNumeric(responseStr, ind + Length('RFC822.SIZE '))), 0); end; Break; end; end; end; function TclCustomImap4.ParseMessageFlags(const AMessageId: string; AIsUid: Boolean): TclMailMessageFlags; var i, ind: Integer; responseStr: string; begin Result := []; for i := 0 to Response.Count - 1 do begin responseStr := UpperCase(Response[i]); if (GetMessageId('FETCH', responseStr, AIsUid) = AMessageId) then begin ind := System.Pos('FLAGS', responseStr); if (ind > 0) then begin Result := GetImapMessageFlagsByStr(System.Copy(responseStr, ind, TextPos(')', responseStr, ind) - ind)); end; Break; end; end; end; procedure TclCustomImap4.PurgeMessages; begin CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('CLOSE', [], [IMAP_OK]); FCurrentMailBox.Clear(); FConnectionState := csAuthenticated; end; procedure TclCustomImap4.ParseMessage(const AMessageId: string; AMessage: TclMailMessage; AIsUid: Boolean); var i, msgSize, size: Integer; begin if (Response.Count < 4) then Exit; msgSize := ExtractMessageSize(Response[0]); if (msgSize = 0) then Exit; Response.Delete(0); i := 0; size := 0; while (i < Response.Count) do begin size := size + Length(Response[i]) + Length(#13#10); if (size <= msgSize) then begin Inc(i); end else if (size - msgSize) < (Length(Response[i]) + Length(#13#10)) then begin Response[i] := system.Copy(Response[i], 1, Length(Response[i]) - (size - msgSize)); Inc(i); end else begin Response.Delete(i); end; end; if (AMessage <> nil) then begin AMessage.Clear(); AMessage.MessageSource := Response; end; end; function TclCustomImap4.GetMessageId(const ACommand, AResponseLine: string; AIsUid: Boolean): string; var ind: Integer; begin ind := System.Pos(#32 + ACommand, UpperCase(AResponseLine)); Result := '0'; if (ind < 4) then Exit; if AIsUid then begin ind := TextPos('UID ', AResponseLine, ind); if (ind > 0) then begin Result := ExtractNumeric(AResponseLine, ind + Length('UID ')); end; end else begin Result := IntToStr(StrToIntDef(Trim(System.Copy(AResponseLine, 2, ind - 1)), 0)); end; end; procedure TclCustomImap4.CheckMessageValid(AIndex: Integer); begin if (AIndex < 1) then begin RaiseError(cMailMessageNoInvalid); end; end; function TclCustomImap4.GetLastCommandTag: string; begin Result := Format('a%.4d', [FCommandTag]); end; procedure TclCustomImap4.SendTaggedCommand(const ACommand: string; const Args: array of const; const AOkResponses: array of Integer); begin FIsTaggedCommand := True; try SendCommandSync(GetNextCommandTag() + #32 + ACommand, AOkResponses, Args); finally FIsTaggedCommand := False; end; end; procedure TclCustomImap4.UidDeleteMessage(const AUid: string); begin UidSetMessageFlags(AUid, fmAdd, [mfDeleted]); end; procedure TclCustomImap4.UidCopyMessage(const AUid, ADestMailBox: string); begin CheckUidValid(AUid); CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('UID COPY %s "%s"', [AUid, ADestMailBox], [IMAP_OK]); FCurrentMessage := 0; end; procedure TclCustomImap4.UidSetMessageFlags(const AUid: string; AMethod: TclSetFlagsMethod; AFlags: TclMailMessageFlags); const methodLexem: array[TclSetFlagsMethod] of string = ('', '+', '-'); var cmd: string; begin CheckUidValid(AUid); CheckConnection([csAuthenticated, csSelected]); cmd := GetStrByImapMessageFlags(AFlags); SendTaggedCommand('UID STORE %s %sFLAGS.SILENT (%s)', [AUid, methodLexem[AMethod], Trim(cmd)], [IMAP_OK]); FCurrentMessage := 0; end; function TclCustomImap4.UidGetMessageFlags( const AUid: string): TclMailMessageFlags; begin CheckUidValid(AUid); CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('UID FETCH %s (FLAGS)', [AUid], [IMAP_OK]); Result := ParseMessageFlags(AUid, True); FCurrentMessage := 0; end; function TclCustomImap4.UidGetMessageSize(const AUid: string): Integer; begin CheckUidValid(AUid); CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('UID FETCH %s (RFC822.SIZE)', [AUid], [IMAP_OK]); Result := ParseMessageSize(AUid, True); FCurrentMessage := 0; end; procedure TclCustomImap4.UidRetrieveMessage(const AUid: string; AMessage: TclMailMessage); begin CheckUidValid(AUid); CheckConnection([csAuthenticated, csSelected]); FTotalBytesToReceive := 0; if Assigned(OnProgress) then begin FTotalBytesToReceive := UidGetMessageSize(AUid); end; try SendTaggedCommand('UID FETCH %s (BODY.PEEK[])', [AUid], [IMAP_OK]); if Assigned(OnProgress) then begin DoProgress(FTotalBytesToReceive, FTotalBytesToReceive); end; finally FTotalBytesToReceive := 0; Connection.OnProgress := nil; end; ParseMessage(AUid, AMessage, True); FCurrentMessage := 0; end; procedure TclCustomImap4.UidRetrieveHeader(const AUid: string; AMessage: TclMailMessage); begin CheckUidValid(AUid); CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('UID FETCH %s (BODY.PEEK[HEADER])', [AUid], [IMAP_OK]); ParseMessage(AUid, AMessage, True); FCurrentMessage := 0; end; procedure TclCustomImap4.CheckUidValid(const AUid: string); begin if (AUid = '') then begin RaiseError(cMailMessageUidInvalid); end; if StrToIntDef(AUid, 0) < 1 then begin RaiseError(cMailMessageUidInvalid); end; end; procedure TclCustomImap4.UidSearchMessages(const ASearchCriteria: string; AMessageList: TStrings); begin CheckConnection([csSelected]); SendTaggedCommand('UID SEARCH %s', [ASearchCriteria], [IMAP_OK]); ParseSearchMessages(AMessageList); end; function TclCustomImap4.GetMessageUid(AIndex: Integer): string; begin CheckMessageValid(AIndex); CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('FETCH %d (UID)', [AIndex], [IMAP_OK]); Result := ParseMessageUid(AIndex); FCurrentMessage := AIndex; end; function TclCustomImap4.ParseMessageUid(AIndex: Integer): string; begin if (Response.Count > 0) and (GetMessageId('FETCH', Response[0], False) = IntToStr(AIndex)) then begin Result := GetMessageId('FETCH', Response[0], True); end else begin Result := ''; end; end; procedure TclCustomImap4.AppendMessage(const AMailBoxName: string; AMessage: TStrings; AFlags: TclMailMessageFlags); var flags: string; begin if (Trim(AMailBoxName) = '') then begin RaiseError(cInvalidArgument); end; CheckConnection([csAuthenticated, csSelected]); flags := GetStrByImapMessageFlags(AFlags); if (flags <> '') then begin flags := Format('(%s) ', [flags]); end; SendTaggedCommand('APPEND "%s" %s{%d}', [AMailBoxName, flags, Length(AMessage.Text)], [IMAP_CONTINUE]); SendMultipleLines(AMessage); SendCommandSync('', [IMAP_OK]); end; procedure TclCustomImap4.ExamineMailBox(const AName: string); begin CheckConnection([csAuthenticated, csSelected]); try SendTaggedCommand('EXAMINE "%s"', [AName], [IMAP_OK]); ParseSelectedMailBox(AName); FConnectionState := csSelected; except on E: EclSocketError do begin FCurrentMailBox.Clear(); FConnectionState := csAuthenticated; raise; end; end; end; procedure TclCustomImap4.Noop; begin SendTaggedCommand('NOOP', [], [IMAP_OK]); end; procedure TclCustomImap4.StartTls; begin SendTaggedCommand('STARTTLS', [], [IMAP_OK]); inherited StartTls(); end; function TclCustomImap4.GetDefaultPort: Integer; begin Result := cDefaultImapPort; end; end.
unit DPM.Controls.GroupButton; interface uses WinApi.Messages, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.StdCtrls; const CM_ACTIVE_CHANGED = CM_BASE + 501; type TDPMGroupButton = class(TCustomLabel) private FActive : boolean; FHover : boolean; FActiveColor : TColor; FHoverColor : TColor; FGroupIndex : NativeUInt; FBarHeight : Integer; procedure SetActive(const Value : boolean); procedure SetActiveColor(const Value : TColor); procedure SetHoverColor(const Value : TColor); procedure SetBarHeight(const Value : Integer); protected procedure WMLButtonDown(var Message : TWMLButtonDown); message WM_LBUTTONDOWN; procedure CMMouseEnter(var Message : TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Message : TMessage); message CM_MOUSELEAVE; procedure Paint; override; procedure SendActiveChangedMessage; procedure CMActiveChanged(var Message : TMessage); message CM_ACTIVE_CHANGED; procedure ChangeScale(M: Integer; D: Integer{$if CompilerVersion >= 31}; isDpiChange: Boolean{$ifend}); override; public constructor Create(AOwner : TComponent); override; published property Active : boolean read FActive write SetActive; property ActiveColor : TColor read FActiveColor write SetActiveColor; property BarHeight : Integer read FBarHeight write SetBarHeight; property Caption; property Font; property Height; property HoverColor : TColor read FActiveColor write SetHoverColor; property Group : NativeUInt read FGroupIndex write FGroupIndex; property Left; property Tag; property Top; property Width; property OnClick; end; implementation uses WinApi.Windows, System.Types, Vcl.Forms, Vcl.Themes; constructor TDPMGroupButton.Create(AOwner : TComponent); begin inherited; FActive := false; FGroupIndex := 0; Alignment := TAlignment.taCenter; AutoSize := false; Width := 65; Height := 24; {$IF CompilerVersion >= 24.0 } {$LEGACYIFEND ON} StyleElements := StyleElements - [seFont]; {$IFEND} Font.Size := 11; Font.Color := StyleServices.GetStyleFontColor(TStyleFont.sfButtonTextNormal); FActiveColor := $00CC7A00; FHoverColor := $006464FA; FBarHeight := 3; end; procedure TDPMGroupButton.ChangeScale(M: Integer; D: Integer{$if CompilerVersion >= 31}; isDpiChange: Boolean{$ifend}); begin FBarHeight := MulDiv(FBarHeight, M, D); inherited; end; procedure TDPMGroupButton.CMActiveChanged(var Message : TMessage); begin //ignore those for other groups. if Message.WParam <> FGroupIndex then exit; //ignore if it's us who sent it! if Message.LParam <> NativeInt(Self) then SetActive(false); //make sure other controls get the message. Message.Result := 0; end; procedure TDPMGroupButton.CMMouseEnter(var Message : TMessage); begin FHover := True; inherited; Invalidate; end; procedure TDPMGroupButton.CMMouseLeave(var Message : TMessage); begin FHover := false; inherited; Invalidate; end; procedure TDPMGroupButton.Paint; var r : TRect; begin inherited; if FHover or FActive then begin r := GetClientRect; if FHover then Canvas.Brush.Color := FHoverColor else Canvas.Brush.Color := FActiveColor; Canvas.Brush.Style := bsSolid; r.Top := r.Bottom - FBarHeight; Canvas.FillRect(r); end; end; procedure TDPMGroupButton.SendActiveChangedMessage; var message : TMessage; // form : TCustomForm; begin message.Msg := CM_ACTIVE_CHANGED; message.LParam := NativeInt(Self); message.WParam := FGroupIndex; if Self.Parent <> nil then Self.Parent.Broadcast(message); // form := GetParentForm(Self); // if form <> nil then // form.Broadcast(message); end; procedure TDPMGroupButton.SetActive(const Value : boolean); begin FActive := Value; // Caption := BoolToStr(FActive,true); if FActive then SendActiveChangedMessage; Refresh; end; procedure TDPMGroupButton.SetActiveColor(const Value : TColor); begin if FActiveColor <> Value then begin FActiveColor := Value; Invalidate; end; end; procedure TDPMGroupButton.SetBarHeight(const Value : Integer); begin if FBarHeight <> value then begin FBarHeight := Value; if FBarHeight < 2 then FBarHeight := 2; if FActive then Invalidate; end; end; procedure TDPMGroupButton.SetHoverColor(const Value : TColor); begin if FHoverColor <> Value then begin FHoverColor := Value; end; end; procedure TDPMGroupButton.WMLButtonDown(var Message : TWMLButtonDown); begin SetActive(true); inherited; end; end.
////////////////////////////////////////////////////////////////////////// // SimplePlay sample // THIS CODE AND INFORMATION IS 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. // Copyright (c) Microsoft Corporation. All rights reserved. // This sample demonstrates how to use the MFPlay API for simple video // playback. ////////////////////////////////////////////////////////////////////////// unit MainUnit; {$mode delphi}{$H+} interface uses Windows, Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ActiveX, Menus, CMC.MFPlay; type { TMFPlaySample } TMFPlaySample = class(TForm) MainMenu1: TMainMenu; MenuItem1: TMenuItem; menuFileOpen: TMenuItem; MenuItem3: TMenuItem; menuClose: TMenuItem; OpenDialog1: TOpenDialog; procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: word; Shift: TShiftState); procedure FormPaint(Sender: TObject); procedure FormResize(Sender: TObject); procedure menuCloseClick(Sender: TObject); procedure menuFileOpenClick(Sender: TObject); private { private declarations } function PlayMediaFile(hwnd: HWnd; sURL: PWideChar): HResult; public { public declarations } end; { TMediaPlayerCallback } //------------------------------------------------------------------- // MediaPlayerCallback class // Implements the callback interface for MFPlay events. //------------------------------------------------------------------- TMediaPlayerCallback = class(TInterfacedObject, IMFPMediaPlayerCallback) public constructor Create; destructor Destroy; override; procedure OnMediaPlayerEvent(pEventHeader: PMFP_EVENT_HEADER); stdcall; end; var MFPlaySample: TMFPlaySample; // Global variables g_pPlayer: IMFPMediaPlayer = nil; // The MFPlay player object. g_pPlayerCB: IMFPMediaPlayerCallback = nil; // Application callback object. g_bHasVideo: boolean = False; // MFPlay event handler functions. procedure OnMediaItemCreated(pEvent: PMFP_MEDIAITEM_CREATED_EVENT); procedure OnMediaItemSet(pEvent: PMFP_MEDIAITEM_SET_EVENT); procedure ShowErrorMessage(format: PCWSTR; hrErr: HRESULT); implementation {$R *.lfm} { TMediaPlayerCallback } constructor TMediaPlayerCallback.Create; begin end; destructor TMediaPlayerCallback.Destroy; begin inherited Destroy; end; //------------------------------------------------------------------- // OnMediaPlayerEvent // Implements IMFPMediaPlayerCallback::OnMediaPlayerEvent. // This callback method handles events from the MFPlay object. //------------------------------------------------------------------- procedure TMediaPlayerCallback.OnMediaPlayerEvent(pEventHeader: PMFP_EVENT_HEADER); stdcall; begin if (FAILED(pEventHeader^.hrEvent)) then begin ShowErrorMessage('Playback error', pEventHeader.hrEvent); exit; end; case (pEventHeader^.eEventType) of MFP_EVENT_TYPE_MEDIAITEM_CREATED: begin OnMediaItemCreated(MFP_GET_MEDIAITEM_CREATED_EVENT(pEventHeader)); end; MFP_EVENT_TYPE_MEDIAITEM_SET: begin OnMediaItemSet(MFP_GET_MEDIAITEM_SET_EVENT(pEventHeader)); end; end; end; { TMFPlaySample } procedure TMFPlaySample.FormCreate(Sender: TObject); begin CoInitializeEx(nil, COINIT_APARTMENTTHREADED or COINIT_DISABLE_OLE1DDE); end; //------------------------------------------------------------------- // OnClose // Handles the WM_CLOSE message. //------------------------------------------------------------------- procedure TMFPlaySample.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin if (g_pPlayer <> nil) then begin g_pPlayer.Shutdown(); g_pPlayer := nil; end; if (g_pPlayerCB <> nil) then g_pPlayerCB := nil; end; procedure TMFPlaySample.FormDestroy(Sender: TObject); begin CoUninitialize(); end; //------------------------------------------------------------------- // OnKeyDown // Handles the WM_KEYDOWN message. //------------------------------------------------------------------- procedure TMFPlaySample.FormKeyDown(Sender: TObject; var Key: word; Shift: TShiftState); var hr: HResult; state: TMFP_MEDIAPLAYER_STATE; begin hr := S_OK; case (Key) of VK_SPACE: // Toggle between playback and paused/stopped. if (g_pPlayer <> nil) then begin state := MFP_MEDIAPLAYER_STATE_EMPTY; hr := g_pPlayer.GetState(state); if (SUCCEEDED(hr)) then begin if (state = MFP_MEDIAPLAYER_STATE_PAUSED) or (state = MFP_MEDIAPLAYER_STATE_STOPPED) then begin hr := g_pPlayer.Play(); end else if (state = MFP_MEDIAPLAYER_STATE_PLAYING) then begin hr := g_pPlayer.Pause(); end; end; end; end; if (FAILED(hr)) then begin ShowErrorMessage('Playback Error', hr); end; end; //------------------------------------------------------------------- // OnPaint // Handles the WM_PAINT message. //------------------------------------------------------------------- procedure TMFPlaySample.FormPaint(Sender: TObject); var ps: PAINTSTRUCT; lhdc: HDC; begin lhdc := BeginPaint(Handle, ps); if ((g_pPlayer <> nil) and g_bHasVideo) then begin // Playback has started and there is video. // Do not draw the window background, because the video // frame fills the entire client area. g_pPlayer.UpdateVideo(); end else begin // There is no video stream, or playback has not started. // Paint the entire client area. FillRect(lhdc, ps.rcPaint, HBRUSH(COLOR_WINDOW + 1)); end; EndPaint(Handle, ps); end; //------------------------------------------------------------------- // OnSize // Handles the WM_SIZE message. //------------------------------------------------------------------- procedure TMFPlaySample.FormResize(Sender: TObject); begin if (g_pPlayer <> nil) then begin // Resize the video. g_pPlayer.UpdateVideo(); end; end; procedure TMFPlaySample.menuCloseClick(Sender: TObject); begin Close; end; //------------------------------------------------------------------- // OnFileOpen // Handles the "File Open" command. //------------------------------------------------------------------- procedure TMFPlaySample.menuFileOpenClick(Sender: TObject); var hr: HResult; lString: string; pwszFilePath: pWideChar; begin hr := S_OK; OpenDialog1.Title := 'Select a File to Play'; if OpenDialog1.Execute then begin lString := OpenDialog1.FileName; pwszFilePath := pWideChar(UTF8Decode(lString)); // Open the media file. hr := PlayMediaFile(Handle, pwszFilePath); if hr = s_OK then Exit; end; end; //------------------------------------------------------------------- // PlayMediaFile // Plays a media file, using the IMFPMediaPlayer interface. //------------------------------------------------------------------- function TMFPlaySample.PlayMediaFile(hwnd: HWnd; sURL: PWideChar): HResult; var lMediaItem: IMFPMediaItem; begin Result := S_OK; // Create the MFPlayer object. if (g_pPlayer = nil) then begin g_pPlayerCB := TMediaPlayerCallback.Create(); if (g_pPlayerCB = nil) then begin Result := E_OUTOFMEMORY; exit; end; Result := MFPCreateMediaPlayer(nil, False, // Start playback automatically? MFP_OPTION_NONE, // Flags g_pPlayerCB, // Callback pointer hwnd, // Video window g_pPlayer); if (FAILED(Result)) then Exit; end; // Create a new media item for this URL. Result := g_pPlayer.CreateMediaItemFromURL(sURL, False, 0, lMediaItem); // The CreateMediaItemFromURL method completes asynchronously. // The application will receive an MFP_EVENT_TYPE_MEDIAITEM_CREATED // event. See MediaPlayerCallback::OnMediaPlayerEvent(). end; procedure ShowErrorMessage(format: PCWSTR; hrErr: HRESULT); var hr: HResult; msg: string; begin hr := S_OK; msg := format + ' (0x' + IntToHex(hrErr, 8) + ')'; if (SUCCEEDED(hr)) then begin Application.MessageBox(PChar(msg), 'Error', MB_ICONERROR); end; end; //------------------------------------------------------------------- // OnMediaItemCreated // Called when the IMFPMediaPlayer::CreateMediaItemFromURL method // completes. //------------------------------------------------------------------- procedure OnMediaItemCreated(pEvent: PMFP_MEDIAITEM_CREATED_EVENT); var hr: HResult; bHasVideo, bIsSelected: boolean; begin hr := S_OK; // The media item was created successfully. if (g_pPlayer <> nil) then begin bHasVideo := False; bIsSelected := False; // Check if the media item contains video. hr := pEvent^.pMediaItem.HasVideo(bHasVideo, bIsSelected); if hr = S_OK then begin g_bHasVideo := bHasVideo and bIsSelected; // Set the media item on the player. This method completes asynchronously. hr := g_pPlayer.SetMediaItem(pEvent^.pMediaItem); end; end; if (FAILED(hr)) then begin ShowErrorMessage('Error playing this file.', hr); end; end; //------------------------------------------------------------------- // OnMediaItemSet // Called when the IMFPMediaPlayer::SetMediaItem method completes. //------------------------------------------------------------------- procedure OnMediaItemSet(pEvent: PMFP_MEDIAITEM_SET_EVENT); var hr: HRESULT; begin hr := g_pPlayer.Play(); if (FAILED(hr)) then begin ShowErrorMessage('IMFPMediaPlayer.Play failed.', hr); end; end; end.
Program json; Uses SysUtils; {$INCLUDE node.pas} {$INCLUDE parser.pas} Type TestResult = (Pass, Fail); TestFn = Function () : TestResult; Test = Class Name : String; Fn : TestFn; Constructor Init(n : String; f: TestFn); End; Constructor Test.Init(n : String; f: TestFn); Begin Name := n; Fn := f; End; Var p : Parser; Var n : Node; Function TestParseString() : TestResult; Begin n := p.Parse('"yee!"'); If Not (n is StringNode) Then Begin TestParseString := Fail; exit; End; If Not ((n as StringNode).Value = 'yee!') Then Begin TestParseString := Fail; exit; End; TestParseString := Pass; End; Function TestParseStringWithEscapedCharacters() : TestResult; Begin n := p.Parse('"\"b"'); If Not (n is StringNode) Then Begin TestParseStringWithEscapedCharacters := Fail; exit; End; If Not ((n as StringNode).Value = '"b') Then Begin TestParseStringWithEscapedCharacters := Fail; exit; End; TestParseStringWithEscapedCharacters := Pass; End; Function TestParseEmptyArray() : TestResult; Begin n := p.Parse('[]'); If Not (n Is ArrayNode) Then Begin TestParseEmptyArray := Fail; exit; End; TestParseEmptyArray := Pass; End; Function TestParseArrayOfStrings() : TestResult; Begin n := p.Parse('[ "a", "b" ]'); If Not (n Is ArrayNode) Then Begin TestParseArrayOfStrings := Fail; exit; End; If Not (((n as ArrayNode).Value[0] as StringNode).Value = 'a') Then Begin TestParseArrayOfStrings := Fail; exit; End; If Not (((n as ArrayNode).Value[1] as StringNode).Value = 'b') Then Begin TestParseArrayOfStrings := Fail; exit; End; TestParseArrayOfStrings := Pass; End; Function TestParseBooleans() : TestResult; Begin n := p.Parse('true'); If Not (n is BooleanNode) Then Begin TestParseBooleans := Fail; exit; End; If Not ((n as BooleanNode).Value = true) Then Begin TestParseBooleans := Fail; exit; End; n := p.Parse('false'); If Not (n is BooleanNode) Then Begin TestParseBooleans := Fail; exit; End; If Not ((n as BooleanNode).Value = false) Then Begin TestParseBooleans := Fail; exit; End; TestParseBooleans := Pass; End; Function TestParseNull() : TestResult; Begin n := p.Parse('null'); If Not (n is NullNode) Then Begin TestParseNull := Fail; exit; End; TestParseNull := Pass; End; Function TestParseObject() : TestResult; Var o : ObjectNode; Begin o := p.Parse('{ "a" : "b", '#9' '#10' "c": [ "d" ] }') as ObjectNode; If Not (o.Value[0].Key = 'a') Then Begin TestParseObject := Fail; exit; End; If Not ((o.Value[0].Value as StringNode).Value = 'b') Then Begin TestParseObject := Fail; exit; End; If Not (o.Value[1].Key = 'c') Then Begin TestParseObject := Fail; exit; End; If Not (((o.Value[1].Value as ArrayNode).Value[0] as StringNode).Value = 'd') Then Begin TestParseObject := Fail; exit; End; TestParseObject := Pass; End; Function TestParseNumber() : TestResult; Var num : NumberNode; Begin num := p.Parse('123.5') as NumberNode; If num.Value <> 123.5 Then Begin TestParseNumber := Fail; exit; End; TestParseNumber := Pass; End; Var t : Test; Var tests : Array[0..15] Of Test; Var res : TestResult; Var out : Integer; Begin p.Init(); tests[0] := Test.Init('Parse string', @TestParseString); tests[1] := Test.Init( 'Parse string with escaped characters', @ TestParseStringWithEscapedCharacters ); tests[2] := Test.Init('Parse empty array', @TestParseEmptyArray); tests[3] := Test.Init('Parse array of strings', @TestParseArrayOfStrings); tests[4] := Test.Init('Parse booleans', @TestParseBooleans); tests[5] := Test.Init('Parse null', @TestParseNull); tests[6] := Test.Init('Parse object', @TestParseObject); tests[7] := Test.Init('Parse number', @TestParseNumber); For t In tests Do Begin If t = Nil Then Begin continue; End; res := t.Fn(); If res = Pass Then Begin WriteLn('[OK] ' + t.Name); End Else Begin WriteLn('[FAIL] ' + t.Name); out := 1; End; End; halt(out); End.
unit uModCreditCard; interface uses uModApp, uModRekening; type TModCreditCard = class(TModApp) private FCARD_CHARGE: Double; FCARD_CODE: string; FCARD_DISCOUNT: Double; FCARD_IS_ACTIVE: Integer; FCARD_IS_CASHBACK: Integer; FCARD_IS_CREDIT: Integer; FCARD_IS_KRING: Integer; FCARD_LIMIT: Double; FCARD_NAME: string; FREKENING: TModRekening; FREKENING_CASH_BACK: TModRekening; public class function GetTableName: string; override; published property CARD_CHARGE: Double read FCARD_CHARGE write FCARD_CHARGE; [AttributeOfCode] property CARD_CODE: string read FCARD_CODE write FCARD_CODE; property CARD_DISCOUNT: Double read FCARD_DISCOUNT write FCARD_DISCOUNT; property CARD_IS_ACTIVE: Integer read FCARD_IS_ACTIVE write FCARD_IS_ACTIVE; property CARD_IS_CASHBACK: Integer read FCARD_IS_CASHBACK write FCARD_IS_CASHBACK; property CARD_IS_CREDIT: Integer read FCARD_IS_CREDIT write FCARD_IS_CREDIT; property CARD_IS_KRING: Integer read FCARD_IS_KRING write FCARD_IS_KRING; property CARD_LIMIT: Double read FCARD_LIMIT write FCARD_LIMIT; [AttributeOfCode] property CARD_NAME: string read FCARD_NAME write FCARD_NAME; property REKENING: TModRekening read FREKENING write FREKENING; // [AttributeOfForeign('REKENING_CASH_BACK_ID')] property REKENING_CASH_BACK: TModRekening read FREKENING_CASH_BACK write FREKENING_CASH_BACK; end; implementation class function TModCreditCard.GetTableName: string; begin inherited; Result := 'REF$CREDIT_CARD'; end; initialization TModCreditCard.RegisterRTTI; end.
unit Demo.ScatterChart.Sample; interface uses System.Classes, Demo.BaseFrame, cfs.GCharts; type TDemo_ScatterChart_Sample = class(TDemoBaseFrame) public procedure GenerateChart; override; end; implementation procedure TDemo_ScatterChart_Sample.GenerateChart; var Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally begin Chart := TcfsGChartProducer.Create; Chart.ClassChartType := TcfsGChartProducer.CLASS_SCATTER_CHART; // Data Chart.Data.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Age'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Weight') ]); Chart.Data.AddRow([ 8, 12]); Chart.Data.AddRow([ 4, 5.5]); Chart.Data.AddRow([ 11, 14]); Chart.Data.AddRow([ 4, 5]); Chart.Data.AddRow([ 3, 3.5]); Chart.Data.AddRow([ 6.5, 7]); // Options Chart.Options.Title('Age vs. Weight comparison'); Chart.Options.HAxis('title', 'Age'); Chart.Options.HAxis('minValue', 0); Chart.Options.HAxis('maxValue', 15); Chart.Options.VAxis('title', 'Weight'); Chart.Options.VAxis('minValue', 0); Chart.Options.VAxis('maxValue', 15); Chart.Options.Legend('position', 'none'); // Generate GChartsFrame.DocumentInit; GChartsFrame.DocumentSetBody('<div id="Chart" style="width:100%;height:100%;"></div>'); GChartsFrame.DocumentGenerate('Chart', Chart); GChartsFrame.DocumentPost; end; initialization RegisterClass(TDemo_ScatterChart_Sample); end.
unit AS_ShellUtils; { Arisesoft Shell Pack Copyright (c) 1996-2001 Arisesoft For conditions of distribution and use, see LICENSE. Shell Utilities } {$I AS_Ver.inc} interface uses Windows, ShlObj, ActiveX, CommCtrl; { Additional registry entries available in shell version at least 4.7 for special paths are kept in: } {$IFNDEF AS_VCL4} const {$IFDEF VER110} {$EXTERNALSYM CSIDL_INTERNET} CSIDL_INTERNET = $0001; {$EXTERNALSYM CSIDL_ALTSTARTUP} CSIDL_ALTSTARTUP = $001D; {$EXTERNALSYM CSIDL_COMMON_ALTSTARTUP} CSIDL_COMMON_ALTSTARTUP = $001E; {$EXTERNALSYM CSIDL_COMMON_FAVORITES} CSIDL_COMMON_FAVORITES = $001F; {$EXTERNALSYM CSIDL_INTERNET_CACHE} CSIDL_INTERNET_CACHE = $0020; {$EXTERNALSYM CSIDL_COOKIES} CSIDL_COOKIES = $0021; {$EXTERNALSYM CSIDL_HISTORY} CSIDL_HISTORY = $0022; {$ELSE} CSIDL_INTERNET = $0001; CSIDL_ALTSTARTUP = $001D; CSIDL_COMMON_ALTSTARTUP = $001E; CSIDL_COMMON_FAVORITES = $001F; CSIDL_INTERNET_CACHE = $0020; CSIDL_COOKIES = $0021; CSIDL_HISTORY = $0022; {$ENDIF} {$ENDIF} const {$EXTERNALSYM SHGFI_ATTR_SPECIFIED} SHGFI_ATTR_SPECIFIED = $000020000; { Initialized interfaces variables } var ShellMalloc: IMalloc; DesktopFolder: IShellFolder; { Low level manipulation by PIDLs } type TRootSpecial = ( rsDesktop, rsInternet, rsPrograms, rsControls, rsPrinters, rsPersonal, rsFavorites, rsStartUp, rsRecent, rsSendTo, rsBitBucket, rsStartMenu, rsMusic, rsVideo, rsDesktopDirectory, rsNetHood, rsFonts, rsCommonStartMenu, rsCommonPrograms, rsCommonStartUp, rsCommonDesktopDirectory, rsAppData, rsPrintHood, rsLocalAppData, rsCommonAppdata, rsWindows, rsSystem, rsProgramFiles, rsCommonDocuments, rsCommonMusic, rsCommonPictures, rsCommonVideos, rsCommonFavorites, rsInternetCache, rsCookies, rsHistory); function CreateSpecialPIDL(RootSpecial: TRootSpecial): PItemIDList; function GetSpecialFolderPath(RootSpecial: TRootSpecial): string; function GetSpecialIcon(RootSpecial: TRootSpecial; Large: Boolean): HICON; function CreatePIDL(Size: Integer): PItemIDList; function PathToPIDL(const Path: WideString): PItemIDList; procedure FreePIDL(PIDL: PItemIDList); function NextPIDL(PIDL: PItemIDList): PItemIDList; function LastPIDL(PIDL: PItemIDList): PItemIDList; function GetPIDLSize(PIDL: PItemIDList): Integer; function GetPIDLCount(PIDL: PItemIDList): Integer; function SamePIDL(PIDL1, PIDL2: PItemIDList): Boolean; function CopyPIDL(PIDL: PItemIDList): PItemIDList; function CopyFirstPIDL(PIDL: PItemIDList): PItemIDList; function ConcatPIDLs(PIDL1, PIDL2: PItemIDList): PItemIDList; function PIDLToString(PIDL: PItemIDList): string; function StringToPIDL(const Value: string): PItemIDList; function GetPIDLNameForAddressBar(PIDL: PItemIDList): string; function GetPIDLDisplayName(PIDL: PItemIDList): string; function GetPIDLPath(PIDL: PItemIDList): string; function GetPIDLTypeName(PIDL: PItemIDList): string; function GetPIDLImage(PIDL: PItemIDList; Large, Open: Boolean): Integer; function GetPIDLIcon(PIDL: PItemIDList; Large: Boolean): HICON; function GetPIDLAttributes(PIDL: PItemIDList; Specified: Cardinal = 0): Cardinal; function HasPIDLAttributes(PIDL: PItemIDList; Attributes: Cardinal): Boolean; procedure StripPIDL(PIDL: PItemIDList; NewCount: Integer); procedure StripLastPIDL(PIDL: PItemIDList); procedure ReducePIDLToFolder(PIDL: PItemIDList); function IsChildPIDL(RootPIDL, PIDL: PItemIDList): Boolean; function IsDesktopPIDL(PIDL: PItemIDList): Boolean; function IsFileSystemPIDL(PIDL: PItemIDList): Boolean; function GetSystemImageListHandle(Large: Boolean): HIMAGELIST; function ShellExecuteCommand(const Operation: string; const FileName: string): Boolean; function ShellExecutePIDL(PIDL: PItemIDList): Boolean; { Other stuff } procedure CreateShellLink(const FileName, ShortcutTo, WorkingDir, Parameters, IconFileName: string; IconIndex: Integer); function GetAssociatedIcon(const FileName: string): HICON; function ExtractShellIcon(Index: Integer; Large: Boolean): HICON; function PathAddBackSlash(const Path: string): string; function PathRemoveBackSlash(const Path: string): string; function GetFileTypeName(const Ext: string): string; function StrRetToString(PIDL: PItemIDList; const StrRet: TStrRet): string; function ValueInFlags(Value, Flags: Cardinal): Boolean; function GetModule(const Name: string): THandle; function GetStrFromModule(Module: THandle; ResIdentifier: LongInt): string; {$IFDEF AS_VCL35} {$EXTERNALSYM StrFormatByteSizeA} function StrFormatByteSizeA(dw: DWORD; pszBuf: PAnsiChar; cchBuf: UINT): PAnsiChar; stdcall; {$EXTERNALSYM StrFormatByteSizeW} function StrFormatByteSizeW(qdw: LONGLONG; szBuf: PWideChar; uiBufSize: UINT): PWideChar; stdcall; {$EXTERNALSYM StrFormatByteSize} function StrFormatByteSize(dw: DWORD; pszBuf: PChar; cchBuf: UINT): PChar; stdcall; {$ELSE} function StrFormatByteSizeA(dw: DWORD; pszBuf: PAnsiChar; cchBuf: UINT): PAnsiChar; stdcall; function StrFormatByteSizeW(qdw: LONGLONG; szBuf: PWideChar; uiBufSize: UINT): PWideChar; stdcall; function StrFormatByteSize(dw: DWORD; pszBuf: PChar; cchBuf: UINT): PChar; stdcall; {$ENDIF} function ByteSizeToFormatStr(ByteSize: LongInt): string; function ShortPathToLongPath(const FileName: string): string; type SHQUERYRBINFO = record cbSize: DWORD; i64Size: Int64; i64NumItems: Int64; end; LPSHQUERYRBINFO = ^SHQUERYRBINFO; TSHQueryRBInfo = SHQUERYRBINFO; {$IFDEF AS_VCL35} {$EXTERNALSYM SHQueryRecycleBinA} function SHQueryRecycleBinA(pszRootPath: PAnsiChar; var pSHQueryRBInfo: TSHQueryRBInfo): HResult; stdcall; {$EXTERNALSYM SHQueryRecycleBinW} function SHQueryRecycleBinW(pszRootPath: PWideChar; var pSHQueryRBInfo: TSHQueryRBInfo): HResult; stdcall; {$EXTERNALSYM SHQueryRecycleBin} function SHQueryRecycleBin(pszRootPath: PChar; var pSHQueryRBInfo: TSHQueryRBInfo): HResult; stdcall; {$ELSE} function SHQueryRecycleBinA(pszRootPath: PAnsiChar; var pSHQueryRBInfo: TSHQueryRBInfo): HResult; stdcall; function SHQueryRecycleBinW(pszRootPath: PWideChar; var pSHQueryRBInfo: TSHQueryRBInfo): HResult; stdcall; function SHQueryRecycleBin(pszRootPath: PChar; var pSHQueryRBInfo: TSHQueryRBInfo): HResult; stdcall; {$ENDIF} {$IFDEF AS_VCL35} {$EXTERNALSYM SHEmptyRecycleBinA} function SHEmptyRecycleBinA(hWnd: HWND; pszRootPath: PAnsiChar; dwFlags: DWORD): HResult; stdcall; {$EXTERNALSYM SHEmptyRecycleBinW} function SHEmptyRecycleBinW(hWnd: HWND; pszRootPath: PWideChar; dwFlags: DWORD): HResult; stdcall; {$EXTERNALSYM SHEmptyRecycleBin} function SHEmptyRecycleBin(hWnd: HWND; pszRootPath: PChar; dwFlags: DWORD): HResult; stdcall; {$ELSE} function SHEmptyRecycleBinA(hWnd: HWND; pszRootPath: PAnsiChar; dwFlags: DWORD): HResult; stdcall; function SHEmptyRecycleBinW(hWnd: HWND; pszRootPath: PWideChar; dwFlags: DWORD): HResult; stdcall; function SHEmptyRecycleBin(hWnd: HWND; pszRootPath: PChar; dwFlags: DWORD): HResult; stdcall; {$ENDIF} { Hints from library Shell32 } function GetShellString(ResIdentifier: LongInt): string; implementation uses Forms, ShellAPI, SysUtils, ComObj, Consts; var DesktopPIDL: PItemIDList; function GetDesktopPIDL: PItemIDList; begin if DesktopPIDL = nil then DesktopPIDL := CreateSpecialPIDL(rsDesktop); Result := DesktopPIDL; end; function CreateSpecialPIDL(RootSpecial: TRootSpecial): PItemIDList; const RootSpecials: array[TRootSpecial] of Integer = ( CSIDL_DESKTOP, CSIDL_INTERNET, CSIDL_PROGRAMS, CSIDL_CONTROLS, CSIDL_PRINTERS, CSIDL_PERSONAL, CSIDL_FAVORITES, CSIDL_STARTUP, CSIDL_RECENT, CSIDL_SENDTO, CSIDL_BITBUCKET, CSIDL_STARTMENU, CSIDL_MYMUSIC, CSIDL_MYVIDEO, // <--- problema no XP (cliente) CSIDL_DESKTOPDIRECTORY, CSIDL_NETHOOD, CSIDL_FONTS, CSIDL_COMMON_STARTMENU, CSIDL_COMMON_PROGRAMS, CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY, CSIDL_APPDATA, CSIDL_PRINTHOOD, CSIDL_LOCAL_APPDATA, CSIDL_COMMON_APPDATA, CSIDL_WINDOWS, CSIDL_SYSTEM, CSIDL_PROGRAM_FILES, CSIDL_COMMON_DOCUMENTS, // <--- problema no XP (cliente) CSIDL_COMMON_MUSIC, CSIDL_COMMON_PICTURES, CSIDL_COMMON_VIDEO, CSIDL_COMMON_FAVORITES, CSIDL_INTERNET_CACHE, CSIDL_COOKIES, CSIDL_HISTORY); begin OLECheck(SHGetSpecialFolderLocation(0, RootSpecials[RootSpecial], Result)); end; function GetSpecialFolderPath(RootSpecial: TRootSpecial): string; var PIDL: PItemIDList; begin PIDL := CreateSpecialPIDL(RootSpecial); Result := GetPIDLPath(PIDL); FreePIDL(PIDL); end; function GetSpecialIcon(RootSpecial: TRootSpecial; Large: Boolean): HICON; var PIDL: PItemIDList; begin PIDL := CreateSpecialPIDL(RootSpecial); Result := GetPIDLIcon(PIDL, Large); FreePIDL(PIDL); end; function PathToPIDL(const Path: WideString): PItemIDList; var Eaten, Attributes: Cardinal; begin Attributes := 0; OLECheck(DesktopFolder.ParseDisplayName(0, nil, POleStr(Path), Eaten, Result, Attributes)); end; function CreatePIDL(Size: Integer): PItemIDList; begin try Result := nil; Result := ShellMalloc.Alloc(Size); if Assigned(Result) then FillChar(Result^, Size, 0); finally end; end; procedure FreePIDL(PIDL: PItemIDList); begin if PIDL <> nil then ShellMalloc.Free(PIDL); end; function NextPIDL(PIDL: PItemIDList): PItemIDList; begin Result := PIDL; Inc(PChar(Result), PIDL^.mkid.cb); end; function LastPIDL(PIDL: PItemIDList): PItemIDList; begin repeat Result := PIDL; PIDL := NextPIDL(Result); until PIDL^.mkid.cb = 0; end; function GetPIDLSize(PIDL: PItemIDList): Integer; begin Result := 0; if Assigned(PIDL) then begin Result := SizeOf(PIDL^.mkid.cb); while PIDL^.mkid.cb <> 0 do begin Result := Result + PIDL^.mkid.cb; PIDL := NextPIDL(PIDL); end; end; end; function GetPIDLCount(PIDL: PItemIDList): Integer; begin Result := 0; if Assigned(PIDL) then while PIDL^.mkid.cb <> 0 do begin Inc(Result); PIDL := NextPIDL(PIDL); end; end; function SamePIDL(PIDL1, PIDL2: PItemIDList): Boolean; begin if Assigned(PIDL1) and Assigned(PIDL2) then Result := DesktopFolder.CompareIDs(0, PIDL1, PIDL2) = 0 else Result := (PIDL1 = nil) and (PIDL2 = nil); end; function CopyPIDL(PIDL: PItemIDList): PItemIDList; var cb: Integer; begin if Assigned(PIDL) then begin cb := GetPIDLSize(PIDL); Result := CreatePIDL(cb); CopyMemory(PChar(Result), PIDL, cb); end else Result := nil; end; function CopyFirstPIDL(PIDL: PItemIDList): PItemIDList; var cb: Integer; begin if Assigned(PIDL) then begin cb := PIDL^.mkid.cb; Result := CreatePIDL(cb + SizeOf(PIDL^.mkid.cb)); CopyMemory(PChar(Result), PIDL, cb); end else Result := nil; end; function ConcatPIDLs(PIDL1, PIDL2: PItemIDList): PItemIDList; var cb1, cb2: Integer; begin if Assigned(PIDL1) then cb1 := GetPIDLSize(PIDL1) - SizeOf(PIDL1^.mkid.cb) else cb1 := 0; cb2 := GetPIDLSize(PIDL2); Result := CreatePIDL(cb1 + cb2); if Assigned(Result) then begin if Assigned(PIDL1) then CopyMemory(PChar(Result), PIDL1, cb1); CopyMemory(PChar(Result) + cb1, PIDL2, cb2); end; end; function PIDLToString(PIDL: PItemIDList): string; var Len, I: Integer; S: string; begin Result := ''; if PIDL^.mkid.cb = 0 then Exit; Len := GetPIDLSize(PIDL); SetLength(S, Len); Move(PIDL^, PChar(S)^, Len); for I := 1 to Len do Result := Result + '#' + IntToStr(Ord(S[I])); end; function StringToPIDL(const Value: string): PItemIDList; var I, Start, Count: Integer; S: string; begin if Value = '' then Result := CreateSpecialPIDL(rsDesktop) else begin Start := 0; Count := 0; for I := 1 to Length(Value) do if (Value[I] = '#') then Inc(Count); SetLength(S, Count); Count := 1; for I := 1 to Length(Value) do if (Value[I] = '#') then begin if Start > 0 then begin S[Count] := Chr(StrToInt(Copy(Value, Start + 1, I - Start - 1))); Inc(Count); end; Start := I; end; S[Length(S)] := Chr(StrToInt(Copy(Value, Start + 1, Length(Value) - Start))); try Result := nil; Result := ShellMalloc.Alloc(Length(S)); if Assigned(Result) then Move(PChar(S)^, Result^, Length(S)); finally end; end; end; function GetPIDLNameForAddressBar(PIDL: PItemIDList): string; var Flags: Cardinal; StrRet: TStrRet; begin Flags := SHGDN_FORPARSING or SHGDN_FORADDRESSBAR; OLECheck(DesktopFolder.GetDisplayNameOf(PIDL, Flags, StrRet)); Result := StrRetToString(PIDL, StrRet); end; function GetPIDLDisplayName(PIDL: PItemIDList): string; var FileInfo: TSHFileInfo; begin SHGetFileInfo(PChar(PIDL), 0, FileInfo, SizeOf(FileInfo), SHGFI_PIDL or SHGFI_DISPLAYNAME); Result := FileInfo.szDisplayName; end; function GetPIDLPath(PIDL: PItemIDList): string; var Buffer: array[0..MAX_PATH - 1] of Char; begin if SHGetPathFromIDList(PIDL, Buffer) then Result := Buffer else Result := ''; end; function GetPIDLTypeName(PIDL: PItemIDList): string; var FileInfo: TSHFileInfo; begin SHGetFileInfo(PChar(PIDL), 0, FileInfo, SizeOf(FileInfo), SHGFI_PIDL or SHGFI_TYPENAME); Result := FileInfo.szTypeName; end; function GetPIDLImage(PIDL: PItemIDList; Large, Open: Boolean): Integer; const IOpen: array[Boolean] of Integer = (0, SHGFI_OPENICON); ILarge: array[Boolean] of Integer = (SHGFI_SMALLICON, SHGFI_LARGEICON); var FileInfo: TSHFileInfo; begin SHGetFileInfo(PChar(PIDL), 0, FileInfo, SizeOf(FileInfo), SHGFI_PIDL or SHGFI_SYSICONINDEX or ILarge[Large] or IOpen[Open]); Result := FileInfo.iIcon; end; function GetPIDLIcon(PIDL: PItemIDList; Large: Boolean): HICON; const ILarge: array[Boolean] of Integer = (SHGFI_SMALLICON, SHGFI_LARGEICON); var FileInfo: TSHFileInfo; begin SHGetFileInfo(PChar(PIDL), 0, FileInfo, SizeOf(FileInfo), SHGFI_PIDL or SHGFI_ICON or ILarge[Large]); Result := FileInfo.hIcon; end; function GetPIDLAttributes(PIDL: PItemIDList; Specified: Cardinal): Cardinal; const ISpecified: array[Boolean] of Integer = (0, SHGFI_ATTR_SPECIFIED); var FileInfo: TSHFileInfo; begin FileInfo.dwAttributes := Specified; SHGetFileInfo(PChar(PIDL), 0, FileInfo, SizeOf(FileInfo), SHGFI_PIDL or SHGFI_ATTRIBUTES or ISpecified[Specified <> 0]); Result := FileInfo.dwAttributes; end; function HasPIDLAttributes(PIDL: PItemIDList; Attributes: Cardinal): Boolean; begin Result := ValueInFlags(Attributes, GetPIDLAttributes(PIDL, Attributes)); end; procedure StripPIDL(PIDL: PItemIDList; NewCount: Integer); var Result: PItemIDList; begin if Assigned(PIDL) then begin repeat Result := PIDL; PIDL := NextPIDL(Result); Dec(NewCount); until (NewCount < 0) or (PIDL^.mkid.cb = 0); if NewCount < 0 then Result^.mkid.cb := 0; end; end; procedure StripLastPIDL(PIDL: PItemIDList); begin if Assigned(PIDL) then LastPIDL(PIDL)^.mkid.cb := 0; end; procedure ReducePIDLToFolder(PIDL: PItemIDList); begin if Assigned(PIDL) then while (PIDL^.mkid.cb <> 0) and not HasPIDLAttributes(PIDL, SFGAO_FOLDER) do StripLastPIDL(PIDL); end; function IsChildPIDL(RootPIDL, PIDL: PItemIDList): Boolean; var TestPIDL: PItemIDList; begin if Assigned(RootPIDL) and Assigned(PIDL) then begin TestPIDL := CopyPIDL(PIDL); try StripPIDL(TestPIDL, GetPIDLCount(RootPIDL)); Result := SamePIDL(TestPIDL, RootPIDL); finally FreePIDL(TestPIDL); end; end else Result := False; end; function IsDesktopPIDL(PIDL: PItemIDList): Boolean; begin Result := SamePIDL(GetDesktopPIDL, PIDL); end; function IsFileSystemPIDL(PIDL: PItemIDList): Boolean; var Attributes: Cardinal; begin Attributes := SFGAO_FILESYSTEM; if Win32MajorVersion > 4 then Attributes := Attributes or SFGAO_FILESYSANCESTOR; Result := HasPIDLAttributes(PIDL, Attributes); end; function GetSystemImageListHandle(Large: Boolean): HIMAGELIST; const ILarge: array[Boolean] of Integer = (SHGFI_SMALLICON, SHGFI_LARGEICON); var FileInfo: TSHFileInfo; begin Result := SHGetFileInfo(PChar(GetDesktopPIDL), 0, FileInfo, SizeOf(FileInfo), SHGFI_PIDL or SHGFI_SYSICONINDEX or ILarge[Large]); end; procedure CreateShellLink(const FileName, ShortcutTo, WorkingDir, Parameters, IconFileName: string; IconIndex: Integer); var Obj: IUnknown; SL: IShellLink; PF: IPersistFile; WS: WideString; begin Obj := CreateComObject(CLSID_ShellLink); SL := Obj as IShellLink; SL.SetPath(PChar(ShortcutTo)); if Parameters <> '' then SL.SetArguments(PChar(Parameters)); if IconFilename <> '' then SL.SetIconLocation(PChar(IconFilename), IconIndex); if WorkingDir <> '' then SL.SetWorkingDirectory(PChar(WorkingDir)); PF := Obj as IPersistFile; WS := Filename; PF.Save(POleStr(WS), True); end; function GetAssociatedIcon(const FileName: string): HICON; var ID: Word; begin ID := 1; Result := ExtractAssociatedIcon(HInstance, PChar(FileName), ID); end; function ExtractShellIcon(Index: Integer; Large: Boolean): HICON; var LargeIconHandle, SmallIconHandle: HICON; begin LargeIconHandle := 0; SmallIconHandle := 0; if ExtractIconEx('shell32.dll', Index, LargeIconHandle, SmallIconHandle, 1) = 2 then begin if Large then begin Result := LargeIconHandle; DestroyIcon(SmallIconHandle); end else begin DestroyIcon(LargeIconHandle); Result := SmallIconHandle; end; end else begin DestroyIcon(LargeIconHandle); DestroyIcon(SmallIconHandle); Result := 0; end; end; function PathAddBackSlash(const Path: string): string; var Len: Integer; begin Result := Path; Len := Length(Path); if (Len > 1) and ((Path[Len] <> '\') or (ByteType(Path, Len) <> mbSingleByte)) then Result := Path + '\'; end; function PathRemoveBackSlash(const Path: string): string; var Len: Integer; begin Result := Path; Len := Length(Path); if (Len > 1) and (Path[Len] = '\') and (ByteType(Path, Len) = mbSingleByte) then Delete(Result, Len, 1); end; function GetFileTypeName(const Ext: string): string; var FileInfo: TSHFileInfo; begin SHGetFileInfo(PChar('*.' + Ext), FILE_ATTRIBUTE_NORMAL, FileInfo, SizeOf(FileInfo), SHGFI_USEFILEATTRIBUTES or SHGFI_TYPENAME); Result := FileInfo.szTypeName; end; function ShellExecuteCommand(const Operation: string; const FileName: string): Boolean; begin Result := ShellExecute(Application.Handle, PChar(Operation), PChar(FileName), nil, nil, SW_SHOW) > 32; end; function ShellExecutePIDL(PIDL: PItemIDList): Boolean; var ShellExecuteInfo: TShellExecuteInfo; begin FillChar(ShellExecuteInfo, SizeOf(ShellExecuteInfo), 0); with ShellExecuteInfo do begin cbSize := SizeOf(ShellExecuteInfo); wnd := Application.Handle; fMask := SEE_MASK_IDLIST or SEE_MASK_INVOKEIDLIST; lpIDList := PIDL; nShow := SW_SHOW; end; Result := ShellExecuteEx(@ShellExecuteInfo); end; function StrRetToString(PIDL: PItemIDList; const StrRet: TStrRet): string; { note: Windows 2000 has StrRetToStr and StrRetToBuf } begin case StrRet.uType of STRRET_WSTR: begin Result := StrRet.pOleStr; ShellMalloc.Free(StrRet.pOleStr); end; STRRET_OFFSET: if Assigned(PIDL) then Result := PChar(PIDL) + StrRet.uOffset else Result := ''; STRRET_CSTR: Result := StrRet.cStr; end; end; function ValueInFlags(Value, Flags: Cardinal): Boolean; begin Result := (Value <> 0) and ((Flags or Value) = Flags) end; function GetModule(const Name: string): THandle; var OldError: LongInt; begin OldError := SetErrorMode(SEM_NOOPENFILEERRORBOX); Result := GetModuleHandle(PChar(Name)); if Result < HINSTANCE_ERROR then Result := LoadLibrary(PChar(Name)); if (Result > 0) and (Result < HINSTANCE_ERROR) then Result := 0; SetErrorMode(OldError); end; function GetStrFromModule(Module: THandle; ResIdentifier: LongInt): string; var Buffer: array[0..200] of Char; begin Buffer[0] := #0; LoadString(Module, ResIdentifier, Buffer, SizeOf(Buffer)); Result := Buffer; end; const shlwapi = 'shlwapi.dll'; {$IFDEF AS_VCL35} {$EXTERNALSYM StrFormatByteSizeA} function StrFormatByteSizeA; external shlwapi name 'StrFormatByteSizeA'; {$EXTERNALSYM StrFormatByteSizeW} function StrFormatByteSizeW; external shlwapi name 'StrFormatByteSizeW'; {$EXTERNALSYM StrFormatByteSize} function StrFormatByteSize; external shlwapi name 'StrFormatByteSizeW'; {$ELSE} function StrFormatByteSizeA; external shlwapi name 'StrFormatByteSizeA'; function StrFormatByteSizeW; external shlwapi name 'StrFormatByteSizeW'; function StrFormatByteSize; external shlwapi name 'StrFormatByteSizeW'; {$ENDIF} function ByteSizeToFormatStr(ByteSize: LongInt): string; var Buffer: array[0..79] of Char; begin Result := StrFormatByteSize(ByteSize, Buffer, SizeOf(Buffer)); end; function ShortPathToLongPath(const FileName: string): string; var PIDL: PItemIDList; begin PIDL := PathToPIDL(FileName); Result := GetPIDLPath(PIDL); FreePIDL(PIDL); end; var ShellModule: THandle; const ShellDllName = 'shell32.dll'; function GetShellModule: THandle; begin if ShellModule = 0 then ShellModule := GetModule(ShellDllName); Result := ShellModule; end; function GetShellString(ResIdentifier: LongInt): string; begin Result := GetStrFromModule(GetShellModule, ResIdentifier); end; {$IFDEF AS_VCL35} {$EXTERNALSYM SHQueryRecycleBinA} function SHQueryRecycleBinA; external shell32 name 'SHQueryRecycleBinA'; {$EXTERNALSYM SHQueryRecycleBinW} function SHQueryRecycleBinW; external shell32 name 'SHQueryRecycleBinW'; {$EXTERNALSYM SHQueryRecycleBin} function SHQueryRecycleBin; external shell32 name 'SHQueryRecycleBinW'; {$ELSE} function SHQueryRecycleBinA; external shell32 name 'SHQueryRecycleBinA'; function SHQueryRecycleBinW; external shell32 name 'SHQueryRecycleBinW'; function SHQueryRecycleBin; external shell32 name 'SHQueryRecycleBinW'; {$ENDIF} {$IFDEF AS_VCL35} {$EXTERNALSYM SHEmptyRecycleBinA} function SHEmptyRecycleBinA; external shell32 name 'SHEmptyRecycleBinA'; {$EXTERNALSYM SHEmptyRecycleBinW} function SHEmptyRecycleBinW; external shell32 name 'SHEmptyRecycleBinW'; {$EXTERNALSYM SHEmptyRecycleBin} function SHEmptyRecycleBin; external shell32 name 'SHEmptyRecycleBinW'; {$ELSE} function SHEmptyRecycleBinA; external shell32 name 'SHEmptyRecycleBinA'; function SHEmptyRecycleBinW; external shell32 name 'SHEmptyRecycleBinW'; function SHEmptyRecycleBin; external shell32 name 'SHEmptyRecycleBinW'; {$ENDIF} initialization OLECheck(ShGetMalloc(ShellMalloc)); OLECheck(SHGetDesktopFolder(DesktopFolder)); finalization FreePIDL(DesktopPIDL); DesktopFolder := nil; ShellMalloc := nil; if ShellModule <> 0 then FreeLibrary(ShellModule); end.
// Windows' FNT/FON unit fi_winfnt; interface implementation uses fi_common, fi_info_reader, fi_utils, classes, streamex, sysutils; const MZ_MAGIC = $5a4d; NE_MAGIC = $454e; // New Executable PE_MAGIC = $4550; // Portable Executable { Reading of PE executables is not implemented yet, since there are no such fonts to test: all FONs in C:\Windows\Fonts are in NE format, as well as everything I found on the Internet. } FNT_V1 = $100; FNT_V2 = $200; FNT_V3 = $300; MAX_COPYRIGHT_LEN = 60; type TFNTHeader = packed record version: Word; fileSize: LongWord; copyright: array [0..MAX_COPYRIGHT_LEN - 1] of Char; fontType, pointSize, vres, hres, ascent, internalLeading, externalLeading: Word; italic, underline, strikeout: Byte; weight: Word; Charset: Byte; pixWidth, pixHeight: Word; pitchAndFamily: Byte; avgWidth, maxWidth: Word; firstChar, lastChar, defaultChar, breakChar: Byte; BytesPerRow: Word; deviceOffset, faceNameOffset, bitsPointer, bitsOffset: LongWord; reserved: Byte; flags: LongWord; aSpace, bSpace, cSpace: Word; colorTableOffset: LongWord; reserved1: array[0..15] of Byte; end; {$IF SIZEOF(TFNTHeader) <> 148} {$FATAL Unexpected size of TFNTHeader} {$ENDIF} procedure ReadFNTInfo(stream: TStream; var info: TFontInfo); var start: Int64; version: Word; copyright: String; italic: Boolean; weight: Word; begin start := stream.Position; version := stream.ReadWordLE; if (version <> FNT_V1) and (version <> FNT_V2) and (version <> FNT_V3) then raise EStreamError.Create('Not a FNT file'); stream.Seek(SizeOf(TFNTHeader.fileSize), soCurrent); SetLength(copyright, MAX_COPYRIGHT_LEN); stream.ReadBuffer(copyright[1], MAX_COPYRIGHT_LEN); info.copyright := TrimRight(copyright); stream.Seek(start + SizeUInt(@TFNTHeader(NIL^).italic), soBeginning); italic := stream.ReadByte = 1; stream.Seek(start + SizeUInt(@TFNTHeader(NIL^).weight), soBeginning); weight := stream.ReadWordLE; if italic then begin if weight = FONT_WEIGHT_REGULAR then info.style := 'Italic' else info.style := GetWeightName(weight) + ' Italic'; end else info.style := GetWeightName(weight); stream.Seek( start + SizeUInt(@TFNTHeader(NIL^).faceNameOffset), soBeginning); stream.Seek(start + stream.ReadDWordLE, soBeginning); info.family := ReadCStr(stream); if (weight = FONT_WEIGHT_REGULAR) and not italic then info.fullName := info.family else info.fullName := info.family + ' ' + info.style; info.format := 'FNT ' + IntToStr(version shr 8); end; procedure ReadFNTFromNE(stream: TStream; var info: TFontInfo); const // Position of the offset to the resource table RES_TABLE_OFFSET_POS = 36; END_TYPES = 0; // Size if the Reserved field in the TYPEINFO structure TYPEINFO_RESERVED_SIZE = SizeOf(LongWord); RT_FONT = $8008; // Total size of the NAMEINFO structure NAMEINFO_SIZE = 12; var start: Int64; resTableOffset: Int64; sizeShift: Word; typeId, itemCount: Word; fontCount: Word = 0; begin start := stream.Position - SizeOf(Word); stream.Seek(start + RES_TABLE_OFFSET_POS, soBeginning); resTableOffset := start + stream.ReadWordLE; stream.Seek(resTableOffset, soBeginning); sizeShift := stream.ReadWordLE; while TRUE do begin // Read TYPEINFO tables typeId := stream.ReadWordLE; if typeId = END_TYPES then break; itemCount := stream.ReadWordLE; if typeId = RT_FONT then begin if itemCount = 0 then raise EStreamError.Create('RT_FONT TYPEINFO is empty'); fontCount := itemCount; stream.Seek(TYPEINFO_RESERVED_SIZE, soCurrent); break; end; stream.Seek( TYPEINFO_RESERVED_SIZE + itemCount * NAMEINFO_SIZE, soCurrent); end; if fontCount = 0 then raise EStreamError.Create('No RT_FONT entries in file'); stream.Seek(stream.ReadWordLE shl sizeShift, soBeginning); ReadFNTInfo(stream, info); // We don't set fontCount as TFontInfo.numFonts, since multiple // FNTs in FON are normally different sizes of the same font. end; procedure ReadWinFNTInfo(stream: TStream; var info: TFontInfo); const HEADER_OFFSET_POS = 60; var magic: Word; headerOffset: LongWord; exeFormat: Word; begin magic := stream.ReadWordLE; if magic = MZ_MAGIC then begin stream.Seek(HEADER_OFFSET_POS - SizeOf(magic), soCurrent); // This field named as eLfanew in some docs headerOffset := stream.ReadWordLE; stream.Seek(headerOffset, soBeginning); exeFormat := stream.ReadWordLE; if exeFormat = NE_MAGIC then begin ReadFNTFromNE(stream, info); exit; end; if exeFormat = PE_MAGIC then raise EStreamError.Create('PE executables are not supported yet'); raise EStreamError.CreateFmt( 'Unsupported executable format 0x%.2x', [exeFormat]); end; if (magic = FNT_V1) or (magic = FNT_V2) or (magic = FNT_V3) then begin stream.Seek(-SizeOf(magic), soCurrent); ReadFNTInfo(stream, info); exit; end; raise EstreamError.Create('Not a Windows font'); end; initialization RegisterReader(@ReadWinFNTInfo, ['.fon', '.fnt']); end.
unit FMX.ISFloatMenu; interface uses System.SysUtils, System.Classes, System.Types, System.UITypes, System.DateUtils, System.Generics.Collections, FMX.Utils, FMX.Types, FMX.Controls, FMX.Objects, FMX.StdCtrls, FMX.Graphics, FMX.MultiResBitmap, FMX.Ani, FMX.Effects, System.Actions, FMX.ActnList, FMX.Layouts, FMX.Filter.Effects, System.Rtti, FMX.IS_Base, FMX.ISIcons; Type TIS_Floatmenu = Class; TIS_Hint = Class(TIS_Control) Private FTextColor : TAlphaColor; FTextFont : TFont; FText : String; FTextAlign : TTextAlign; FTimer : TTimer; procedure SetText (const Value: String); procedure SetTextColor(const Value: TAlphaColor); procedure SetTextFont (const Value: TFont); procedure SetTextAlign(const Value: TTextAlign); Protected Procedure Paint; Override; Public Constructor Create(aOwner : TComponent); Override; Procedure Show; procedure Hide(Sender : TObject); Property Text : String Read FText Write SetText; Property TextFont : TFont Read FTextFont Write SetTextFont; Property TextColor : TAlphaColor Read FTextColor Write SetTextColor; Property TextAlign : TTextAlign Read FTextAlign Write SetTextAlign; End; [ComponentPlatformsAttribute (pidWin32 or pidWin64 or pidOSX32 or pidiOSDevice32 or pidiOSDevice64 or pidAndroid)] TIS_FloatOption = Class(TIS_CircleIcon) Private FHint : TIS_Hint; FAni : TFloatAnimation; FOpen : Boolean; FFloatMenu : TIS_FloatMenu; FShowHint : Boolean; function GetText : String; function GetTextBackground : TAlphaColor; function GetTextColor : TAlphaColor; function GetTextFont : TFont; function GetTextAlign : TTextAlign; function GetHintColor : TAlphaColor; procedure SetText (const Value: String); procedure SetTextBackground(const Value: TAlphaColor); procedure SetTextColor (const Value: TAlphaColor); procedure SetTextFont (const Value: TFont); procedure SetTextAlign (const Value: TTextAlign); procedure SetHintColor (const Value: TAlphaColor); procedure FinishAnimation (Sender: TObject); Protected procedure Loaded; Override; Procedure Clicked; Override; Property Open : Boolean Read FOpen Write FOpen; Property FloatMenu : TIS_FloatMenu Read FFloatMenu Write FFloatMenu; Public Constructor Create(aOwner : TComponent); Override; Procedure HideHint; Published Property ShowHint : Boolean Read FShowHint Write FShowHint; Property HintColor : TAlphaColor Read GetHintColor Write SetHintColor; Property Text : String Read GetText Write SetText; Property TextColor : TAlphaColor Read GetTextColor Write SetTextColor; Property TextFont : TFont Read GetTextFont Write SetTextFont; Property TextBackground : TAlphaColor Read GetTextBackground Write SetTextBackground; Property TextAlign : TTextAlign Read GetTextAlign Write SetTextAlign; End; TIS_OptionItem = class(TCollectionItem) Private FOption : TIS_FloatOption; Protected function GetDisplayName: String; override; Public constructor Create(Collection: TCollection); Override; published property Opcao : TIS_FloatOption read FOption write FOption; end; TIS_Options = class(TCollection) Private FImageMenu : TIS_FloatMenu; function GetItem(Index: Integer): TIS_OptionItem; procedure SetItem(Index: Integer; Value: TIS_OptionItem); Protected function GetOwner: TPersistent; override; Public constructor Create; function Add: TIS_OptionItem; property Items[Index: Integer]: TIS_OptionItem read GetItem write SetItem; end; [ComponentPlatformsAttribute (pidWin32 or pidWin64 or pidOSX32 or pidiOSDevice32 or pidiOSDevice64 or pidAndroid)] TIS_FloatMenu = Class(TIS_CircleIcon) Private FAnimate : Boolean; FAnimateTime : Single; FSpace : Single; FOptions : TIS_Options; FOpen : Boolean; Protected procedure DoCloseMenu; Virtual; procedure DoOpenMenu; Virtual; Procedure Clicked; Override; Public Constructor Create(aOwner : TComponent); Override; Procedure OpenMenu; Procedure CloseMenu; Published Property Animate : Boolean Read FAnimate Write FAnimate; Property AnimateTime : Single Read FAnimateTime Write FAnimateTime; Property Options : TIS_Options Read FOptions Write FOptions; Property Space : Single Read FSpace Write FSpace; End; Procedure Register; implementation Procedure Register; Begin RegisterComponents('Imperium Software', [TIS_FloatMenu, TIS_FLoatOption]); End; // TIS_OptionItem constructor TIS_OptionItem.Create(Collection: TCollection); Begin Inherited; FOption := TIS_FloatOption.Create(FOption); End; function TIS_OpTionItem.GetDisplayName: String; Begin Result := 'Option'+(ID+1).ToString; End; // TIS_Options Constructor TIS_Options.Create; begin inherited Create(TIS_OptionItem); end; Function TIS_Options.Add : TIS_OptionItem; begin Result := TIS_OptionItem(inherited Add); end; Function TIS_Options.GetItem(Index: Integer): TIS_OptionItem; begin Result := TIS_OptionItem(inherited GetItem(Index)); end; Procedure TIS_Options.SetItem(Index: Integer; Value: TIS_OptionItem); begin inherited SetItem(Index, Value); end; function TIS_Options.GetOwner: TPersistent; begin Result := FImageMenu; end; { TIS_Hint } constructor TIS_Hint.Create(aOwner: TComponent); begin inherited; Width := 150; Height := 26; Color := TAlphaColorRec.Gray; Text := 'Hint...'; TextColor := TAlphaColorRec.Black; FTimer := TTimer.Create(Self); FTimer.Interval := 4003; FTimer.OnTimer := Hide; FTimer.Enabled := False; end; procedure TIS_Hint.Show; begin Visible := True; Opacity := 1; FTimer.Enabled := True; BringToFront; end; procedure TIS_Hint.Hide(Sender: TObject); begin FTimer.Enabled := False; TAnimator.AnimateFloat(Self, 'Opacity', 0, 1); end; procedure TIS_Hint.Paint; Var Save : TCanvasSaveState; begin inherited; Save := Canvas.SaveState; Canvas.Fill.Color := TextColor; Canvas.Font.Assign(TextFont); Canvas.FillText(TRectF.Create(0, 0, Width-1, Height-1), Text, False, Opacity, [], TextAlign); Canvas.RestoreState(Save); end; procedure TIS_Hint.SetText(const Value: String); begin FText := Value; Repaint; end; procedure TIS_Hint.SetTextAlign(const Value: TTextAlign); begin FTextAlign := Value; Repaint; end; procedure TIS_Hint.SetTextColor(const Value: TAlphaColor); begin FTextColor := Value; Repaint; end; procedure TIS_Hint.SetTextFont(const Value: TFont); begin FTextFont := Value; Repaint; end; { TIS_FloatOption } procedure TIS_FloatOption.Clicked; begin inherited; FloatMenu.CloseMenu; end; constructor TIS_FloatOption.Create(aOwner: TComponent); begin inherited; FHint := TIS_Hint .Create(Self); FAni := TFloatAnimation.Create(Self); FAni.Parent := Self; FAni.PropertyName := 'Position.Y'; FAni.OnFinish := FinishAnimation; FAni.Stored := False; FHint.Stored := False; FShowHint := False; end; Procedure TIS_FloatOption.FinishAnimation(Sender : TObject); Begin if Not FOpen then Begin Visible := False; End Else Begin If FShowHint Then Begin FHint.Parent := Self.Parent; FHint.Position.Y := Position.Y + (Height - FHint.Height)/2; FHint.Position.X := Position.X - 170; FHint.Show; End; End; End; function TIS_FloatOption.GetHintColor: TAlphaColor; begin Result := FHint.Color; end; function TIS_FloatOption.GetText: String; begin Result := FHint.Text; end; function TIS_FloatOption.GetTextAlign: TTextAlign; begin Result := FHint.TextAlign; end; function TIS_FloatOption.GetTextBackground: TAlphaColor; begin Result := FHint.Color; end; function TIS_FloatOption.GetTextColor: TAlphaColor; begin Result := FHint.textColor; end; function TIS_FloatOption.GetTextFont: TFont; begin Result := FHint.TextFont; end; procedure TIS_FloatOption.HideHint; begin FHint.Visible := False; end; procedure TIS_FloatOption.Loaded; begin inherited; if not (csDesigning in ComponentState) then Position.Y := -1000; end; procedure TIS_FloatOption.SetHintColor(const Value: TAlphaColor); begin FHint.Color := Value; end; procedure TIS_FloatOption.SetText(const Value: String); begin FHint.Text := Value; end; procedure TIS_FloatOption.SetTextAlign(const Value: TTextAlign); begin FHint.TextAlign := Value; end; procedure TIS_FloatOption.SetTextBackground(const Value: TAlphaColor); begin FHint.Color := Value; end; procedure TIS_FloatOption.SetTextColor(const Value: TAlphaColor); begin FHint.TextColor := Value; end; procedure TIS_FloatOption.SetTextFont(const Value: TFont); begin FHint.TextFont.Assign(Value); end; { TIS_FloatMenu } procedure TIS_FloatMenu.DoOpenMenu; Var x : Integer; O : TIS_FloatOption; Begin FOpen := True; for x := 0 to Options.Count-1 do Begin O := Options.Items[x].FOption; O.Parent := Parent; O.FloatMenu := Self; O.Position.X := Position.X + (Width -O.Width )/2; O.Position.Y := Position.Y + (Height-O.Height)/2; O.Visible := True; O.Open := True; O.BringToFront; O.FAni.StartValue := O.Position.Y; O.FAni.StopValue := O.Position.Y - (Height+FSpace) * (X+1); O.FAni.Duration := FAnimateTime; O.FAni.Start; End; BringToFront; End; procedure TIS_FloatMenu.DoCloseMenu; Var x : Integer; O : TIS_FloatOption; Begin FOpen := False; for x := 0 to Options.Count-1 do Begin O := Options.Items[x].FOption; O.HideHint; O.Open := False; O.FAni.StartValue := O.Position.Y; O.FAni.StopValue := Position.Y + (Height-O.Height)/2; O.FAni.Start; End; End; procedure TIS_FloatMenu.OpenMenu; begin DoOpenMenu; end; procedure TIS_FloatMenu.CloseMenu; begin DoCloseMenu; end; procedure TIS_FloatMenu.Clicked; begin inherited; if Not FOpen then Begin if FAnimate then TAnimator.AnimateFloat(Self.FIcon, 'RotationAngle', 90, FAnimateTime); DoOpenMenu; End Else Begin if FAnimate then TAnimator.AnimateFloat(Self.FIcon, 'RotationAngle', 0, FAnimateTime); DoCloseMenu; end; Inherited; end; constructor TIS_FloatMenu.Create(aOwner: TComponent); begin inherited; RotationAngle := 0; FSpace := 10; FOpen := False; Options := TIS_Options.Create; ShowShadow := True; Color := TAlphaColorRec.Cadetblue; IconColor := TAlphaColorRec.White; FAnimate := True; FAnimateTime := 0.3; end; end.
unit uPaymentCard; interface uses ADODB, uMRTraceControl, uPayment, uMRPCCharge, uMRPinPad, uPCCIntegration, uCCMercuryIntegration, uCreditCardFunction, Classes, uOperationSystem, DbClient, ProcessorInterface, SimpleProcessorFactory, SimpleDeviceFactory, DeviceIntegrationInterface; const SERVICE_ORDER_PREFIX = 'SO'; type TPaymentCard = class(TPayment) private FProcessorType: Integer; FTroutD: String; FCardSwiped: WideString; FRefundID: Integer; FRefundDate: TDateTime; FRefundCardInt : TStringList; procedure NeedSwipe(Sender: TObject; var SwipedTrack: WideString; var Canceled: Boolean); procedure SucessFullSwipe(Sender: TObject; const ACardNumber, ACardMember, ACardExpireDate: WideString); procedure NeedTroutD(Sender: TObject; var ATrouD, ARefNo, AAuthCode: WideString; var ACanceled: Boolean); function GetRefundInfo : Boolean; function ReturnErrorMsg(AIDError:String):String; procedure printDeclinedReceipt(); protected indexProcessor: Integer; indexDevice: Integer; processor: IProcessor; device: IDeviceIntegration; factoryProcessor: TProcessorFactory; factoryDevice: TDeviceFactory; FPinpad: TMRPinpad; function VoidSaleTransaction(): Boolean; procedure BeforeProcessPayment; override; procedure BeforeDeletePayment; override; // procedure FillParameters(FCmdPayment : TADOCommand); override; procedure SetProperties(ADSPayment: TADODataSet); override; procedure MoveValues(); function GetAutoProcess: Boolean; override; function GetSQLFields: String; override; function CanDelete: Boolean; override; function getTicketNumber: String; procedure LoadProcessorParameters(); public constructor Create(AADOConnection: TADOConnection; ATraceControl: TMrTraceControl); override; destructor Destroy; override; property CardSwiped : WideString read FCardSwiped write FCardSwiped; property RefundID : Integer read FRefundID write FRefundID; property RefundDate : TDateTime read FRefundDate write FRefundDate; end; implementation uses SysUtils, uSystemConst, ufrmPCCharge, uFrmPCCSwipeCard, uNumericFunctions, uMsgBox, Math, Registry, Windows, Dialogs, uDocumentInfo, ufrmPCVoid, DateUtils,uDebugFunctions, DB, frmCardNumberDialogView, PrintReceiptDeclinedView; { TPaymentCard } destructor TPaymentCard.Destroy; begin if Assigned(fPinPad) then begin freeAndNil(fPinPad); end; if Assigned(FRefundCardInt) then FreeAndNil(FRefundCardInt); inherited; end; function TPaymentCard.getTicketNumber: String; begin case DocumentType of dtInvoice: Result := IntToStr(FIDPreSale); dtServiceOrder: Result := SERVICE_ORDER_PREFIX + IntToStr(FIDPreSale); end; end; { procedure TPaymentCard.FillParameters(FCmdPayment: TADOCommand); begin inherited; FTraceControl.TraceIn(Self.ClassName + '.FillParameters'); // Antonio 11/30/2015 - MR-263 if ( processResult <> nil ) then begin if ( processResult.ChipMethod = 'chip') then begin FCmdPayment.Parameters.ParamByName('NumMeioQuitPrevisto').Value := 'A:'+ FAuthorization + ' R:' + FTroutD + ' L:' + FLastDigits + ' M:' + FMerchantID + ' E:' + FEntryMethod + ' D:' + FDate + ' T:' + FTime + ' C:' + 'chip' + ' P:' + FAppLabel + ' AID:' + FAID + ' TVR:' + FTVR + ' IAD:' + FIAD + ' TSI:' + FTSI + ' ARC:' + FARC + ' CVM:' + FCVM+ ' TC:'+ FAppLabelTranCode; end else begin FCmdPayment.Parameters.ParamByName('NumMeioQuitPrevisto').Value := 'A:'+ FAuthorization + ' R:' + FTroutD + ' L:' + FLastDigits + ' M:' + FMerchantID + ' E:' + FEntryMethod + ' D:' + FDate + ' T:' + FTime + ' C:' + ' P:' + FAppLabel end; end; FTraceControl.TraceOut; end; } function TPaymentCard.GetSQLFields: String; begin Result := (inherited GetSQLFields) + ',NumMeioQuitPrevisto'; FTraceControl.TraceOut; end; procedure TPaymentCard.NeedSwipe(Sender: TObject; var SwipedTrack: WideString; var Canceled: Boolean); var FrmSC: TFrmPCCSwipeCard; iIDMeioPag : Integer; begin FrmSC := TFrmPCCSwipeCard.Create(nil); try Canceled := not FrmSC.Start(SwipedTrack, iIDMeioPag); //Trocar o ID do Meio Pag pelo que foi feito no swipe if (not Canceled) and (iIDMeioPag <> -1) then IDPaymentType := iIDMeioPag; finally FreeAndNil(FrmSC); end; FTraceControl.TraceOut; end; procedure TPaymentCard.BeforeProcessPayment; begin inherited; FTraceControl.TraceIn(Self.ClassName + '.BeforeProcessPayment'); if GetAutoProcess then begin factoryDevice := TDeviceFactory.Create(); device := factoryDevice.CreateDevice(indexDevice); device.SetProcessor(processor); device.SetPinPad(FPinpad); // ... this method will be overrided by specialization... ( credit, debit, prepaid ) end; { //##NEWCARD if GetAutoProcess then begin case FProcessorType of PROCESSOR_MERCURY, PROCESSOR_WORLDPAY : begin FAuthorization := ''; FTroutD := ''; FTransactResult := DoMercury; processorMessage := processResult.Msg; salePaymentValue := FPaymentValue; // get real amount authorized from Mercury // Antonio 09/16/2015 ( under test) FPaymentValue := processResult.Authorize; FTroutD := processResult.RefNo; FLastDigits := processResult.LastDigits; FCardType := processResult.CardType; setIdMeioPrevisto(FCardType); FMerchantID := processResult.MerchantID; FEntryMethod := processResult.EntryMethod; // to EMV response chipMethod = chip if ( lowercase(processResult.ChipMethod) = 'chip' ) then begin FDate := processResult.DateTransaction; FTime := processResult.TimeTransaction; FAppLabel := processResult.AppLabel; FAID := processResult.AppLabelAID; FTVR := processResult.AppLabelTVR; FIAD := processResult.AppLabelIAD; FTSI := processResult.AppLabelTSI; FARC := processResult.AppLabelARC; FCVM := processResult.AppLabelCVM; FAppLabelTranCode := processResult.AppLabelTranCode; //FAppLabelRecordNo := processResult.AppLabelRecordNo; end; end; end; if not FTransactResult then begin // Antonio 09/22/2015 case processResult.TransactionReturn of ttrDeclined: begin // Alex 09/25/2015 If ( ( processResult is TCCreditDSIEMVx ) or ( processResult is TCDebitDSIEMVx ) ) Then printDeclinedReceipt(); end; end; raise Exception.Create('CARD NOT CHARGED!_' + processorMessage); // Antonio 2013 Nov 6, MR-84 end; end; } FTraceControl.TraceOut; end; { procedure TPaymentCard.PreparePCC; begin FTraceControl.TraceIn(Self.ClassName + '.PreparePCC'); FPCCT.Path := FPCCharge.Path; FPCCT.User := FPCCharge.User; FPCCT.TimeOut := FPCCharge.TimeOut; FPCCT.Multi := IntToStr(Byte(FPCCharge.MultTrans)); FPCCT.LastValidDate := IntToStr(FPCCharge.LastDate); FPCCT.PrintReceipts := IntToStr(FPCCharge.PrintNum); FPCCT.Processor := FPCCharge.Processor; FPCCT.Port := FPCCharge.Port; FPCCT.IPAddress := FPCCharge.Server; FPCCT.MerchantNumber := FPCCharge.MercantAcc; FPCCT.OnNeedSwipe := NeedSwipe; FPCCT.AfterSucessfullSwipe := SucessFullSwipe; FPCCT.OnNeedTroutD := nil; FTraceControl.TraceOut; end; } procedure TPaymentCard.SucessFullSwipe(Sender: TObject; const ACardNumber, ACardMember, ACardExpireDate: WideString); begin // Adicionar neste evento qualquer código que precise ser executado após // uma tentativa bem sucedida de leitura do cartão FTraceControl.TraceIn(Self.ClassName + '.SucessFullSwipe'); FTraceControl.TraceOut; end; { procedure TPaymentCard.MoveValues(); begin FAuthorization := processResult.AuthCode; FPaymentValue := processResult.Authorize; FTroutD := processResult.RefNo; FLastDigits := processResult.LastDigits; FCardType := processResult.CardType; setIdMeioPrevisto(FCardType); FMerchantID := processResult.MerchantID; FEntryMethod := processResult.EntryMethod; // to EMV response chipMethod = chip if ( lowercase(processResult.ChipMethod) = 'chip' ) then begin FDate := processResult.DateTransaction; FTime := processResult.TimeTransaction; FAppLabel := processResult.AppLabel; FAID := processResult.AppLabelAID; FTVR := processResult.AppLabelTVR; FIAD := processResult.AppLabelIAD; FTSI := processResult.AppLabelTSI; FARC := processResult.AppLabelARC; FCVM := processResult.AppLabelCVM; FAppLabelTranCode := processResult.AppLabelTranCode; //FAppLabelRecordNo := processResult.AppLabelRecordNo; end; End; } (* procedure TPaymentCard.SetProperties(ADSPayment: TADODataSet); var Field: String; pA, pR, pL, pM, pE, pD, pT, pC,pP, pAid, pIad, pTvr, pTsi, pArc, pCvm: Integer; begin inherited; FTraceControl.TraceIn(Self.ClassName + '.SetProperties'); if ( not ADSPayment.fieldByName('NumMeioQuitPrevisto').IsNull ) then begin Field := ADSPayment.FieldByName('NumMeioQuitPrevisto').Value; //showmessage(' field : ' + field); pA := Pos('A:', Field); pR := Pos('R:', Field); pL := Pos('L:', Field); FAuthorization := copy(Field, pA+2, pR-1); FTroutD := copy(Field, pR+2, pL-1); FLastDigits := copy(Field, pL+2, pM-1);// Length(Field)) was replaced to pM-1; // Antonio 09/30/2015 FMerchantID := copy(field, pM+2, pE-1); FEntryMethod := copy(field, pE+2, pD-1); FDate := copy(field, pD+2, pT-1); FTime := copy(field, pT+2, pC-1); FAppLabel := copy(field, pP+2, pAid-1); end; FTraceControl.TraceOut; end; *) function TPaymentCard.GetAutoProcess: Boolean; begin FTraceControl.TraceIn(Self.ClassName + '.GetAutoProcess'); //amfsouza Result := ( FProcessorType <> 0 ) and ( FProcessorType <> 3 ); FTraceControl.TraceOut; end; constructor TPaymentCard.Create(AADOConnection: TADOConnection; ATraceControl: TMrTraceControl); var buildInfo: String; begin inherited Create(AADOConnection, ATraceControl); FRemovePaymentWhenDeleting := False; // Alex 10/05/2015 LoadProcessorParameters(); end; function TPaymentCard.CanDelete: Boolean; begin FTraceControl.TraceIn(Self.ClassName + '.CanDelete'); Result := True; // Alex 10/05/2015 False; FTraceControl.TraceOut; end; { function TPaymentCard.DoMercury: Boolean; begin Result := False; Result := ExecuteMercury; if Result then begin FAuthorization := processResult.AuthCode; FTroutD := processResult.RefNo; FLastDigits := processResult.LastDigits; end; FTraceControl.TraceOut; end; } { function TPaymentCard.ExecuteMercury: Boolean; begin FTraceControl.TraceIn(Self.ClassName + '.ExecuteMercury'); Result := MercuryResult; FTraceControl.TraceOut; end; } { function TPaymentCard.MercuryResult: Boolean; var sMsg: String; sMsg2 : String; begin FTraceControl.TraceIn(Self.ClassName + '.MercuryResult'); Result := False; sMsg := ''; sMsg2 := ''; try if FMercuryWidget <> nil then begin processResult := FMercuryWidget.getActiveTransaction(); sMsg2 := ReturnErrorMsg(FMercuryWidget.ErrorCode); case processResult.TransactionReturn of ttrSuccessfull: begin Result := True; sMsg := Format('%S'#13#10'Auth: %S'#13#10'RefNumber: %S'#13#10'RefDataD: %S', [processResult.Msg, processResult.ResultAuth, processResult.ResultRefNo, processResult.ResultAcqRefData]); end; ttrNotSuccessfull: begin sMsg := Format('%S'#13#10'Reason: %S', [processResult.Msg, processResult.ResultAuth]) + sMsg2; raise Exception.Create(sMsg); end; ttrError: begin sMsg := Format(#13#10'Error: %S', [processResult.Msg]) + sMsg2; raise Exception.Create(sMsg); end; ttrException: begin sMsg := Format(''#13#10'Error: %S', [processResult.Msg + ' ' + FErrorMsg]); raise Exception.Create(sMsg); end; end; end; except FErrorMsg := sMsg; end; FTraceControl.TraceOut; end; } { procedure TPaymentCard.NeedTroutD(Sender: TObject; var ATrouD, ARefNo, AAuthCode: WideString; var ACanceled: Boolean); var PCV: TfrmPCVoid; begin PCV := TfrmPCVoid.Create(nil); try ARefNo := IntToStr(RefundID); ACanceled := not PCV.Start(PaymentValue, ATrouD, ARefNo, AAuthCode, FRefundCardInt); finally PCV.Free; end; end; } { function TPaymentCard.GetRefundInfo : Boolean; var sResult : String; cInvoicePayment : Currency; begin FTraceControl.TraceIn(Self.ClassName + '.GetRefundInfo'); with TADODataSet.Create(nil) do try try Connection := FADOConnection; CommandText := 'SELECT NumMeioQuitPrevisto, ValorNominal FROM Fin_Lancamento WHERE IDPreSale = :IDPreSale'; Parameters.ParamByName('IDPreSale').Value := RefundID; Open; Result := not IsEmpty; if Result then begin if not Assigned(FRefundCardInt) then FRefundCardInt := TStringList.Create; FRefundCardInt.Clear; cInvoicePayment := 0; First; while not EOF do begin FRefundCardInt.Add(FieldByName('NumMeioQuitPrevisto').AsString); cInvoicePayment := cInvoicePayment + FieldByName('ValorNominal').AsCurrency; Next; end; if ABS(FPaymentValue) <> ABS(cInvoicePayment) then Result := False; end; Close; finally Free; end; except on E: Exception do begin Result := False; ErrorMsg := E.Message; FTraceControl.SaveTrace(FIDUser, E.Message, Self.ClassName); end; end; FTraceControl.TraceOut; end; } function TPaymentCard.VoidSaleTransaction: Boolean; // must be inside dsiClientX begin Result := (FRefundID <> 0) and (FPaymentValue < 0) and (DaysBetween(Trunc(PaymentDate), Trunc(FRefundDate)) = 0) and GetRefundInfo; end; function TPaymentCard.ReturnErrorMsg(AIDError: String): String; begin if (AIDError = '1') or (AIDError = '2') then Result := Format(#13#10'%S'#13#10'%S'#13#10'%S', ['Visa/MasterCard: 800-944-1111', 'Amex: 800-528-2121', 'Discover: 800-347-1111']) else Result := ''; end; { function TPaymentCard.getPaymentCard(arg_processor, arg_paymentType: Integer): TCCWidget; begin case (arg_paymentType) of PAYMENT_TYPE_CREDIT: begin result := TCCredit.Create(); end; PAYMENT_TYPE_DEBIT: begin result := TCDebit.Create(); end; PAYMENT_TYPE_GIFTCARD: begin result := TCPrePaid.Create(); end; end; end; } { procedure TPaymentCard.printDeclinedReceipt; var receipt: TPrintReceiptDeclined; dataField : String; sql: TSTringList; begin try sql := TStringList.Create; sql.Add('select ' + QuotedStr(processResult.MerchantID) + 'as MerchantID'); sql.add(', ' + QuotedStr(processResult.LastDigits) + ' as LastDigit'); sql.Add(', ' + QuotedStr(processResult.CardType) + ' as CardType'); sql.add(', ' + QuotedStr(processResult.InvoiceNo) + ' as Invoice'); sql.add(', ' + QuotedStr(floatToStr(processResult.Purchase)) + ' as Amount'); sql.Add(', ' + QuotedStr( processResult.DeclinedDateTime) + ' as SaleDateTime'); sql.add(', ' + QuotedStr(processResult.EntryMethod) + ' as EntryMethod'); dataField := 'A:' + FAuthorization + ' R:' + FTroutD + ' L:' + FLastDigits + ' M:' + FMerchantID + ' E:' + FEntryMethod + ' D:' + FDate + ' T:' + FTime + ' C:' + 'chip' + ' P:' + FAppLabel + ' AID:' + FAID + ' TVR:' + FTVR + ' IAD:' + FIAD + ' TSI:' + FTSI + ' ARC:' + FARC + ' CVM:' + FCVM+ ' TC:'+ FAppLabelTranCode; sql.add(', ' + QuotedStr( dataField ) + ' as NumMeioQuitPrevisto'); sql.add('from Sys_Module'); receipt := TPrintReceiptDeclined.Create(nil); receipt.start(FIDPreSale, RECEIPT_TYPE_DECLINED, sql.GetText); finally freeAndNil(receipt); freeAndNil(sql); end; end; } { procedure TPaymentCard.BeforeDeletePayment; var processAproved: Boolean; oldPaymentValue : Currency; begin processAproved := false; if ( processResult is TCCreditDSIEMVx ) then begin if ( FPaymentValue > 0 ) then begin TCCreditDSIEMVx(processResult).FIsSale := False; processAproved := TCCreditDSIEMVx(processResult).VoidSale(); end else if ( FPaymentValue < 0 ) then begin processAproved := TCCreditDSIEMVx(processResult).VoidReturn(); end; end else if ( processResult is TCCreditDSIPDCx ) then begin if ( FPaymentValue > 0 ) then begin processAproved := TCCreditDSIPDCx(processResult).VoidSale(); end else if ( FPaymentValue < 0 ) then begin processAproved := TCCreditDSIPDCx(processResult).VoidReturn(); end; end; if ( processAproved ) then begin MoveValues(); FPaymentValue := (-1) * FPaymentValue; InsertPayment(); end; inherited; end; } (* all below disabled { TPaymentDebitCard } procedure TPaymentDebitCard.BeforeProcessPayment; begin inherited; end; function TPaymentDebitCard.ExecuteMercury: Boolean; begin FTraceControl.TraceIn(Self.ClassName + '.ExecuteMercuryDebitCard'); if not Assigned(FMercuryWidget) then begin FMercuryWidget := getPaymentCard(fProcessorType, PAYMENT_TYPE_DEBIT); end; with TCDebit(FMercuryWidget) do begin //Manual entry card OnNeedSwipe := NeedSwipe; AfterSucessfullSwipe := AfterSucessfullSwipe; if VoidSaleTransation then OnNeedTroutD := NeedTroutD else OnNeedTroutD := nil; FPinPad.FBaudRate := Self.FPinPad.Baud; FPinPad.FComPort := Self.FPinPad.Comm; FPinPad.FTimeout := StrToInt(Self.FPinPad.TimeOut); Memo := PaymentMemo; OperatorID := IntToStr(FIDUser); InvoiceNo := getTicketNumber; RefNo := FMercuryWidget.InvoiceNo; Purchase := FPaymentValue; FCashBack := 0; // see this field Track2 := CardSwiped; TCDebit(FMercuryWidget).setDebitDevice(FProcessorType, fProcessingType); processResult := getActiveTransaction(); processResult.OnNeedSwipe := NeedSwipe; processResult.FCardSwiped := CardSwiped; if (FPaymentValue > 0) then begin ProcessSale; end else begin ProcessReturn; end; end; Result := inherited ExecuteMercury; FTraceControl.TraceOut; end; function TPaymentDebitCard.ExecutePCCharge: Boolean; var iAction: Integer; begin FTraceControl.TraceIn(Self.ClassName + '.ExecutePCCharge'); if (FPaymentValue > 0) then iAction := DEBIT_SALE else iAction := DEBIT_RETURN; if not FPCCT.RetailDebitCardPresent(MyFormatCur(Abs(FPaymentValue), '.'), '0.00', getTicketNumber, CardSwiped, iAction) then FErrorMsg := FPCCT.ErrorDesc; Result := inherited ExecutePCCharge; FTraceControl.TraceOut; end; function TPaymentDebitCard.GetPaymentType: Integer; begin Result := PAYMENT_TYPE_DEBIT; end; procedure TPaymentDebitCard.PreparePCC; begin inherited; FTraceControl.TraceIn(Self.ClassName + '.PreparePCC'); FPCCT.PinTimeOut := StrToIntDef(FPinPad.TimeOut, 0); FPCCT.PinEncryptMethod := StrToIntDef(FPinPad.EncryptMethod, 0); FPCCT.PinDevice := StrToIntDef(FPinPad.GetDevice, 0); FPCCT.PinBaud := FPinPad.Baud; FPCCT.PinDataBits := FPinPad.DataBits; FPCCT.PinParity := FPinPad.Parity; FPCCT.PinComm := FPinPad.Comm; FTraceControl.TraceOut; end; { TPaymentCreditCard } function TPaymentCreditCard.ExecutePCCharge: Boolean; var iMsgResult: Integer; begin FTraceControl.TraceIn(Self.ClassName + '.ExecutePCCharge'); if CardSwiped = '' then iMsgResult := MsgBox('Is the customer card present?_Total to be proccessed: ' + FormatCurr('#,##0.00', FPaymentValue), vbYesNoCancel) else iMsgResult := vbYes; case iMsgResult of vbYes: Result := ExecutePCChargeWithCard; vbNo: Result := ExecutePCChargeNoCard; vbCancel: FErrorMsg := 'Canceled.'; end; Result := inherited ExecutePCCharge; FTraceControl.TraceOut; end; function TPaymentCreditCard.GetPaymentType: Integer; begin Result := PAYMENT_TYPE_CARD; end; function TPaymentCreditCard.ExecutePCChargeNoCard: Boolean; begin FTraceControl.TraceIn(Self.ClassName + '.ExecutePCChargeNoCard'); with TfrmPCCharge.Create(nil) do try Result := Start(FPCCT, getTicketNumber, FPaymentValue); if not Result then FErrorMsg := 'Canceled by user.'; finally Free; end; FTraceControl.TraceOut; end; function TPaymentCreditCard.ExecutePCChargeWithCard: Boolean; begin FTraceControl.TraceIn(Self.ClassName + '.ExecutePCChargeWithCard'); Result := FPCCT.RetailCreditOrAutorizationCardPresent(MyFormatCur(Abs(FPaymentValue), '.'), getTicketNumber, CardSwiped, FPaymentValue < 0); if not Result then FErrorMsg := FPCCT.ErrorDesc; FTraceControl.TraceOut; end; function TPaymentCreditCard.ExecuteMercury: Boolean; var iMsgResult: Integer; begin case ( fProcessingType ) of PROCESSING_TYPE_DSICLIENTX: begin if CardSwiped = '' then iMsgResult := MsgBox('Is the customer card present?_Total to be proccessed: ' + FormatCurr('#,##0.00', FPaymentValue), vbYesNoCancel) else iMsgResult := vbYes; case iMsgResult of vbYes: Result := ExecuteMercuryWithCard; vbNo: Result := ExecuteMercuryNoCard; vbCancel: FErrorMsg := 'Canceled.'; end; end; PROCESSING_TYPE_DSIPDCX, PROCESSING_TYPE_DSIEMVUS: begin result := ExecuteMercuryWithCard; end; else begin raise Exception.Create('Dsi Device not found. See Client Parameter settings'); end; end; Result := inherited ExecuteMercury; FTraceControl.TraceOut; end; function TPaymentCreditCard.ExecuteMercuryNoCard: Boolean; var sCardNumber, sMemberName, sExpireDate, sStreetAddress, sZipCode, sCVV2 : String; begin with TfrmPCCharge.Create(nil) do try Result := StartMercury(sCardNumber, sMemberName, sExpireDate, sStreetAddress, sZipCode, sCVV2); if Result then begin if not Assigned(FMercuryWidget) then begin FMercuryWidget := getPaymentCard(fProcessorType, PAYMENT_TYPE_CREDIT); end; with TCCredit(FMercuryWidget) do begin //Manual entry card OnNeedSwipe := nil; AfterSucessfullSwipe := nil; if VoidSaleTransation then OnNeedTroutD := NeedTroutD else OnNeedTroutD := nil; Memo := PaymentMemo; OperatorID := IntToStr(FIDUser); InvoiceNo := getTicketNumber; RefNo := FMercuryWidget.InvoiceNo; Purchase := FPaymentValue; Tax := 0; AcctNo := sCardNumber; ExpDate := sExpireDate; Address := sStreetAddress; Zip := sZipCode; CustomerCode := sMemberName; Track2 := ''; CVVData := sCVV2; TCCredit(FMercuryWidget).setCreditDevice(fProcessorType, fProcessingType); if (FPaymentValue > 0) then begin ProcessSale; end else if VoidSaleTransation then begin VoidSale end else begin ProcessReturn; end end; end else FErrorMsg := 'Canceled by user.'; finally Free; end; FTraceControl.TraceOut; end; function TPaymentCreditCard.ExecuteMercuryWithCard: Boolean; begin if not Assigned(FMercuryWidget) then FMercuryWidget := getPaymentCard(fProcessorType, PAYMENT_TYPE_CREDIT); with TCCredit(FMercuryWidget) do begin AfterSucessfullSwipe := AfterSucessfullSwipe; if VoidSaleTransation then OnNeedTroutD := NeedTroutD else OnNeedTroutD := nil; Memo := PaymentMemo; OperatorID := IntToStr(FIDUser); InvoiceNo := getTicketNumber; RefNo := FMercuryWidget.InvoiceNo; Purchase := FPaymentValue; Tax := 0; FCardSwiped := CardSwiped; TCCredit(FMercuryWidget).setCreditDevice(fProcessorType, fProcessingType); processResult := getActiveTransaction(); processResult.OnNeedSwipe := NeedSwipe; ProcessResult.FCardSwiped := CardSwiped; if (FPaymentValue > 0) then ProcessSale else if VoidSaleTransation then begin VoidSale; end else ProcessReturn; end; FTraceControl.TraceOut; end; procedure TPaymentCreditCard.BeforeProcessPayment; begin inherited; end; { TPaymentPrePaid } procedure TPaymentPrePaid.BeforeProcessPayment; begin inherited; end; constructor TPaymentPrePaid.Create(AADOConnection: TADOConnection; ATraceControl: TMrTraceControl); begin inherited Create(AADOConnection, ATraceControl); end; function TPaymentPrePaid.ExecuteMercury: Boolean; var iMsgResult: Integer; begin FTraceControl.TraceIn(Self.ClassName + '.ExecuteMercury'); if CardSwiped = '' then iMsgResult := MsgBox('Is the customer card present?_Total to be proccessed: ' + FormatCurr('#,##0.00', FPaymentValue), vbYesNoCancel) else iMsgResult := vbYes; case iMsgResult of vbYes: Result := ExecuteMercuryWithCard; vbNo: Result := ExecuteMercuryNoCard; vbCancel: FErrorMsg := 'Canceled.'; end; Result := inherited ExecuteMercury; FTraceControl.TraceOut; end; function TPaymentPrePaid.ExecuteMercuryNoCard: Boolean; var sCardNumber, sMemberName, sExpireDate, sStreetAddress, sZipCode, sCVV2 : String; begin FTraceControl.TraceIn(Self.ClassName + '.ExecuteMercuryNoCard'); with TCardNumberDlgView.Create(nil) do try if not Assigned(FMercuryWidget) then FMercuryWidget := getPaymentCard(FProcessorType, PAYMENT_TYPE_GIFTCARD); setMercuryObject(FMercuryWidget); Result := Start(sCardNumber); if Result then begin if not Assigned(FMercuryWidget) then FMercuryWidget := getPaymentCard(FProcessorType, PAYMENT_TYPE_GIFTCARD); with TCPrePaid(FMercuryWidget) do begin //Manual entry card OnNeedSwipe := nil; AfterSucessfullSwipe := nil; if VoidSaleTransation then OnNeedTroutD := NeedTroutD else OnNeedTroutD := nil; Memo := PaymentMemo; OperatorID := IntToStr(FIDUser); InvoiceNo := getTicketNumber; RefNo := FMercuryWidget.InvoiceNo; Purchase := FPaymentValue; Tax := 0; AcctNo := sCardNumber; ExpDate := sExpireDate; Address := sStreetAddress; Zip := sZipCode; CustomerCode := sMemberName; Track2 := ''; CVVData := sCVV2; TCPrepaid(FMercuryWidget).setCreditDevice(FProcessorType, fProcessingType); if (FPaymentValue > 0) then prePaidNoNSFSale // else // if VoidSaleTransation then // VoidSale else ProcessReturn; end; end else FErrorMsg := 'Canceled by user.'; finally Free; end; FTraceControl.TraceOut; end; function TPaymentPrePaid.ExecuteMercuryWithCard: Boolean; begin FTraceControl.TraceIn(Self.ClassName + '.ExecuteMercuryWithCard'); if not Assigned(FMercuryWidget) then FMercuryWidget := getPaymentCard(FProcessorType, PAYMENT_TYPE_GIFTCARD); with TCPrePaid(FMercuryWidget) do begin OnNeedSwipe := NeedSwipe; AfterSucessfullSwipe := AfterSucessfullSwipe; if VoidSaleTransation then OnNeedTroutD := NeedTroutD else OnNeedTroutD := nil; Memo := PaymentMemo; OperatorID := IntToStr(FIDUser); InvoiceNo := getTicketNumber; RefNo := FMercuryWidget.InvoiceNo; Purchase := FPaymentValue; Tax := 0; CardSwiped := CardSwiped; TCPrePaid(FMercuryWidget).setCreditDevice(fProcessorType, fProcessingType); processResult := getActiveTransaction(); processResult.OnNeedSwipe := NeedSwipe; ProcessResult.FCardSwiped := CardSwiped; if (FPaymentValue > 0) then ProcessSale else if VoidSaleTransation then begin VoidSale; TraceControl.SaveTrace(FIdUser, 'Debug-Step VoidSale ( Credit Card) - Value: ' + CurrToStr(FPaymentValue), '(PII):'+ self.ClassName); end else ProcessReturn(); end; FTraceControl.TraceOut; end; function TPaymentPrePaid.getCardNumber: Boolean; begin result := false; if not Assigned(FMercuryWidget) then FMercuryWidget := getPaymentCard(FProcessorType, PAYMENT_TYPE_GIFTCARD); with TCPrePaid(FMercuryWidget) do begin OnNeedSwipe := NeedSwipe; AfterSucessfullSwipe := AfterSucessfullSwipe; if VoidSaleTransation then OnNeedTroutD := NeedTroutD else OnNeedTroutD := nil; Memo := PaymentMemo; OperatorID := IntToStr(FIDUser); InvoiceNo := getTicketNumber; RefNo := FMercuryWidget.InvoiceNo; Purchase := FPaymentValue; Tax := 0; CardSwiped := CardSwiped; result := ( FCardSwiped <> '' ); end; end; function TPaymentPrePaid.getPaymentType: Integer; begin // 3 end; *) procedure TPaymentCard.BeforeDeletePayment; begin inherited; end; function TPaymentCard.GetRefundInfo: Boolean; begin end; procedure TPaymentCard.MoveValues; begin end; procedure TPaymentCard.NeedTroutD(Sender: TObject; var ATrouD, ARefNo, AAuthCode: WideString; var ACanceled: Boolean); var PCV: TfrmPCVoid; begin PCV := TfrmPCVoid.Create(nil); try ARefNo := IntToStr(RefundID); ACanceled := not PCV.Start(PaymentValue, ATrouD, ARefNo, AAuthCode, FRefundCardInt); finally PCV.Free; end; end; procedure TPaymentCard.printDeclinedReceipt; begin end; procedure TPaymentCard.SetProperties(ADSPayment: TADODataSet); begin inherited; end; procedure TPaymentCard.LoadProcessorParameters; var buildInfo: String; begin with TRegistry.Create do try if ( getOS(buildInfo) = osW7 ) then RootKey := HKEY_CURRENT_USER else RootKey := HKEY_LOCAL_MACHINE; OpenKey(REGISTRY_PATH, True); // get parameters to processor indexProcessor := ReadInteger('ProcessorType'); factoryProcessor := TProcessorFactory.Create(); processor := factoryProcessor.CreateProcessor(indexProcessor); // Even name of fields in Registry looks like Mercury, parameters getting any processor (Mercury, WorldPay, etc) is due old code writen on the past processor.SetIPProcessorAddress(ReadString('MercuryIPs')); processor.SetIPPort(ReadString('MercuryIPPort')); processor.SetMerchantID(ReadString('MercuryMerchatID')); processor.SetConnectionTimeOut(ReadInteger('MercuryConnectTimeout')); processor.SetResponseTimeOut(ReadInteger('MercuryResponseTimeout')); processor.SetGiftIP(readString('MercuryGiftIPs')); processor.SetGiftPort(readString('MercuryGiftIPPort')); //PinPad FPinpad := TMRPinPad.Create(); fPinPad.Device := ReadString('PinPadDevice'); fPinPad.Baud := ReadString('PinPadBaud'); fPinPad.Parity := ReadString('PinPadParity'); fPinPad.DataBits := ReadString('PinPadDataBits'); fPinPad.Comm := ReadString('PinPadComm'); fPinPad.EncryptMethod := ReadString('PinEncryptMethod'); fPinPad.TimeOut := ReadString('PinTimeOut'); // Dsi, DsiPDCX, DsiEMV,.... others... indexDevice := readInteger('ProcessType'); finally Free; end; end; end.
unit f1df_Ctrlm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, ExtCtrls, cxCheckBox, cxDropDownEdit, cxCalendar, cxLookAndFeelPainters, StdCtrls, cxButtons, FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase, pFIBDatabase, ActnList, cxLabel, iBase, PackageLoad, ZTypes, ZProc, Unit_ZGlobal_Consts, zMessages, cxButtonEdit, cxGraphics, dxStatusBar, Registry; type Tf1DfCtrl = class(TForm) PanelMan: TPanel; MaskEditFio: TcxMaskEdit; Bevel1: TBevel; PanelData: TPanel; MaskEditSumPerer: TcxMaskEdit; MaskEditSumVipl: TcxMaskEdit; MaskEditSumNar: TcxMaskEdit; MaskEditSumUd: TcxMaskEdit; DateEditCame: TcxDateEdit; DateEditLeave: TcxDateEdit; MaskEditKod1Df: TcxMaskEdit; Bevel2: TBevel; YesBtn: TcxButton; CancelBtn: TcxButton; ActionList: TActionList; DB: TpFIBDatabase; DefaultTransaction: TpFIBTransaction; StProc: TpFIBStoredProc; LabelFIO: TcxLabel; LabelTin: TcxLabel; LabelSumNar: TcxLabel; LabelSumVipl: TcxLabel; LabelSumUd: TcxLabel; LabelSumPerer: TcxLabel; LabelDateCame: TcxLabel; LabelDateLeave: TcxLabel; LabelKod1DF: TcxLabel; ActionYes: TAction; ActionCancel: TAction; LabelPriv: TcxLabel; ButtonEditPriv: TcxButtonEdit; MaskEditTin: TcxButtonEdit; CheckBoxIsAdd: TcxCheckBox; dxStatusBar1: TdxStatusBar; Actions: TActionList; Action1: TAction; Action2: TAction; Action3: TAction; procedure ActionYesExecute(Sender: TObject); procedure ActionCancelExecute(Sender: TObject); procedure ButtonEditPrivPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure MaskEditTinKeyPress(Sender: TObject; var Key: Char); procedure MaskEditTinPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure Action2Execute(Sender: TObject); procedure RestoreFromBuffer(Sender:TObject); procedure FormShow(Sender: TObject); procedure FormResize(Sender: TObject); private PLanguageIndex:byte; PDb_handle:TISC_DB_HANDLE; PId:integer; PId1DfHeader:Integer; Pfs:TZControlFormStyle; ChIndex:integer; public constructor Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE; fs:TZControlFormStyle;Id:integer;ShowIsAdd:boolean=True;ChildIndex:integer=0);reintroduce; function DeleteRecord:boolean; function PrepareData:boolean; property Id:integer read PId; end; function f1df_ctrl_show(AOwner:TComponent;DB_handle:TISC_DB_HANDLE;fs:TZControlFormStyle;ID:integer;ShowIsAdd:boolean=True;ChildIndex:integer=0):Variant; implementation {$R *.dfm} function f1df_ctrl_show(AOwner:TComponent;DB_handle:TISC_DB_HANDLE;fs:TZControlFormStyle;ID:integer;ShowIsAdd:boolean=True;ChildIndex:integer=0):Variant; var f1dfCtrl:Tf1DfCtrl; begin f1dfCtrl := Tf1DfCtrl.Create(AOwner,DB_handle,fs,ID,ShowIsAdd,ChildIndex); if fs=zcfsDelete then result:=f1dfCtrl.DeleteRecord else begin if f1dfCtrl.PrepareData then begin if f1dfCtrl.ShowModal=mrYes then Result:=f1dfCtrl.id else Result:=0; end; end; f1dfCtrl.Destroy; end; constructor Tf1DfCtrl.Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE; fs:TZControlFormStyle;Id:integer;ShowIsAdd:boolean=True; ChildIndex:integer=0); begin inherited Create(AOwner); PLanguageIndex := LanguageIndex; if fs<>zcfsInsert then PId := Id else PId1DfHeader := Id; Pfs := fs; //------------------------------------------------------------------------------ PDB_Handle := DB_Handle; LabelFIO.Caption := LabelFIO_Caption[PLanguageIndex]; LabelTin.Caption := LabelTin_Caption[PLanguageIndex]; LabelSumNar.Caption := LabelSumNar_Caption[PLanguageIndex]; LabelSumVipl.Caption := LabelSumVipl_Caption[PLanguageIndex]; LabelSumUd.Caption := LabelSumUd_Caption[PLanguageIndex]; LabelSumPerer.Caption := LabelSumPerer_Caption[PLanguageIndex]; LabelDateCame.Caption := LabelDateCame_Caption[PLanguageIndex]; LabelDateLeave.Caption := LabelDateLeave_Caption[PLanguageIndex]; LabelKod1DF.Caption := LabelKod1DF_Caption[PLanguageIndex]; LabelPriv.Caption := LabelPrivilege_Caption[PLanguageIndex]; YesBtn.Caption := YesBtn_Caption[PLanguageIndex]; CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex]; CheckBoxIsAdd.Properties.Caption := Caption_Insert[PLanguageIndex]; CheckBoxIsAdd.Visible := ShowIsAdd; //------------------------------------------------------------------------------ MaskEditSumVipl.Properties.MaskKind := emkRegExpr; MaskEditSumNar.Properties.MaskKind := emkRegExpr; MaskEditSumUd.Properties.MaskKind := emkRegExpr; MaskEditSumPerer.Properties.MaskKind := emkRegExpr; MaskEditSumVipl.Properties.EditMask := '[-]?\d\d?\d?\d?\d?\d?\d?\d?\d?\d?\d?\d?\d? (['+ZSystemDecimalSeparator+']\d\d?)?'; MaskEditSumUd.Properties.EditMask := '[-]?\d\d?\d?\d?\d?\d?\d?\d?\d?\d?\d?\d?\d? (['+ZSystemDecimalSeparator+']\d\d?)?'; MaskEditSumNar.Properties.EditMask := '[-]?\d\d?\d?\d?\d?\d?\d?\d?\d?\d?\d?\d?\d? (['+ZSystemDecimalSeparator+']\d\d?)?'; MaskEditSumPerer.Properties.EditMask := '[-]?\d\d?\d?\d?\d?\d?\d?\d?\d?\d?\d?\d?\d? (['+ZSystemDecimalSeparator+']\d\d?)?'; case fs of zcfsInsert : Caption := Caption_Insert[PLanguageIndex]; zcfsUpdate : Caption := Caption_Update[PLanguageIndex]; zcfsShowDetails : Caption := Caption_Detail[PLanguageIndex]; zcfsDelete : Caption := Caption_Delete[PLanguageIndex]; end; DateEditCame.Text := ''; DateEditLeave.Text := ''; ChIndex:=ChildIndex; //****************************************************************************** dxStatusBar1.Panels[0].Text := 'F9 - '+'Занести до буфера'; dxStatusBar1.Panels[1].Text := 'F10 - '+YesBtn.Caption; dxStatusBar1.Panels[2].Text := 'Esc - '+CancelBtn.Caption; //****************************************************************************** end; function Tf1DfCtrl.DeleteRecord:boolean; begin Result := False; if ZShowMessage(Caption_Delete[PLanguageIndex],DeleteRecordQuestion_Text[PLanguageIndex],mtConfirmation,[mbYes,mbNo])=mrYes then try case ChIndex of 0: begin DB.Handle := PDb_handle; StProc.StoredProcName := 'Z_1DF_REPORT_D'; StProc.Transaction.StartTransaction; StProc.Prepare; StProc.ParamByName('ID').AsInteger := Pid; StProc.ExecProc; StProc.Transaction.Commit; Result:=True; end; 2: begin DB.Handle := PDb_handle; StProc.StoredProcName := 'Z_1DF_TEMP_D'; StProc.Transaction.StartTransaction; StProc.Prepare; StProc.ParamByName('ID').AsInteger := Pid; StProc.ExecProc; StProc.Transaction.Commit; Result:=True; end; end; except on e:exception do begin StProc.Transaction.Rollback; ZShowMessage(Error_Caption[PLanguageIndex],e.Message,mtError,[mbOK]); end; end; end; function Tf1DfCtrl.PrepareData; //var Man:Variant; begin Result := False; case Pfs of zcfsInsert: begin Result:=True; { Man:=LoadPeopleModal(Self,PDB_Handle); if VarArrayDimCount(Man)> 0 then If Man[0]<>NULL then begin MaskEditFio.Text := VarToStrDef(Man[1],'')+' '+VarToStrDef(Man[2],'')+' '+VarToStrDef(Man[3],''); MaskEditTin.Text := VarToStrDef(Man[5],''); Result := True; end;} end; zcfsUpdate: try case ChIndex of 0: begin DB.Handle := PDb_handle; StProc.StoredProcName := 'Z_1DF_REPORT_S_BY_KEY'; StProc.Transaction.StartTransaction; StProc.Prepare; StProc.ParamByName('IN_ID').AsInteger := PId; StProc.ExecProc; PId1DfHeader := StProc.ParamByName('ID_1DF').AsInteger; MaskEditFio.Text := VarToStrDef(StProc.ParamByName('FIO').AsVariant,''); MaskEditTin.Text := varToStrDef(StProc.ParamByName('TIN_PASPORT').AsVariant,''); if VarIsNull(StProc.ParamByName('SUM_NAR').AsVariant) then MaskEditSumNar.Text := '' else MaskEditSumNar.Text := FloatToStrF(StProc.ParamByName('SUM_NAR').AsFloat,ffFixed,16,2); if VarIsNull(StProc.ParamByName('SUM_VIPL').AsVariant) then MaskEditSumVipl.Text := '' else MaskEditSumVipl.Text := FloatToStrF(StProc.ParamByName('SUM_VIPL').AsFloat,ffFixed,16,2); if VarIsNull(StProc.ParamByName('SUM_UD').AsVariant) then MaskEditSumUd.Text := '' else MaskEditSumUd.Text := FloatToStrF(StProc.ParamByName('SUM_UD').AsFloat,ffFixed,16,2); if VarIsNull(StProc.ParamByName('SUM_PERER').AsVariant) then MaskEditSumPerer.Text := '' else MaskEditSumPerer.Text := FloatToStrF(StProc.ParamByName('SUM_PERER').AsFloat,ffFixed,16,2); if VarIsNull(StProc.ParamByName('DATE_CAME').AsVariant) then DateEditCame.EditValue := NULL else DateEditCame.Date := StProc.ParamByName('DATE_CAME').AsDate; if VarIsNull(StProc.ParamByName('DATE_LEAVE').AsVariant) then DateEditLeave.EditValue := Null else DateEditLeave.Date := StProc.ParamByName('DATE_LEAVE').AsDate; MaskEditKod1Df.Text := VarToStrDef(StProc.ParamByName('KOD_1DF').AsVariant,''); ButtonEditPriv.Text := VarToStrDef(StProc.ParamByName('KOD_PRIV').AsVariant,''); CheckBoxIsAdd.EditValue := StProc.ParamByName('IS_ADD').AsVariant; StProc.Transaction.Commit; Result:=True; end; 2: begin DB.Handle := PDb_handle; StProc.StoredProcName := 'Z_1DF_TEMP_S_BY_KEY'; StProc.Transaction.StartTransaction; StProc.Prepare; StProc.ParamByName('ID').AsInteger := PId; StProc.ExecProc; MaskEditFio.Text := VarToStrDef(StProc.ParamByName('FIO').AsVariant,''); MaskEditTin.Text := varToStrDef(StProc.ParamByName('TIN').AsVariant,''); if VarIsNull(StProc.ParamByName('s_nar').AsVariant) then MaskEditSumNar.Text := '' else MaskEditSumNar.Text := FloatToStrF(StProc.ParamByName('s_nar').AsFloat,ffFixed,16,2); if VarIsNull(StProc.ParamByName('S_DOH').AsVariant) then MaskEditSumVipl.Text := '' else MaskEditSumVipl.Text := FloatToStrF(StProc.ParamByName('S_DOH').AsFloat,ffFixed,16,2); if VarIsNull(StProc.ParamByName('S_TAXN').AsVariant) then MaskEditSumUd.Text := '' else MaskEditSumUd.Text := FloatToStrF(StProc.ParamByName('S_TAXN').AsFloat,ffFixed,16,2); if VarIsNull(StProc.ParamByName('S_TAXP').AsVariant) then MaskEditSumPerer.Text := '' else MaskEditSumPerer.Text := FloatToStrF(StProc.ParamByName('S_TAXP').AsFloat,ffFixed,16,2); if VarIsNull(StProc.ParamByName('D_PRIYN').AsVariant) then DateEditCame.EditValue := NULL else DateEditCame.Date := StProc.ParamByName('D_PRIYN').AsDate; if VarIsNull(StProc.ParamByName('D_ZVILN').AsVariant) then DateEditLeave.EditValue := Null else DateEditLeave.Date := StProc.ParamByName('D_ZVILN').AsDate; if VarIsNull(StProc.ParamByName('ozn_pilg').AsInteger) then ButtonEditPriv.Text:='' else ButtonEditPriv.Text:= StProc.ParamByName('ozn_pilg').AsString; if VarIsNull(StProc.ParamByName('ozn_doh').AsVariant) then MaskEditKod1Df.Text:='' else MaskEditKod1Df.Text:=StProc.ParamByName('ozn_doh').AsString; // CheckBoxIsAdd.EditValue := StProc.ParamByName('IS_ADD').AsVariant; // MaskEditKod1Df.Text := VarToStrDef(StProc.ParamByName('KOD_1DF').AsVariant,''); // ButtonEditPriv.Text := VarToStrDef(StProc.ParamByName('KOD_PRIV').AsVariant,''); StProc.Transaction.Commit; Result:=True; end; end; except on e:exception do begin ZShowMessage(Error_Caption[PLanguageIndex],e.Message,mtError,[mbOk]); StProc.Transaction.Rollback; end; end; zcfsShowDetails: try PanelMan.Enabled := False; PanelData.Enabled := False; YesBtn.Visible := False; CancelBtn.Caption := ExitBtn_Caption[PLanguageIndex]; DB.Handle := PDb_handle; CheckBoxIsAdd.Properties.ReadOnly := True; case ChIndex of 0: begin StProc.StoredProcName := 'Z_1DF_REPORT_S_BY_KEY'; StProc.Transaction.StartTransaction; StProc.Prepare; StProc.ParamByName('IN_ID').AsInteger := PId; StProc.ExecProc; MaskEditFio.Text := VarToStrDef(StProc.ParamByName('FIO').AsVariant,''); MaskEditTin.Text := varToStrDef(StProc.ParamByName('TIN_PASPORT').AsVariant,''); if VarIsNull(StProc.ParamByName('SUM_NAR').AsVariant) then MaskEditSumNar.Text := '' else MaskEditSumNar.Text := FloatToStrF(StProc.ParamByName('SUM_NAR').AsFloat,ffFixed,16,2); if VarIsNull(StProc.ParamByName('SUM_VIPL').AsVariant) then MaskEditSumVipl.Text := '' else MaskEditSumVipl.Text := FloatToStrF(StProc.ParamByName('SUM_VIPL').AsFloat,ffFixed,16,2); if VarIsNull(StProc.ParamByName('SUM_UD').AsVariant) then MaskEditSumUd.Text := '' else MaskEditSumUd.Text := FloatToStrF(StProc.ParamByName('SUM_UD').AsFloat,ffFixed,16,2); if VarIsNull(StProc.ParamByName('SUM_PERER').AsVariant) then MaskEditSumPerer.Text := '' else MaskEditSumPerer.Text := FloatToStrF(StProc.ParamByName('SUM_PERER').AsFloat,ffFixed,16,2); if VarIsNull(StProc.ParamByName('DATE_CAME').AsVariant) then DateEditCame.EditValue := NULL else DateEditCame.Date := StProc.ParamByName('DATE_CAME').AsDate; if VarIsNull(StProc.ParamByName('DATE_LEAVE').AsVariant) then DateEditLeave.EditValue := Null else DateEditLeave.Date := StProc.ParamByName('DATE_LEAVE').AsDate; CheckBoxIsAdd.EditValue := StProc.ParamByName('IS_ADD').AsVariant; MaskEditKod1Df.Text := VarToStrDef(StProc.ParamByName('KOD_1DF').AsVariant,''); ButtonEditPriv.Text := VarToStrDef(StProc.ParamByName('KOD_PRIV').AsVariant,''); StProc.Transaction.Commit; Result:=True; end; 2: begin StProc.StoredProcName := 'Z_1DF_TEMP_S_BY_KEY'; StProc.Transaction.StartTransaction; StProc.Prepare; StProc.ParamByName('ID').AsInteger := PId; StProc.ExecProc; MaskEditFio.Text := VarToStrDef(StProc.ParamByName('FIO').AsVariant,''); MaskEditTin.Text := varToStrDef(StProc.ParamByName('TIN').AsVariant,''); if VarIsNull(StProc.ParamByName('s_nar').AsVariant) then MaskEditSumNar.Text := '' else MaskEditSumNar.Text := FloatToStrF(StProc.ParamByName('s_nar').AsFloat,ffFixed,16,2); if VarIsNull(StProc.ParamByName('S_DOH').AsVariant) then MaskEditSumVipl.Text := '' else MaskEditSumVipl.Text := FloatToStrF(StProc.ParamByName('S_DOH').AsFloat,ffFixed,16,2); if VarIsNull(StProc.ParamByName('S_TAXN').AsVariant) then MaskEditSumUd.Text := '' else MaskEditSumUd.Text := FloatToStrF(StProc.ParamByName('S_TAXN').AsFloat,ffFixed,16,2); if VarIsNull(StProc.ParamByName('S_TAXP').AsVariant) then MaskEditSumPerer.Text := '' else MaskEditSumPerer.Text := FloatToStrF(StProc.ParamByName('S_TAXP').AsFloat,ffFixed,16,2); if VarIsNull(StProc.ParamByName('D_PRIYN').AsVariant) then DateEditCame.EditValue := NULL else DateEditCame.Date := StProc.ParamByName('D_PRIYN').AsDate; if VarIsNull(StProc.ParamByName('D_ZVILN').AsVariant) then DateEditLeave.EditValue := Null else DateEditLeave.Date := StProc.ParamByName('D_ZVILN').AsDate; if VarIsNull(StProc.ParamByName('ozn_doh').AsVariant) then MaskEditKod1Df.Text:='' else MaskEditKod1Df.Text:=StProc.ParamByName('ozn_doh').AsString; if VarIsNull(StProc.ParamByName('ozn_pilg').AsInteger) then ButtonEditPriv.Text:='' else ButtonEditPriv.Text:= StProc.ParamByName('ozn_pilg').AsString; // CheckBoxIsAdd.EditValue := StProc.ParamByName('IS_ADD').AsVariant; // MaskEditKod1Df.Text := VarToStrDef(StProc.ParamByName('KOD_1DF').AsVariant,''); // ButtonEditPriv.Text := VarToStrDef(StProc.ParamByName('KOD_PRIV').AsVariant,''); StProc.Transaction.Commit; Result:=True; end; end; except on e:exception do begin ZShowMessage(Error_Caption[PLanguageIndex],e.Message,mtError,[mbOk]); StProc.Transaction.Rollback; end; end; end; end; procedure Tf1DfCtrl.ActionYesExecute(Sender: TObject); begin DB.Handle := PDb_handle; with StProc do try case ChIndex of 0: begin case pfs of zcfsInsert: StoredProcName := 'Z_1DF_REPORT_I'; zcfsUpdate: StoredProcName := 'Z_1DF_REPORT_U'; end; Transaction.StartTransaction; Prepare; if MaskEditTin.Text='' then ParamByName('TIN_PASPORT').AsVariant := NULL else ParamByName('TIN_PASPORT').AsString := MaskEditTin.Text; ParamByName('TIN').AsVariant := ParamByName('TIN_PASPORT').AsVariant; if MaskEditSumNar.Text='' then ParamByName('SUM_NAR').AsFloat := 0 else ParamByName('SUM_NAR').AsFloat := StrToFloat(MaskEditSumNar.Text); if MaskEditSumVipl.Text='' then ParamByName('SUM_VIPL').AsFloat := 0 else ParamByName('SUM_VIPL').AsFloat := StrToFloat(MaskEditSumVipl.Text); if MaskEditSumUd.Text='' then ParamByName('SUM_UD').AsFloat := 0 else ParamByName('SUM_UD').AsFloat := StrToFloat(MaskEditSumUd.Text); if MaskEditSumPerer.Text='' then ParamByName('SUM_PERER').AsFloat := 0 else ParamByName('SUM_PERER').AsFloat := StrToFloat(MaskEditSumPerer.Text); if DateToStr(DateEditCame.Date)='00.00.0000' then ParamByName('DATE_CAME').AsVariant := NULL else ParamByName('DATE_CAME').AsDate := DateEditCame.Date; if DateToStr(DateEditLeave.Date)='00.00.0000' then ParamByName('DATE_LEAVE').AsVariant := NULL else ParamByName('DATE_LEAVE').AsDate := DateEditLeave.Date; if MaskEditFio.Text='' then ParamByName('FIO').AsVariant := NULL else ParamByName('FIO').AsString := MaskEditFio.Text; if MaskEditKod1Df.Text='' then ParamByName('KOD_1DF').AsVariant := NULL else ParamByName('KOD_1DF').AsInteger := StrToInt(MaskEditKod1Df.Text); ParamByName('ID_1DF_HEADER').AsInteger := PId1DfHeader; if ButtonEditPriv.Text='' then ParamByName('KOD_PRIV').AsInteger := 0 else ParamByName('KOD_PRIV').AsInteger := StrToInt(ButtonEditPriv.Text); ParamByName('IS_ADD').AsString := CheckBoxIsAdd.EditValue; if Pfs=zcfsUpdate then ParamByName('ID').AsInteger:=PId; ExecProc; if Pfs=zcfsinsert then PId:=ParamByName('ID').AsInteger; Transaction.Commit; ModalResult := mrYes; end; 2: begin case pfs of zcfsInsert: StoredProcName := 'Z_1DF_TEMP_I'; zcfsUpdate: StoredProcName := 'Z_1DF_TEMP_U'; end; Transaction.StartTransaction; Prepare; if MaskEditTin.Text='' then ParamByName('TIN').AsVariant := NULL else ParamByName('TIN').AsString := MaskEditTin.Text; ParamByName('TIN').AsVariant := ParamByName('TIN').AsVariant; if MaskEditSumNar.Text='' then ParamByName('s_nar').AsFloat := 0 else ParamByName('s_nar').AsFloat := StrToFloat(MaskEditSumNar.Text); if MaskEditSumVipl.Text='' then ParamByName('s_doh').AsFloat := 0 else ParamByName('s_doh').AsFloat := StrToFloat(MaskEditSumVipl.Text); if MaskEditSumUd.Text='' then ParamByName('s_taxn').AsFloat := 0 else ParamByName('s_taxn').AsFloat := StrToFloat(MaskEditSumUd.Text); if MaskEditSumPerer.Text='' then ParamByName('s_taxp').AsFloat := 0 else ParamByName('s_taxp').AsFloat := StrToFloat(MaskEditSumPerer.Text); if DateToStr(DateEditCame.Date)='00.00.0000' then ParamByName('d_priyn').AsVariant := NULL else ParamByName('d_priyn').AsDate := DateEditCame.Date; if DateToStr(DateEditLeave.Date)='00.00.0000' then ParamByName('d_zviln').AsVariant := NULL else ParamByName('d_zviln').AsDate := DateEditLeave.Date; if MaskEditFio.Text='' then ParamByName('FIO').AsVariant := NULL else ParamByName('FIO').AsString := MaskEditFio.Text; if MaskEditKod1Df.Text='' then ParamByName('ozn_doh').AsVariant := NULL else ParamByName('ozn_doh').AsInteger := StrToInt(MaskEditKod1Df.Text); ParamByName('ID_1DF_HEADER').AsInteger := PId1DfHeader; if ButtonEditPriv.Text='' then ParamByName('ozn_pilg').AsInteger := 0 else ParamByName('ozn_pilg').AsInteger := StrToInt(ButtonEditPriv.Text); {ParamByName('IS_ADD').AsString := CheckBoxIsAdd.EditValue;} // if Pfs=zcfsUpdate then ParamByName('ID').AsInteger:=PId; // if Pfs=zcfsinsert then PId:=ParamByName('ID').AsInteger; ExecProc; Transaction.Commit; ModalResult := mrYes; end; end; except on e:exception do begin ZShowMessage(Error_Caption[PLanguageIndex],e.Message,mtError,[mbOk]); Transaction.Rollback; end; end; end; procedure Tf1DfCtrl.ActionCancelExecute(Sender: TObject); begin ModalResult:=mrCancel; end; procedure Tf1DfCtrl.ButtonEditPrivPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var Priv:variant; begin Priv:=LoadPrivileges(self,PDb_handle,zfsModal); if VarArrayDimCount(Priv)> 0 then ButtonEditPriv.Text := VarToStrDef(Priv[7],'') end; procedure Tf1DfCtrl.MaskEditTinKeyPress(Sender: TObject; var Key: Char); begin if (Length(MaskEditTin.Text)=10) and (Key<>#7) and (key<>#8) then Key:=#0; end; procedure Tf1DfCtrl.MaskEditTinPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var Man:variant; begin Man:=LoadPeopleModal(Self,PDB_Handle); if VarArrayDimCount(Man)> 0 then If Man[0]<>NULL then begin MaskEditFio.Text := VarToStrDef(Man[1],'')+' '+VarToStrDef(Man[2],'')+' '+VarToStrDef(Man[3],''); MaskEditTin.Text := VarToStrDef(Man[5],''); end; end; procedure Tf1DfCtrl.Action2Execute(Sender: TObject); var reg: TRegistry; Key:string; begin CancelBtn.SetFocus; Key := '\Software\Zarplata\F1dfCtrl'; reg:=TRegistry.Create; try reg.RootKey:=HKEY_CURRENT_USER; reg.OpenKey(Key,True); reg.WriteString('IsBuffer','1'); reg.WriteString('Tin',MaskEditTin.Text); reg.WriteString('FIO',MaskEditFio.Text); if((MaskEditSumNar.Text<>''){ or (MaskEditSumNar.Text<>'0.00')}) then reg.WriteCurrency('SummaNar',StrToFloat(MaskEditSumNar.Text)); if((MaskEditSumVipl.Text<>''){ or (MaskEditSumVipl.Text<>'0.00')}) then reg.WriteCurrency('SummaVipl',StrToFloat(MaskEditSumVipl.Text)); if((MaskEditSumUd.Text<>''){ or (MaskEditSumUd.Text<>'0.00')}) then reg.WriteCurrency('SummaUd',StrToFloat(MaskEditSumUd.Text)); if((MaskEditSumPerer.Text<>''){ or (MaskEditSumPerer.Text<>'0.00')}) then reg.WriteCurrency('SummaPerer',StrToFloat(MaskEditSumPerer.Text)); if(DateEditCame.EditValue<>null) then reg.WriteDate('DateCame',DateEditCame.EditValue); if(DateEditLeave.EditValue<>null) then reg.WriteDate('DateLeave',DateEditLeave.EditValue); if(MaskEditKod1Df.Text<>'') then reg.WriteCurrency('Kod1Df',StrToFloat(MaskEditKod1Df.Text)); reg.WriteString('Priv',ButtonEditPriv.Text); finally reg.Free; end; end; procedure Tf1DfCtrl.RestoreFromBuffer(Sender:TObject); var reg:TRegistry; Kod:integer; Key:string; begin Key := '\Software\Zarplata\F1dfCtrl'; reg := TRegistry.Create; reg.RootKey:=HKEY_CURRENT_USER; if not reg.OpenKey(Key,False) then begin reg.free; Exit; end; if reg.ReadString('IsBuffer')<>'1' then begin reg.Free; exit; end; //try MaskEditTin.Text := reg.ReadString('Tin'); MaskEditFio.Text := reg.ReadString('FIO'); if(reg.ValueExists('SummaNar')) then MaskEditSumNar.Text:=FloatToStr(reg.ReadCurrency('SummaNar')) else MaskEditSumNar.Text:=''; if(reg.ValueExists('SummaVipl')) then MaskEditSumVipl.Text:=FloatToStr(reg.ReadCurrency('SummaVipl')) else MaskEditSumVipl.Text:=''; if(reg.ValueExists('SummaUd')) then MaskEditSumUd.Text:=FloatToStr(reg.ReadCurrency('SummaUd')) else MaskEditSumUd.Text:=''; if(reg.ValueExists('SummaPerer')) then MaskEditSumPerer.Text:=FloatToStr(reg.ReadCurrency('SummaPerer')) else MaskEditSumPerer.Text:=''; if(reg.ValueExists('DateCame')) then DateEditCame.EditValue:=reg.ReadDate('DateCame') else DateEditCame.EditValue:=null; if(reg.ValueExists('DateLeave')) then DateEditLeave.EditValue:=reg.ReadDate('DateLeave') else DateEditLeave.EditValue:=null; if(reg.ValueExists('Kod1Df')<>Null) then MaskEditKod1Df.Text:=FloatToStr(reg.ReadCurrency('Kod1Df')) else MaskEditKod1Df.Text:=''; ButtonEditPriv.Text := reg.ReadString('Priv'); //finally DateEditCame.SetFocus; Reg.Free; //end; end; procedure Tf1DfCtrl.FormShow(Sender: TObject); begin if Pfs=zcfsInsert then RestoreFromBuffer(self); FormResize(sender); end; procedure Tf1DfCtrl.FormResize(Sender: TObject); var i:byte; begin for i:=0 to dxStatusBar1.Panels.Count-1 do dxStatusBar1.Panels[i].Width := Width div dxStatusBar1.Panels.Count; end; end.
unit Embedded_GUI_AVR_Common; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Dialogs, LCLType, Controls, ProjectIntf, Embedded_GUI_Embedded_List_Const; // Unit wird von "./Tools/Ebedded_List_to_const" generiert. type { TAVR_ProjectOptions } TAVR_ProjectOptions = class AvrdudeCommand: record Path, ConfigPath, AVR_AVRDude_Typ, Programmer, COM_Port, Baud: string; BitClock: string; Verbose: integer; Disable_Auto_Erase, Chip_Erase: boolean; end; AVR_SubArch, AVR_FPC_Typ: string; AsmFile: boolean; procedure Save_to_Project(AProject: TLazProject); procedure Load_from_Project(AProject: TLazProject); end; type TAVR_TemplatesPara = record Name, AVR_SubArch, AVR_FPC_Typ, AVR_AVRDude_Typ, Programmer, COM_Port, Baud: string; BitClock: string; Verbose: integer; Disable_Auto_Erase, Chip_Erase: boolean; end; const AVR_TemplatesPara: array of TAVR_TemplatesPara = (( Name: 'Arduino UNO'; AVR_SubArch: 'AVR5'; AVR_FPC_Typ: 'atmega328p'; AVR_AVRDude_Typ: 'atmega328p'; Programmer: 'arduino'; COM_Port: '/dev/ttyACM0'; Baud: '115200'; BitClock: '1'; Verbose: 1; Disable_Auto_Erase: False; Chip_Erase: False; ), ( Name: 'Arduino Nano (old Bootloader)'; AVR_SubArch: 'AVR5'; AVR_FPC_Typ: 'atmega328p'; AVR_AVRDude_Typ: 'atmega328p'; Programmer: 'arduino'; COM_Port: '/dev/ttyUSB0'; Baud: '57600'; BitClock: '1'; Verbose: 1; Disable_Auto_Erase: False; Chip_Erase: False; ), ( Name: 'Arduino Nano'; AVR_SubArch: 'AVR5'; AVR_FPC_Typ: 'atmega328p'; AVR_AVRDude_Typ: 'atmega328p'; Programmer: 'arduino'; COM_Port: '/dev/ttyUSB0'; Baud: '115200'; BitClock: '1'; Verbose: 1; Disable_Auto_Erase: False; Chip_Erase: False; ), ( Name: 'Arduino Mega'; AVR_SubArch: 'AVR6'; AVR_FPC_Typ: 'atmega2560'; AVR_AVRDude_Typ: 'atmega2560'; Programmer: 'wiring'; COM_Port: '/dev/ttyUSB0'; Baud: '115200'; BitClock: '1'; Verbose: 1; Disable_Auto_Erase: True; Chip_Erase: False; ), ( Name: 'ATmega328P'; AVR_SubArch: 'AVR5'; AVR_FPC_Typ: 'atmega328p'; AVR_AVRDude_Typ: 'atmega328p'; Programmer: 'usbasp'; COM_Port: ''; Baud: ''; BitClock: '1'; Verbose: 1; Disable_Auto_Erase: False; Chip_Erase: False; ), ( Name: 'ATtiny2313A'; AVR_SubArch: 'AVR25'; AVR_FPC_Typ: 'attiny2313a'; AVR_AVRDude_Typ: 'attiny2313'; Programmer: 'usbasp'; COM_Port: ''; Baud: ''; BitClock: '1'; Verbose: 1; Disable_Auto_Erase: False; Chip_Erase: False; ), ( Name: 'ATtiny13A'; AVR_SubArch: 'AVR25'; AVR_FPC_Typ: 'attiny13a'; AVR_AVRDude_Typ: 'attiny13'; Programmer: 'usbasp'; COM_Port: ''; Baud: ''; BitClock: '1'; Verbose: 1; Disable_Auto_Erase: False; Chip_Erase: False; )); var AVR_ProjectOptions: TAVR_ProjectOptions; implementation { TProjectOptions } procedure TAVR_ProjectOptions.Save_to_Project(AProject: TLazProject); var pr, s: string; i: integer; begin s := AvrdudeCommand.Path + ' '; if AvrdudeCommand.ConfigPath <> '' then begin s += '-C' + AvrdudeCommand.ConfigPath + ' '; end; for i := 0 to AvrdudeCommand.Verbose - 1 do begin s += '-v '; end; s += '-p' + AvrdudeCommand.AVR_AVRDude_Typ + ' ' + '-c' + AvrdudeCommand.Programmer + ' '; pr := upCase(AvrdudeCommand.Programmer); if (pr = 'ARDUINO') or (pr = 'STK500V1') or (pr = 'WIRING') then begin s += '-P' + AvrdudeCommand.COM_Port + ' ' + '-b' + AvrdudeCommand.Baud + ' '; end; if (pr = 'AVR109') then begin s += '-P' + AvrdudeCommand.COM_Port + ' '; end; if AvrdudeCommand.BitClock <> '1' then begin s += '-B' + AvrdudeCommand.BitClock + ' '; end; if AvrdudeCommand.Disable_Auto_Erase then begin s += '-D '; end; if AvrdudeCommand.Chip_Erase then begin s += '-e '; end; with AProject.LazCompilerOptions do begin s += '-Uflash:w:' + TargetFilename + '.hex:i'; ExecuteAfter.Command := s; TargetCPU := 'avr'; TargetOS := 'embedded'; TargetProcessor := AVR_SubArch; CustomOptions := '-Wp' + AVR_FPC_Typ; if AsmFile then begin CustomOptions := CustomOptions + LineEnding + '-al'; end; end; end; procedure TAVR_ProjectOptions.Load_from_Project(AProject: TLazProject); var s: string; function Find(const Source: string; const Sub: string): string; var p, Index: integer; begin p := pos(Sub, Source); Result := ''; if p > 0 then begin p += Length(Sub); Index := p; while (Index <= Length(Source)) and (s[Index] > #32) do begin Result += Source[Index]; Inc(Index); end; end; end; function FindVerbose(Source: string): integer; var ofs: integer = 1; p: integer; begin Result := 0; repeat p := pos('-v', Source, ofs); if p > 0 then begin Inc(Result); ofs := p + 2; end; until p = 0; end; begin AVR_SubArch := AProject.LazCompilerOptions.TargetProcessor; s := AProject.LazCompilerOptions.CustomOptions; AsmFile := Pos('-al', s) > 0; AVR_FPC_Typ := Find(s, '-Wp'); s := AProject.LazCompilerOptions.ExecuteAfter.Command; AvrdudeCommand.Path := Copy(s, 0, pos(' ', s) - 1); AvrdudeCommand.ConfigPath := Find(s, '-C'); AvrdudeCommand.AVR_AVRDude_Typ := Find(s, '-p'); AvrdudeCommand.Programmer := Find(s, '-c'); AvrdudeCommand.COM_Port := Find(s, '-P'); AvrdudeCommand.Baud := Find(s, '-b'); AvrdudeCommand.Verbose := FindVerbose(s); AvrdudeCommand.BitClock := Find(s, '-B'); AvrdudeCommand.Disable_Auto_Erase := pos('-D', s) > 0; AvrdudeCommand.Chip_Erase := pos('-e', s) > 0; end; end.
unit UnitShowWorkTransactions; // 欢乐幻灵·显示工作步骤 interface uses Windows, Messages, SysUtils, Classes, Controls, Forms, StdCtrls, Grids, frmTemplate; type TFormShowWorkTransactions = class(TfTemplate) StringGridTransactions: TStringGrid; ButtonHide: TButton; lblRepeatCount: TLabel; procedure ButtonHideClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } procedure ShowTransactions; end; var FormShowWorkTransactions: TFormShowWorkTransactions; implementation {$R *.dfm} uses UnitGlobal, UnitConsts, UnitTypesAndVars, UnitClasses, ClsGames; procedure TFormShowWorkTransactions.ShowTransactions; const MinRowCount = 10; var i:integer; tmpTransaction: TTransaction; begin if not self.Visible then Exit; // 设置网格行数 if ThisWork.Count > MinRowCount then StringGridTransactions.RowCount := ThisWork.Count + 1 else begin StringGridTransactions.RowCount := MinRowCount + 1; // 清除网格内信息 for i := 1 to StringGridTransactions.RowCount - 1 do StringGridTransactions.Rows[i].Clear; end; StringGridTransactions.Row := 1; with StringGridTransactions do for i := 0 to ThisWork.Count - 1 do begin tmpTransaction := ThisWork.GetTransactionByIndex(i); if tmpTransaction = ThisWork.GetCurrTransaction then StringGridTransactions.Row := i + 1; Cells[0, i + 1] := IntToStr(i); // 步骤编号 Cells[1, i + 1] := tmpTransaction.Caption; // 步骤说明 if tmpTransaction.State = 1 then // 执行状态 Cells[2, i + 1] := '√' else if tmpTransaction.State = -1 then Cells[2, i + 1] := '×'; end; if ThisWork.RepeatCount = -1 then lblRepeatCount.Caption := Format('无限循环,现在是第%d次', [ThisWork.RepeatCounter + 1]) else lblRepeatCount.Caption := Format('共需要循环%d次,现在是第%d次', [ThisWork.RepeatCount, ThisWork.RepeatCounter + 1]); end; procedure TFormShowWorkTransactions.ButtonHideClick(Sender: TObject); begin Close; end; procedure TFormShowWorkTransactions.FormCreate(Sender: TObject); begin // 设置窗体位置 self.CFormName := IDS_WorkTransactionsFormName; inherited; //设置表头 with StringGridTransactions do begin Cells[0, 0] := 'No.'; Cells[1, 0] := '行为名称'; Cells[2, 0] := 'OK'; end; end; procedure TFormShowWorkTransactions.FormShow(Sender: TObject); begin Caption := '显示工作步骤·' + HLInfoList.GlobalHL.UserName; ShowTransactions; end; end.
unit Common.Barcode; interface uses Common.Barcode.IBarcode, FMX.Objects, System.Generics.Collections, Common.Barcode.Drawer; type TBarcodeType = (EAN8, EAN13, UPCA, UPCE, ITF14, GS128, Code128); TBarcode = class private class var Impementations: TDictionary<TBarcodeType, TClass>; class constructor Create; class destructor Destroy; class function GetImplement(const AType: TBarcodeType): IBarcode; private FBarcode: IBarcode; function GetRawData: string; procedure SetRawData(const Value: string); function GetAddonData: string; procedure SetAddonData(const Value: string); public constructor Create(const AType: TBarcodeType); destructor Destroy; override; property RawData: string read GetRawData write SetRawData; property AddonData: string read GetAddonData write SetAddonData; function SVG: string; overload; class function SVG(AType: TBarcodeType; RawData: string): string; overload; static; class function SVG(AType: TBarcodeType; RawData, AddonData: string): string; overload; static; class procedure RegisterBarcode(const AType: TBarcodeType; const AImplementation: TClass); end; TBarcodeTypeHelper = record helper for TBarcodeType function ToString: string; end; TBarcodeCustom = class abstract(TInterfacedObject, IBarcode) protected FEncodeData: string; FRawData: string; FRawAddon: string; function GetLength: integer; virtual; abstract; function GetType: TBarcodeType; virtual; abstract; procedure ValidateRawAddon(const Value: string); virtual; abstract; procedure ValidateRawData(const Value: string); virtual; abstract; function GetCRC(const ARawData: string): integer; virtual; abstract; function CheckCRC(const ARawData: string): boolean; virtual; procedure Encode; virtual; abstract; //IBarcode function GetRawData: string; procedure SetRawData(const Value: string); function GetAddonData: string; procedure SetAddonData(const Value: string); function GetSVG: string; virtual; end; implementation uses System.SysUtils; { TBarcode } constructor TBarcode.Create(const AType: TBarcodeType); begin FBarcode := TBarcode.GetImplement(AType); if FBarcode = nil then raise Exception.Create('Barcode not implements.'); end; destructor TBarcode.Destroy; begin FBarcode := nil; end; function TBarcode.SVG: string; begin result := FBarcode.SVG; end; class constructor TBarcode.Create; begin TBarcode.Impementations := TDictionary<TBarcodeType, TClass>.Create; end; class destructor TBarcode.Destroy; begin TBarcode.Impementations.Free; end; function TBarcode.GetAddonData: string; begin result := FBarcode.AddonData; end; class function TBarcode.GetImplement(const AType: TBarcodeType): IBarcode; var BarcodeClass: TClass; Obj: TObject; begin if not TBarcode.Impementations.TryGetValue(AType, BarcodeClass) then begin result := nil; exit; end; Obj := BarcodeClass.Create; Supports(Obj, IBarcode, result); end; function TBarcode.GetRawData: string; begin result := FBarcode.RawData end; class procedure TBarcode.RegisterBarcode(const AType: TBarcodeType; const AImplementation: TClass); begin if Supports(AImplementation, IBarcode) then TBarcode.Impementations.AddOrSetValue(AType, AImplementation); end; procedure TBarcode.SetAddonData(const Value: string); begin FBarcode.AddonData := Value; end; procedure TBarcode.SetRawData(const Value: string); begin FBarcode.RawData := Value; end; class function TBarcode.SVG(AType: TBarcodeType; RawData, AddonData: string): string; var Barcode: TBarcode; begin Barcode := TBarcode.Create(AType); try Barcode.RawData := RawData; Barcode.AddonData := AddonData; result := Barcode.SVG; finally Barcode.Free; end; end; class function TBarcode.SVG(AType: TBarcodeType; RawData: string): string; begin result := TBarcode.SVG(AType, RawData, string.Empty); end; { TBarcodeTypeHelper } function TBarcodeTypeHelper.ToString: string; begin case self of EAN8: result := 'EAN8'; EAN13: result := 'EAN13'; UPCA: result := 'UPC-A'; UPCE: result := 'UPC-E'; ITF14: result := 'ITF-14'; GS128: result := 'GS-128'; Code128: result := 'Code-128'; else result := 'unknown'; end; end; { TBarcodeCustom } function TBarcodeCustom.CheckCRC(const ARawData: string): boolean; var RawCRC: integer; CRC: integer; begin RawCRC := int32.Parse(string(ARawData[ARawData.Length])); CRC := self.GetCRC(ARawData); result := RawCRC = CRC; end; function TBarcodeCustom.GetAddonData: string; begin result := FRawAddon; end; function TBarcodeCustom.GetRawData: string; begin result := FRawData; end; function TBarcodeCustom.GetSVG: string; var Drawer: IBarcodeDrawer; begin Drawer := TBarcodeDrawer.Create; result := Drawer.SVG(FEncodeData); end; procedure TBarcodeCustom.SetAddonData(const Value: string); begin ValidateRawAddon(Value); FRawAddon := Value; Encode; end; procedure TBarcodeCustom.SetRawData(const Value: string); begin ValidateRawData(Value.Trim); FRawData := Value.Trim; Encode; end; end.
unit CCJCALL_Status; { © PgkSoft 05.08.2015 Журнал регистрации вызовов IP-телефонии Определение статуса пропущенного вызова } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ComCtrls, ToolWin, DB, ADODB, ActnList; type TfrmCCJCALL_Status = class(TForm) pnlTop: TPanel; pnlTop_RN: TPanel; pnlTop_Phone: TPanel; pnlTop_CallDate: TPanel; pnlOrderStatus: TPanel; Label1: TLabel; edOrderStatus: TEdit; btnSlDrivers: TButton; pnlCheckNote: TPanel; pnlCheckNote_Count: TPanel; pnlCheckNote_Status: TPanel; pnlTool: TPanel; pnlTool_Bar: TPanel; tlbarControl: TToolBar; tlbtnOk: TToolButton; tlbtnExit: TToolButton; pnlTool_Show: TPanel; pnlNote: TPanel; mNote: TMemo; aMain: TActionList; aMain_Ok: TAction; aMain_Exit: TAction; aMain_SlOrderStatus: TAction; spSetStatus: TADOStoredProc; procedure FormCreate(Sender: TObject); procedure FormActivate(Sender: TObject); procedure aMain_OkExecute(Sender: TObject); procedure aMain_ExitExecute(Sender: TObject); procedure aMain_SlOrderStatusExecute(Sender: TObject); procedure edOrderStatusChange(Sender: TObject); private { Private declarations } ISignActive : integer; ISignExec : integer; CodeAction : string; NRN : integer; { Регистрационный номер } NUSER : integer; Phone : string; SCallDate : string; SNOTE : string; SStatus : string; NHist : integer; procedure ShowGets; public { Public declarations } procedure SetCodeAction(Parm : string); procedure SetRN(Parm : integer); procedure SetPhone(Parm : string); procedure SetSCallDate(Parm : string); procedure SetUser(Parm : integer); procedure SetNote(Parm : string); procedure SetRNHist(Parm : integer); function GetSignExec : integer; function GetStatus : string; end; var frmCCJCALL_Status: TfrmCCJCALL_Status; implementation uses Util, UMAIN, UCCenterJournalNetZkz, UReference; {$R *.dfm} procedure TfrmCCJCALL_Status.FormCreate(Sender: TObject); begin { Инициализация } ISignActive := 0; ISignExec := 0; CodeAction := ''; NRN := 0; NUSER := 0; Phone := ''; SCallDate := ''; SNOTE := ''; NHist := 0; end; procedure TfrmCCJCALL_Status.FormActivate(Sender: TObject); var SCaption : string; begin if ISignActive = 0 then begin { Иконка окна } FCCenterJournalNetZkz.imgMain.GetIcon(115,self.Icon); { Отображаем реквизиты заказа } SCaption := 'Рег. № ' + VarToStr(NRN); pnlTop_RN.Caption := SCaption; pnlTop_RN.Width := TextPixWidth(SCaption, pnlTop_RN.Font) + 20; SCaption := 'Тел. ' + Phone; pnlTop_Phone.Caption := SCaption; pnlTop_Phone.Width := TextPixWidth(SCaption, pnlTop_Phone.Font) + 20; SCaption := SCallDate; pnlTop_CallDate.Caption := SCaption; pnlTop_CallDate.Width := TextPixWidth(SCaption, pnlTop_CallDate.Font) + 10; { Текущее значение примечания } mNote.Text := SNOTE; { Форма активна } ISignActive := 1; ShowGets; end; end; procedure TfrmCCJCALL_Status.ShowGets; var SCaption : string; begin if ISignActive = 1 then begin { Контроль на пустую строку } if length(edOrderStatus.Text) = 0 then begin aMain_Ok.Enabled := false; edOrderStatus.Color := TColor(clYellow); end else begin aMain_Ok.Enabled := true; edOrderStatus.Color := TColor(clWindow); end; { Количество символов в примечании } SCaption := VarToStr(length(mNote.Text)); pnlCheckNote_Count.Caption := SCaption; pnlCheckNote_Count.Width := TextPixWidth(SCaption, pnlCheckNote_Count.Font) + 20; end; end; procedure TfrmCCJCALL_Status.SetCodeAction(Parm : string); begin CodeAction := parm; end; procedure TfrmCCJCALL_Status.SetRN(Parm : integer); begin NRN := parm; end; procedure TfrmCCJCALL_Status.SetPhone(Parm : string); begin Phone := parm; end; procedure TfrmCCJCALL_Status.SetSCallDate(Parm : string); begin SCallDate := parm; end; procedure TfrmCCJCALL_Status.SetUser(Parm : integer); begin NUSER := parm; end; procedure TfrmCCJCALL_Status.SetNote(Parm : string); begin SNOTE := parm; end; procedure TfrmCCJCALL_Status.SetRNHist(Parm : integer); begin NHist := parm; end; function TfrmCCJCALL_Status.GetSignExec : integer; begin result := ISignExec; end; function TfrmCCJCALL_Status.GetStatus : string; begin result := SStatus; end; procedure TfrmCCJCALL_Status.aMain_OkExecute(Sender: TObject); var IErr : integer; SErr : string; begin if CodeAction = 'JCall_Status' then begin if MessageDLG('Подтвердите выполнение операции.',mtConfirmation,[mbYes,mbNo],0) = mrNo then exit; try spSetStatus.Parameters.ParamValues['@PRN'] := NRN; spSetStatus.Parameters.ParamValues['@RN_HIST'] := NHist; spSetStatus.Parameters.ParamValues['@USER'] := NUSER; spSetStatus.Parameters.ParamValues['@Status'] := edOrderStatus.Text; spSetStatus.Parameters.ParamValues['@SNOTE'] := mNote.Text; spSetStatus.Parameters.ParamValues['@SignUpdJournal'] := 1; spSetStatus.ExecProc; IErr := spSetStatus.Parameters.ParamValues['@RETURN_VALUE']; if IErr <> 0 then begin SErr := spSetStatus.Parameters.ParamValues['@SErr']; ShowMessage(SErr); end else begin ISignExec := 1; SStatus := edOrderStatus.Text; self.Close; end; except on e:Exception do begin ShowMessage(e.Message); end; end; end; end; procedure TfrmCCJCALL_Status.aMain_ExitExecute(Sender: TObject); begin self.close; end; procedure TfrmCCJCALL_Status.aMain_SlOrderStatusExecute(Sender: TObject); var DescrSelect : string; begin try frmReference := TfrmReference.Create(Self); frmReference.SetMode(cFReferenceModeSelect); frmReference.SetReferenceIndex(cFReferenceOrderStatus); frmReference.SetReadOnly(cFReferenceNoReadOnly); try frmReference.ShowModal; DescrSelect := frmReference.GetDescrSelect; if length(DescrSelect) > 0 then edOrderStatus.Text := DescrSelect; finally frmReference.Free; end; except end; end; procedure TfrmCCJCALL_Status.edOrderStatusChange(Sender: TObject); begin ShowGets; end; end.
{******************************************************************************* * qFStrings * * * * Библиотека компонентов для работы с формой редактирования (qFControls) * * Константы * * Copyright © 2005, Олег Г. Волков, Донецкий Национальный Университет * *******************************************************************************} unit qFStrings; interface const qFHighlightColor = $8080FF; qFDefaultLabelColor = $008000; qFBlockedColor = $EBEBEB; qFSpravColor = $F5E1E0; qFDefaultInterval = 120; qFDefaultWidth = 200; qFDefaultHeight = 21; qFDButtonSize = 21; qFMouseY = qFDefaultHeight div 2; qFMouseX = 10; qFDefaultDisplayName = 'Назва поля'; qFFieldIsEmpty = 'Не заповнено поле '; qFErrorCaption = 'Помилка!'; qFInformCaption = 'Увага!'; // vallkor qFConfirmCaption = 'Підтвердження'; qFYesCaption = 'Так'; qFNoCaption = 'Ні'; qFControlBlocked = 'Не можна змінити значення у режимі перегляду!'; qFNotInteger = ': поле має бути цілим числом!'; qFNegative = ': поле не може бути від''ємним!'; qFZero = ': поле не може бути нулем!'; qFNotFloat = ': поле має бути числом!'; qFMustBe = 'Повинно бути'; qFErrorMsg = 'При занесенні у бази виникла помилка'; qFLockErrorMsg = 'Інший користувач блокує цей запис! Спробуйте ще через деякий час.'; qFGetErrorMsg = 'При отриманні даних з бази виникла помилка'; qFConfirmDeleteMsg = 'Ви справді бажаєте вилучити цей запис?'; qFEmpty = 'Немає даних!'; qFCantCreateForm = 'Неможливо створити форму (клас не зареєстрований?)'; qFNoDatabase = 'Не підключена база даних!'; qFSpravHint = 'Щоб відкрити довідник, натисніть <Ctrl+Enter>'; qFCantPrepare = 'Не можливо підготувати форму: немає ключа (where)!'; qFCantOk = 'Не можливо занести дані: немає ключа (where)!'; qFPeriodError = 'Невірно введені дати періоду. '; qFDateFieldIsEmpty = 'Не заповнено поле дати '; implementation end.
unit ibSHDDLWizardActions; interface uses SysUtils, Classes, Controls, Menus, SHDesignIntf, ibSHDesignIntf; type TibSHDDLWizardToolbarAction_ = class(TSHAction) private procedure ShowChangedWizard; public constructor Create(AOwner: TComponent); override; function SupportComponent(const AClassIID: TGUID): Boolean; override; procedure EventExecute(Sender: TObject); override; procedure EventHint(var HintStr: String; var CanShow: Boolean); override; procedure EventUpdate(Sender: TObject); override; end; implementation uses ibSHConsts, ibSHDDLWizardEditors, ibSHWizardChangeFrm, ibSHWizardDomainFrm, ibSHWizardTableFrm, ibSHWizardFieldFrm, ibSHWizardIndexFrm, ibSHWizardConstraintFrm, ibSHWizardViewFrm, ibSHWizardProcedureFrm, ibSHWizardTriggerFrm, ibSHWizardGeneratorFrm, ibSHWizardExceptionFrm, ibSHWizardFunctionFrm, ibSHWizardFilterFrm, ibSHWizardRoleFrm; { TibSHDDLWizardToolbarAction_ } constructor TibSHDDLWizardToolbarAction_.Create(AOwner: TComponent); begin inherited Create(AOwner); FCallType := actCallToolbar; Caption := Format('%s', ['DDL Wizard...']); Hint := Caption; ShortCut := TextToShortCut('Ctrl+W'); SHRegisterComponentForm(IibSHDomain, 'DDL_WIZARD.DOMAIN', TibSHWizardDomainForm); // SHRegisterComponentForm(IibSHTable, 'DDL_WIZARD.TABLE', TibSHWizardTableForm); SHRegisterComponentForm(IibSHTable, 'DDL_WIZARD.TABLE', TibSHWizardTableForm); SHRegisterComponentForm(IibSHIndex, 'DDL_WIZARD.INDEX', TibSHWizardIndexForm); SHRegisterComponentForm(IibSHField, 'DDL_WIZARD.FIELD', TibSHWizardFieldForm); SHRegisterComponentForm(IibSHConstraint, 'DDL_WIZARD.CONSTRAINT', TibSHWizardConstraintForm); SHRegisterComponentForm(IibSHView, 'DDL_WIZARD.VIEW', TibSHWizardViewForm); SHRegisterComponentForm(IibSHProcedure, 'DDL_WIZARD.PROCEDURE', TibSHWizardProcedureForm); SHRegisterComponentForm(IibSHTrigger, 'DDL_WIZARD.TRIGGER', TibSHWizardTriggerForm); SHRegisterComponentForm(IibSHGenerator, 'DDL_WIZARD.GENERATOR', TibSHWizardGeneratorForm); SHRegisterComponentForm(IibSHException, 'DDL_WIZARD.EXCEPTION', TibSHWizardExceptionForm); SHRegisterComponentForm(IibSHFunction, 'DDL_WIZARD.FUNCTION', TibSHWizardFunctionForm); SHRegisterComponentForm(IibSHFilter, 'DDL_WIZARD.FILTER', TibSHWizardFilterForm); SHRegisterComponentForm(IibSHRole, 'DDL_WIZARD.ROLE', TibSHWizardRoleForm); SHRegisterComponentForm(IibSHSQLEditor, 'DDL_WIZARD.CHANGE', TibSHWizardChangeForm); // SHRegisterComponentForm(IibSHSQLPlayer, 'DDL_WIZARD.CHANGE', TibSHWizardChangeForm); Visible := False; end; function TibSHDDLWizardToolbarAction_.SupportComponent(const AClassIID: TGUID): Boolean; begin Result := IsEqualGUID(AClassIID, IibSHDomain) or IsEqualGUID(AClassIID, IibSHTable) or // Если закомментить то пропадут визарды на поля IsEqualGUID(AClassIID, IibSHField) or IsEqualGUID(AClassIID, IibSHConstraint) or IsEqualGUID(AClassIID, IibSHIndex) or IsEqualGUID(AClassIID, IibSHView) or IsEqualGUID(AClassIID, IibSHProcedure) or IsEqualGUID(AClassIID, IibSHTrigger) or IsEqualGUID(AClassIID, IibSHGenerator) or IsEqualGUID(AClassIID, IibSHException) or IsEqualGUID(AClassIID, IibSHFunction) or IsEqualGUID(AClassIID, IibSHFilter) or IsEqualGUID(AClassIID, IibSHRole) or IsEqualGUID(AClassIID, IibSHSQLEditor) or IsEqualGUID(AClassIID, IibSHSQLPlayer); end; procedure TibSHDDLWizardToolbarAction_.EventExecute(Sender: TObject); begin if Supports(Designer.CurrentComponent, IibSHDBObject) then begin if AnsiSameText(Designer.CurrentComponentForm.CallString, SCallFields) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallConstraints) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallIndices) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallTriggers) then Designer.ShowModal((Designer.CurrentComponentForm as IibSHTableForm).DBComponent , Format('DDL_WIZARD.%s', [AnsiUpperCase((Designer.CurrentComponentForm as IibSHTableForm).DBComponent.Association)])) else begin if Supports(Designer.CurrentComponent, IibSHTable) then Designer.UnderConstruction else Designer.ShowModal(Designer.CurrentComponent, Format('DDL_WIZARD.%s', [AnsiUpperCase(Designer.CurrentComponent.Association)])); end; end; if Supports(Designer.CurrentComponent, IibSHSQLEditor) {or Supports(Component, IibSHSQLPlayer)} then begin try if Designer.ShowModal(Designer.CurrentComponent, 'DDL_WIZARD.CHANGE') = mrOK then ShowChangedWizard; finally Designer.CurrentComponent.Tag := 0; end; end; end; procedure TibSHDDLWizardToolbarAction_.EventHint(var HintStr: String; var CanShow: Boolean); begin end; procedure TibSHDDLWizardToolbarAction_.EventUpdate(Sender: TObject); begin { TODO -oBuzz : Разобраться таки как обрубить на хер визард на таблицу } if Assigned(Designer.CurrentComponentForm) and Supports(Designer.CurrentComponent, IibSHDDLInfo) and Supports(Designer.CurrentComponentForm, IibSHDDLForm) and ( // AnsiSameText(Designer.CurrentComponentForm.CallString, SCallSourceDDL) or (( AnsiSameText(Designer.CurrentComponentForm.CallString, SCallCreateDDL) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallAlterDDL) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallRecreateDDL) ) and (Designer.CurrentComponent.Association<>SClassHintTable) ) or // AnsiSameText(Designer.CurrentComponentForm.CallString, SCallDropDDL) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallFields) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallConstraints) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallIndices) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallTriggers) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallDDLText) ) then begin Visible := True; end else Visible := False; if Visible then if AnsiSameText(Designer.CurrentComponentForm.CallString, SCallFields) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallConstraints) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallIndices) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallTriggers) then Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanPause else Enabled := True; end; procedure TibSHDDLWizardToolbarAction_.ShowChangedWizard; var vClassIID: TGUID; vComponentClass: TSHComponentClass; vComponent, vDDLGenerator: TSHComponent; vDBObjectIntf: IibSHDBObject; vDDLGeneratorIntf: IibSHDDLGenerator; begin case Designer.CurrentComponent.Tag of -1: Exit; 0: vClassIID := IibSHDomain; 1: Designer.UnderConstruction;//vClassIID := IibSHTable; // 1: vClassIID := IibSHTable; 2: vClassIID := IibSHField; 3: vClassIID := IibSHConstraint; 4: vClassIID := IibSHIndex; 5: vClassIID := IibSHView; 6: vClassIID := IibSHProcedure; 7: vClassIID := IibSHTrigger; 8: vClassIID := IibSHGenerator; 9: vClassIID := IibSHException; 10: vClassIID := IibSHFunction; 11: vClassIID := IibSHFilter; 12: vClassIID := IibSHRole; end; try // // // vComponentClass := Designer.GetComponent(IibSHDDLGenerator); if Assigned(vComponentClass) then begin vDDLGenerator := vComponentClass.Create(nil); Supports(vDDLGenerator, IibSHDDLGenerator, vDDLGeneratorIntf); end; Assert(vDDLGeneratorIntf <> nil, 'DDLGenerator = nil'); // // // vComponentClass := Designer.GetComponent(vClassIID); if Assigned(vComponentClass) then vComponent := vComponentClass.Create(nil); if Assigned(vComponent) then begin Supports(vComponent, IibSHDBObject, vDBObjectIntf); vDBObjectIntf.OwnerIID := Designer.CurrentComponent.OwnerIID; vDBObjectIntf.State := csCreate; vDBObjectIntf.Caption := Format('NEW_%s', [UpperCase(vComponent.Association)]); if Supports(Designer.CurrentComponent, IibSHSQLEditor) then vComponent.Tag := 100; // if Supports(Component, IibSHSQLPlayer) then vComponent.Tag := 200; // vDDLGeneratorIntf.UseFakeValues := False; // Designer.TextToStrings(vDDLGeneratorIntf.GetDDLText(vDBObjectIntf), vDBObjectIntf.CreateDDL); Designer.ShowModal(vComponent, Format('DDL_WIZARD.%s', [AnsiUpperCase(vComponent.Association)])); end; finally vDDLGeneratorIntf := nil; FreeAndNil(vDDLGenerator); vDBObjectIntf := nil; FreeAndNil(vComponent); end; end; end.
unit Internet; interface uses Windows, Forms, WinInet, SysUtils, Classes, BasicFunctions; type TWebFileDownloader = class(TThread) private FFileURL: string; FFileName: string; procedure ForceProcessMessages; procedure EnforceDirectory(const _Path: string); protected procedure Execute; override; function GetWebFile (const _FileURL, _FileName: String): boolean; public constructor Create(const _FileURL, _FileName: String); destructor Destroy; override; end; function GetWebContent (const _FileURL: String): string; implementation constructor TWebFileDownloader.Create(const _FileURL, _FileName: String); begin inherited Create(true); Priority := TpLowest; FFileURL := CopyString(_FileURL); FFileName := CopyString(_FileName); ReturnValue := 0; Resume; end; procedure TWebFileDownloader.Execute; begin if GetWebFile(FFileURL,FFileName) then ReturnValue := 1; inherited; end; destructor TWebFileDownloader.Destroy; begin FFileURL := ''; FFilename := ''; inherited Destroy; end; procedure TWebFileDownloader.EnforceDirectory(const _Path: string); var UpperPath: string; begin UpperPath := ExtractFileDir(ExcludeTrailingPathDelimiter(_Path)); if not DirectoryExists(UpperPath) then begin EnforceDirectory(UpperPath); end; ForceDirectories(_Path); end; function TWebFileDownloader.GetWebFile (const _FileURL, _FileName: String): boolean; const BufferSize = 1024; var hSession, hURL: HInternet; Buffer: array[1..BufferSize] of Byte; BufferLen: DWORD; f: File; sAppName: string; begin sAppName := ExtractFileName(Application.ExeName) ; hSession := InternetOpen(PChar(sAppName), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0) ; try hURL := InternetOpenURL(hSession, PChar(_FileURL), nil, 0, INTERNET_FLAG_RELOAD, 0) ; try EnforceDirectory(IncludeTrailingBackslash(ExtractFileDir(_FileName))); AssignFile(f, _FileName) ; Rewrite(f,1) ; repeat InternetReadFile(hURL, @Buffer, SizeOf(Buffer), BufferLen) ; BlockWrite(f, Buffer, BufferLen); synchronize(ForceProcessMessages); until BufferLen = 0; CloseFile(f); except InternetCloseHandle(hURL); Result := false; InternetCloseHandle(hSession); exit; end; InternetCloseHandle(hURL); finally InternetCloseHandle(hSession); Result := true; end end; procedure TWebFileDownloader.ForceProcessMessages; begin Application.ProcessMessages; end; function GetWebContent (const _FileURL: String): string; const BufferSize = 1024; var hSession, hURL: HInternet; Buffer: array[1..BufferSize] of Byte; BufferLen,i: DWORD; sAppName: string; begin Result := ''; sAppName := ExtractFileName(Application.ExeName) ; hSession := InternetOpen(PChar(sAppName), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0) ; try hURL := InternetOpenURL(hSession, PChar(_FileURL), nil, 0, INTERNET_FLAG_RELOAD, 0) ; try repeat InternetReadFile(hURL, @Buffer, SizeOf(Buffer), BufferLen) ; for i := 1 to Bufferlen do begin Result := Result + Char(Buffer[i]); end; until BufferLen = 0; finally InternetCloseHandle(hURL) end finally InternetCloseHandle(hSession) end end; end.
(* * FPG EDIT : Edit FPG file from DIV2, FENIX and CDIV * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * *) unit uPCX; interface uses SysUtils, FileUtil, classes; type uPCX_header = record manufacturer, version, encoding, bits_per_pixel : byte; xmin, ymin, xmax, ymax, hres, vres : word; palette16 : Array [0 .. 47] of byte; reserved, color_planes : byte; // (1) 8bits (3) 24 bits bytes_per_line, palette_type, Hresol, Vresol : word; filler : Array [0 .. 53] of byte; end; var PCX_header : uPCX_header; //PCX_palette: Array [0 .. 767] of byte; function load_PCX_header(str : string): Boolean; function is_PCX : Boolean; implementation function load_PCX_header(str : string): boolean; var f : TFileStream; begin result := false; if not FileExistsUTF8(str) { *Converted from FileExists* } then Exit; f := TFileStream.Create(str, fmOpenRead); f.Read(PCX_header, SizeOf(uPCX_header)); f.free; result := true; end; function is_PCX : Boolean; begin is_PCX := false; if (PCX_header.manufacturer = 10) and (PCX_header.version = 5) and (PCX_header.encoding = 1) and (PCX_header.bits_per_pixel = 8) and (PCX_header.color_planes = 1) then is_PCX := true; end; end.
//------------------------------------------------------------------------------ //ZoneOptions UNIT //------------------------------------------------------------------------------ // What it does- // This unit is used to gain access to configuration variables loaded from // Zone.ini. // // Changes - // January 7th, 2007 - RaX - Broken out from ServerOptions. // //------------------------------------------------------------------------------ unit ZoneOptions; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses IniFiles; type //------------------------------------------------------------------------------ //TZoneOptions CLASS //------------------------------------------------------------------------------ TZoneOptions = class(TMemIniFile) private //private variables fID : LongWord; fPort : Word; fEnabled : boolean; fWANIP : String; fLANIP : String; fCharaIP : String; fCharaPort : Word; fCharaKey : String; fInterIP : String; fInterPort : Word; fInterKey : String; fZoneTick : Word;//The amount of time in milliseconds to sleep // between packet processes. fEventTick : Word;//The amount of time in milliseconds to sleep // between event processes. fCharClickArea: Word;//The number of cells away from a character that //They can click to move to. fCharShowArea : Word;//The distance in cells away from a character that //other entities appear in. fIndySchedulerType : Byte; fIndyThreadPoolSize : Word; fBaseXPMultiplier: LongWord; fJobXPMultiplier: LongWord; fMaxBaseLevel : Word; fMaxJobLevel : Word; fMaxBaseLevelsPerEXPGain : Word; fMaxJobLevelsPerEXPGain : Word; fFullHPOnLevelUP : Boolean; fFullSPOnLevelUP : Boolean; fKickOnShutdown : Boolean; fMaxStats : Integer; fMaxStackItem : Word; fMaxItems : Word; fGroundItemTimeout : LongWord; fDynamicMapLoading : Boolean; fAllowInstance : Boolean; //Gets/Sets procedure SetPort(Value : Word); procedure SetWANIP(Value : String); procedure SetLANIP(Value : String); procedure SetCharaIP(Value : String); procedure SetCharaPort(Value : Word); public //Server property Enabled : boolean read fEnabled; property ID : LongWord read fID; //Communication property Port : Word read fPort write SetPort; property WANIP : String read fWANIP write SetWANIP; property LANIP : String read fLANIP write SetLANIP; property CharaIP : String read fCharaIP write SetCharaIP; property CharaPort : Word read fCharaPort write SetCharaPort; property CharaKey : string read fCharaKey; property InterIP : String read fInterIP; property InterPort : Word read fInterPort; property InterKey : string read fInterKey; //Security //Options //Performance property ZoneTick : Word read fZoneTick; property EventTick : Word read fEventTick; property CharClickArea: Word read fCharClickArea; property CharShowArea : Word read fCharShowArea; property IndySchedulerType : Byte read fIndySchedulerType; property IndyThreadPoolSize : Word read fIndyThreadPoolSize; //Game property KickOnShutdown : Boolean read fKickOnShutdown; property BaseXPMultiplier: LongWord read fBaseXPMultiplier; property JobXPMultiplier: LongWord read fJobXPMultiplier; property MaxBaseLevel : Word read fMaxBaseLevel; property MaxJobLevel : Word read fMaxJobLevel; property MaxBaseLevelsPerEXPGain : Word read fMaxBaseLevelsPerEXPGain; property MaxJobLevelsPerEXPGain : Word read fMaxJobLevelsPerEXPGain; property FullHPOnLevelUp : Boolean read fFullHPOnLevelUp; property FullSPOnLevelUp : Boolean read fFullSPOnLevelUp; property MaxCharacterStats : Integer read fMaxStats; property MaxStackItem : Word read fMaxStackItem; property MaxItems : Word read fMaxItems; property GroundItemTimeout : LongWord read fGroundItemTimeout; property DynamicMapLoading : Boolean read fDynamicMapLoading; property AllowInstance : Boolean read fAllowInstance; //Public methods procedure Load; procedure Save; end; //------------------------------------------------------------------------------ implementation uses Classes, SysUtils, Math, NetworkConstants; //------------------------------------------------------------------------------ //Load PROCEDURE //------------------------------------------------------------------------------ // What it does- // This routine is called to load the ini file values from file itself. // This routine contains multiple subroutines. Each one loads a different // portion of the ini. All changes to said routines should be documented in // THIS changes block. // // Changes - // September 21st, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TZoneOptions.Load; var Section : TStringList; //-------------------------------------------------------------------------- //LoadServer SUB PROCEDURE //-------------------------------------------------------------------------- procedure LoadServer; begin ReadSectionValues('Server', Section); fEnabled := StrToBoolDef(Section.Values['Enabled'] ,true); fID := EnsureRange(StrToIntDef(Section.Values['ID'] ,1), Low(LongWord), High(LongWord)); end;{Subroutine LoadServer} //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //LoadCommunication SUB PROCEDURE //-------------------------------------------------------------------------- procedure LoadCommunication; begin ReadSectionValues('Communication', Section); fPort := EnsureRange(StrToIntDef(Section.Values['Port'], 5121), 1, MAX_PORT); if Section.Values['WANIP'] = '' then begin Section.Values['WANIP'] := '127.0.0.1'; end; fWANIP := Section.Values['WANIP']; if Section.Values['LANIP'] = '' then begin Section.Values['LANIP'] := '127.0.0.1'; end; fLANIP := Section.Values['LANIP']; if Section.Values['CharaIP'] = '' then begin Section.Values['CharaIP'] := '127.0.0.1'; end; fCharaIP := Section.Values['CharaIP']; fCharaPort := EnsureRange(StrToIntDef(Section.Values['CharaPort'], 6121), 1, MAX_PORT); fCharaKey := Section.Values['CharaKey']; if Section.Values['InterIP'] = '' then begin Section.Values['InterIP'] := '127.0.0.1'; end; fInterIP := Section.Values['InterIP']; fInterPort := EnsureRange(StrToIntDef(Section.Values['InterPort'], 4000), 1, MAX_PORT); fInterKey := Section.Values['InterKey']; end;{Subroutine LoadCommunication} //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //LoadSecurity SUB PROCEDURE //-------------------------------------------------------------------------- procedure LoadSecurity; begin ReadSectionValues('Security', Section); end;{Subroutine LoadSecurity} //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //LoadPerformance SUB PROCEDURE //-------------------------------------------------------------------------- procedure LoadPerformance; begin ReadSectionValues('Performance', Section); fZoneTick := EnsureRange(StrToIntDef(Section.Values['Zone Tick'], 10), Low(Word), High(Word)); fEventTick := EnsureRange(StrToIntDef(Section.Values['Event Tick'], 10), Low(Word), High(Word)); fCharClickArea:= EnsureRange(StrToIntDef(Section.Values['Click Area'], 16), Low(Word), High(Word)); fCharShowArea := EnsureRange(StrToIntDef(Section.Values['Show Area'], 16), Low(Word), High(Word)); fIndySchedulerType := EnsureRange(StrToIntDef(Section.Values['Indy Scheduler Type'], 0), 0, 1); fIndyThreadPoolSize := EnsureRange(StrToIntDef(Section.Values['Indy Thread Pool Size'], 1), 1, High(Word)); end;{Subroutine LoadPerformance} //-------------------------------------------------------------------------- //-------------------------------------------------------------- //LoadGame SUB PROCEDURE //-------------------------------------------------------------- procedure LoadGame; begin ReadSectionValues('Game', Section); fKickOnShutdown := StrToBoolDef(Section.Values['Kick On Shutdown'] ,False); fBaseXPMultiplier := Min(StrToIntDef(Section.Values['Base EXP Multiplier'], 1), High(LongWord)); fJobXPMultiplier := Min(StrToIntDef(Section.Values['Job EXP Multiplier'], 1), High(LongWord)); fMaxBaseLevel := Min(StrToIntDef(Section.Values['Max. Base Level'], 99), High(Word)); fMaxJobLevel := Min(StrToIntDef(Section.Values['Max. Job Level'], 99), High(Word)); fMaxBaseLevelsPerEXPGain := Min(StrToIntDef(Section.Values['Max. Base Levels Allowed Per EXP Gain'], 1), High(Word)); fMaxJobLevelsPerEXPGain := Min(StrToIntDef(Section.Values['Max. Job Levels Allowed Per EXP Gain'], 1), High(Word)); fFullHPOnLevelUp := StrToBoolDef(Section.Values['Full HP on Level up?'], TRUE); fFullSPOnLevelUp := StrToBoolDef(Section.Values['Full SP on Level up?'], TRUE); fMaxStats := StrToIntDef(Section.Values['Max. Character Stats'], 99); fMaxStackItem := EnsureRange(StrToIntDef(Section.Values['MaxStackItem'], 30000),0,High(Word)); fMaxItems := EnsureRange(StrToIntDef(Section.Values['MaxItems'], 100),0,High(Word)); fGroundItemTimeout := EnsureRange(StrToIntDef(Section.Values['GroundItemTimeout'], 60),1,High(Word)); fDynamicMapLoading := StrToBoolDef(Section.Values['Dynamic Map Loading'], true); fAllowInstance := StrToBoolDef(Section.Values['Allow Instance'], true); end;{Subroutine LoadPerformance} //-------------------------------------------------------------- //-------------------------------------------------------------------------- //LoadOptions SUB PROCEDURE //-------------------------------------------------------------------------- procedure LoadOptions; begin ReadSectionValues('Options', Section); end;{Subroutine LoadOptions} //-------------------------------------------------------------------------- begin Section := TStringList.Create; Section.QuoteChar := '"'; Section.Delimiter := ','; LoadServer; LoadCommunication; LoadSecurity; LoadPerformance; LoadGame; LoadOptions; Section.Free; end;{Load} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Save() PROCEDURE //------------------------------------------------------------------------------ // What it does- // This routine saves all configuration values defined here to the .ini // file. // // Changes - // September 21st, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TZoneOptions.Save; begin //Server WriteString('Server','Enabled',BoolToStr(Enabled)); WriteString('Server','ID',IntToStr(ID)); //Communication WriteString('Communication','WANIP',WANIP); WriteString('Communication','LANIP',LANIP); WriteString('Communication','Port', IntToStr(Port)); WriteString('Communication','CharaIP',fCharaIP); WriteString('Communication','CharaPort',IntToStr(fCharaPort)); WriteString('Communication','CharaKey',fCharaKey); WriteString('Communication','InterIP',fInterIP); WriteString('Communication','InterPort',IntToStr(fInterPort)); WriteString('Communication','InterKey',fInterKey); //Security //Performance WriteString('Performance','Zone Tick',IntToStr(fZoneTick)); WriteString('Performance','Event Tick',IntToStr(fEventTick)); WriteString('Performance','Click Area',IntToStr(fCharClickArea)); WriteString('Performance','ShowArea',IntToStr(fCharShowArea)); WriteString('Performance','Indy Scheduler Type',IntToStr(IndySchedulerType)); WriteString('Performance','Indy Thread Pool Size',IntToStr(IndyThreadPoolSize)); //Game WriteString('Game','Kick On Shutdown',BoolToStr(fKickOnShutdown)); WriteString('Game','Base EXP Multiplier',IntToStr(fBaseXPMultiplier)); WriteString('Game','Job EXP Multiplier',IntToStr(fJobXPMultiplier)); WriteString('Game','Max. Base Level',IntToStr(fMaxBaseLevel)); WriteString('Game','Max. Job Level',IntToStr(fMaxJobLevel)); WriteString('Game','Max. Base Levels Allowed Per EXP Gain',IntToStr(fMaxBaseLevelsPerEXPGain)); WriteString('Game','Max. Job Levels Allowed Per EXP Gain',IntToStr(fMaxJobLevelsPerEXPGain)); WriteString('Game','Full HP On Level Up?',BoolToStr(fFullHPOnLevelUp)); WriteString('Game','Full SP On Level Up?',BoolToStr(fFullSPOnLevelUp)); WriteString('Game','Max. Character Stats',IntToStr(fMaxStats)); WriteString('Game','MaxStackItem',IntToStr(fMaxStackItem)); WriteString('Game','MaxItems',IntToStr(fMaxItems)); WriteString('Game','GroundItemTimeout', IntToStr(fGroundItemTimeout)); WriteString('Game','Dynamic Map Loading',BoolToStr(fDynamicMapLoading)); WriteString('Game','Allow Instance',BoolToStr(fAllowInstance)); //Options UpdateFile; end;{Save} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetPort() PROCEDURE //------------------------------------------------------------------------------ // What it does- // Property Set Routine for ZonePort. Ensures that if the Zone port is // changed for whatever reason, that it gets written to the .ini immediately. // The same is true for all communication variables. // // Changes - // September 21st, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TZoneOptions.SetPort(Value : word); begin if fPort <> Value then begin fPort := Value; WriteString('Communication', 'Port', IntToStr(Port)); end; end;{SetPort} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetWANIP() PROCEDURE //------------------------------------------------------------------------------ // What it does- // Property Set Routine for WAN IP, and save to .ini // Changes - // November 29th, 2006 - RaX - Created. // March 13th, 2007 - Aeomin - Modify Header // //------------------------------------------------------------------------------ procedure TZoneOptions.SetWANIP(Value : String); begin if fWANIP <> Value then begin fWANIP := Value; WriteString('Communication', 'WANIP', WANIP); end; end;{SetWANIP} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetLANIP() PROCEDURE //------------------------------------------------------------------------------ // What it does- // Property Set Routine for LAN IP, and save to .ini // Changes - // November 29th, 2006 - RaX - Created. // March 13th, 2007 - Aeomin - Modify Header // //------------------------------------------------------------------------------ procedure TZoneOptions.SetLANIP(Value : String); begin if fWANIP <> Value then begin fWANIP := Value; WriteString('Communication', 'LANIP', LANIP); end; end;{SetLANIP} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetCharaPort() PROCEDURE //------------------------------------------------------------------------------ // What it does- // Property Set Routine for Character Server Port, and save to .ini // Changes - // January 14th, 2007 - Tsusai - Created. // March 13th, 2007 - Aeomin - Modify Header // //------------------------------------------------------------------------------ procedure TZoneOptions.SetCharaPort(Value : Word); begin if fCharaPort <> Value then begin fCharaPort := Value; WriteString('Communication', 'CharaPort', IntToStr(CharaPort)); end; end;{SetCharaPort} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetCharaIP() PROCEDURE //------------------------------------------------------------------------------ // What it does- // Property Set Routine for Character Server IP, and save to .ini // Changes - // January 14th, 2007 - Tsusai - Created. // March 13th, 2007 - Aeomin - Modify Header // //------------------------------------------------------------------------------ procedure TZoneOptions.SetCharaIP(Value : String); begin if fCharaIP <> Value then begin fCharaIP := Value; WriteString('Communication', 'CharaIP', CharaIP); end; end;{SetLoginIP} //------------------------------------------------------------------------------ end{ServerOptions}.
{******************************************************************} { SVG fill classes } { } { home page : http://www.mwcs.de } { email : martin.walter@mwcs.de } { } { date : 05-04-2008 } { } { Use of this file is permitted for commercial and non-commercial } { use, as long as the author is credited. } { This file (c) 2005, 2008 Martin Walter } { } { Thanks to: } { Kiriakos Vlahos (deprecated xlink:href to href) } { Kiriakos Vlahos (fixed gradient transform) } { Kiriakos Vlahos (fixed LinearGradient and RadialGradient) } { Kiriakos Vlahos (Refactoring parsing) } { } { This Software is distributed on an "AS IS" basis, WITHOUT } { WARRANTY OF ANY KIND, either express or implied. } { } { *****************************************************************} unit SVGPaint; interface uses Winapi.Windows, Winapi.GDIPOBJ, Winapi.GDIPAPI, System.UITypes, System.Classes, XmlLite, SVGTypes, SVG; type TStopColors = record Colors: packed array of ARGB; Positions: packed array of Single; Count: Integer; end; TSVGStop = class(TSVGObject) strict private FStop: TFloat; FStopColor: TColor; FOpacity: TFloat; protected procedure AssignTo(Dest: TPersistent); override; public procedure Clear; override; procedure ReadIn(const Reader: IXMLReader); override; function ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean; override; procedure PaintToGraphics(Graphics: TGPGraphics); override; procedure PaintToPath(Path: TGPGraphicsPath); override; property Stop: TFloat read FStop write FStop; property StopColor: TColor read FStopColor write FStopColor; property Opacity: TFloat read FOpacity write FOpacity; end; TSVGFiller = class abstract (TSVGMatrix) public function GetBrush(Alpha: Byte; const DestObject: TSVGBasic; IsStrokeBrush: Boolean = False): TGPBrush; virtual; abstract; procedure PaintToGraphics(Graphics: TGPGraphics); override; procedure PaintToPath(Path: TGPGraphicsPath); override; end; TSVGGradient = class abstract (TSVGFiller) { SpreadMethod is not implemented Assumed to be repeat for LinearGradient and pad for RadialGradient } private FURI: string; FGradientUnits: TGradientUnits; protected procedure AssignTo(Dest: TPersistent); override; function GetColors(Alpha: Byte): TStopColors; virtual; public function ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean; override; class function Features: TSVGElementFeatures; override; end; TSVGLinearGradient = class(TSVGGradient) private FX1: TFloat; FY1: TFloat; FX2: TFloat; FY2: TFloat; protected procedure AssignTo(Dest: TPersistent); override; public function ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean; override; function GetBrush(Alpha: Byte; const DestObject: TSVGBasic; IsStrokeBrush: Boolean = False): TGPBrush; override; procedure Clear; override; property X1: TFloat read FX1 write FX1; property Y1: TFloat read FY1 write FY1; property X2: TFloat read FX2 write FX2; property Y2: TFloat read FY2 write FY2; end; TSVGRadialGradient = class(TSVGGradient) private FCX: TFloat; FCY: TFloat; FR: TFloat; FFX: TFloat; FFY: TFloat; protected procedure AssignTo(Dest: TPersistent); override; public procedure Clear; override; procedure ReadIn(const Reader: IXMLReader); override; function ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean; override; function GetBrush(Alpha: Byte; const DestObject: TSVGBasic; IsStrokeBrush: Boolean = False): TGPBrush; override; property CX: TFloat read FCX write FCX; property CY: TFloat read FCY write FCY; property R: TFloat read FR write FR; property FX: TFloat read FFX write FFX; property FY: TFloat read FFY write FFY; end; implementation uses System.Types, System.SysUtils, System.Math, SVGCommon, SVGParse, SVGStyle, SVGColor; // TSVGStop procedure TSVGStop.PaintToPath(Path: TGPGraphicsPath); begin end; procedure TSVGStop.ReadIn(const Reader: IXMLReader); Var S: string; begin inherited; // opacity and stop-color are CSS properties if not HasValue(FOpacity) then begin if Assigned(FStyle) then begin S := FStyle['stop-opacity']; if S <> '' then FOpacity := EnsureRange(ParsePercent(S), 0, 1); end end; if not HasValue(FOpacity) then FOpacity := 1; // default if FStopColor = SVG_INHERIT_COLOR then begin if Assigned(FStyle) then begin S := FStyle['stop-color']; if S <> '' then FStopColor := GetSVGColor(S); end end; if FStopColor = SVG_INHERIT_COLOR then FStopColor := TColors.Black; // default if GetRoot.Grayscale then FStopColor := GetSVGGrayscale(FStopColor) else if (GetRoot.FixedColor <> SVG_INHERIT_COLOR) and (FStopColor <> SVG_NONE_COLOR) then FStopColor := GetRoot.FixedColor; end; function TSVGStop.ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean; begin Result := True; case SVGAttr of saOffset: FStop := ParsePercent(AttrValue); saStopOpacity: FOpacity := EnsureRange(ParsePercent(AttrValue), 0, 1); saStopColor: FStopColor := GetSVGColor(AttrValue); else Result := inherited; end; end; procedure TSVGStop.AssignTo(Dest: TPersistent); begin inherited; if Dest is TSVGStop then begin TSVGStop(Dest).FStop := FStop; TSVGStop(Dest).FStopColor := FStopColor; TSVGStop(Dest).FOpacity := FOpacity; end; end; procedure TSVGStop.Clear; begin inherited; FOpacity := UndefinedFloat; FStopColor := SVG_INHERIT_COLOR; end; procedure TSVGStop.PaintToGraphics(Graphics: TGPGraphics); begin end; // TSVGFiller procedure TSVGFiller.PaintToPath(Path: TGPGraphicsPath); begin end; procedure TSVGFiller.PaintToGraphics(Graphics: TGPGraphics); begin end; // TSVGGradient function TSVGGradient.ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean; begin Result := True; case SVGAttr of saGradientUnits: FGradientUnits := ParseGradientUnits(AttrValue); saXlinkHref: FURI := AttrValue; saHref: FURI := AttrValue; saGradientTransform: LocalMatrix := ParseTransform(AttrValue); else Result := inherited; end; end; // TSVGLinearGradient function TSVGLinearGradient.ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean; begin Result := True; case SVGAttr of saX1: FX1 := ParseLength(AttrValue); saX2: FX2 := ParseLength(AttrValue); saY1: FY1 := ParseLength(AttrValue); saY2: FY2 := ParseLength(AttrValue); else Result := inherited; end; end; procedure TSVGLinearGradient.AssignTo(Dest: TPersistent); begin inherited; if Dest is TSVGLinearGradient then begin TSVGLinearGradient(Dest).FX1 := FX1; TSVGLinearGradient(Dest).FY1 := FY1; TSVGLinearGradient(Dest).FX2 := FX2; TSVGLinearGradient(Dest).FY2 := FY2; end; end; procedure TSVGLinearGradient.Clear; begin inherited; FX1 := UndefinedFloat; FX2 := UndefinedFloat; FY1 := UndefinedFloat; FY2 := UndefinedFloat; end; function TSVGLinearGradient.GetBrush(Alpha: Byte; const DestObject: TSVGBasic; IsStrokeBrush: Boolean): TGPBrush; var Brush: TGPLinearGradientBrush; TGP: TGPMatrix; Colors: TStopColors; BoundsRect: TRectF; MX1, MX2, MY1, MY2: TFloat; SWAdj: TFloat; begin if IsStrokeBrush then SWAdj := DestObject.StrokeWidth / 2 else SWAdj := 0; BoundsRect := DestObject.ObjectBounds; BoundsRect.Inflate(SWAdj, SWAdj); if HasValue(FX1) then MX1 := FX1 - SWAdj else MX1 := BoundsRect.Left; if HasValue(FX2) then MX2 := FX2 + SWAdj else MX2 := BoundsRect.Right; if HasValue(FY1) then MY1 := FY1 - SWAdj else MY1 := BoundsRect.Top; if HasValue(FY2) then MY2 := FY2 + SWAdj else MY2 := BoundsRect.Top; if FGradientUnits = guObjectBoundingBox then begin // X1, X2, Y1, Y2 are relative to the Object Bounding Rect if HasValue(FX1) then MX1 := BoundsRect.Left + FX1 * BoundsRect.Width; if HasValue(FX2) then MX2 := BoundsRect.Left + FX2 * BoundsRect.Width; if HasValue(FY1) then MY1 := BoundsRect.Top + FY1 * BoundsRect.Height; if HasValue(FY2) then MY2 := BoundsRect.Top + FY2 * BoundsRect.Height; end; Brush := TGPLinearGradientBrush.Create(MakePoint(MX1, MY1), MakePoint(MX2, MY2), 0, 0); if not LocalMatrix.IsEmpty then begin TGP := LocalMatrix.ToGPMatrix; Brush.SetTransform(TGP); TGP.Free; end; Colors := GetColors(Alpha); Brush.SetInterpolationColors(PGPColor(Colors.Colors), PSingle(Colors.Positions), Colors.Count); Result := Brush; end; // TSVGRadialGradient procedure TSVGRadialGradient.AssignTo(Dest: TPersistent); begin inherited; if Dest is TSVGRadialGradient then begin TSVGRadialGradient(Dest).FCX := FCX; TSVGRadialGradient(Dest).FCY := FCY; TSVGRadialGradient(Dest).FFX := FFX; TSVGRadialGradient(Dest).FFY := FFY; TSVGRadialGradient(Dest).FR := FR; end; end; procedure TSVGRadialGradient.Clear; begin inherited; FCX := UndefinedFloat; FCY := UndefinedFloat; FR := UndefinedFloat; FFX := FCX; FFY := FCY; end; procedure TSVGRadialGradient.ReadIn(const Reader: IXMLReader); begin inherited; if not HasValue(FFX) then FFX := FCX; if not HasValue(FFY) then FFY := FCY; end; function TSVGRadialGradient.ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean; begin Result := True; case SVGAttr of saCx: FCX := ParseLength(AttrValue); saCy: FCY := ParseLength(AttrValue); saR: FR := ParseLength(AttrValue); saFx: FFX := ParseLength(AttrValue); saFy: FFY := ParseLength(AttrValue); else Result := inherited; end; end; function TSVGRadialGradient.GetBrush(Alpha: Byte; const DestObject: TSVGBasic; IsStrokeBrush: Boolean): TGPBrush; var Brush: TGPPathGradientBrush; Path: TGPGraphicsPath; TGP: TGPMatrix; Colors: TStopColors; RevColors: TStopColors; BoundsRect: TRectF; MCX, MCY, MR, MFX, MFY: TFloat; SWAdj: TFloat; i: integer; begin if IsStrokeBrush then SWAdj := DestObject.StrokeWidth / 2 else SWAdj := 0; BoundsRect := DestObject.ObjectBounds; BoundsRect.Inflate(SWAdj, SWAdj); if HasValue(FCX) then MCX := FCX else MCX := BoundsRect.Left + 0.5 * BoundsRect.Width; if HasValue(FFX) then MFX := FFX else MFX := MCX; if HasValue(FCY) then MCY := FCY else MCY := BoundsRect.Top + 0.5 * BoundsRect.Height; if HasValue(FFY) then MFY := FFY else MFY := MCY; if HasValue(FR) then MR := FR + SWAdj else MR := 0.5 * Sqrt(Sqr(BoundsRect.Width) + Sqr(BoundsRect.Height))/Sqrt(2); if FGradientUnits = guObjectBoundingBox then begin // CX, CY, R, FX, FY are relative to the Object Bounding Rect if HasValue(FCX) then MCX := BoundsRect.Left + FCX * BoundsRect.Width; if HasValue(FFX) then MFX := BoundsRect.Left + FFX * BoundsRect.Width; if HasValue(FCY) then MCY := BoundsRect.Top + FCY * BoundsRect.Height; if HasValue(FFY) then MFY := BoundsRect.Top + FFY * BoundsRect.Height; if HasValue(FR) then MR := FR * Sqrt(Sqr(BoundsRect.Width) + Sqr(BoundsRect.Height))/Sqrt(2); end; Path := TGPGraphicsPath.Create; if HasValue(FR) then Path.AddEllipse(MCX - MR, MCY - MR, 2 * MR, 2 * MR) else Path.AddEllipse(ToGPRectF(BoundsRect)); Brush := TGPPathGradientBrush.Create(Path); Path.Free; Colors := GetColors(Alpha); SetLength(RevColors.Colors, Colors.Count); SetLength(RevColors.Positions, Colors.Count); // Reverse colors! TGPPathGradientBrush uses colors from outside to inside unlike svg for i := 0 to Colors.Count - 1 do begin RevColors.Colors[i] := Colors.Colors[Colors.Count - 1 - i]; RevColors.Positions[i] := 1 - Colors.Positions[Colors.Count - 1 - i]; end; if Colors.Count > 0 then // Temporarily store last color. Used in TSVGBasic.BeforePaint DestObject.FillColor := Integer(RevColors.Colors[0]); Brush.SetInterpolationColors(PARGB(RevColors.Colors), PSingle(RevColors.Positions), Colors.Count); if HasValue(FFX) and HasValue(FFY) then Brush.SetCenterPoint(MakePoint(MFX, MFY)); if not LocalMatrix.IsEmpty then begin TGP := LocalMatrix.ToGPMatrix; Brush.SetTransform(TGP); TGP.Free; end; Result := Brush; end; procedure TSVGGradient.AssignTo(Dest: TPersistent); begin inherited; if Dest is TSVGGradient then begin TSVGGradient(Dest).FURI := FURI; TSVGGradient(Dest).FGradientUnits := FGradientUnits; end; end; class function TSVGGradient.Features: TSVGElementFeatures; begin Result := [sefMayHaveChildren]; end; function TSVGGradient.GetColors(Alpha: Byte): TStopColors; var C, Start, ColorCount: Integer; Stop: TSVGStop; Item: TSVGGradient; begin Result.Count := 0; if FURI = '' then Item := Self else begin Item := TSVGGradient(GetRoot.FindByID(FURI)); if not (Item is TSVGGradient) then Exit; end; Start := 0; ColorCount := Item.Count; if Item.Count = 0 then Exit; if TSVGStop(Item.Items[ColorCount - 1]).Stop < 1 then Inc(ColorCount); if TSVGStop(Item.Items[0]).Stop > 0 then begin Inc(ColorCount); Inc(Start); end; SetLength(Result.Colors, ColorCount); SetLength(Result.Positions, ColorCount); if Start > 0 then begin Stop := TSVGStop(Item.Items[0]); Result.Colors[0] := ConvertColor(Stop.StopColor, Round(Alpha * Stop.Opacity)); Result.Positions[0] := 0; end; for C := 0 to Item.Count - 1 do begin Stop := TSVGStop(Item.Items[C]); Result.Colors[C + Start] := ConvertColor(Stop.StopColor, Round(Alpha * Stop.Opacity)); Result.Positions[C + Start] := Stop.Stop; end; if (ColorCount - Start) > Item.Count then begin Stop := TSVGStop(Item.Items[Item.Count - 1]); Result.Colors[ColorCount - 1] := ConvertColor(Stop.StopColor, Round(Alpha * Stop.Opacity)); Result.Positions[ColorCount - 1] := 1; end; Result.Count := ColorCount; end; end.
unit tMapping; {******************************************************************************* Program Modifications: ------------------------------------------------------------------------------- Date ID Description ------------------------------------------------------------------------------- 11/17/2014 CB01 class to hold Samplet Unit - Cover Letter - Artifact text box mappings ********************************************************************************} interface uses SysUtils; type BasicMapping = record SampleUnit : integer; CoverLetterName : string; CoverLetterTextBox : string; ArtifactName : string; ArtifactTextBox : string; end; MappingSet = array[0..100] of BasicMapping; Function FormattedMapping(mapping : BasicMapping) : string; Function AssignBasicMapping(SUnit : integer; CLName, CLTextBox, AName, ATextBox : string) : BasicMapping; implementation Function FormattedMapping(mapping : BasicMapping) : string; begin with mapping do result := IntToStr(SampleUnit) + '->' + CoverLetterName + '.' + CoverLetterTextBox + '<=' + ArtifactName + ArtifactTextBox + '! '; end; Function AssignBasicMapping(SUnit : integer; CLName, CLTextBox, AName, ATextBox : string) : BasicMapping; begin with result do begin SampleUnit := SUnit; CoverLetterName := CLName; CoverLetterTextBox := CLTextBox; ArtifactName := AName; ArtifactTextBox := ATextBox; end; end ; end.
unit GLDSkewParamsFrame; interface uses Classes, Controls, Forms, ComCtrls, StdCtrls, GL, GLDTypes, GLDSystem, GLDAxisFrame, GLDModifyLimitEffectFrame, GLDUpDown; type TGLDSkewParamsFrame = class(TFrame) GB_Rotate: TGroupBox; L_Amount: TLabel; L_Direction: TLabel; E_Amount: TEdit; E_Direction: TEdit; UD_Amount: TGLDUpDown; UD_Direction: TGLDUpDown; F_Axis: TGLDAxisFrame; F_LimitEffect: TGLDModifyLimitEffectFrame; procedure ValueChangeUD(Sender: TObject); procedure AxisChange(Sender: TObject); procedure EditEnter(Sender: TObject); private FDrawer: TGLDDrawer; procedure SetDrawer(Value: TGLDDrawer); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; function HaveSkew: GLboolean; function GetParams: TGLDSkewParams; procedure SetParams(const Params: TGLDSkewParams); procedure SetParamsFrom(Source: TPersistent); procedure ApplyParams; property Drawer: TGLDDrawer read FDrawer write SetDrawer; end; implementation {$R *.dfm} uses SysUtils, GLDConst, GLDX, GLDModify; constructor TGLDSkewParamsFrame.Create(AOwner: TComponent); begin inherited Create(AOwner); FDrawer := nil; F_Axis.OnAxisChange := Self.AxisChange; end; function TGLDSkewParamsFrame.HaveSkew: GLboolean; begin Result := False; if Assigned(FDrawer) and Assigned(FDrawer.EditedModify) and (FDrawer.EditedModify is TGLDSkew) then Result := True; end; function TGLDSkewParamsFrame.GetParams: TGLDSkewParams; begin if HaveSkew then Result.Center := TGLDSkew(FDrawer.EditedModify).Center.Vector3f else Result.Center := GLD_VECTOR3F_ZERO; Result.Amount := UD_Amount.Position; Result.Direction := UD_Direction.Position; Result.Axis := F_Axis.Axis; Result.LimitEffect := F_LimitEffect.CB_LimitEffect.Checked; Result.UpperLimit := F_LimitEffect.UD_UpperLimit.Position; Result.LowerLimit := F_LimitEffect.UD_LowerLimit.Position; end; procedure TGLDSkewParamsFrame.SetParams(const Params: TGLDSkewParams); begin UD_Amount.Position := Params.Amount; UD_Direction.Position := Params.Direction; F_Axis.Axis := Params.Axis; F_LimitEffect.SetParams(Params.LimitEffect, Params.UpperLimit, Params.LowerLimit); end; procedure TGLDSkewParamsFrame.SetParamsFrom(Source: TPersistent); begin if Assigned(Source) and (Source is TGLDSkew) then SetParams(TGLDSkew(Source).Params); end; procedure TGLDSkewParamsFrame.ApplyParams; begin if HaveSkew then TGLDSkew(FDrawer.EditedModify).Params := GetParams; end; procedure TGLDSkewParamsFrame.ValueChangeUD(Sender: TObject); begin if HaveSkew then with TGLDSkew(FDrawer.EditedModify) do if Sender = UD_Amount then Amount := UD_Amount.Position else if Sender = UD_Direction then Direction := UD_Direction.Position else if Sender = F_LimitEffect.CB_LimitEffect then LimitEffect := F_LimitEffect.CB_LimitEffect.Checked else if Sender = F_LimitEffect.UD_UpperLimit then UpperLimit := F_LimitEffect.UD_UpperLimit.Position else if Sender = F_LimitEffect.UD_LowerLimit then LowerLimit := F_LimitEffect.UD_LowerLimit.Position; end; procedure TGLDSkewParamsFrame.AxisChange(Sender: TObject); begin if HaveSkew then with TGLDSkew(FDrawer.EditedModify) do Axis := F_Axis.Axis; end; procedure TGLDSkewParamsFrame.EditEnter(Sender: TObject); begin ApplyParams; end; procedure TGLDSkewParamsFrame.Notification(AComponent: TComponent; Operation: TOperation); begin if Assigned(FDrawer) and (AComponent = FDrawer.Owner) and (Operation = opRemove) then FDrawer := nil; inherited Notification(AComponent, Operation); end; procedure TGLDSkewParamsFrame.SetDrawer(Value: TGLDDrawer); begin FDrawer := Value; if Assigned(FDrawer) then SetParamsFrom(FDrawer.EditedModify); end; end.
unit lotofacil_constantes; {$mode objfpc}{$H+} interface uses Classes, SysUtils; const lotofacil_url_download = 'http://loterias.caixa.gov.br/wps/portal/loterias/landing/lotofacil/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOLNDH0MPAzcDbz8vTxNDRy9_Y2NQ13CDA0sTIEKIoEKnN0dPUzMfQwMDEwsjAw8XZw8XMwtfQ0MPM2I02-AAzgaENIfrh-FqsQ9wBmoxN_FydLAGAgNTKEK8DkRrACPGwpyQyMMMj0VAcySpRM!/dl5/d5/L2dBISEvZ0FBIS9nQSEh/pw/Z7_61L0H0G0J0VSC0AC4GLFAD2003/res/id=buscaResultado/c=cacheLevelPage/=/?timestampAjax=@timestamp@&concurso=@concurso@'; const // As constantes abaixo, são utilizado no controle de filtros, // assim, fica mais fácil mapear, uma lista de valores pra cada // controle. ID_NOVOS_REPETIDOS = 0; ID_PAR_IMPAR = 1; ID_PRIMO_NAO_PRIMO = 2; ID_EXTERNO_INTERNO = 3; ID_DEZENA_2 = 4; ID_B1_QT_VZ = 5; ID_B2_QT_VZ = 6; ID_B3_QT_VZ = 7; ID_B4_QT_VZ = 8; ID_B5_QT_VZ = 9; ID_B6_QT_VZ = 10; ID_B7_QT_VZ = 11; ID_B8_QT_VZ = 12; ID_B9_QT_VZ = 13; ID_B10_QT_VZ = 14; ID_B11_QT_VZ = 15; ID_B12_QT_VZ = 16; ID_B13_QT_VZ = 17; ID_B14_QT_VZ = 18; ID_B15_QT_VZ = 19; ID_CMP_B1_QT_VZ = 20; ID_CMP_B2_QT_VZ = 21; ID_CMP_B3_QT_VZ = 22; ID_CMP_B4_QT_VZ = 23; ID_CMP_B5_QT_VZ = 24; ID_CMP_B6_QT_VZ = 25; ID_CMP_B7_QT_VZ = 26; ID_CMP_B8_QT_VZ = 27; ID_CMP_B9_QT_VZ = 28; ID_CMP_B10_QT_VZ = 29; ID_CMP_B11_QT_VZ = 30; ID_CMP_B12_QT_VZ = 31; ID_CMP_B13_QT_VZ = 32; ID_CMP_B14_QT_VZ = 33; ID_CMP_B15_QT_VZ = 34; ID_HORIZONTAL = 35; ID_VERTICAL = 36; ID_DIAGONAL_ESQUERDA = 37; ID_DIAGONAL_DIREITA = 38; ID_ESQUERDA_DIREITA = 39; ID_SUPERIOR_INFERIOR = 40; ID_SUPERIOR_ESQUERDA_INFERIOR_DIREITA = 41; ID_SUPERIOR_DIREITA_INFERIOR_ESQUERDA = 42; ID_CRUZETA = 43; ID_LOSANGO = 44; ID_QUINTETO = 45; ID_TRIANGULO = 46; ID_TRIO = 47; ID_X1_X2 = 48; ID_DEZENA = 49; ID_UNIDADE = 50; ID_ALGARISMO = 51; ID_SOMA_BOLAS = 52; ID_SOMA_ALGARISMO = 53; ID_LINHA_COLUNA = 54; ID_FREQUENCIA = 55; ID_DF_MENOR_MAIOR = 56; ID_DF_PAR_IMPAR = 57; ID_DF_QT_DF_1 = 58; ID_DF_QT_DF_1_A_QT_DF_2 = 59; ID_DF_QT_DF_1_A_QT_DF_3 = 60; ID_B1_B15 = 61; ID_B2_B14 = 62; ID_B3_B13 = 63; ID_B4_B12 = 64; ID_B5_B11 = 65; ID_B6_B10 = 66; ID_B7_B9 = 67; ID_B1_B8_B15 = 68; ID_B2_B8_B14 = 69; ID_B3_B8_B13 = 70; ID_B4_B8_B12 = 71; ID_B5_B8_B11 = 72; ID_B6_B8_B10 = 73; ID_B7_B8_B9 = 74; ID_ULTIMO = 67; TOTAL_DE_FILTROS = ID_ULTIMO + 1; // Indica qual é o último controle implementado. ID_ULTIMO_IMPLEMENTADO = ID_B7_B9; // Constantes utilizadas pra serem atribuídas na propriedade 'tag' // de cada controle que é utilizada nos filtros por bola, que seria // os filtros utilizando as tabelas binárias do banco de dados. const ID_BIN_PAR = 1; ID_BIN_IMPAR = 2; ID_BIN_PRIMO = 3; ID_BIN_NAO_PRIMO = 4; ID_BIN_EXTERNO = 5; ID_BIN_INTERNO = 6; // Horizontal. ID_BIN_HRZ_1 = 7; ID_BIN_HRZ_2 = 8; ID_BIN_HRZ_3 = 9; ID_BIN_HRZ_4 = 10; ID_BIN_HRZ_5 = 11; // Vertical. ID_BIN_VRT_1 = 12; ID_BIN_VRT_2 = 13; ID_BIN_VRT_3 = 14; ID_BIN_VRT_4 = 15; ID_BIN_VRT_5 = 16; // Diagonal esquerda. ID_BIN_DGE_1 = 17; ID_BIN_DGE_2 = 18; ID_BIN_DGE_3 = 19; ID_BIN_DGE_4 = 20; ID_BIN_DGE_5 = 21; // Diagonal direita. ID_BIN_DGD_1 = 22; ID_BIN_DGD_2 = 23; ID_BIN_DGD_3 = 24; ID_BIN_DGD_4 = 25; ID_BIN_DGD_5 = 26; // Esquerda, direita. // Superior, inferior. ID_BIN_ESQ = 27; ID_BIN_DIR = 28; ID_BIN_SUP = 29; ID_BIN_INF = 30; // Superior esquerda, inferior direita // Superior direita, inferior esquerda ID_BIN_SUP_ESQ = 31; ID_BIN_INF_DIR = 32; ID_BIN_SUP_DIR = 33; ID_BIN_INF_ESQ = 34; // Cruzeta. ID_BIN_CRZ_1 = 35; ID_BIN_CRZ_2 = 36; ID_BIN_CRZ_3 = 37; ID_BIN_CRZ_4 = 38; ID_BIN_CRZ_5 = 39; // Losango. ID_BIN_LSNG_1 = 40; ID_BIN_LSNG_2 = 41; ID_BIN_LSNG_3 = 42; ID_BIN_LSNG_4 = 43; ID_BIN_LSNG_5 = 44; // Quinteto. ID_BIN_QNT_1 = 45; ID_BIN_QNT_2 = 46; ID_BIN_QNT_3 = 47; ID_BIN_QNT_4 = 48; ID_BIN_QNT_5 = 49; // Triângulo. ID_BIN_TRNG_1 = 50; ID_BIN_TRNG_2 = 51; ID_BIN_TRNG_3 = 52; ID_BIN_TRNG_4 = 53; // Trio. ID_BIN_TRIO_1 = 54; ID_BIN_TRIO_2 = 55; ID_BIN_TRIO_3 = 56; ID_BIN_TRIO_4 = 57; ID_BIN_TRIO_5 = 58; ID_BIN_TRIO_6 = 59; ID_BIN_TRIO_7 = 60; ID_BIN_TRIO_8 = 61; ID_BIN_X1 = 62; ID_BIN_X2 = 63; // Constantes utilizar pra serem utilizadas // nos controles de estatística por concurso. ID_POR_CONCURSO_PAR_IMPAR = 65; ID_POR_CONCURSO_PRIMO_NAO_PRIMO = 67; ID_POR_CONCURSO_EXTERNO_INTERNO = 69; // Horizontal. ID_POR_CONCURSO_HORIZONTAL = 71; ID_POR_CONCURSO_HRZ_2 = 72; ID_POR_CONCURSO_HRZ_3 = 73; ID_POR_CONCURSO_HRZ_4 = 74; ID_POR_CONCURSO_HRZ_5 = 75; // Vertical. ID_POR_CONCURSO_VRT_1 = 76; ID_POR_CONCURSO_VRT_2 = 77; ID_POR_CONCURSO_VRT_3 = 78; ID_POR_CONCURSO_VRT_4 = 79; ID_POR_CONCURSO_VRT_5 = 80; // Diagonal esquerda. ID_POR_CONCURSO_DGE_1 = 81; ID_POR_CONCURSO_DGE_2 = 82; ID_POR_CONCURSO_DGE_3 = 83; ID_POR_CONCURSO_DGE_4 = 84; ID_POR_CONCURSO_DGE_5 = 85; // Diagonal direita. ID_POR_CONCURSO_DGD_1 = 86; ID_POR_CONCURSO_DGD_2 = 87; ID_POR_CONCURSO_DGD_3 = 88; ID_POR_CONCURSO_DGD_4 = 89; ID_POR_CONCURSO_DGD_5 = 90; // Esquerda, direita. // Superior, inferior. ID_POR_CONCURSO_ESQ = 91; ID_POR_CONCURSO_DIR = 92; ID_POR_CONCURSO_SUP = 93; ID_POR_CONCURSO_INF = 94; // Superior esquerda, inferior direita // Superior direita, inferior esquerda ID_POR_CONCURSO_SUP_ESQ = 95; ID_POR_CONCURSO_INF_DIR = 96; ID_POR_CONCURSO_SUP_DIR = 97; ID_POR_CONCURSO_INF_ESQ = 98; // Cruzeta. ID_POR_CONCURSO_CRZ_1 = 99; ID_POR_CONCURSO_CRZ_2 = 100; ID_POR_CONCURSO_CRZ_3 = 101; ID_POR_CONCURSO_CRZ_4 = 38; ID_POR_CONCURSO_CRZ_5 = 39; // Losango. ID_POR_CONCURSO_LSNG_1 = 40; ID_POR_CONCURSO_LSNG_2 = 41; ID_POR_CONCURSO_LSNG_3 = 42; ID_POR_CONCURSO_LSNG_4 = 43; ID_POR_CONCURSO_LSNG_5 = 44; // Quinteto. ID_POR_CONCURSO_QNT_1 = 45; ID_POR_CONCURSO_QNT_2 = 46; ID_POR_CONCURSO_QNT_3 = 47; ID_POR_CONCURSO_QNT_4 = 48; ID_POR_CONCURSO_QNT_5 = 49; // Triângulo. ID_POR_CONCURSO_TRNG_1 = 50; ID_POR_CONCURSO_TRNG_2 = 51; ID_POR_CONCURSO_TRNG_3 = 52; ID_POR_CONCURSO_TRNG_4 = 53; // Trio. ID_POR_CONCURSO_TRIO_1 = 54; ID_POR_CONCURSO_TRIO_2 = 55; ID_POR_CONCURSO_TRIO_3 = 56; ID_POR_CONCURSO_TRIO_4 = 57; ID_POR_CONCURSO_TRIO_5 = 58; ID_POR_CONCURSO_TRIO_6 = 59; ID_POR_CONCURSO_TRIO_7 = 60; ID_POR_CONCURSO_TRIO_8 = 61; ID_POR_CONCURSO_X1 = 62; ID_POR_CONCURSO_X2 = 63; ID_POR_CONCURSO_NOVOS_REPETIDOS = 64; const ID_MARCAR_NAO = 0; ID_MARCAR_SIM = 1; ID_DESMARCAR_TUDO = 2; ID_MARCACAO_PARCIAL = 3; filtro_order_by: array [0..2, 0..1] of string = ( //('Soma da frequencia de bolas', 'concurso_soma_frequencia_bolas'), //('Id sequencial combinações em grupos', 'id_seq_cmb_em_grupos'), ('Id sequencial da combinação (não recomendado)', 'lotofacil_num.ltf_id'), ('Id alternado de novos x repetidos', 'novos_repetidos_id_alternado'), ('Id sequencial de novos x repetidos', 'novos_repetidos_id') ); implementation end.
unit feli_ascii_art; {$mode objfpc} interface // uses ; type FeliAsciiArt = class(TObject) public class function getCharFromRGBAverage(average: int64): ansiString; static; class function generate(filepath: ansiString; height: int64 = 64; width: int64 = 64): ansiString; static; end; implementation uses feli_stack_tracer, feli_constants, feli_logger, fpreadpng, fpreadjpeg, fpimage, sysutils, fpcanvas, fpimgcanv; class function FeliAsciiArt.getCharFromRGBAverage(average: int64): ansiString; static; const // denseChars = '$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`''. '; // denseChars = '$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`''. '; denseChars = '@B8WMoahkbdZ0OQYXvunxft-_+~. '; // denseChars = '$@B%yxz+=- '; var denseCharsLength: int64; scalingFactor: real; selected: ansiString; selectedIndex: integer; begin denseCharsLength := length(denseChars) - 1; scalingFactor := denseCharsLength/256; selected := ' '; try selectedIndex := Round(average * scalingFactor); selected := denseChars[selectedIndex + 1]; except on E: Exception do begin selected := ' '; end; end; result := selected; end; class function FeliAsciiArt.generate(filepath: ansiString; height: int64 = 64; width: int64 = 64): ansiString; static; var AWidth, AHeight: integer; image, resultImage: TFPCustomImage; pngReader, jpegReader: TFPCustomImageReader; canvas: TFPImageCanvas; i, j: integer; colours: TFPColor; meanRGB: int64; asciiArt: ansiString; begin FeliStackTrace.trace('begin', 'function FeliAsciiArt.generate(filepath: ansiString): ansiString;'); asciiArt := ''; AWidth := width; AHeight := height; try image := TFPMemoryImage.create(0 ,0); try pngReader := TFPReaderPNG.create(); jpegReader := TFPReaderJPEG.create(); try image.LoadFromFile(filepath, pngReader); except on E: Exception do begin FeliLogger.error(e.message); FeliLogger.info('Trying Jpeg Reader'); image.LoadFromFile(filepath, jpegReader); end; end; finally pngReader.free(); end; if (Image.Width / Image.Height) > (AWidth / AHeight) then AHeight := Round(AWidth / (Image.Width / Image.Height)) else if (Image.Width / Image.Height) < (AWidth / AHeight) then AWidth := Round(AHeight * (Image.Width / Image.Height)); try resultImage := TFPMemoryImage.create(AWidth, AHeight); canvas := TFPImageCanvas.create(resultImage); canvas.StretchDraw(0, 0, AWidth, AHeight, Image); try for j := 0 to (resultImage.height - 1) do begin for i := 0 to (resultImage.width - 1) do begin colours := resultImage.Colors[i, j]; meanRGB := Round((colours.Red + colours.Green + colours.Blue) / 3); meanRGB := Round(meanRGB / 256); asciiArt := asciiArt + FeliAsciiArt.getCharFromRGBAverage(meanRGB); end; asciiArt := asciiArt + lineSeparator; end; except on E: Exception do begin FeliLogger.error(e.Message); end; end; finally resultImage.free(); canvas.free(); end; finally image.free(); end; result := asciiArt; FeliStackTrace.trace('end', 'function FeliAsciiArt.generate(filepath: ansiString): ansiString;'); end; end.
unit sgDriverAudio; //============================================================================= // sgDriverAudio.pas //============================================================================= // // The Audio Driver is responsible for providing an interface between SwinGame // code and the drivers. It can interface between any audio driver provided // It should not be changed, any changes to this file will probably cause all // the audio drivers to break. // // // // Notes: // - Pascal PChar is equivalent to a C-type string // - Pascal Word is equivalent to a Uint16 // - Pascal LongWord is equivalent to a Uint32 // //============================================================================= interface uses sgTypes, sgDriverAudioSDL2; type // These function and procedure pointers are required by the AudioDriverRecord OpenAudioProcedure = function () : Boolean; CloseAudioProcedure = procedure (); LoadSoundEffectProcedure = function (const filename, name : String) : SoundEffect; SetMusicVolumeProcedure = procedure (newVolume : Single); GetMusicVolumeProcedure = function () : Single; GetErrorProcedure = function () : String; FreeSoundEffectProcedure = procedure (effect : SoundEffect); LoadMusicProcedure = function (const filename, name : String) : Music; FreeMusicProcedure = procedure (music : Music); PlaySoundEffectProcedure = function (effect : SoundEffect; loops : Integer; volume : Single) : Boolean; PlayMusicProcedure = function (music : Music; loops : Integer) : Boolean; FadeMusicInProcedure = function (music : Music; loops, ms : Integer) : Boolean; FadeMusicOutProcedure = function (ms : Integer) : Boolean; GetSoundEffectVolumeProcedure = function(effect : SoundEffect) : Single; SetSoundEffectVolumeProcedure = procedure(effect : SoundEffect; newVolume : Single); SoundEffectPlayingProcedure = function(effect : SoundEffect) : Boolean; MusicPlayingProcedure = function() : Boolean; PauseMusicProcedure = procedure(); ResumeMusicProcedure = procedure(); StopMusicProcedure = procedure(); StopSoundEffectProcedure = procedure(effect : SoundEffect); // Stores the functions and procedures from the current audio driver // So that calling AudioDriver.OpenAudio() will call the appropriate method // from the driver. // The names of the record fields should be clear and indicitive of what the // procedure does or should do. AudioDriverRecord = record OpenAudio : OpenAudioProcedure; CloseAudio : CloseAudioProcedure; LoadSoundEffect : LoadSoundEffectProcedure; SetMusicVolume : SetMusicVolumeProcedure; GetMusicVolume : GetMusicVolumeProcedure; GetError : GetErrorProcedure; FreeSoundEffect : FreeSoundEffectProcedure; LoadMusic : LoadMusicProcedure; FreeMusic : FreeMusicProcedure; PlaySoundEffect : PlaySoundEffectProcedure; PlayMusic : PlayMusicProcedure; FadeMusicIn : FadeMusicInProcedure; FadeMusicOut : FadeMusicOutProcedure; GetSoundEffectVolume : GetSoundEffectVolumeProcedure; SetSoundEffectVolume : SetSoundEffectVolumeProcedure; SoundEffectPlaying : SoundEffectPlayingProcedure; MusicPlaying : MusicPlayingProcedure; PauseMusic : PauseMusicProcedure; ResumeMusic : ResumeMusicProcedure; StopMusic : StopMusicProcedure; StopSoundEffect : StopSoundEffectProcedure; end; var // Global variable used to allow SwinGame to access the functions and procedures // of the audio driver. AudioDriver : AudioDriverRecord; implementation //============================================================================= // Default functions and procedures that allow lazy loading of the AudioDriver // They are loaded into the AudioiDriver by default and when called load the // current default audio driver. They then call the audio driver again to make // sure the appropriate action is completed. // Naming : Default____Procedure //============================================================================= // TODO: // - Create LoadDriver function that accepts an enum describing the driver // to load. This function will replace LoadDefaultAudioDriver() //============================================================================= procedure LoadDefaultAudioDriver(); begin LoadSDL2MixerAudioDriver(); end; //============================================================================= function DefaultOpenAudioProcedure() : Boolean; begin LoadDefaultAudioDriver(); result := AudioDriver.OpenAudio(); end; procedure DefaultCloseAudioProcedure(); begin LoadDefaultAudioDriver(); AudioDriver.CloseAudio(); end; function DefaultLoadSoundEffectProcedure(const filename, name : String) : SoundEffect; begin LoadDefaultAudioDriver(); result := AudioDriver.LoadSoundEffect(filename, name); end; procedure DefaultSetMusicVolumeProcedure(newVolume : Single); begin LoadDefaultAudioDriver(); AudioDriver.SetMusicVolume(newVolume); end; function DefaultGetMusicVolumeProcedure() : Single; begin LoadDefaultAudioDriver(); result := AudioDriver.GetMusicVolume(); end; function DefaultGetErrorProcedure() : String; begin LoadDefaultAudioDriver(); result := AudioDriver.GetError(); end; procedure DefaultFreeSoundEffectProcedure(effect : SoundEffect); begin LoadDefaultAudioDriver(); AudioDriver.FreeSoundEffect(effect); end; function DefaultLoadMusicProcedure(const filename, name : String) : Music; begin LoadDefaultAudioDriver(); result := AudioDriver.LoadMusic(filename, name); end; procedure DefaultFreeMusicProcedure(music : Music); begin LoadDefaultAudioDriver(); AudioDriver.FreeMusic(music); end; function DefaultPlaySoundEffectProcedure(effect : SoundEffect; loops : Integer; volume : Single) : Boolean; begin LoadDefaultAudioDriver(); result := AudioDriver.PlaySoundEffect(effect, loops, volume); end; function DefaultPlayMusicProcedure(music : Music; loops : Integer) : Boolean; begin LoadDefaultAudioDriver(); result := AudioDriver.PlayMusic(music, loops); end; function DefaultFadeMusicInProcedure(music : Music; loops, ms : Integer) : Boolean; begin LoadDefaultAudioDriver(); result := AudioDriver.FadeMusicIn(music, loops, ms); end; function DefaultFadeMusicOutProcedure(ms : Integer) : Boolean; begin LoadDefaultAudioDriver(); result := AudioDriver.FadeMusicOut(ms); end; procedure DefaultSetSoundEffectVolumeProcedure(effect : SoundEffect; newVolume : Single); begin LoadDefaultAudioDriver(); AudioDriver.SetSoundEffectVolume(effect, newVolume); end; function DefaultGetSoundEffectVolumeProcedure(effect : SoundEffect) : Single; begin LoadDefaultAudioDriver(); result := AudioDriver.GetSoundEffectVolume(effect); end; function DefaultSoundEffectPlayingProcedure(effect : SoundEffect) : Boolean; begin LoadDefaultAudioDriver(); result := AudioDriver.SoundEffectPlaying(effect); end; function DefaultMusicPlayingProcedure() : Boolean; begin LoadDefaultAudioDriver(); result := AudioDriver.MusicPlaying(); end; procedure DefaultPauseMusicProcedure(); begin LoadDefaultAudioDriver(); AudioDriver.PauseMusic(); end; procedure DefaultResumeMusicProcedure(); begin LoadDefaultAudioDriver(); AudioDriver.ResumeMusic(); end; procedure DefaultStopMusicProcedure(); begin LoadDefaultAudioDriver(); AudioDriver.StopMusic(); end; procedure DefaultStopSoundEffectProcedure(effect : SoundEffect); begin LoadDefaultAudioDriver(); AudioDriver.StopSoundEffect(effect); end; //============================================================================= initialization begin AudioDriver.OpenAudio := @DefaultOpenAudioProcedure; AudioDriver.CloseAudio := @DefaultCloseAudioProcedure; AudioDriver.LoadSoundEffect := @DefaultLoadSoundEffectProcedure; AudioDriver.SetMusicVolume := @DefaultSetMusicVolumeProcedure; AudioDriver.GetMusicVolume := @DefaultGetMusicVolumeProcedure; AudioDriver.GetError := @DefaultGetErrorProcedure; AudioDriver.FreeSoundEffect := @DefaultFreeSoundEffectProcedure; AudioDriver.LoadMusic := @DefaultLoadMusicProcedure; AudioDriver.FreeMusic := @DefaultFreeMusicProcedure; AudioDriver.PlaySoundEffect := @DefaultPlaySoundEffectProcedure; AudioDriver.PlayMusic := @DefaultPlayMusicProcedure; AudioDriver.FadeMusicIn := @DefaultFadeMusicInProcedure; AudioDriver.FadeMusicOut := @DefaultFadeMusicOutProcedure; AudioDriver.SetSoundEffectVolume := @DefaultSetSoundEffectVolumeProcedure; AudioDriver.GetSoundEffectVolume := @DefaultGetSoundEffectVolumeProcedure; AudioDriver.SoundEffectPlaying := @DefaultSoundEffectPlayingProcedure; AudioDriver.MusicPlaying := @DefaultMusicPlayingProcedure; AudioDriver.PauseMusic := @DefaultPauseMusicProcedure; AudioDriver.ResumeMusic := @DefaultResumeMusicProcedure; AudioDriver.StopMusic := @DefaultStopMusicProcedure; AudioDriver.StopSoundEffect := @DefaultStopSoundEffectProcedure; end; end.
unit ASUP_LoaderPrintDocs_Consts; interface resourcestring Ini_ID_PROP_DOCTOR_REG = 'ID_PROP_DOCTOR_REG'; Ini_ID_PROP_CANDIDAT_REG = 'ID_PROP_CANDIDAT_REG'; Path_ALL_Reports = 'Reports\Asup'; Error_Caption = 'Помилка'; Error_LoadBPL_Text = 'Не можливо загрузити пакет:'; YesBtn_Caption = 'Гаразд'; CancelBtn_Caption = 'Відміна'; FontBtn_Caption = 'Шрифт'; Label_Department_Caption = 'Підрозділ'; Label_DateSelect_Caption = 'Дата формування:'; FormOptions_Caption = 'Параметри'; Label_DateBeg_Caption = 'Введіть період з'; Label_DateEnd_Caption = 'по'; E_NotSelectDepartment_Text = 'Треба обрати підрозділ!'; E_NotSelectWorkReason_Text = 'Треба обрати підставу праці!'; E_Terms_Text = 'Дата початку не може перевищувати дату закінчення!'; CheckBoxWithChild_Caption = 'з підлеглими'; implementation end.
(* Category: SWAG Title: GRAPHICS ROUTINES Original name: 0246.PAS Description: Bezier Curve Example Author: ALEKSANDAR DLABAC Date: 03-04-97 13:18 *) Program Bezier; { ██████████████████████████████████████████████████ ███▌▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▐███▒▒ ███▌██ ██▐███▒▒ ███▌██ Bezier curve example ██▐███▒▒ ███▌██ ██▐███▒▒ ███▌██ Aleksandar Dlabac ██▐███▒▒ ███▌██ (C) 1992. Dlabac Bros. Company ██▐███▒▒ ███▌██ ------------------------------ ██▐███▒▒ ███▌██ adlabac@urcpg.urc.cg.ac.yu ██▐███▒▒ ███▌██ adlabac@urcpg.pmf.cg.ac.yu ██▐███▒▒ ███▌██ ██▐███▒▒ ███▌▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▐███▒▒ ██████████████████████████████████████████████████▒▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ } Uses Crt, Graph; Const Quality = 100; { Greater number - greater quality, slower program } Points : array [1..4,'X'..'Y'] of integer = { Control points } ((43,123),(345,10),(530,423),(245,345)); { for Bezier curve } Var Gd, Gm, I : integer; Function Power (Base:real;Pow:integer) : real; Var Temp : real; I : integer; Begin Temp:=1; For I:=1 to Pow do Temp:=Temp*Base; Power:=Temp End; Begin Gd:=Detect; InitGraph (Gd,Gm,''); SetColor (LightRed); {< This part of code } MoveTo (Points [1,'X'],Points [1,'Y']); {< draws control polygon } For I:=2 to 4 do {< using control points } LineTo (Points [I,'X'],Points [I,'Y']); {< in light red color. } SetColor (Yellow); { Following code draws curve } MoveTo (Points [1,'X'],Points [1,'Y']); For I:=0 to Quality do LineTo (Round (Power (1-I/Quality,3)*Points [1,'X']+3*I/Quality*Power (1-I/Quality,2)*Points [2,'X']+ 3*Power (I/Quality,2)*(1-I/Quality)*Points [3,'X']+Power (I/Quality,3)*Points [4,'X']), Round (Power (1-I/Quality,3)*Points [1,'Y']+3*I/Quality*Power (1-I/Quality,2)*Points [2,'Y']+ 3*Power (I/Quality,2)*(1-I/Quality)*Points [3,'Y']+Power (I/Quality,3)*Points [4,'Y'])); Repeat Until ReadKey<>#0; CloseGraph End.
unit DXPCommonTypes; interface type { TDXPBoundLines } TDXPBoundLines = set of ( blLeft, // left line blTop, // top line blRight, // right line blBottom // bottom line ); { TDXPControlStyle } TDXPControlStyle = set of ( csRedrawCaptionChanged, // (default) csRedrawBorderChanged, // csRedrawEnabledChanged, // (default) csRedrawFocusedChanged, // (default) csRedrawMouseDown, // (default) csRedrawMouseEnter, // (default) csRedrawMouseLeave, // (default) csRedrawMouseMove, // csRedrawMouseUp, // (default) csRedrawParentColorChanged, // (default) csRedrawParentFontChanged, // csRedrawPosChanged, // csRedrawResized // ); { TDXPDrawState } TDXPDrawState = set of ( dsDefault, // default dsHighlight, // highlighted dsClicked, // clicked dsFocused // focused ); { TDXPGlyphLayout } TDXPGlyphLayout = ( glBottom, // bottom glyph glCenter, // centered glyph glTop // top glyph ); { TDXPTheme } TDXPTheme = ( WindowsXP, // WindowsXP theme OfficeXP // OfficeXP theme ); implementation end.
unit AutoTablesDelphiSDK; interface uses System.SysUtils, System.Classes, System.JSON, FireDAC.Stan.Intf, System.StrUtils, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, REST.Client, REST.Backend.Endpoint, REST.Types, REST.Backend.EMSProvider, REST.Backend.ServiceComponents, REST.Backend.Providers; type TSDKClient = class(TComponent) private { Private declarations } FUserName, FPassword: String; public { Public declarations } FEMSProvider: TEMSProvider; FBackendAuth: TBackendAuth; constructor Create(AOwner: TComponent); destructor Destroy; function LoginAPI(const UserName, Password: String): Boolean; function GetAPI(const APath: String): TBytesStream; function PostAPI(const APath: String; ABytesStream: TBytesStream): TBytesStream; function DeleteAPI(const APath: String): TBytesStream; function getlogger(Aformat: String = ''): TBytesStream; function postlogger(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletelogger(AID: String; Aformat: String = ''): TBytesStream; published property Username: String read FUsername write FUsername; property Password: String read FPassword write FPassword; end; implementation constructor TSDKClient.Create(AOwner: TComponent); begin inherited Create(AOwner); FEMSProvider := TEMSProvider.Create(AOwner); FBackendAuth := TBackendAuth.Create(AOwner); FEMSProvider.URLHost := 'localhost'; FEMSProvider.URLPort := StrToInt('8080'); FEMSProvider.URLBasePath := ''; FEMSProvider.URLProtocol := 'http'; FBackendAuth.Provider := FEMSProvider; FUserName := ''; FPassword := ''; end; destructor TSDKClient.Destroy; begin inherited Destroy; FBackendAuth.DisposeOf; end; function TSDKClient.LoginAPI(const UserName, Password: String): Boolean; begin if not FBackendAuth.LoggedIn then begin FBackendAuth.UserName := UserName; FBackendAuth.Password := Password; FBAckendAuth.Login; if FBackendAuth.LoggedIn then begin if FBackendAuth.LoggedInToken = '' then begin FBackendAuth.Authentication := TBackendAuthentication.Default; Result := False; end else begin FBackendAuth.Authentication := TBackendAuthentication.Session; Result := True; end; end; end else Result := True; end; function TSDKClient.GetAPI(const APath: String): TBytesStream; var EndPoint: TBackendEndpoint; begin Result := TBytesStream.Create; EndPoint := TBackendEndpoint.Create(Self); EndPoint.Provider := FEMSProvider; EndPoint.Auth := FBackendAuth; try EndPoint.Resource := APath; EndPoint.Method := TRESTRequestMethod.rmGET; EndPoint.Execute; Result := TBytesStream.Create(EndPoint.Response.RawBytes); if EndPoint.Response.StatusCode>=400 then begin raise Exception.Create(EndPoint.Response.StatusText); end; finally EndPoint.DisposeOf; end; end; function TSDKClient.PostAPI(const APath: String; ABytesStream: TBytesStream): TBytesStream; var EndPoint: TBackendEndpoint; begin EndPoint := TBackendEndpoint.Create(Self); EndPoint.Provider := FEMSProvider; EndPoint.Auth := FBackendAuth; try EndPoint.Resource := APath; EndPoint.Method := TRESTRequestMethod.rmPOST; EndPoint.AddBody(ABytesStream,TRESTContentType.ctAPPLICATION_JSON); EndPoint.Execute; Result := TBytesStream.Create(EndPoint.Response.RawBytes); if EndPoint.Response.StatusCode>=400 then begin raise Exception.Create(EndPoint.Response.StatusText); end; finally EndPoint.DisposeOf; end; end; function TSDKClient.DeleteAPI(const APath: String): TBytesStream; var EndPoint: TBackendEndpoint; begin Result := TBytesStream.Create; EndPoint := TBackendEndpoint.Create(Self); EndPoint.Provider := FEMSProvider; EndPoint.Auth := FBackendAuth; try EndPoint.Resource := APath; EndPoint.Method := TRESTRequestMethod.rmDELETE; EndPoint.Execute; Result := TBytesStream.Create(EndPoint.Response.RawBytes); if EndPoint.Response.StatusCode>=400 then begin raise Exception.Create(EndPoint.Response.StatusText); end; finally EndPoint.DisposeOf; end; end; function TSDKClient.getlogger(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getlogger/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postlogger(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postlogger/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletelogger(AID: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletelogger/?ID='+AID+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; end.
unit pSHGotoLineNumberFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, pSHConsts, pSHIntf, pSHCommon; type TpSHGotoLineNumberForm = class(TForm) pnlOKCancelHelp: TPanel; Bevel1: TBevel; Panel6: TPanel; btnOK: TButton; btnCancel: TButton; btnHelp: TButton; bvlLeft: TBevel; bvlTop: TBevel; bvlRight: TBevel; bvlBottom: TBevel; pnlClient: TPanel; cbLineNumber: TComboBox; Label1: TLabel; procedure FormCreate(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); private { Private declarations } FShowIndent: Boolean; FGotoLineNumberHistory: IpSHUserInputHistory; FGotoLineNumberValue: Integer; FMaxLineNumber: Integer; function GetShowIndent: Boolean; procedure SetShowIndent(Value: Boolean); procedure SetGotoLineNumberHistory(const Value: IpSHUserInputHistory); protected procedure DoSaveSettings; procedure DoRestoreSettings; public { Public declarations } property ShowIndent: Boolean read GetShowIndent write SetShowIndent; property GotoLineNumberHistory: IpSHUserInputHistory read FGotoLineNumberHistory write SetGotoLineNumberHistory; property MaxLineNumber: Integer read FMaxLineNumber write FMaxLineNumber; property GotoLineNumberValue: Integer read FGotoLineNumberValue; end; var pSHGotoLineNumberForm: TpSHGotoLineNumberForm; implementation {$R *.dfm} { TpSHGotoLineNumberForm } procedure TpSHGotoLineNumberForm.FormCreate(Sender: TObject); begin AntiLargeFont(Self); BorderIcons := [biSystemMenu]; Position := poScreenCenter; pnlClient.Caption := ''; // CaptionOK := Format('%s', [SCaptionButtonOK]); // CaptionCancel := Format('%s', [SCaptionButtonCancel]); // CaptionHelp := Format('%s', [SCaptionButtonHelp]); ShowIndent := True; end; procedure TpSHGotoLineNumberForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); var S: string; begin if ModalResult = mrOK then begin S := cbLineNumber.Text; FGotoLineNumberValue := StrToIntDef(S, 0); if (not ((FGotoLineNumberValue >= 1) and (FGotoLineNumberValue <= MaxLineNumber))) then begin MessageDlg(Format(SLineNumberOutOfRange, [MaxLineNumber]), mtWarning, [mbOK], 0); CanClose := False; end else begin DoSaveSettings; GotoLineNumberHistory := nil; end; end; end; function TpSHGotoLineNumberForm.GetShowIndent: Boolean; begin Result := FShowIndent; end; procedure TpSHGotoLineNumberForm.SetShowIndent(Value: Boolean); begin FShowIndent := Value; bvlLeft.Visible := FShowIndent; bvlTop.Visible := FShowIndent; bvlRight.Visible := FShowIndent; end; procedure TpSHGotoLineNumberForm.SetGotoLineNumberHistory( const Value: IpSHUserInputHistory); begin FGotoLineNumberHistory := Value; DoRestoreSettings; end; procedure TpSHGotoLineNumberForm.DoSaveSettings; begin if Assigned(FGotoLineNumberHistory) then FGotoLineNumberHistory.AddToGotoLineNumberHistory(IntToStr(GotoLineNumberValue)); end; procedure TpSHGotoLineNumberForm.DoRestoreSettings; begin if Assigned(FGotoLineNumberHistory) then begin cbLineNumber.Items.Text := FGotoLineNumberHistory.GotoLineNumberHistory.Text; if FGotoLineNumberHistory.GotoLineNumberHistory.Count > 0 then cbLineNumber.ItemIndex := 0; end; end; end.
unit trl_usysutils; {$mode objfpc}{$H+} interface uses Classes, SysUtils, trl_isysutils, base64; type { TSysUtils } TSysUtils = class(TInterfacedObject, ISysUtils) protected // ISysUtils function NewGID: string; function NewGuid: TGuid; end; implementation { TSysUtils } function TSysUtils.NewGID: string; var mGuid: TGuid; mEncStream: TBase64EncodingStream; mStrStream: TStringStream; begin mGuid := NewGuid; mStrStream := TStringStream.Create; try mEncStream := TBase64EncodingStream.Create(mStrStream); try mEncStream.Write(mGuid, SizeOf(mGuid)); finally mEncStream.Free; end; Result := mStrStream.DataString; while Result[Length(Result)] = '=' do Delete(Result, Length(Result), 1); finally mStrStream.Free; end; end; function TSysUtils.NewGuid: TGuid; begin CreateGUID(Result); end; end.
{******************************************************************************* * uDateControl * * * * Библиотека компонентов для работы с формой редактирования (qFControls) * * Работа с полем ввода даты (TqFDateControl) * * Copyright © 2005-2007, Олег Г. Волков, Донецкий Национальный Университет * *******************************************************************************} unit uDateControl; interface uses SysUtils, Classes, Controls, uFControl, StdCtrls, Graphics, uLabeledFControl, ComCtrls, ToolEdit, Registry; type TqFDateControl = class(TqFLabeledControl) private FOldOnEnterEvent: TNotifyEvent; FDateControl: TDateEdit; FCheckDateIsEmpty: Boolean; function GetKeyDown: TKeyEvent; procedure SetKeyDown(e: TKeyEvent); function GetKeyUp: TKeyEvent; procedure SetKeyUp(e: TKeyEvent); protected procedure PrepareRest; override; procedure SetValue(Val: Variant); override; function GetValue: Variant; override; procedure Loaded; override; public constructor Create(AOwner: TComponent); override; procedure Highlight(HighlightOn: Boolean); override; procedure ShowFocus; override; function ToString: string; override; procedure Block(Flag: Boolean); override; procedure LoadFromRegistry(reg: TRegistry); override; // vallkor procedure SaveIntoRegistry(reg: TRegistry); override; // vallkor function Check: string; override; published property OnKeyDown: TKeyEvent read GetKeyDown write SetKeyDown; property OnKeyUp: TKeyEvent read GetKeyUp write SetKeyUp; property CheckDateIsEmpty: Boolean read FCheckDateIsEmpty write FCheckDateIsEmpty default True; end; procedure Register; {$R *.res} implementation uses qFStrings, Variants, qFTools; function TqFDateControl.GetKeyDown: TKeyEvent; begin Result := FDateControl.OnKeyDown; end; procedure TqFDateControl.SetKeyDown(e: TKeyEvent); begin FDateControl.OnKeyDown := e; end; function TqFDateControl.GetKeyUp: TKeyEvent; begin Result := FDateControl.OnKeyUp; end; procedure TqFDateControl.SetKeyUp(e: TKeyEvent); begin FDateControl.OnKeyUp := e; end; procedure TqFDateControl.Block(Flag: Boolean); begin inherited Block(Flag); if Flag then begin FOldOnEnterEvent := FDateControl.OnEnter; FDateControl.Enabled := False; end else begin FDateControl.Enabled := True; end; end; procedure TqFDateControl.Loaded; begin FDateControl.OnChange := FOnChange; inherited Loaded; end; procedure TqFDateControl.Highlight(HighlightOn: Boolean); begin inherited Highlight(HighlightOn); if HighlightOn then FDateControl.Color := qFHighlightColor else if FOldColor <> 0 then FDateControl.Color := FOldColor; Repaint; end; procedure TqFDateControl.ShowFocus; begin inherited ShowFocus; qFSafeFocusControL(FDateControl); end; function TqFDateControl.ToString: string; begin if VarIsNull(Value) then Result := 'Null' else if Value <= 0 then Result := 'Null' else Result := QuotedStr(DateToStr(Value)); end; procedure TqFDateControl.SetValue(Val: Variant); begin inherited SetValue(Val); if VarIsNull(Val) or (Val = 0) then begin FDateControl.Date := StrToDate('01.01.1900'); FDateControl.Text := ''; end else FDateControl.Date := Val; end; function TqFDateControl.GetValue: Variant; begin if Trim(FDateControl.Text) = '' then Result := Null else begin Result := Trunc(FDateControl.Date); //if Result <= 0 then Result := Null; end; end; constructor TqFDateControl.Create(AOwner: TComponent); begin inherited Create(AOwner); FDateControl := TDateEdit.Create(Self); FDateControl.Parent := Self; FDateControl.OnChange := FOnChange; FDateControl.Text := ''; Asterisk := False; FCheckDateIsEmpty := False; PrepareRest; FOldColor := FDateControl.Color; end; procedure TqFDateControl.PrepareRest; begin FDateControl.Width := Width - Interval - 3; FDateControl.Height := qFDefaultHeight; FDateControl.Left := Interval; FDateControl.Top := (Height - FDateControl.Height) div 2; end; procedure Register; begin RegisterComponents('qFControls', [TqFDateControl]); end; procedure TqFDateControl.LoadFromRegistry(reg: TRegistry); // vallkor begin inherited LoadFromRegistry(reg); try Value := Reg.ReadDate('Value'); except end; end; procedure TqFDateControl.SaveIntoRegistry(reg: TRegistry); // vallkor begin inherited SaveIntoRegistry(reg); if not VarIsNull(Value) then Reg.WriteDate('Value', VarToDateTime(Value)); end; function TqFDateControl.Check: string; begin if Required and FCheckDateIsEmpty then if VarIsNull(Value) or VarIsEmpty(Value) or (Value <= 0) then Result := qFDateFieldIsEmpty + '"' + DisplayName + '"!' else Result := '' else Result := ''; end; end.
{**************************************************************************************************} { } { Project JEDI Code Library (JCL) } { } { 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 JclCompression.pas. } { } { The Initial Developer of the Original Code is Matthias Thoma. } { All Rights Reserved. } { } { Contributors: } { } {**************************************************************************************************} { } { Alternatively, the contents of this file may be used under the terms of the GNU Lesser General } { Public License (the "LGPL License"), in which case the provisions of the LGPL License are } { applicable instead of those above. If you wish to allow use of your version of this file only } { under the terms of the LGPL License and not to allow others to use your version of this file } { under the MPL, indicate your decision by deleting the provisions above and replace them with the } { notice and other provisions required by the LGPL License. If you do not delete the provisions } { above, a recipient may use your version of this file under either the MPL or the LGPL License. } { } { For more information about the LGPL: } { http://www.gnu.org/copyleft/lesser.html } { } {**************************************************************************************************} { } { This unit is still in alpha state. It is likely that it will change a lot. Suggestions are } { welcome. } { } {**************************************************************************************************} // Last modified: $Date: 2005/03/08 08:33:15 $ // For history see end of file unit JclCompression; interface uses {$IFDEF MSWINDOWS} Windows, {$ENDIF MSWINDOWS} {$IFDEF UNIX} Types, {$ENDIF UNIX} {$IFDEF HAS_UNIT_LIBC} Libc, {$ENDIF HAS_UNIT_LIBC} SysUtils, Classes, JclBase, zlibh; {**************************************************************************************************} { TJclCompressionStream - - ----------------------- -------------------------- - - TJclCompressStream TJclDecompressStream - - --------------------------------- --------------------------------- - - - - - - - - - - - - TJclZLibCompressStream - TBZIP2CompressStram TJclZLibDecompressStream - TBZIP2DeCompressStream - - - TGZDecompressStream TGZCompressStream } {**************************************************************************************************} type TJclCompressionStream = class(TStream) private FOnProgress: TNotifyEvent; FBuffer: Pointer; FBufferSize: Cardinal; FStream: TStream; protected function SetBufferSize(Size: Cardinal): Cardinal; virtual; procedure Progress(Sender: TObject); dynamic; property OnProgress: TNotifyEvent read FOnProgress write FOnProgress; public constructor Create(Stream: TStream); destructor Destroy; override; function Read(var Buffer; Count: Longint): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; function Seek(Offset: Longint; Origin: Word): Longint; override; procedure Reset; virtual; end; TJclCompressStream = class(TJclCompressionStream) public function Flush: Integer; dynamic; abstract; constructor Create(Destination: TStream); end; TJclDecompressStream = class(TJclCompressionStream) public constructor Create(Source: TStream); end; // ZIP Support TJclCompressionLevel = Integer; TJclZLibCompressStream = class(TJclCompressStream) private FWindowBits: Integer; FMemLevel: Integer; FMethod: Integer; FStrategy: Integer; FDeflateInitialized: Boolean; FCompressionLevel: Integer; protected ZLibRecord: TZStreamRec; procedure SetCompressionLevel(Value: Integer); procedure SetStrategy(Value: Integer); procedure SetMemLevel(Value: Integer); procedure SetMethod(Value: Integer); procedure SetWindowBits(Value: Integer); public constructor Create(Destination: TStream; CompressionLevel: TJclCompressionLevel = -1); destructor Destroy; override; function Flush: Integer; override; procedure Reset; override; function Seek(Offset: Longint; Origin: Word): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; property WindowBits: Integer read FWindowBits write SetWindowBits; property MemLevel: Integer read FMemLevel write SetMemLevel; property Method: Integer read FMethod write SetMethod; property Strategy: Integer read FStrategy write SetStrategy; property CompressionLevel: Integer read FCompressionLevel write SetCompressionLevel; end; TJclZLibDecompressStream = class(TJclDecompressStream) private FWindowBits: Integer; FInflateInitialized: Boolean; protected ZLibRecord: TZStreamRec; procedure SetWindowBits(Value: Integer); public constructor Create(Source: TStream; WindowBits: Integer = DEF_WBITS); destructor Destroy; override; function Read(var Buffer; Count: Longint): Longint; override; function Seek(Offset: Longint; Origin: Word): Longint; override; property WindowBits: Integer read FWindowBits write SetWindowBits; end; // GZIP Support TJclGZIPCompressionStream = class(TJclCompressionStream) end; TJclGZIPDecompressionStream = class(TJclDecompressStream) end; // RAR Support TJclRARCompressionStream = class(TJclCompressionStream) end; TJclRARDecompressionStream = class(TJclDecompressStream) end; // TAR Support TJclTARCompressionStream = class(TJclCompressionStream) end; TJclTARDecompressionStream = class(TJclDecompressStream) end; // BZIP2 Support (* TJclBZIP2CompressStream = class(TJclCompressStream) private FDeflateInitialized: Boolean; protected BZLibRecord: TBZStream; public function Flush: Integer; override; function Seek(Offset: Longint; Origin: Word): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; constructor Create(Destination: TStream; CompressionLevel: TJclCompressionLevel = -1); destructor Destroy; override; end; TJclBZIP2DecompressStream = class(TJclDecompressStream) private FInflateInitialized: Boolean; protected BZLibRecord: TBZStream; public function Read(var Buffer; Count: Longint): Longint; override; function Seek(Offset: Longint; Origin: Word): Longint; override; constructor Create(Source: TStream); overload; destructor Destroy; override; end; *) EJclCompressionError = class(EJclError); implementation uses JclResources; const JclDefaultBufferSize = 131072; // 128k //=== { TJclCompressionStream } ============================================== constructor TJclCompressionStream.Create(Stream: TStream); begin inherited Create; FBuffer := nil; SetBufferSize(JclDefaultBufferSize); end; destructor TJclCompressionStream.Destroy; begin SetBufferSize(0); inherited Destroy; end; function TJclCompressionStream.Read(var Buffer; Count: Longint): Longint; begin raise EJclCompressionError.CreateRes(@RsCompressionReadNotSupported); end; function TJclCompressionStream.Write(const Buffer; Count: Longint): Longint; begin raise EJclCompressionError.CreateRes(@RsCompressionWriteNotSupported); end; function TJclCompressionStream.Seek(Offset: Longint; Origin: Word): Longint; begin raise EJclCompressionError.CreateRes(@RsCompressionSeekNotSupported); end; procedure TJclCompressionStream.Reset; begin raise EJclCompressionError.CreateRes(@RsCompressionResetNotSupported); end; function TJclCompressionStream.SetBufferSize(Size: Cardinal): Cardinal; begin if FBuffer <> nil then FreeMem(FBuffer, FBufferSize); FBufferSize := Size; if FBufferSize > 0 then GetMem(FBuffer, FBufferSize) else FBuffer := nil; Result := FBufferSize; end; procedure TJclCompressionStream.Progress(Sender: TObject); begin if Assigned(FOnProgress) then FOnProgress(Sender); end; //=== { TJclCompressStream } ================================================= constructor TJclCompressStream.Create(Destination: TStream); begin inherited Create(Destination); FStream := Destination; end; //=== { TJclDecompressStream } =============================================== constructor TJclDecompressStream.Create(Source: TStream); begin inherited Create(Source); FStream := Source; end; //=== { TJclZLibCompressionStream } ========================================== { Error checking helper } function ZLibCheck(const ErrCode: Integer): Integer; begin Result := ErrCode; if ErrCode < 0 then case ErrCode of Z_ERRNO: raise EJclCompressionError.CreateRes(@RsCompressionZLibZErrNo); Z_STREAM_ERROR: raise EJclCompressionError.CreateRes(@RsCompressionZLibZStreamError); Z_DATA_ERROR: raise EJclCompressionError.CreateRes(@RsCompressionZLibZDataError); Z_MEM_ERROR: raise EJclCompressionError.CreateRes(@RsCompressionZLibZMemError); Z_BUF_ERROR: raise EJclCompressionError.CreateRes(@RsCompressionZLibZBufError); Z_VERSION_ERROR: raise EJclCompressionError.CreateRes(@RsCompressionZLibZVersionError); else raise EJclCompressionError.CreateRes(@RsCompressionZLibError); end; end; constructor TJclZLibCompressStream.Create(Destination: TStream; CompressionLevel: TJclCompressionLevel); begin inherited Create(Destination); Assert(FBuffer <> nil); Assert(FBufferSize > 0); // Initialize ZLib StreamRecord with ZLibRecord do begin zalloc := nil; // Use build-in memory allocation functionality zfree := nil; next_in := nil; avail_in := 0; next_out := FBuffer; avail_out := FBufferSize; end; FWindowBits := DEF_WBITS; FMemLevel := DEF_MEM_LEVEL; FMethod := Z_DEFLATED; FStrategy := Z_DEFAULT_STRATEGY; FCompressionLevel := CompressionLevel; FDeflateInitialized := False; end; destructor TJclZLibCompressStream.Destroy; begin Flush; if FDeflateInitialized then begin ZLibRecord.next_in := nil; ZLibRecord.avail_in := 0; ZLibRecord.avail_out := 0; ZLibRecord.next_out := nil; ZLibCheck(deflateEnd(ZLibRecord)); end; inherited Destroy; end; function TJclZLibCompressStream.Write(const Buffer; Count: Longint): Longint; begin if not FDeflateInitialized then begin ZLibCheck(deflateInit(ZLibRecord, FCompressionLevel)); FDeflateInitialized := True; end; ZLibRecord.next_in := @Buffer; ZLibRecord.avail_in := Count; while ZLibRecord.avail_in > 0 do begin ZLibCheck(deflate(ZLibRecord, Z_NO_FLUSH)); if ZLibRecord.avail_out = 0 then // Output buffer empty. Write to stream and go on... begin FStream.WriteBuffer(FBuffer^, FBufferSize); Progress(Self); ZLibRecord.next_out := FBuffer; ZLibRecord.avail_out := FBufferSize; end; end; Result := Count; end; function TJclZLibCompressStream.Flush: Integer; begin Result := 0; if FDeflateInitialized then begin ZLibRecord.next_in := nil; ZLibRecord.avail_in := 0; while (ZLibCheck(deflate(ZLibRecord, Z_FINISH)) <> Z_STREAM_END) and (ZLibRecord.avail_out = 0) do begin FStream.WriteBuffer(FBuffer^, FBufferSize); Progress(Self); ZLibRecord.next_out := FBuffer; ZLibRecord.avail_out := FBufferSize; Inc(Result, FBufferSize); end; if ZLibRecord.avail_out < FBufferSize then begin FStream.WriteBuffer(FBuffer^, FBufferSize-ZLibRecord.avail_out); Progress(Self); Inc(Result, FBufferSize - ZLibRecord.avail_out); ZLibRecord.next_out := FBuffer; ZLibRecord.avail_out := FBufferSize; end; end; end; function TJclZLibCompressStream.Seek(Offset: Longint; Origin: Word): Longint; begin if (Offset = 0) and (Origin = soFromCurrent) then Result := ZLibRecord.total_in else if (Offset = 0) and (Origin = soFromBeginning) and (ZLibRecord.total_in = 0) then Result := 0 else Result := inherited Seek(Offset, Origin); end; procedure TJclZLibCompressStream.SetWindowBits(Value: Integer); begin FWindowBits := Value; end; procedure TJclZLibCompressStream.SetMethod(Value: Integer); begin FMethod := Value; end; procedure TJclZLibCompressStream.SetStrategy(Value: Integer); begin FStrategy := Value; if FDeflateInitialized then ZLibCheck(deflateParams(ZLibRecord, FCompressionLevel, FStrategy)); end; procedure TJclZLibCompressStream.SetMemLevel(Value: Integer); begin FMemLevel := Value; end; procedure TJclZLibCompressStream.SetCompressionLevel(Value: Integer); begin FCompressionLevel := Value; if FDeflateInitialized then ZLibCheck(deflateParams(ZLibRecord, FCompressionLevel, FStrategy)); end; procedure TJclZLibCompressStream.Reset; begin if FDeflateInitialized then begin Flush; ZLibCheck(deflateReset(ZLibRecord)); end; end; //=== { TJclZLibDecompressionStream } ======================================= constructor TJclZLibDecompressStream.Create(Source: TStream; WindowBits: Integer = DEF_WBITS); begin inherited Create(Source); // Initialize ZLib StreamRecord with ZLibRecord do begin zalloc := nil; // Use build-in memory allocation functionality zfree := nil; next_in := nil; avail_in := 0; next_out := FBuffer; avail_out := FBufferSize; end; FInflateInitialized := False; FWindowBits := WindowBits; end; destructor TJclZLibDecompressStream.Destroy; begin if FInflateInitialized then begin FStream.Seek(-ZLibRecord.avail_in, soFromCurrent); ZLibCheck(inflateEnd(ZLibRecord)); end; inherited Destroy; end; function TJclZLibDecompressStream.Read(var Buffer; Count: Longint): Longint; begin if not FInflateInitialized then begin ZLibCheck(InflateInit2(ZLibRecord, FWindowBits)); FInflateInitialized := True; end; ZLibRecord.next_out := @Buffer; ZLibRecord.avail_out := Count; while ZLibRecord.avail_out > 0 do // as long as we have data begin if ZLibRecord.avail_in = 0 then begin ZLibRecord.avail_in := FStream.Read(FBuffer^, FBufferSize); if ZLibRecord.avail_in = 0 then begin Result := Count - Longint(ZLibRecord.avail_out); Exit; end; ZLibRecord.next_in := FBuffer; end; if ZLibRecord.avail_in > 0 then begin ZLibCheck(inflate(ZLibRecord, Z_NO_FLUSH)); Progress(Self); end; end; Result := Count; end; function TJclZLibDecompressStream.Seek(Offset: Longint; Origin: Word): Longint; begin if (Offset = 0) and (Origin = soFromCurrent) then Result := ZLibRecord.total_out else Result := inherited Seek(Offset, Origin); end; procedure TJclZLibDecompressStream.SetWindowBits(Value: Integer); begin FWindowBits := Value; end; //=== { TJclBZLibCompressionStream } ========================================= (* { Error checking helper } function BZIP2LibCheck(const ErrCode: Integer): Integer; begin Result := ErrCode; if ErrCode < 0 then begin case ErrCode of Z_ERRNO: raise EJclCompressionError.CreateRes(@RsCompressionZLibZErrNo); Z_STREAM_ERROR: raise EJclCompressionError.CreateRes(@RsCompressionZLibZStreamError); Z_DATA_ERROR: raise EJclCompressionError.CreateRes(@RsCompressionZLibZDataError); Z_MEM_ERROR: raise EJclCompressionError.CreateRes(@RsCompressionZLibZMemError); Z_BUF_ERROR: raise EJclCompressionError.CreateRes(@RsCompressionZLibZBufError); Z_VERSION_ERROR: raise EJclCompressionError.CreateRes(@RsCompressionZLibZVersionError); else raise EJclCompressionError.CreateRes(@RsCompressionZLibError); end; end; end; constructor TJclBZIP2CompressStream.Create(Destination: TStream; CompressionLevel: TJclCompressionLevel); begin inherited Create(Destination); Assert(FBuffer <> nil); Assert(FBufferSize > 0); // Initialize ZLib StreamRecord with BZLibRecord do begin bzalloc := nil; // Use build-in memory allocation functionality bzfree := nil; next_in := nil; avail_in := 0; next_out := FBuffer; avail_out := FBufferSize; end; FDeflateInitialized := False; end; destructor TJclBZIP2CompressStream.Destroy; begin Flush; if FDeflateInitialized then BZIP2LibCheck(BZ2_bzCompressEnd(@BZLibRecord)); inherited Destroy; end; function TJclBZIP2CompressStream.Write(const Buffer; Count: Longint): Longint; begin if not FDeflateInitialized then begin BZIP2LibCheck(BZ2_bzCompressInit(@BZLibRecord,9,0,0)); FDeflateInitialized := True; end; BZLibRecord.next_in := @Buffer; BZLibRecord.avail_in := Count; while BZLibRecord.avail_in > 0 do begin BZIP2LibCheck(BZ2_bzCompress(@BZLibRecord, BZ_RUN)); if BZLibRecord.avail_out = 0 then // Output buffer empty. Write to stream and go on... begin FStream.WriteBuffer(FBuffer^, FBufferSize); Progress(Self); BZLibRecord.next_out := FBuffer; BZLibRecord.avail_out := FBufferSize; end; end; Result := Count; end; function TJclBZIP2CompressStream.Flush: Integer; begin Result := 0; if FDeflateInitialized then begin BZLibRecord.next_in := nil; BZLibRecord.avail_in := 0; while (BZIP2LibCheck(BZ2_bzCompress(@BZLibRecord, BZ_FLUSH)) <> Z_STREAM_END) and (BZLibRecord.avail_out = 0) do begin FStream.WriteBuffer(FBuffer^, FBufferSize); Progress(Self); BZLibRecord.next_out := FBuffer; BZLibRecord.avail_out := FBufferSize; Result := Result + FBufferSize; end; if BZLibRecord.avail_out < FBufferSize then begin FStream.WriteBuffer(FBuffer^, FBufferSize-BZLibRecord.avail_out); Progress(Self); Result := Result + FBufferSize-BZLibRecord.avail_out; BZLibRecord.next_out := FBuffer; BZLibRecord.avail_out := FBufferSize; end; end; end; function TJclBZIP2CompressStream.Seek(Offset: Longint; Origin: Word): Longint; begin if (Offset = 0) and (Origin = soFromCurrent) then Result := BZLibRecord.total_in_lo32 else if (Offset = 0) and (Origin = soFromBeginning) and (BZLibRecord.total_in_lo32 = 0) then Result := 0 else Result := inherited Seek(Offset, Origin); end; //=== { TJclZLibDecompressionStream } ======================================== constructor TJclBZIP2DecompressStream.Create(Source: TStream); begin inherited Create(Source); // Initialize ZLib StreamRecord with BZLibRecord do begin bzalloc := nil; // Use build-in memory allocation functionality bzfree := nil; opaque := nil; next_in := nil; state := nil; avail_in := 0; next_out := FBuffer; avail_out := FBufferSize; end; FInflateInitialized := False; end; destructor TJclBZIP2DecompressStream.Destroy; begin if FInflateInitialized then begin FStream.Seek(-BZLibRecord.avail_in, soFromCurrent); BZIP2LibCheck(BZ2_bzDecompressEnd(@BZLibRecord)); end; inherited Destroy; end; function TJclBZIP2DecompressStream.Read(var Buffer; Count: Longint): Longint; var avail_out_ctr: Integer; begin if not FInflateInitialized then begin BZIP2LibCheck(BZ2_bzDecompressInit(@BZLibRecord,0,0)); FInflateInitialized := True; end; BZLibRecord.next_out := @Buffer; BZLibRecord.avail_out := Count; avail_out_ctr := Count; while avail_out_ctr > 0 do // as long as we have data begin if BZLibRecord.avail_in = 0 then begin BZLibRecord.avail_in := FStream.Read(FBuffer^, FBufferSize); if BZLibRecord.avail_in = 0 then begin Result := Count - avail_out_ctr; Exit; end; BZLibRecord.next_in := FBuffer; end; if BZLibRecord.avail_in > 0 then begin BZIP2LibCheck(BZ2_bzDecompress(@BZLibRecord)); avail_out_ctr := Count - BZLibRecord.avail_out; end end; Result := Count; end; function TJclBZIP2DecompressStream.Seek(Offset: Longint; Origin: Word): Longint; begin if (Offset = 0) and (Origin = soFromCurrent) then Result := BZLibRecord.total_out_lo32 else Result := inherited Seek(Offset, Origin); end; *) // History: // $Log: JclCompression.pas,v $ // Revision 1.8 2005/03/08 08:33:15 marquardt // overhaul of exceptions and resourcestrings, minor style cleaning // // Revision 1.7 2005/02/27 14:55:25 marquardt // changed overloaded constructors to constructor with default parameter (BCB friendly) // // Revision 1.6 2005/02/24 16:34:39 marquardt // remove divider lines, add section lines (unfinished) // // Revision 1.5 2005/02/24 07:36:24 marquardt // resolved the compiler warnings, style cleanup, removed code from JclContainerIntf.pas // // Revision 1.4 2004/11/17 03:24:43 mthoma // Just noticed that I checked in the wrong version... this one is bugfixed and contains // $date and $log // end.
unit StmCpx1; interface {$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF} uses math, util1,Dgraphic,Ncdef2; function fonctionRe(z:TfloatComp):float;pascal; function fonctionIm(z:TfloatComp):float;pascal; function fonctionComp(x,y:float):TfloatComp;pascal; function fonctionComp1(rho,theta:float):TfloatComp;pascal; function fonctionMdl(z:TfloatComp):float;pascal; function fonctionAngle(z:TfloatComp):float;pascal; function fonctionAngle1(x,y:float):float;pascal; function fonctionConj(z:TfloatComp):TfloatComp;pascal; function fonctionCstr(z:TfloatComp;n,m:smallInt):AnsiString;pascal; implementation function fonctionRe(z:TfloatComp):float; begin result:=z.x; end; function fonctionIm(z:TfloatComp):float; begin result:=z.y; end; function fonctionComp(x,y:float):TfloatComp; begin result.x:=x; result.y:=y; end; function fonctionComp1(rho,theta:float):TfloatComp; begin result.x:=rho*cos(theta); result.y:=rho*sin(theta); end; function fonctionMdl(z:TfloatComp):float; begin result:=sqrt(sqr(z.x)+sqr(z.y)); end; function fonctionAngle(z:TfloatComp):float; begin if (z.x=0) and (z.y=0) then result:=0 else result:=arcTan2(z.y,z.x); { L'ordre est bien y,x } end; function fonctionAngle1(x,y:float):float; begin if (x=0) and (y=0) then result:=0 else result:=arcTan2(y,x); { L'ordre est bien y,x } end; function fonctionCstr(z:TfloatComp;n,m:smallInt):AnsiString; begin result:=Estr1(z.x,n,m)+'+i'+Estr1(z.y,n,m); end; function fonctionConj(z:TfloatComp):TfloatComp; begin result.x:=z.x; result.y:=-z.y; end; end.
// // EE_EXPORT -- Export procedures and functions // unit ee_export; {$MODE OBJFPC} interface uses Crt, Classes, DateUtils, // For SecondsBetween Process, SysUtils, USupportLibrary, UTextFile, ee_global; function ExportEventLog(el: string) : string; implementation function GetPathLastRun(sEventLog: string): string; // // Create a path fro the lastrun file containing the date time of the last run. // var r: string; begin //r := GetProgramFolder() + '\' + gsComputerName + '\' + sEventLog + '.lastexport'; //MakeFolderTree(r); r := GetLocalExportFolder(sEventLog) + '\lastexport.dtm'; MakeFolderTree(r); GetPathLastRun := r; end; // of function GetPathLastRun function LastRunGet(sEventLog: string): string; // // Returns the date and time in proper format YYYY-MM-DD HH:MM:SS back from a file in variable sPath // When the file does not exist, create one, otherwise read the datatime in the file. // var sPath: string; f: TextFile; r: string; begin sPath := GetPathLastRun(sEventLog); //WriteLn(' LastRunGet(): ', sPath); if FileExists(sPath) = true then begin //WriteLn('LastRunGet(): Read the line with the last date time from ' + sPath); AssignFile(f, sPath); {I+} // Open the file in read mode. Reset(f); ReadLn(f, r); CloseFile(f); end else begin //WriteLn('LastRunGet(): File ' + sPath + ' not found create a new file'); AssignFile(f, sPath); {I+} // Open the file in write mode. ReWrite(f); r := GetProperDateTime(Now()); WriteLn(f, r); CloseFile(f); end; LastRunGet := r; end; function LastRunPut(sEventLog: string): string; // // Put the current date time using Now() in the file sPath. // var sPath: string; f: TextFile; r: string; begin sPath := GetPathLastRun(sEventLog); if FileExists(sPath) = true then begin AssignFile(f, sPath); {I+} // Open the file in write mode. ReWrite(f); r := GetProperDateTime(Now()); WriteLn(f, r); CloseFile(f); end else begin WriteLn('ERROR LastRunPut(): can''t find the file ' + sPath); end; LastRunPut := r; end; // of function LastRunPut. function RunLogparser(sPathLpr: string; sEventLog: string; sDateTimeLast: string; sDateTimeNow: string): integer; // // Run Logparser.exe for a specific Event Log. // // sPathLpr Full path to the export file; d:\folder\folder\file.lpr // sEventLog Name of Event Log to export. // sDateTimeLast Date Time of the last export; format: YYYY-MM-DD HH:MM:SS // sDateTimeNow Current Date Time; format: YYYY-MM-DD HH:MM:SS // // Returns a integer containing the error level value of the Logparser command. // var p: TProcess; // Process c: AnsiString; // Command Line begin // logparser.exe -i:EVT -o:TSV // "SELECT TimeGenerated,EventLog,ComputerName,EventId,EventType,REPLACE_STR(Strings,'\u000d\u000a','|') AS Strings FROM \\NS00DC066\Security WHERE TimeGenerated>'2015-06-02 13:48:00' AND TimeGenerated<='2015-06-02 13:48:46'" -stats:OFF -oSeparator:"|" // >"D:\ADBEHEER\Scripts\000134\export\NS00DC066\20150602-134800-72Od1Q7jYYJsZqFW.lpr" // // Added export fields (Issue2): // - EventLog // - ComputerName c := 'logparser.exe -i:EVT -o:TSV '; c := c + '"SELECT TimeGenerated,EventLog,ComputerName,EventId,EventType,REPLACE_STR(Strings,''\u000d\u000a'',''|'') AS Strings '; c := c + 'FROM '+ sEventLog + ' '; // Issue1 fix: https://github.com/PerryvandenHondel/NS-148-export-events/issues/1 c := c + 'WHERE TimeGenerated>=''' + sDateTimeLast + ''' AND TimeGenerated<''' + sDateTimeNow + '''" '; c := c + '-stats:OFF -oSeparator:"|" '; c := c + '>' + sPathLpr; WriteLn('RunLogparser(): running command line:'); WriteLn; WriteLn(c); WriteLn; // Setup the process to be executed. p := TProcess.Create(nil); p.Executable := 'cmd.exe'; p.Parameters.Add('/c ' + c); // Check if the output is cleaner on the screen. p.Options := [poWaitOnExit, poUsePipes]; // OLD: p.Options := [poWaitOnExit]; // Run the sub process. p.Execute; RunLogparser := p.ExitStatus; end; // of procedure RunLogparser function ExportEventLog(el: string) : string; // // Export Event logs // // el Name of the event log to export // // Returns the full path to the export file // var sDateTimeLast: string; sDateTimeNow: string; sPathLpr: string; intResult: integer; r: string; begin // Initialize all variables r := ''; sDateTimeLast := LastRunGet(el); sDateTimeNow := LastRunPut(el); // Build the path of the export file sPathLpr := GetPathExport(el, sDateTimeLast) + EXTENSION_LPR; WriteLn('ExportEventLog()'); WriteLn(' Event log: ', el); WriteLn(' DT Last: ', sDateTimeLast); WriteLn(' DT Now: ', sDateTimeNow); WriteLn(' Export to: ', sPathLpr); WriteLn; intResult := RunLogparser(sPathLpr, el, sDateTimeLast, sDateTimeNow); if intResult = 0 then begin WriteLn('Logparser ran OK!'); r := sPathLpr; end else begin WriteLn('Logparser returned an error: ', intResult); end; // if else ExportEventLog := r; end; // procedure ExportEventLog end. // end of unit ee_export
unit GameUnit; interface uses GameObjectUnit,ColliderUnit,Vcl.Forms,Vcl.Controls,Vcl.StdCtrls, Types,Classes,Math,Windows,SysUtils,Vcl.ExtCtrls,System.Generics.Collections; type TGame = class private _ground: TList<TGameObject>; // границы игрового поля, список представляет собой набор по умолчанию из четырех сторон _obstacles: TList<TGameObject>; // неподвижные препятствия, кнопки _tanks: TList<TGameObject>; // подвижные объекты, текстовые поля _collider: TCollider; // объект, разрешающий столкновения объектов _step_of_game: Integer; // такт игры _handle_form: TForm; // форма для нашей игры _buttons: TList<TButton>; // список кнопок _labels: TList<TLabel>; // список лейблов _timer: TTimer; procedure ReadFromForm(_only_ground: Boolean); procedure WriteToForm(); procedure Step(); procedure TimerEvent(Sender: TObject); public constructor Create(HF: TForm; speed:integer = 200); destructor Destroy(); override; procedure Start(); procedure Stop(); function IsGameStart(): Boolean; procedure ChangeSpeedOfGame(_new_speed: Integer); function CheckTheGame(): Boolean; end; implementation { TGame } constructor TGame.Create(HF:TForm; speed:integer = 200); var i: Integer; AButton: TButton; ALabel: TLabel; RandomX: Integer; RandomY: Integer; begin OutputDebugString('Game is Creating.'); _handle_form := HF; _ground := TList<TGameObject>.Create; _obstacles := TList<TGameObject>.Create; _tanks := TList<TGameObject>.Create; _collider := TCollider.Create; _buttons := TList<TButton>.Create; _labels := TList<TLabel>.Create; _buttons.Clear(); _labels.Clear(); Randomize; for i := 0 to _handle_form.ComponentCount - 1 do begin if(_handle_form.Components[i] is TButton)then begin AButton:=((_handle_form.Components[i]) as TButton); _buttons.Add(AButton); _obstacles.Add(TGameObject.Create(TRect.Create(AButton.Left, AButton.Top, AButton.Left+AButton.Width, AButton.Top+AButton.Height), TPoint.Create(0,0))); end; if(_handle_form.Components[i] is TLabel)then begin ALabel:=((_handle_form.Components[i]) as TLabel); if(ALabel.Caption = 'T')then begin RandomX:=RandomRange(-15,15); RandomY:=RandomRange(-15,15); while((Abs(RandomX) <= 5) OR (Abs(RandomY) <= 5)) do begin RandomX:=RandomRange(-15,15); RandomY:=RandomRange(-15,15); end; _labels.Add(ALabel); _tanks.Add(TGameObject.Create(TRect.Create(ALabel.Left, ALabel.Top, ALabel.Left+ALabel.Width, ALabel.Top+ALabel.Height), TPoint.Create(RandomX,RandomY))); end; end; end; _ground.Add(TGameObject.Create(TRect.Create( 0, -2, _handle_form.ClientWidth,0), TPoint.Create(0,0))); _ground.Add(TGameObject.Create(TRect.Create( 0, _handle_form.ClientHeight, _handle_form.ClientWidth,2+_handle_form.ClientHeight), TPoint.Create(0,0))); _ground.Add(TGameObject.Create(TRect.Create( -2, 0, 0,_handle_form.ClientHeight), TPoint.Create(0,0))); _ground.Add(TGameObject.Create(TRect.Create( _handle_form.ClientWidth, 0, _handle_form.ClientWidth+2,_handle_form.ClientHeight), TPoint.Create(0,0))); _timer := TTimer.Create(nil); _timer.OnTimer:= TimerEvent; _step_of_game:=speed; _timer.Interval:=_step_of_game; _timer.Enabled:=False; OutputDebugString('Game have been created.'); end; destructor TGame.Destroy; begin OutputDebugString('Game is deleting.'); _ground.DeleteRange(0,_ground.Count); _obstacles.DeleteRange(0,_obstacles.Count); _tanks.DeleteRange(0,_obstacles.Count); _buttons.Clear(); _labels.Clear(); _buttons.Free; _labels.Free; _ground.Free; _obstacles.Free; _tanks.Free; _collider.Free; _timer.Free; OutputDebugString('Game have been deleted.'); inherited; end; procedure TGame.ChangeSpeedOfGame(_new_speed: Integer); begin _step_of_game := _new_speed; _timer.Interval:=_step_of_game; end; function TGame.IsGameStart: Boolean; begin Result := _timer.Enabled; end; function TGame.CheckTheGame(): Boolean; var i,j: Integer; _all_objects: TList<TGameObject>; begin _all_objects := TList<TGameObject>.Create; _all_objects.AddRange(_obstacles); _all_objects.AddRange(_ground); _all_objects.AddRange(_tanks); Result := true; for i:= 0 to _all_objects.Count - 1 do begin for j:= i+1 to _all_objects.Count -1 do begin if(_all_objects[i].Interaction(_all_objects[j]))then begin Result := false; break; end; end; if(Result = false)then break; end; _all_objects.Clear(); _all_objects.Free; end; procedure TGame.WriteToForm(); var i: Integer; begin for i:= 0 to _labels.Count - 1 do begin TLabel(_labels.Items[i]).Left := _tanks.Items[i].GetRect().Location.X; TLabel(_labels.Items[i]).Top := _tanks.Items[i].GetRect().Location.Y; //TLabel(_labels.Items[i]).Caption:=IntToStr(_tanks.Items[i].GetVelocity().X)+ //';'+IntToStr(_tanks.Items[i].GetVelocity().Y); end; for i:= 0 to _buttons.Count - 1 do begin TButton(_buttons.Items[i]).Left := _obstacles.Items[i].GetRect().Left; TButton(_buttons.Items[i]).Top := _obstacles.Items[i].GetRect().Top; end; end; procedure TGame.ReadFromForm(_only_ground: Boolean); var i:integer; begin If(not(_only_ground))then begin for i:= 0 to _tanks.Count - 1 do begin _tanks.Items[i].SetRect(Rect(_labels.Items[i].Left, _labels.Items[i].Top, _labels.Items[i].Left+_labels.Items[i].Width, _labels.Items[i].Top+_labels.Items[i].Height)); end; for i:= 0 to _buttons.Count - 1 do begin _obstacles.Items[i].SetRect(Rect(_buttons.Items[i].Left, _buttons.Items[i].Top, _buttons.Items[i].Left+_buttons.Items[i].Width, _buttons.Items[i].Top+_buttons.Items[i].Height)); end; end; _ground.Items[0].SetRect(Rect( 0, -2, _handle_form.ClientWidth,0)); _ground.Items[1].SetRect(Rect( 0, _handle_form.ClientHeight, _handle_form.ClientWidth,2+_handle_form.ClientHeight)); _ground.Items[2].SetRect(Rect( -2, 0, 0,_handle_form.ClientHeight)); _ground.Items[3].SetRect(Rect( _handle_form.ClientWidth, 0, _handle_form.ClientWidth+2,_handle_form.ClientHeight)); end; procedure TGame.Start; begin _timer.Enabled := True; end; procedure TGame.Step; var i: Integer; _all_objects: TList<TGameObject>; begin for i:=0 to _tanks.Count - 1 do // производим шаг каждого танка begin _tanks.Items[i].Step(); end; _all_objects := TList<TGameObject>.Create; _all_objects.AddRange(_tanks); _all_objects.AddRange(_obstacles); _all_objects.AddRange(_ground); _collider.SetGameObjects(_all_objects); // установка списка объектов для распознавания коллизий _collider.DoWork(); _all_objects.Clear(); _all_objects.Free; end; procedure TGame.Stop; begin _timer.Enabled := false; end; procedure TGame.TimerEvent(Sender: TObject); begin ReadFromForm(true); Step(); WriteToForm(); end; end.
unit uLinkListEditorDatabases; interface uses Generics.Defaults, Generics.Collections, Winapi.Windows, Winapi.ActiveX, System.SysUtils, System.Classes, Vcl.Controls, Vcl.Graphics, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Forms, Dmitry.Utils.System, Dmitry.Utils.Files, Dmitry.Controls.WatermarkedEdit, Dmitry.Controls.WebLink, UnitDBDeclare, UnitDBFileDialogs, UnitINI, uConstants, uMemory, uRuntime, uLogger, uConfiguration, uStringUtils, uDBForm, uDBTypes, uDBConnection, uDBScheme, uDBEntities, uDBContext, uDBManager, uVclHelpers, uIconUtils, uTranslate, uAssociations, uTranslateUtils, uShellUtils, uShellIntegration, uGraphicUtils, uBitmapUtils, uFormInterfaces, uCollectionUtils, uDialogUtils, uLinkListEditorUpdateDirectories, uProgramStatInfo; type TLinkListEditorDatabases = class(TInterfacedObject, ILinkEditor) private FOwner: TDBForm; FDeletedCollections: TStrings; FForm: IFormLinkItemEditorData; procedure LoadIconForLink(Link: TWebLink; Path, Icon: string); procedure OnCollectionIconClick(Sender: TObject); procedure OnChangePlaceClick(Sender: TObject); procedure OnPreviewOptionsClick(Sender: TObject); procedure OnUpdateOptionsClick(Sender: TObject); procedure OnCompactAndRepairClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure UpdateCompactAndRepairLabel; public constructor Create(Owner: TDBForm); destructor Destroy; override; procedure SetForm(Form: IFormLinkItemEditorData); procedure CreateNewItem(Sender: ILinkItemSelectForm; var Data: TDataObject; Verb: string; Elements: TListElements); procedure CreateEditorForItem(Sender: ILinkItemSelectForm; Data: TDataObject; EditorData: IFormLinkItemEditorData); procedure UpdateItemFromEditor(Sender: ILinkItemSelectForm; Data: TDataObject; EditorData: IFormLinkItemEditorData); procedure FillActions(Sender: ILinkItemSelectForm; AddActionProc: TAddActionProcedure); function OnDelete(Sender: ILinkItemSelectForm; Data: TDataObject; Editor: TPanel): Boolean; function OnApply(Sender: ILinkItemSelectForm): Boolean; end; procedure UpdateCurrentCollectionDirectories(CollectionFile: string); implementation const CHANGE_DB_ICON = 1; CHANGE_DB_CAPTION_EDIT = 2; CHANGE_DB_CHANGE_PATH = 3; CHANGE_DB_PATH = 4; CHANGE_DB_DESC_EDIT = 5; CHANGE_DB_DESC_LABEL = 6; CHANGE_DB_UPDATE_OPTIONS = 7; CHANGE_DB_PREVIEW_OPTIONS = 7; CHANGE_DB_COMPACT_AND_REPAIR = 8; procedure UpdateCurrentCollectionDirectories(CollectionFile: string); var Data: TList<TDataObject>; Editor: ILinkEditor; begin Editor := TLinkListEditorUpdateDirectories.Create(); try Data := TList<TDataObject>.Create; try ReadDatabaseSyncDirectories(TList<TDatabaseDirectory>(Data), CollectionFile); if LinkItemSelectForm.Execute(480, TA('Directories synchronization with collection', 'CollectionSettings'), Data, Editor) then SaveDatabaseSyncDirectories(TList<TDatabaseDirectory>(Data), CollectionFile); finally FreeList(Data); end; finally Editor := nil; end; end; { TLinkListEditorDatabases } constructor TLinkListEditorDatabases.Create(Owner: TDBForm); begin FOwner := Owner; FDeletedCollections := TStringList.Create; end; procedure TLinkListEditorDatabases.CreateEditorForItem( Sender: ILinkItemSelectForm; Data: TDataObject; EditorData: IFormLinkItemEditorData); var DI: TDatabaseInfo; WlIcon: TWebLink; WlChangeLocation, WLUpdateOptions, WlPreviewOptions, WlCompactAndRepair: TWebLink; WedCaption, WedDescription: TWatermarkedEdit; LbInfo, LbDescription: TLabel; Editor: TPanel; begin Editor := EditorData.EditorPanel; DI := TDatabaseInfo(Data); WlIcon := Editor.FindChildByTag<TWebLink>(CHANGE_DB_ICON); WedCaption := Editor.FindChildByTag<TWatermarkedEdit>(CHANGE_DB_CAPTION_EDIT); WlChangeLocation := Editor.FindChildByTag<TWebLink>(CHANGE_DB_CHANGE_PATH); LbInfo := Editor.FindChildByTag<TLabel>(CHANGE_DB_PATH); WedDescription := Editor.FindChildByTag<TWatermarkedEdit>(CHANGE_DB_DESC_EDIT); LbDescription := Editor.FindChildByTag<TLabel>(CHANGE_DB_DESC_LABEL); WLUpdateOptions := Editor.FindChildByTag<TWebLink>(CHANGE_DB_UPDATE_OPTIONS); WlPreviewOptions := Editor.FindChildByTag<TWebLink>(CHANGE_DB_PREVIEW_OPTIONS); WlCompactAndRepair := Editor.FindChildByTag<TWebLink>(CHANGE_DB_COMPACT_AND_REPAIR); if WlIcon = nil then begin WlIcon := TWebLink.Create(Editor); WlIcon.Parent := Editor; WlIcon.Tag := CHANGE_DB_ICON; WlIcon.Width := 16; WlIcon.Height := 16; WlIcon.Left := 8; WlIcon.Top := 8; WlIcon.OnClick := OnCollectionIconClick; end; if LbInfo = nil then begin LbInfo := TLabel.Create(Editor); LbInfo.Parent := Editor; LbInfo.Tag := CHANGE_DB_PATH; LbInfo.Left := 35; LbInfo.Top := 8; LbInfo.Width := 350; LbInfo.AutoSize := False; LbInfo.EllipsisPosition := epPathEllipsis; end; if WedCaption = nil then begin WedCaption := TWatermarkedEdit.Create(Editor); WedCaption.Parent := Editor; WedCaption.Tag := CHANGE_DB_CAPTION_EDIT; WedCaption.Top := LbInfo.Top + LbInfo.Height + 5; WedCaption.Left := 35; WedCaption.Width := 200; WedCaption.OnKeyDown := FormKeyDown; end; if WlChangeLocation = nil then begin WlChangeLocation := TWebLink.Create(Editor); WlChangeLocation.Parent := Editor; WlChangeLocation.Tag := CHANGE_DB_CHANGE_PATH; WlChangeLocation.Height := 26; WlChangeLocation.Text := FOwner.L('Change file'); WlChangeLocation.RefreshBuffer(True); WlChangeLocation.Top := WedCaption.Top + WedCaption.Height div 2 - WlChangeLocation.Height div 2; WlChangeLocation.Left := 240; WlChangeLocation.LoadFromResource('NAVIGATE'); WlChangeLocation.OnClick := OnChangePlaceClick; end; if WedDescription = nil then begin WedDescription := TWatermarkedEdit.Create(Editor); WedDescription.Parent := Editor; WedDescription.Tag := CHANGE_DB_DESC_EDIT; WedDescription.Top := WedCaption.Top + WedCaption.Height + 5;; WedDescription.Left := 35; WedDescription.Width := 200; WedDescription.OnKeyDown := FormKeyDown; end; if LbDescription = nil then begin LbDescription := TLabel.Create(Editor); LbDescription.Parent := Editor; LbDescription.Tag := CHANGE_DB_DESC_LABEL; LbDescription.Caption := FOwner.L('Description'); LbDescription.Left := WedDescription.AfterRight(5); LbDescription.Top := WedDescription.Top + WedDescription.Height div 2 - LbDescription.Height div 2; end; if WLUpdateOptions = nil then begin WLUpdateOptions := TWebLink.Create(Editor); WLUpdateOptions.Parent := Editor; WLUpdateOptions.Tag := CHANGE_DB_UPDATE_OPTIONS; WLUpdateOptions.Height := 26; WLUpdateOptions.Text := FOwner.L('Change synchronization settings'); WLUpdateOptions.Top := WedDescription.Top + WedDescription.Height + 8; WLUpdateOptions.Left := 35; WLUpdateOptions.IconWidth := 16; WLUpdateOptions.IconHeight := 16; WLUpdateOptions.LoadFromResource('SYNC'); WLUpdateOptions.RefreshBuffer(True); WLUpdateOptions.OnClick := OnUpdateOptionsClick; end; if WlPreviewOptions = nil then begin WlPreviewOptions := TWebLink.Create(Editor); WlPreviewOptions.Parent := Editor; WlPreviewOptions.Tag := CHANGE_DB_UPDATE_OPTIONS; WlPreviewOptions.Height := 26; WlPreviewOptions.Text := FOwner.L('Change preview options'); WlPreviewOptions.Top := WLUpdateOptions.Top + WLUpdateOptions.Height + 8; WlPreviewOptions.Left := 35; WlPreviewOptions.IconWidth := 16; WlPreviewOptions.IconHeight := 16; WlPreviewOptions.LoadFromResource('PICTURE'); WlPreviewOptions.RefreshBuffer(True); WlPreviewOptions.OnClick := OnPreviewOptionsClick; end; if WlCompactAndRepair = nil then begin WlCompactAndRepair := TWebLink.Create(Editor); WlCompactAndRepair.Parent := Editor; WlCompactAndRepair.Tag := CHANGE_DB_COMPACT_AND_REPAIR; WlCompactAndRepair.Height := 26; WlCompactAndRepair.Left := 35; WlCompactAndRepair.Top := WlPreviewOptions.Top + WlPreviewOptions.Height + 8; WlCompactAndRepair.IconWidth := 16; WlCompactAndRepair.IconHeight := 16; WlCompactAndRepair.LoadFromResource('SERIES_SETTINGS'); WlCompactAndRepair.OnClick := OnCompactAndRepairClick; end; UpdateCompactAndRepairLabel; WlCompactAndRepair.RefreshBuffer(True); LoadIconForLink(WlIcon, DI.Path, DI.Icon); WedCaption.Text := DI.Title; LbInfo.Caption := DI.Path; WedDescription.Text := DI.Description; end; procedure TLinkListEditorDatabases.CreateNewItem(Sender: ILinkItemSelectForm; var Data: TDataObject; Verb: string; Elements: TListElements); var Link: TWebLink; Info: TLabel; DI: TDatabaseInfo; Context: IDBContext; function L(Text: string): string; begin Result := Text; end; procedure CreateSampleDB; var SaveDialog: DBSaveDialog; FileName: string; begin // Sample DB SaveDialog := DBSaveDialog.Create; try SaveDialog.Filter := L('PhotoDB Files (*.photodb)|*.photodb'); if SaveDialog.Execute then begin FileName := SaveDialog.FileName; FDeletedCollections.Remove(FileName, False); if GetExt(FileName) <> 'PHOTODB' then FileName := FileName + '.photodb'; if TDBManager.CreateExampleDB(FileName) then Data := TDatabaseInfo.Create(GetFileNameWithoutExt(FileName), FileName, Application.ExeName + ',0', ''); end; finally F(SaveDialog); end; end; procedure OpenDB; var OpenDialog: DBOpenDialog; FileName, Title, Description: string; NewCollectionContext: IDBContext; Settings: TSettings; SettingsRepository: ISettingsRepository; begin OpenDialog := DBOpenDialog.Create; try OpenDialog.Filter := L('PhotoDB Files (*.photodb)|*.photodb'); if FileExistsSafe(Context.CollectionFileName) then OpenDialog.SetFileName(Context.CollectionFileName); if OpenDialog.Execute then begin FileName := OpenDialog.FileName; if TDBScheme.IsOldColectionFile(FileName) then begin if TDBManager.UpdateDatabaseQuery(FileName) then TDBScheme.UpdateCollection(FileName, 0, True); end; if TDBScheme.IsValidCollectionFile(FileName) then begin FDeletedCollections.Remove(FileName, False); NewCollectionContext := TDBContext.Create(FileName); SettingsRepository := NewCollectionContext.Settings; Settings := SettingsRepository.Get; try Title := GetFileNameWithoutExt(OpenDialog.FileName); Description := ''; if Length(Settings.Name) > 0 then begin Title := Settings.Name; Description := Settings.Description; end; Data := TDatabaseInfo.Create(Title, OpenDialog.FileName, Application.ExeName + ',0', Description); finally F(Settings); end; end else if TDBScheme.IsNewColectionFile(FileName) then begin MessageBoxDB(FOwner.Handle, FOwner.L('This collection should be opened in newer program version. Try to download the laters program version from official site.'), FOwner.L('Warning'), '', TD_BUTTON_YESNOCANCEL, TD_ICON_WARNING); end; end; finally F(OpenDialog); end; end; begin Context := DBManager.DBContext; if Data = nil then begin if Verb = 'Create' then CreateSampleDB; if Verb = 'Open' then OpenDB; Exit; end; DI := TDatabaseInfo(Data); Link := TWebLink(Elements[leWebLink]); Info := TLabel(Elements[leInfoLabel]); Link.Text := DI.Title; if AnsiLowerCase(DI.Path) = AnsiLowerCase(Context.CollectionFileName) then Link.Font.Style := [fsBold]; Info.Caption := DI.Path; Info.EllipsisPosition := epPathEllipsis; LoadIconForLink(Link, DI.Path, DI.Icon); end; destructor TLinkListEditorDatabases.Destroy; begin FForm := nil; F(FDeletedCollections); inherited; end; procedure TLinkListEditorDatabases.FillActions(Sender: ILinkItemSelectForm; AddActionProc: TAddActionProcedure); begin AddActionProc(['Create', 'Open'], procedure(Action: string; WebLink: TWebLink) begin if Action = 'Create' then begin WebLink.Text := FOwner.L('Create new'); WebLink.LoadFromResource('NEW'); end; if Action = 'Open' then begin WebLink.Text := FOwner.L('Open existing'); WebLink.LoadFromResource('EXPLORER'); end; end ); end; procedure TLinkListEditorDatabases.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then FForm.ApplyChanges; end; procedure TLinkListEditorDatabases.LoadIconForLink(Link: TWebLink; Path, Icon: string); var Ico: HIcon; GraphicClass: TGraphicClass; Graphic: TGraphic; B: TBitmap; begin if IsIconPath(Icon) then begin if Icon <> '' then Ico := ExtractSmallIconByPath(Icon) else Ico := ExtractAssociatedIconSafe(Path); try Link.LoadFromHIcon(Ico); finally DestroyIcon(Ico); end; Exit; end; GraphicClass := TFileAssociations.Instance.GetGraphicClass(ExtractFileExt(Icon)); if GraphicClass = nil then Exit; Graphic := GraphicClass.Create; try Graphic.LoadFromFile(Icon); B := TBitmap.Create; try AssignGraphic(B, Graphic); CenterBitmap24To32ImageList(B, Link.IconWidth); Link.LoadBitmap(B); Link.RefreshBuffer; finally F(B); end; finally F(Graphic); end; end; procedure TLinkListEditorDatabases.OnUpdateOptionsClick(Sender: TObject); var DI: TDatabaseInfo; Editor: TPanel; begin Editor := TPanel(TControl(Sender).Parent); DI := TDatabaseInfo(Editor.Tag); UpdateCurrentCollectionDirectories(DI.Path); end; procedure TLinkListEditorDatabases.OnPreviewOptionsClick(Sender: TObject); var DI: TDatabaseInfo; Editor: TPanel; begin Editor := TPanel(TControl(Sender).Parent); DI := TDatabaseInfo(Editor.Tag); CollectionPreviewSettings.Execute(DI.Path); end; function TLinkListEditorDatabases.OnApply(Sender: ILinkItemSelectForm): Boolean; var DialogResult: Integer; Text: string; FileName: string; DI: TDatabaseInfo; begin for DI in TList<TDatabaseInfo>(Sender.DataList) do FDeletedCollections.Remove(DI.Path, False); if FDeletedCollections.Count = 0 then Exit(True); Text := FOwner.L('Do you want to delete files below for deleted collections?') + sLineBreak + FDeletedCollections.Join(sLineBreak); DialogResult := MessageBoxDB(FOwner.Handle, Text, FOwner.L('Warning'), '', TD_BUTTON_YESNOCANCEL, TD_ICON_WARNING); if ID_CANCEL = DialogResult then Exit(False); if ID_YES = DialogResult then for FileName in FDeletedCollections do SilentDeleteFile(Screen.ActiveFormHandle, FileName, True); Exit(True); end; procedure TLinkListEditorDatabases.OnChangePlaceClick(Sender: TObject); var DI: TDatabaseInfo; LbInfo: TLabel; Editor: TPanel; OpenDialog: DBOpenDialog; begin Editor := TPanel(TControl(Sender).Parent); DI := TDatabaseInfo(Editor.Tag); OpenDialog := DBOpenDialog.Create; try OpenDialog.Filter := FOwner.L('PhotoDB Files (*.photodb)|*.photodb'); OpenDialog.FilterIndex := 0; OpenDialog.SetFileName(DI.Path); if OpenDialog.Execute and TDBScheme.IsValidCollectionFile(OpenDialog.FileName) then begin LbInfo := Editor.FindChildByTag<TLabel>(CHANGE_DB_PATH); LbInfo.Caption := OpenDialog.FileName; DI.Path := OpenDialog.FileName; end; finally F(OpenDialog); end; end; function TLinkListEditorDatabases.OnDelete(Sender: ILinkItemSelectForm; Data: TDataObject; Editor: TPanel): Boolean; var DI: TDatabaseInfo; Context: IDBContext; begin DI := TDatabaseInfo(Editor.Tag); Context := DBManager.DBContext; if AnsiLowerCase(Context.CollectionFileName) = AnsiLowerCase(DI.Path) then begin MessageBoxDB(FOwner.Handle, FOwner.L('Active collection can''t be deleted! Please change active collection and try again.'), FOwner.L('Warning'), '', TD_BUTTON_OK, TD_ICON_WARNING); Exit(False); end; if FileExistsSafe(DI.Path) then begin TryRemoveConnection(DI.Path, True); FDeletedCollections.Add(DI.Path); end; Result := True; end; procedure TLinkListEditorDatabases.OnCollectionIconClick(Sender: TObject); var DI: TDatabaseInfo; Icon, TmpDir: string; Editor: TPanel; WlIcon: TWebLink; OpenPictureDialog: DBOpenPictureDialog; Bitmap: TBitmap; ExeExts: TDictionary<string, string>; begin Editor := TPanel(TControl(Sender).Parent); DI := TDatabaseInfo(Editor.Tag); WlIcon := Editor.FindChildByTag<TWebLink>(CHANGE_DB_ICON); Icon := DI.Icon; ExeExts := TDictionary<string, string>.Create; OpenPictureDialog := DBOpenPictureDialog.Create; try ExeExts.Add('.ico,.exe,.dll,.scr,.ocx', TA('Icons and executables', 'Associations')); OpenPictureDialog.Filter := TFileAssociations.Instance.GetExtendedFullFilter(True, True, ExeExts); if OpenPictureDialog.Execute then begin Icon := OpenPictureDialog.FileName; if IsIconPath(Icon) then begin if ChangeIconDialog(0, Icon) then begin DI.Icon := Icon; LoadIconForLink(WlIcon, DI.Path, DI.Icon); end; end else begin if DBLoadImage(Icon, Bitmap, 32, 32) then begin TmpDir := GetAppDataDirectory + TmpDirectory; CreateDirA(TmpDir); Icon := GetTempFileNameEx(TmpDir, '.bmp'); Bitmap.SaveToFile(Icon); F(Bitmap); DI.Icon := Icon; LoadIconForLink(WlIcon, DI.Path, DI.Icon); end; end; end; finally F(OpenPictureDialog); F(ExeExts); end; end; procedure TLinkListEditorDatabases.SetForm(Form: IFormLinkItemEditorData); begin FForm := Form; end; procedure TLinkListEditorDatabases.UpdateCompactAndRepairLabel; var Editor: TPanel; DI: TDatabaseInfo; WlCompactAndRepair: TWebLink; begin Editor := FForm.EditorPanel; DI := TDatabaseInfo(Editor.Tag); WlCompactAndRepair := Editor.FindChildByTag<TWebLink>(CHANGE_DB_COMPACT_AND_REPAIR); WlCompactAndRepair.Text := FormatEx(FOwner.L('Compact ({0}) and repair'), [SizeInText(GetFileSizeByName(DI.Path))]); end; procedure TLinkListEditorDatabases.UpdateItemFromEditor( Sender: ILinkItemSelectForm; Data: TDataObject; EditorData: IFormLinkItemEditorData); var DI: TDatabaseInfo; WedCaption, WedDesctiption: TWatermarkedEdit; Editor: TPanel; begin Editor := EditorData.EditorPanel; DI := TDatabaseInfo(Data); WedCaption := Editor.FindChildByTag<TWatermarkedEdit>(CHANGE_DB_CAPTION_EDIT); WedDesctiption := Editor.FindChildByTag<TWatermarkedEdit>(CHANGE_DB_DESC_EDIT); DI.Assign(EditorData.EditorData); DI.Title := WedCaption.Text; DI.Description := WedDesctiption.Text; end; procedure TLinkListEditorDatabases.OnCompactAndRepairClick(Sender: TObject); var DI: TDatabaseInfo; Editor: TPanel; CompactThread: TThread; ProgressForm: IBackgroundTaskStatusForm; begin if ID_YES <> MessageBoxDB(Screen.ActiveFormHandle, TA('Do you really want to compact collection file and check it for errors?', 'System'), TA('Warning'), TD_BUTTON_YESNO, TD_ICON_WARNING) then Exit; ProgramStatistics.CompactCollectionUsed; Editor := TPanel(TControl(Sender).Parent); DI := TDatabaseInfo(Editor.Tag); ProgressForm := BackgroundTaskStatusForm; try CompactThread := TThread.CreateAnonymousThread( procedure var Data: TDatabaseInfo; StartC: Cardinal; IsTaskComplete: Boolean; ErrorMessage: string; begin Data := DI.Clone as TDatabaseInfo; StartC := GetTickCount; IsTaskComplete := False; ErrorMessage := ''; try //to call show modal before end of all update process Sleep(100); CoInitializeEx(nil, COM_MODE); try TThread.Synchronize(nil, procedure begin ProgressForm.SetText(TA('Locking file...', 'System')); ProgressForm.SetProgress(100, 0); end ); try while GetTickCount - StartC < 10000 do begin Sleep(100); if TryRemoveConnection(Data.Path, True) then begin TThread.Synchronize(nil, procedure begin ProgressForm.SetText(TA('Executing, %', 'System')); end ); PackTable(Data.Path, procedure(Sender: TObject; Total, Value: Int64) begin TThread.Synchronize(nil, procedure begin ProgressForm.SetProgress(Total, Value); end ); end ); IsTaskComplete := True; Break; end; end; except on e: Exception do begin EventLog(e); ErrorMessage := e.Message; end; end; finally CoUninitialize; end; finally TThread.Synchronize(nil, procedure begin ProgressForm.CloseForm; if IsTaskComplete then MessageBoxDB(Screen.ActiveFormHandle, TA('Operation completed successfully!', 'System'), TA('Information'), TD_BUTTON_OK, TD_ICON_INFORMATION) else begin if ErrorMessage <> '' then MessageBoxDB(Screen.ActiveFormHandle, FormatEx(TA('An unhandled error occurred: {0}!'), [ErrorMessage]), TA('Error'), TD_BUTTON_OK, TD_ICON_ERROR) else MessageBoxDB(Screen.ActiveFormHandle, TA('Failed to lock collection file, try again in a few seconds!', 'System'), TA('Warning'), TD_BUTTON_OK, TD_ICON_WARNING); end; UpdateCompactAndRepairLabel; end ); end; end ); CompactThread.FreeOnTerminate := True; CompactThread.Start; ProgressForm.ShowModal; finally ProgressForm := nil; end; end; end.