hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
163 values
lang
stringclasses
53 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
112
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
113
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
float64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
113
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
3
1.05M
avg_line_length
float64
1
966k
max_line_length
int64
1
977k
alphanum_fraction
float64
0
1
478866827527333a68a2b674327363c4b6489343
4,579
pas
Pascal
stm32f7xx_hal_pcd_ex.pas
Laksen/fp-stm32f7xx_hal
01dce5d827016a1a0711269addbd720e87983d1c
[ "MIT" ]
5
2015-09-26T08:18:04.000Z
2019-02-11T03:54:18.000Z
stm32f7xx_hal_pcd_ex.pas
Laksen/fp-stm32f7xx_hal
01dce5d827016a1a0711269addbd720e87983d1c
[ "MIT" ]
null
null
null
stm32f7xx_hal_pcd_ex.pas
Laksen/fp-stm32f7xx_hal
01dce5d827016a1a0711269addbd720e87983d1c
[ "MIT" ]
3
2015-09-26T08:18:05.000Z
2022-01-18T15:57:20.000Z
(* Ported to Pascal by: Jeppe Johansen - jeppe@j-software.dk *) (** ****************************************************************************** * @file stm32f7xx_hal_pcd_ex.h * @author MCD Application Team * @version V1.0.1 * @date 25-June-2015 * @brief Header file of PCD HAL module. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2015 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** *) unit stm32f7xx_hal_pcd_ex; interface uses stm32f7xx_defs, stm32f7xx_hal, stm32f7xx_hal_pcd; const PCD_LPM_L0_ACTIVE = $00; (* on *) PCD_LPM_L1_ACTIVE = $01; (* LPM L1 sleep *) type PCD_LPM_MsgTypeDef = integer; function HAL_PCDEx_SetTxFiFo(var hpcd: PCD_HandleTypeDef; fifo: byte; size: word): HAL_StatusTypeDef; function HAL_PCDEx_SetRxFiFo(var hpcd: PCD_HandleTypeDef; size: word): HAL_StatusTypeDef; function HAL_PCDEx_ActivateLPM(var hpcd: PCD_HandleTypeDef): HAL_StatusTypeDef; function HAL_PCDEx_DeActivateLPM(var hpcd: PCD_HandleTypeDef): HAL_StatusTypeDef; procedure HAL_PCDEx_LPM_Callback(var hpcd: PCD_HandleTypeDef; msg: PCD_LPM_MsgTypeDef); external name 'HAL_PCDEx_LPM_Callback'; implementation function HAL_PCDEx_SetTxFiFo(var hpcd: PCD_HandleTypeDef; fifo: byte; size: word): HAL_StatusTypeDef; var Tx_Offset, i: longword; begin Tx_Offset := hpcd.Instance^.GRXFSIZ; if (fifo = 0) then hpcd.Instance^.DIEPTXF0_HNPTXFSIZ := (size shl 16) or Tx_Offset else begin Tx_Offset := Tx_Offset + ((hpcd.Instance^.DIEPTXF0_HNPTXFSIZ) shr 16); for i := 0 to fifo - 2 do Tx_Offset := Tx_Offset + (hpcd.Instance^.DIEPTXF[i] shr 16); (* Multiply Tx_Size by 2 to get higher performance *) hpcd.Instance^.DIEPTXF[fifo - 1] := (size shl 16) or Tx_Offset; end; exit(HAL_OK); end; function HAL_PCDEx_SetRxFiFo(var hpcd: PCD_HandleTypeDef; size: word): HAL_StatusTypeDef; begin hpcd.Instance^.GRXFSIZ := size; exit(HAL_OK); end; function HAL_PCDEx_ActivateLPM(var hpcd: PCD_HandleTypeDef): HAL_StatusTypeDef; var USBx: PPCD_TypeDef; begin USBx := hpcd.Instance; hpcd.lpm_active := True; hpcd.LPM_State := LPM_L0; USBx^.GINTMSK := USBx^.GINTMSK or USB_OTG_GINTMSK_LPMINTM; USBx^.GLPMCFG := USBx^.GLPMCFG or (USB_OTG_GLPMCFG_LPMEN or USB_OTG_GLPMCFG_LPMACK or USB_OTG_GLPMCFG_ENBESL); exit(HAL_OK); end; function HAL_PCDEx_DeActivateLPM(var hpcd: PCD_HandleTypeDef): HAL_StatusTypeDef; var USBx: PPCD_TypeDef; begin USBx := hpcd.Instance; hpcd.lpm_active := False; USBx^.GINTMSK := USBx^.GINTMSK and (not USB_OTG_GINTMSK_LPMINTM); USBx^.GLPMCFG := USBx^.GLPMCFG and (not (USB_OTG_GLPMCFG_LPMEN or USB_OTG_GLPMCFG_LPMACK or USB_OTG_GLPMCFG_ENBESL)); exit(HAL_OK); end; procedure HAL_PCDEx_LPM_Callback_stub(var hpcd: PCD_HandleTypeDef; msg: PCD_LPM_MsgTypeDef); assembler; public name 'HAL_PCDEx_LPM_Callback'; asm .weak HAL_PCDEx_LPM_Callback end; end.
35.223077
141
0.710636
475dee24264206f1b5336a541febe379c8781bc6
155
dpr
Pascal
source/InnoCallback.dpr
thenickdude/InnoCallback
2ada374d44a0964f19dc334352ab4f98818f8aef
[ "WTFPL" ]
24
2018-04-18T13:49:11.000Z
2022-03-23T07:34:56.000Z
source/InnoCallback.dpr
thenickdude/InnoCallback
2ada374d44a0964f19dc334352ab4f98818f8aef
[ "WTFPL" ]
1
2018-04-19T03:33:06.000Z
2018-04-19T06:42:45.000Z
source/InnoCallback.dpr
thenickdude/InnoCallback
2ada374d44a0964f19dc334352ab4f98818f8aef
[ "WTFPL" ]
5
2018-06-12T21:19:21.000Z
2020-09-16T12:18:51.000Z
library InnoCallback; uses SysUtils, Classes, innocallbackengine in 'innocallbackengine.pas', ASMInline in 'ASMInline.pas'; begin end.
14.090909
50
0.709677
f1cb15ae7229607c9fe3102fe3d79900e92aa66e
82,460
pas
Pascal
references/embarcadero/rio/10_3_1/patched/fmx/FMX.Ani.pas
zekiguven/alcinoe
e55c5368ee8bfe7cd6d92424c29ab07d8a3e844c
[ "Apache-2.0" ]
2
2020-02-17T18:42:30.000Z
2020-11-14T04:57:48.000Z
references/embarcadero/rio/10_3_1/patched/fmx/FMX.Ani.pas
zekiguven/alcinoe
e55c5368ee8bfe7cd6d92424c29ab07d8a3e844c
[ "Apache-2.0" ]
2
2019-06-23T00:02:43.000Z
2019-10-12T22:39:28.000Z
references/embarcadero/rio/10_3_1/patched/fmx/FMX.Ani.pas
zekiguven/alcinoe
e55c5368ee8bfe7cd6d92424c29ab07d8a3e844c
[ "Apache-2.0" ]
null
null
null
{*******************************************************} { } { Delphi FireMonkey Platform } { } { Copyright(c) 2011-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit FMX.Ani; interface {$SCOPEDENUMS ON} uses System.Classes, System.UITypes, System.Rtti, System.Generics.Collections, FMX.Types, FMX.Graphics; type ITriggerAnimation = interface ['{8A291102-742F-45CB-9159-4E1D283AAF20}'] procedure StartTriggerAnimation(const AInstance: TFmxObject; const ATrigger: string); procedure StartTriggerAnimationWait(const AInstance: TFmxObject; const ATrigger: string); end; /// <summary>Helpers class for quick using animation. Don't use synchronous animation on the Android. /// Android uses asynchronous animation model.</summary> TAnimator = class private type TAnimationDestroyer = class private procedure DoAniFinished(Sender: TObject); end; private class var FDestroyer: TAnimationDestroyer; private class procedure CreateDestroyer; class procedure Uninitialize; public { animations } class procedure StartAnimation(const Target: TFmxObject; const AName: string); class procedure StopAnimation(const Target: TFmxObject; const AName: string); class procedure StartTriggerAnimation(const Target: TFmxObject; const AInstance: TFmxObject; const ATrigger: string); class procedure StartTriggerAnimationWait(const Target: TFmxObject; const AInstance: TFmxObject; const ATrigger: string); class procedure StopTriggerAnimation(const Target: TFmxObject; const AInstance: TFmxObject; const ATrigger: string); { default } class procedure DefaultStartTriggerAnimation(const Target, AInstance: TFmxObject; const ATrigger: string); static; class procedure DefaultStartTriggerAnimationWait(const Target: TFmxObject; const AInstance: TFmxObject; const ATrigger: string); { animation property } /// <summary>Asynchronously animates float type property and don't wait finishing of animation.</summary> class procedure AnimateFloat(const Target: TFmxObject; const APropertyName: string; const NewValue: Single; Duration: Single = 0.2; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); /// <summary>Asynchronously animates float type property with start delay and don't wait finishing of animation.</summary> class procedure AnimateFloatDelay(const Target: TFmxObject; const APropertyName: string; const NewValue: Single; Duration: Single = 0.2; Delay: Single = 0.0; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); /// <summary>Synchronously animates float type property and wait finishing of animation.</summary> /// <remarks>Don't use it on the Android. See detains in comment <c>TAnimator</c>.</remarks> class procedure AnimateFloatWait(const Target: TFmxObject; const APropertyName: string; const NewValue: Single; Duration: Single = 0.2; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); /// <summary>Asynchronously animates integer type property and don't wait finishing of animation.</summary> class procedure AnimateInt(const Target: TFmxObject; const APropertyName: string; const NewValue: Integer; Duration: Single = 0.2; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); /// <summary>Synchronously animates integer type property and wait finishing of animation.</summary> /// <remarks>Don't use it on the Android. See detains in comment <c>TAnimator</c>.</remarks> class procedure AnimateIntWait(const Target: TFmxObject; const APropertyName: string; const NewValue: Integer; Duration: Single = 0.2; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); /// <summary>Asynchronously animates color type property and don't wait finishing of animation.</summary> class procedure AnimateColor(const Target: TFmxObject; const APropertyName: string; NewValue: TAlphaColor; Duration: Single = 0.2; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); /// <summary>Stops all current animations of specified property of <c>Target</c> object.</summary> class procedure StopPropertyAnimation(const Target: TFmxObject; const APropertyName: string); end; { TAnimation } TAnimation = class(TFmxObject) public const DefaultAniFrameRate = 60; public class var AniFrameRate: Integer; private type TTriggerRec = record Name: string; Prop: TRttiProperty; Value: Boolean; end; private class var FAniThread: TTimer; private fOvershoot: Single; // https://quality.embarcadero.com/browse/RSP-16991 FTickCount : Integer; FDuration: Single; FDelay, FDelayTime: Single; FTime: Single; FInverse: Boolean; FSavedInverse: Boolean; FTrigger, FTriggerInverse: TTrigger; FLoop: Boolean; FPause: Boolean; FRunning: Boolean; FOnFinish: TNotifyEvent; FOnProcess: TNotifyEvent; FInterpolation: TInterpolationType; FAnimationType: TAnimationType; FEnabled: Boolean; FAutoReverse: Boolean; FTriggerList: TList<TTriggerRec>; FInverseTriggerList: TList<TTriggerRec>; FTargetClass: TClass; procedure SetEnabled(const Value: Boolean); procedure SetTrigger(const Value: TTrigger); procedure SetTriggerInverse(const Value: TTrigger); procedure ParseTriggers(const AInstance: TFmxObject; Normal, Inverse: Boolean); class procedure Uninitialize; function OvershootStored: Boolean; // https://quality.embarcadero.com/browse/RSP-16991 protected ///<summary>Return normalized CurrentTime value between 0..1 </summary> function GetNormalizedTime: Single; procedure FirstFrame; virtual; procedure ProcessAnimation; virtual; abstract; procedure DoProcess; virtual; procedure DoFinish; virtual; procedure Loaded; override; procedure ParentChanged; override; procedure AssignTo(Dest: TPersistent); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Start; virtual; procedure Stop; virtual; procedure StopAtCurrent; virtual; procedure StartTrigger(const AInstance: TFmxObject; const ATrigger: string); procedure StopTrigger(const AInstance: TFmxObject; const ATrigger: string); procedure ProcessTick(time, deltaTime: Single); property Running: Boolean read FRunning; property Pause: Boolean read FPause write FPause; property AnimationType: TAnimationType read FAnimationType write FAnimationType default TAnimationType.In; property AutoReverse: Boolean read FAutoReverse write FAutoReverse default False; property Enabled: Boolean read FEnabled write SetEnabled default False; property Delay: Single read FDelay write FDelay; property Duration: Single read FDuration write FDuration nodefault; property Interpolation: TInterpolationType read FInterpolation write FInterpolation default TInterpolationType.Linear; property Inverse: Boolean read FInverse write FInverse default False; ///<summary>Normalized CurrentTime value between 0..1 </summary> property NormalizedTime: Single read GetNormalizedTime; property Loop: Boolean read FLoop write FLoop default False; property Trigger: TTrigger read FTrigger write SetTrigger; property TriggerInverse: TTrigger read FTriggerInverse write SetTriggerInverse; property CurrentTime: Single read FTime; property OnProcess: TNotifyEvent read FOnProcess write FOnProcess; property OnFinish: TNotifyEvent read FOnFinish write FOnFinish; class property AniThread: TTimer read FAniThread; property Overshoot: Single read fOvershoot write fOvershoot Stored OvershootStored; // https://quality.embarcadero.com/browse/RSP-16991 end; { TCustomPropertyAnimation } TCustomPropertyAnimation = class(TAnimation) private protected FInstance: TObject; FRttiProperty: TRttiProperty; FPath, FPropertyName: string; procedure SetPropertyName(const AValue: string); function FindProperty: Boolean; procedure ParentChanged; override; procedure AssignTo(Dest: TPersistent); override; public property PropertyName: string read FPropertyName write SetPropertyName; procedure Start; override; procedure Stop; override; end; { TFloatAnimation } TFloatAnimation = class(TCustomPropertyAnimation) private FStartFloat: Single; FStopFloat: Single; FStartFromCurrent: Boolean; protected procedure ProcessAnimation; override; procedure FirstFrame; override; procedure AssignTo(Dest: TPersistent); override; public constructor Create(AOwner: TComponent); override; published property AnimationType default TAnimationType.In; property AutoReverse default False; property Enabled default False; property Delay; property Duration nodefault; property Interpolation default TInterpolationType.Linear; property Inverse default False; property Loop default False; property OnProcess; property OnFinish; property PropertyName; property StartValue: Single read FStartFloat write FStartFloat stored True nodefault; property StartFromCurrent: Boolean read FStartFromCurrent write FStartFromCurrent default False; property StopValue: Single read FStopFloat write FStopFloat stored True nodefault; property Trigger; property TriggerInverse; end; { TIntAnimation } TIntAnimation = class(TCustomPropertyAnimation) private FStartValue: Integer; FStopValue: Integer; FStartFromCurrent: Boolean; protected procedure ProcessAnimation; override; procedure FirstFrame; override; procedure AssignTo(Dest: TPersistent); override; public constructor Create(AOwner: TComponent); override; published property AnimationType default TAnimationType.In; property AutoReverse default False; property Enabled default False; property Delay; property Duration nodefault; property Interpolation default TInterpolationType.Linear; property Inverse default False; property Loop default False; property OnProcess; property OnFinish; property PropertyName; property StartValue: Integer read FStartValue write FStartValue stored True nodefault; property StartFromCurrent: Boolean read FStartFromCurrent write FStartFromCurrent default False; property StopValue: Integer read FStopValue write FStopValue stored True nodefault; property Trigger; property TriggerInverse; end; { TColorAnimation } TColorAnimation = class(TCustomPropertyAnimation) private FStartColor: TAlphaColor; FStopColor: TAlphaColor; FStartFromCurrent: Boolean; protected procedure ProcessAnimation; override; procedure FirstFrame; override; procedure AssignTo(Dest: TPersistent); override; public constructor Create(AOwner: TComponent); override; published property AnimationType default TAnimationType.In; property AutoReverse default False; property Enabled default False; property Delay; property Duration nodefault; property Interpolation default TInterpolationType.Linear; property Inverse default False; property Loop default False; property OnProcess; property OnFinish; property PropertyName; property StartValue: TAlphaColor read FStartColor write FStartColor; property StartFromCurrent: Boolean read FStartFromCurrent write FStartFromCurrent default False; property StopValue: TAlphaColor read FStopColor write FStopColor; property Trigger; property TriggerInverse; end; { TGradientAnimation } TGradientAnimation = class(TCustomPropertyAnimation) private FStartGradient: TGradient; FStopGradient: TGradient; FStartFromCurrent: Boolean; procedure SetStartGradient(const Value: TGradient); procedure SetStopGradient(const Value: TGradient); protected procedure ProcessAnimation; override; procedure FirstFrame; override; procedure AssignTo(Dest: TPersistent); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property AnimationType default TAnimationType.In; property AutoReverse default False; property Enabled default False; property Delay; property Duration nodefault; property Interpolation default TInterpolationType.Linear; property Inverse default False; property Loop default False; property OnProcess; property OnFinish; property PropertyName; property StartValue: TGradient read FStartGradient write SetStartGradient; property StartFromCurrent: Boolean read FStartFromCurrent write FStartFromCurrent default False; property StopValue: TGradient read FStopGradient write SetStopGradient; property Trigger; property TriggerInverse; end; { TRectAnimation } TRectAnimation = class(TCustomPropertyAnimation) private FStartRect: TBounds; FCurrent: TBounds; FStopRect: TBounds; FStartFromCurrent: Boolean; procedure SetStartRect(const Value: TBounds); procedure SetStopRect(const Value: TBounds); protected procedure ProcessAnimation; override; procedure FirstFrame; override; procedure AssignTo(Dest: TPersistent); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property AnimationType default TAnimationType.In; property AutoReverse default False; property Enabled default False; property Delay; property Duration nodefault; property Interpolation default TInterpolationType.Linear; property Inverse default False; property Loop default False; property OnProcess; property OnFinish; property PropertyName; property StartValue: TBounds read FStartRect write SetStartRect; property StartFromCurrent: Boolean read FStartFromCurrent write FStartFromCurrent default False; property StopValue: TBounds read FStopRect write SetStopRect; property Trigger; property TriggerInverse; end; { TBitmapAnimation } TBitmapAnimation = class(TCustomPropertyAnimation) private FStartBitmap: TBitmap; FStopBitmap: TBitmap; procedure SetStartBitmap(Value: TBitmap); procedure SetStopBitmap(Value: TBitmap); protected procedure ProcessAnimation; override; procedure AssignTo(Dest: TPersistent); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property AnimationType default TAnimationType.In; property AutoReverse default False; property Enabled default False; property Delay; property Duration nodefault; property Interpolation default TInterpolationType.Linear; property Inverse default False; property Loop default False; property OnProcess; property OnFinish; property PropertyName; property StartValue: TBitmap read FStartBitmap write SetStartBitmap; property StopValue: TBitmap read FStopBitmap write SetStopBitmap; property Trigger; property TriggerInverse; end; { TBitmapListAnimation } TBitmapListAnimation = class(TCustomPropertyAnimation) private type TAnimationBitmap = class(TBitmap) private [Weak] FAnimation: TBitmapListAnimation; protected procedure ReadStyleLookup(Reader: TReader); override; end; private FAnimationCount: Integer; FAnimationBitmap: TBitmap; FLastAnimationStep: Integer; FAnimationRowCount: Integer; FAnimationLookup: string; procedure SetAnimationBitmap(Value: TBitmap); procedure SetAnimationRowCount(const Value: Integer); procedure SetAnimationLookup(const Value: string); procedure RefreshBitmap(const WorkBitmap: TBitmap = nil); protected procedure ProcessAnimation; override; procedure AssignTo(Dest: TPersistent); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property AnimationBitmap: TBitmap read FAnimationBitmap write SetAnimationBitmap; property AnimationLookup: string read FAnimationLookup write SetAnimationLookup; property AnimationCount: Integer read FAnimationCount write FAnimationCount; property AnimationRowCount: Integer read FAnimationRowCount write SetAnimationRowCount default 1; property AnimationType default TAnimationType.In; property AutoReverse default False; property Enabled default False; property Delay; property Duration nodefault; property Interpolation default TInterpolationType.Linear; property Inverse default False; property Loop default False; property OnProcess; property OnFinish; property PropertyName; property Trigger; property TriggerInverse; end; { Key Animations } { TKey } TKey = class(TCollectionItem) private FKey: Single; procedure SetKey(const Value: Single); public procedure Assign(Source: TPersistent); override; published property Key: Single read FKey write SetKey; end; { TKeys } TKeys = class(TCollection) public function FindKeys(const Time: Single; var Key1, Key2: TKey): Boolean; end; { TColorKey } TColorKey = class(TKey) private FValue: TAlphaColor; public procedure Assign(Source: TPersistent); override; published property Value: TAlphaColor read FValue write FValue; end; { TColorKeyAnimation } TColorKeyAnimation = class(TCustomPropertyAnimation) private FKeys: TKeys; FStartFromCurrent: Boolean; procedure SetKeys(const Value: TKeys); protected procedure ProcessAnimation; override; procedure FirstFrame; override; procedure AssignTo(Dest: TPersistent); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property AnimationType default TAnimationType.In; property AutoReverse default False; property Enabled default False; property Delay; property Duration nodefault; property Interpolation default TInterpolationType.Linear; property Inverse default False; property Keys: TKeys read FKeys write SetKeys; property Loop default False; property OnProcess; property OnFinish; property PropertyName; property StartFromCurrent: Boolean read FStartFromCurrent write FStartFromCurrent; property Trigger; property TriggerInverse; end; { TFloatKey } TFloatKey = class(TKey) private FValue: Single; published property Value: Single read FValue write FValue; end; { TFloatKeyAnimation } TFloatKeyAnimation = class(TCustomPropertyAnimation) private FKeys: TKeys; FStartFromCurrent: Boolean; procedure SetKeys(const Value: TKeys); protected procedure ProcessAnimation; override; procedure FirstFrame; override; procedure AssignTo(Dest: TPersistent); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property AnimationType default TAnimationType.In; property AutoReverse default False; property Enabled default False; property Delay; property Duration nodefault; property Interpolation default TInterpolationType.Linear; property Inverse default False; property Keys: TKeys read FKeys write SetKeys; property Loop default False; property OnProcess; property OnFinish; property PropertyName; property StartFromCurrent: Boolean read FStartFromCurrent write FStartFromCurrent; property Trigger; property TriggerInverse; end; function InterpolateLinear(t, B, C, D: Single): Single; function InterpolateSine(t, B, C, D: Single; AType: TAnimationType): Single; function InterpolateQuint(t, B, C, D: Single; AType: TAnimationType): Single; function InterpolateQuart(t, B, C, D: Single; AType: TAnimationType): Single; function InterpolateQuad(t, B, C, D: Single; AType: TAnimationType): Single; function InterpolateExpo(t, B, C, D: Single; AType: TAnimationType): Single; function InterpolateElastic(t, B, C, D, A, P: Single; AType: TAnimationType): Single; function InterpolateCubic(t, B, C, D: Single; AType: TAnimationType): Single; function InterpolateCirc(t, B, C, D: Single; AType: TAnimationType): Single; function InterpolateBounce(t, B, C, D: Single; AType: TAnimationType): Single; function InterpolateBack(t, B, C, D, S: Single; AType: TAnimationType): Single; implementation uses System.Types, System.Math, System.SysUtils, System.StrUtils, System.SyncObjs, {$IFDEF MACOS}Macapi.CoreFoundation, {$ENDIF} FMX.Platform, FMX.Forms, FMX.Utils, FMX.MultiResBitmap; function InterpolateBack(t, B, C, D, S: Single; AType: TAnimationType): Single; begin case AType of TAnimationType.In: begin if S = 0 then S := 1.70158; t := t / D; Result := C * t * t * ((S + 1) * t - S) + B; end; TAnimationType.Out: begin if S = 0 then S := 1.70158; t := t / D - 1; Result := C * (t * t * ((S + 1) * t + S) + 1) + B; end; TAnimationType.InOut: begin if S = 0 then S := 1.70158; t := t / (D / 2); if t < 1 then begin S := S * 1.525; Result := C / 2 * (t * t * ((S + 1) * t - S)) + B; end else begin t := t - 2; S := S * 1.525; Result := C / 2 * (t * t * ((S + 1) * t + S) + 2) + B; end; end; else Result := 0; end; end; function InterpolateBounce(t, B, C, D: Single; AType: TAnimationType): Single; function _EaseOut(t, B, C, D: Single): Single; begin t := t / D; if t < 1 / 2.75 then begin Result := C * (7.5625 * t * t) + B; end else if t < 2 / 2.72 then begin t := t - (1.5 / 2.75); Result := C * (7.5625 * t * t + 0.75) + B; end else if t < 2.5 / 2.75 then begin t := t - (2.25 / 2.75); Result := C * (7.5625 * t * t + 0.9375) + B; end else begin t := t - (2.625 / 2.75); Result := C * (7.5625 * t * t + 0.984375) + B; end; end; function _EaseIn(t, B, C, D: Single): Single; begin Result := C - _EaseOut(D - t, 0, C, D) + B; end; begin case AType of TAnimationType.In: begin Result := _EaseIn(t, B, C, D); end; TAnimationType.Out: begin Result := _EaseOut(t, B, C, D); end; TAnimationType.InOut: begin if t < D / 2 then Result := _EaseIn(t * 2, 0, C, D) * 0.5 + B else Result := _EaseOut(t * 2 - D, 0, C, D) * 0.5 + C * 0.5 + B; end; else Result := 0; end; end; function InterpolateCirc(t, B, C, D: Single; AType: TAnimationType): Single; begin case AType of TAnimationType.In: begin t := t / D; Result := -C * (Sqrt(1 - t * t) - 1) + B; end; TAnimationType.Out: begin t := t / D - 1; Result := C * Sqrt(1 - t * t) + B; end; TAnimationType.InOut: begin t := t / (D / 2); if t < 1 then Result := -C / 2 * (Sqrt(1 - t * t) - 1) + B else begin t := t - 2; Result := C / 2 * (Sqrt(1 - t * t) + 1) + B; end; end; else Result := 0; end; end; function InterpolateCubic(t, B, C, D: Single; AType: TAnimationType): Single; begin case AType of TAnimationType.In: begin t := t / D; Result := C * t * t * t + B; end; TAnimationType.Out: begin t := t / D - 1; Result := C * (t * t * t + 1) + B; end; TAnimationType.InOut: begin t := t / (D / 2); if t < 1 then Result := C / 2 * t * t * t + B else begin t := t - 2; Result := C / 2 * (t * t * t + 2) + B; end; end; else Result := 0; end; end; function InterpolateElastic(t, B, C, D, A, P: Single; AType: TAnimationType): Single; var S: Single; begin case AType of TAnimationType.In: begin if t = 0 then begin Result := B; Exit; end; t := t / D; if t = 1 then begin Result := B + C; Exit; end; if P = 0 then P := D * 0.3; if (A = 0) or (A < Abs(C)) then begin A := C; S := P / 4; end else begin S := P / (2 * Pi) * ArcSin((C / A)); end; t := t - 1; Result := -(A * Power(2, (10 * t)) * Sin((t * D - S) * (2 * Pi) / P)) + B; end; TAnimationType.Out: begin if t = 0 then begin Result := B; Exit; end; t := t / D; if t = 1 then begin Result := B + C; Exit; end; if P = 0 then P := D * 0.3; if (A = 0) or (A < Abs(C)) then begin A := C; S := P / 4; end else begin S := P / (2 * Pi) * ArcSin((C / A)); end; Result := A * Power(2, (-10 * t)) * Sin((t * D - S) * (2 * Pi) / P) + C + B; end; TAnimationType.InOut: begin if t = 0 then begin Result := B; Exit; end; t := t / (D / 2); if t = 2 then begin Result := B + C; Exit; end; if P = 0 then P := D * (0.3 * 1.5); if (A = 0) or (A < Abs(C)) then begin A := C; S := P / 4; end else begin S := P / (2 * Pi) * ArcSin((C / A)); end; if t < 1 then begin t := t - 1; Result := -0.5 * (A * Power(2, (10 * t)) * Sin((t * D - S) * (2 * Pi) / P)) + B; end else begin t := t - 1; Result := A * Power(2, (-10 * t)) * Sin((t * D - S) * (2 * Pi) / P) * 0.5 + C + B; end; end; else Result := 0; end; end; function InterpolateExpo(t, B, C, D: Single; AType: TAnimationType): Single; begin case AType of TAnimationType.In: begin If t = 0 Then Result := B else Result := C * Power(2, (10 * (t / D - 1))) + B; end; TAnimationType.Out: begin If t = D then Result := B + C else Result := C * (-Power(2, (-10 * t / D)) + 1) + B; end; TAnimationType.InOut: begin if t = 0 then begin Result := B; Exit; end; if t = D then begin Result := B + C; Exit; end; t := t / (D / 2); if t < 1 then Result := C / 2 * Power(2, (10 * (t - 1))) + B else begin t := t - 1; Result := C / 2 * (-Power(2, (-10 * t)) + 2) + B; end; end; else Result := 0; end; end; function InterpolateLinear(t, B, C, D: Single): Single; begin Result := C * t / D + B; end; function InterpolateQuad(t, B, C, D: Single; AType: TAnimationType): Single; begin case AType of TAnimationType.In: begin t := t / D; Result := C * t * t + B; end; TAnimationType.Out: begin t := t / D; Result := -C * t * (t - 2) + B; end; TAnimationType.InOut: begin t := t / (D / 2); if t < 1 then Result := C / 2 * t * t + B else begin t := t - 1; Result := -C / 2 * (t * (t - 2) - 1) + B; end; end; else Result := 0; end; end; function InterpolateQuart(t, B, C, D: Single; AType: TAnimationType): Single; begin case AType of TAnimationType.In: begin t := t / D; Result := C * t * t * t * t + B; end; TAnimationType.Out: begin t := t / D - 1; Result := -C * (t * t * t * t - 1) + B; end; TAnimationType.InOut: begin t := t / (D / 2); if t < 1 then Result := C / 2 * t * t * t * t + B else begin t := t - 2; Result := -C / 2 * (t * t * t * t - 2) + B; end; end; else Result := 0; end; end; function InterpolateQuint(t, B, C, D: Single; AType: TAnimationType): Single; begin case AType of TAnimationType.In: begin t := t / D; Result := C * t * t * t * t * t + B; end; TAnimationType.Out: begin t := t / D - 1; Result := C * (t * t * t * t * t + 1) + B; end; TAnimationType.InOut: begin t := t / (D / 2); if t < 1 then Result := C / 2 * t * t * t * t * t + B else begin t := t - 2; Result := C / 2 * (t * t * t * t * t + 2) + B; end; end; else Result := 0; end; end; function InterpolateSine(t, B, C, D: Single; AType: TAnimationType): Single; begin case AType of TAnimationType.In: begin Result := -C * Cos(t / D * (Pi / 2)) + C + B; end; TAnimationType.Out: begin Result := C * Sin(t / D * (Pi / 2)) + B; end; TAnimationType.InOut: begin Result := -C / 2 * (Cos(Pi * t / D) - 1) + B; end; else Result := 0; end; end; { TAnimator.TAnimationDestroyer } procedure TAnimator.TAnimationDestroyer.DoAniFinished(Sender: TObject); begin TThread.ForceQueue(nil, procedure begin TAnimation(Sender).DisposeOf; end); end; { TAnimator } class procedure TAnimator.StartAnimation(const Target: TFmxObject; const AName: string); var I: Integer; E: TAnimation; begin I := 0; while (Target.Children <> nil) and (I < Target.Children.Count) do begin if Target.Children[I] is TAnimation then if CompareText(TAnimation(Target.Children[I]).Name, AName) = 0 then begin E := TAnimation(Target.Children[I]); E.Start; end; Inc(I); end; end; class procedure TAnimator.StopAnimation(const Target: TFmxObject; const AName: string); var I: Integer; E: TAnimation; begin if Target.Children <> nil then for I := Target.Children.Count - 1 downto 0 do if TFmxObject(Target.Children[I]) is TAnimation then if CompareText(TAnimation(Target.Children[I]).Name, AName) = 0 then begin E := TAnimation(Target.Children[I]); E.Stop; end; end; class procedure TAnimator.StartTriggerAnimation(const Target: TFmxObject; const AInstance: TFmxObject; const ATrigger: string); var Animatable: ITriggerAnimation; begin StopTriggerAnimation(Target, AInstance, ATrigger); if Supports(Target, ITriggerAnimation, Animatable) then Animatable.StartTriggerAnimation(AInstance, ATrigger) else DefaultStartTriggerAnimation(Target, AInstance, ATrigger); end; class procedure TAnimator.DefaultStartTriggerAnimation(const Target: TFmxObject; const AInstance: TFmxObject; const ATrigger: string); var I: Integer; Control: IControl; begin if (Target <> nil) and (Target.Children <> nil) then for I := 0 to Target.Children.Count - 1 do begin if Target.Children[I] is TAnimation then TAnimation(Target.Children[I]).StartTrigger(AInstance, ATrigger); if Supports(Target.Children[I], IControl, Control) and Control.Locked and not Control.HitTest then StartTriggerAnimation(Target.Children[I], AInstance, ATrigger); end; end; class procedure TAnimator.StartTriggerAnimationWait(const Target: TFmxObject; const AInstance: TFmxObject; const ATrigger: string); var Animatable: ITriggerAnimation; begin StopTriggerAnimation(Target, AInstance, ATrigger); if Supports(Target, ITriggerAnimation, Animatable) then Animatable.StartTriggerAnimationWait(AInstance, ATrigger) else DefaultStartTriggerAnimationWait(Target, AInstance, ATrigger); end; class procedure TAnimator.DefaultStartTriggerAnimationWait(const Target, AInstance: TFmxObject; const ATrigger: string); var I: Integer; Control: IControl; begin if Target.Children <> nil then for I := 0 to Target.Children.Count - 1 do begin if Target.Children[I] is TAnimation then begin TAnimation(Target.Children[I]).StartTrigger(AInstance, ATrigger); while TAnimation(Target.Children[I]).Running do begin Application.ProcessMessages; Sleep(0); end; end; if Supports(Target.Children[I], IControl, Control) and Control.Locked and not Control.HitTest then StartTriggerAnimationWait(Target.Children[I], AInstance, ATrigger); end; end; class procedure TAnimator.StopTriggerAnimation(const Target: TFmxObject; const AInstance: TFmxObject; const ATrigger: string); var Item: TFmxObject; Control: IControl; begin if Target.Children <> nil then for Item in Target.Children do begin if TFmxObject(Item) is TAnimation then TAnimation(Item).StopTrigger(AInstance, ATrigger); if Supports(Item, IControl, Control) and Control.Locked and not Control.HitTest then StopTriggerAnimation(Item, AInstance, ATrigger); end; end; { Property animation } class procedure TAnimator.AnimateColor(const Target: TFmxObject; const APropertyName: string; NewValue: TAlphaColor; Duration: Single = 0.2; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); var Animation: TColorAnimation; begin StopPropertyAnimation(Target, APropertyName); CreateDestroyer; Animation := TColorAnimation.Create(Target); Animation.Parent := Target; Animation.AnimationType := AType; Animation.Interpolation := AInterpolation; Animation.OnFinish := FDestroyer.DoAniFinished; Animation.Duration := Duration; Animation.PropertyName := APropertyName; Animation.StartFromCurrent := True; Animation.StopValue := NewValue; Animation.Start; end; class procedure TAnimator.AnimateFloat(const Target: TFmxObject; const APropertyName: string; const NewValue: Single; Duration: Single = 0.2; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); var Animation: TFloatAnimation; begin StopPropertyAnimation(Target, APropertyName); CreateDestroyer; Animation := TFloatAnimation.Create(nil); Animation.Parent := Target; Animation.AnimationType := AType; Animation.Interpolation := AInterpolation; Animation.OnFinish := FDestroyer.DoAniFinished; Animation.Duration := Duration; Animation.PropertyName := APropertyName; Animation.StartFromCurrent := True; Animation.StopValue := NewValue; Animation.Start; end; class procedure TAnimator.AnimateFloatDelay(const Target: TFmxObject; const APropertyName: string; const NewValue: Single; Duration: Single = 0.2; Delay: Single = 0.0; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); var Animation: TFloatAnimation; begin CreateDestroyer; Animation := TFloatAnimation.Create(nil); Animation.Parent := Target; Animation.AnimationType := AType; Animation.Interpolation := AInterpolation; Animation.Delay := Delay; Animation.Duration := Duration; Animation.PropertyName := APropertyName; Animation.StartFromCurrent := True; Animation.OnFinish := FDestroyer.DoAniFinished; Animation.StopValue := NewValue; Animation.Start; end; class procedure TAnimator.AnimateFloatWait(const Target: TFmxObject; const APropertyName: string; const NewValue: Single; Duration: Single = 0.2; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); var Animation: TFloatAnimation; begin StopPropertyAnimation(Target, APropertyName); Animation := TFloatAnimation.Create(nil); try Animation.Parent := Target; Animation.AnimationType := AType; Animation.Interpolation := AInterpolation; Animation.Duration := Duration; Animation.PropertyName := APropertyName; Animation.StartFromCurrent := True; Animation.StopValue := NewValue; Animation.Start; while Animation.FRunning do begin Application.ProcessMessages; Sleep(0); end; finally Animation.DisposeOf; end; end; class procedure TAnimator.AnimateInt(const Target: TFmxObject; const APropertyName: string; const NewValue: Integer; Duration: Single = 0.2; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); var Animation: TIntAnimation; begin CreateDestroyer; StopPropertyAnimation(Target, APropertyName); Animation := TIntAnimation.Create(nil); Animation.Parent := Target; Animation.AnimationType := AType; Animation.Interpolation := AInterpolation; Animation.OnFinish := FDestroyer.DoAniFinished; Animation.Duration := Duration; Animation.PropertyName := APropertyName; Animation.StartFromCurrent := True; Animation.StopValue := NewValue; Animation.Start; end; class procedure TAnimator.AnimateIntWait(const Target: TFmxObject; const APropertyName: string; const NewValue: Integer; Duration: Single = 0.2; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); var Animation: TIntAnimation; begin StopPropertyAnimation(Target, APropertyName); Animation := TIntAnimation.Create(nil); try Animation.Parent := Target; Animation.AnimationType := AType; Animation.Interpolation := AInterpolation; Animation.Duration := Duration; Animation.PropertyName := APropertyName; Animation.StartFromCurrent := True; Animation.StopValue := NewValue; Animation.Start; while Animation.FRunning do begin Application.ProcessMessages; Sleep(0); end; finally Animation.DisposeOf; end; end; class procedure TAnimator.StopPropertyAnimation(const Target: TFmxObject; const APropertyName: string); var I: Integer; begin I := Target.ChildrenCount - 1; while I >= 0 do begin if (Target.Children[I] is TCustomPropertyAnimation) and (CompareText(TCustomPropertyAnimation(Target.Children[I]).PropertyName, APropertyName) = 0) then TFloatAnimation(Target.Children[I]).Stop; if I > Target.ChildrenCount then I := Target.ChildrenCount; Dec(I); end; end; class procedure TAnimator.CreateDestroyer; begin if FDestroyer = nil then FDestroyer := TAnimationDestroyer.Create; end; class procedure TAnimator.Uninitialize; begin FreeAndNil(FDestroyer); end; { TAniThread } type TTimerThread = class(TThread) private FTimerEvent: TNotifyEvent; FInterval: Cardinal; FEnabled: Boolean; FEnabledEvent: TEvent; procedure SetEnabled(const Value: Boolean); procedure SetInterval(const Value: Cardinal); protected procedure Execute; override; procedure DoInterval; public constructor Create; destructor Destroy; override; property Interval: Cardinal read FInterval write SetInterval; property Enabled: Boolean read FEnabled write SetEnabled; property OnTimer: TNotifyEvent read FTimerEvent write FTimerEvent; end; TThreadTimer = class(TTimer) private FThread: TTimerThread; protected procedure SetOnTimer(Value: TNotifyEvent); override; procedure SetEnabled(Value: Boolean); override; procedure SetInterval(Value: Cardinal); override; procedure UpdateTimer; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; TAniThread = class({$IFDEF ANDROID}TThreadTimer{$ELSE}TTimer{$ENDIF}) private FAniList: TList<TAnimation>; FTime, FDeltaTime: Double; FTimerService: IFMXTimerService; procedure OneStep; procedure DoSyncTimer(Sender: TObject); public constructor Create; reintroduce; destructor Destroy; override; procedure AddAnimation(const Ani: TAnimation); procedure RemoveAnimation(const Ani: TAnimation); end; constructor TAniThread.Create; begin inherited Create(nil); if not TPlatformServices.Current.SupportsPlatformService(IFMXTimerService, FTimerService) then raise EUnsupportedPlatformService.Create('IFMXTimerService'); TAnimation.AniFrameRate := EnsureRange(TAnimation.AniFrameRate, 5, 100); Interval := Trunc(1000 / TAnimation.AniFrameRate / 10) * 10; if (Interval <= 0) then Interval := 1; OnTimer := DoSyncTimer; FAniList := TList<TAnimation>.Create; FTime := FTimerService.GetTick; Enabled := False; end; destructor TAniThread.Destroy; begin FreeAndNil(FAniList); FTimerService := nil; inherited; end; procedure TAniThread.AddAnimation(const Ani: TAnimation); begin if FAniList.IndexOf(Ani) < 0 then FAniList.Add(Ani); if not Enabled and (FAniList.Count > 0) then FTime := FTimerService.GetTick; Enabled := FAniList.Count > 0; end; procedure TAniThread.RemoveAnimation(const Ani: TAnimation); begin FAniList.Remove(Ani); Enabled := FAniList.Count > 0; end; procedure TAniThread.DoSyncTimer(Sender: TObject); begin OneStep; if TAnimation.AniFrameRate < 5 then TAnimation.AniFrameRate := 5; Interval := Trunc(1000 / TAnimation.AniFrameRate / 10) * 10; if (Interval <= 0) then Interval := 1; end; procedure TAniThread.OneStep; var I: Integer; NewTime: Double; [unsafe] Ani: TAnimation; begin NewTime := FTimerService.GetTick; FDeltaTime := NewTime - FTime; FTime := NewTime; if FDeltaTime <= 0 then Exit; if FAniList.Count > 0 then begin I := FAniList.Count - 1; while I >= 0 do begin Ani := FAniList[I]; if Ani.FRunning then begin if (Ani.StyleName <> '') and (CompareText(Ani.StyleName, 'caret') = 0) then begin Ani.Tag := Ani.Tag + 1; if Ani.Tag mod 12 = 0 then Ani.ProcessTick(FTime, FDeltaTime); end else Ani.ProcessTick(FTime, FDeltaTime); end; Dec(I); if I >= FAniList.Count then I := FAniList.Count - 1; end; end; end; { TAnimation } procedure TAnimation.ParentChanged; begin inherited; ParseTriggers(nil, False, False); end; procedure TAnimation.AssignTo(Dest: TPersistent); var DestAnimation: TAnimation; begin if Dest is TAnimation then begin DestAnimation := TAnimation(Dest); DestAnimation.AnimationType := AnimationType; DestAnimation.AutoReverse := AutoReverse; DestAnimation.Duration := Duration; DestAnimation.Delay := Delay; DestAnimation.Interpolation := Interpolation; DestAnimation.Inverse := Inverse; DestAnimation.Loop := Loop; DestAnimation.Trigger := Trigger; DestAnimation.TriggerInverse := TriggerInverse; DestAnimation.Enabled := Enabled; DestAnimation.overshoot := overshoot; // https://quality.embarcadero.com/browse/RSP-16991 end else inherited; end; constructor TAnimation.Create(AOwner: TComponent); begin inherited; FEnabled := False; Duration := 0.2; fOvershoot := 0.0; // https://quality.embarcadero.com/browse/RSP-16991 end; destructor TAnimation.Destroy; begin if AniThread <> nil then TAniThread(AniThread).FAniList.Remove(Self); FreeAndNil(FTriggerList); FreeAndNil(FInverseTriggerList); inherited; end; procedure TAnimation.FirstFrame; begin end; procedure TAnimation.Loaded; begin inherited; if not (csDesigning in ComponentState) and Enabled then Start; end; function TAnimation.OvershootStored: Boolean; begin result := FOverShoot <> 0; // https://quality.embarcadero.com/browse/RSP-16991 end; procedure TAnimation.SetEnabled(const Value: Boolean); begin if FEnabled <> Value then begin FEnabled := Value; if not(csDesigning in ComponentState) and not(csLoading in ComponentState) and not(csReading in ComponentState) then begin if FEnabled then Start else Stop; end; end; end; procedure TAnimation.SetTrigger(const Value: TTrigger); begin FTrigger := Value; ParseTriggers(nil, False, False); end; procedure TAnimation.SetTriggerInverse(const Value: TTrigger); begin FTriggerInverse := Value; ParseTriggers(nil, False, False); end; function TAnimation.GetNormalizedTime: Single; begin Result := 0; if (FDuration > 0) and (FDelayTime <= 0) then begin case FInterpolation of TInterpolationType.Linear: Result := InterpolateLinear(FTime, 0, 1, FDuration); TInterpolationType.Quadratic: Result := InterpolateQuad(FTime, 0, 1, FDuration, FAnimationType); TInterpolationType.Cubic: Result := InterpolateCubic(FTime, 0, 1, FDuration, FAnimationType); TInterpolationType.Quartic: Result := InterpolateQuart(FTime, 0, 1, FDuration, FAnimationType); TInterpolationType.Quintic: Result := InterpolateQuint(FTime, 0, 1, FDuration, FAnimationType); TInterpolationType.Sinusoidal: Result := InterpolateSine(FTime, 0, 1, FDuration, FAnimationType); TInterpolationType.Exponential: Result := InterpolateExpo(FTime, 0, 1, FDuration, FAnimationType); TInterpolationType.Circular: Result := InterpolateCirc(FTime, 0, 1, FDuration, FAnimationType); TInterpolationType.Elastic: Result := InterpolateElastic(FTime, 0, 1, FDuration, 0, 0, FAnimationType); TInterpolationType.Back: Result := InterpolateBack(FTime, 0, 1, FDuration, fOvershoot, FAnimationType); // https://quality.embarcadero.com/browse/RSP-16991 TInterpolationType.Bounce: Result := InterpolateBounce(FTime, 0, 1, FDuration, FAnimationType); end; end; end; procedure TAnimation.DoProcess; begin if Assigned(FOnProcess) then FOnProcess(Self); end; procedure TAnimation.DoFinish; begin if Assigned(FOnFinish) then FOnFinish(Self); end; procedure TAnimation.ProcessTick(time, deltaTime: Single); var Control: IControl; begin inherited; if [csDesigning, csDestroying] * ComponentState <> [] then Exit; if Supports(Parent, IControl, Control) and (not Control.Visible) then Stop; if (not FRunning) or FPause then Exit; if (FDelay > 0) and (FDelayTime <> 0) then begin if FDelayTime > 0 then begin FDelayTime := FDelayTime - deltaTime; if FDelayTime <= 0 then begin FDelayTime := 0; if FInverse then FTime := FDuration else FTime := 0; FirstFrame; ProcessAnimation; DoProcess; end; end; Exit; end; if FInverse then FTime := FTime - deltaTime else FTime := FTime + deltaTime; if FTime >= FDuration then begin FTime := FDuration; if FLoop then begin if FAutoReverse then begin FInverse := True; FTime := FDuration; end else FTime := 0; end else if FAutoReverse and (FTickCount = 0) then begin Inc(FTickCount); FInverse := True; FTime := FDuration; end else FRunning := False; end else if FTime <= 0 then begin FTime := 0; if FLoop then begin if FAutoReverse then begin FInverse := False; FTime := 0; end else FTime := FDuration; end else if FAutoReverse and (FTickCount = 0) then begin Inc(FTickCount); FInverse := False; FTime := 0; end else FRunning := False; end; ProcessAnimation; DoProcess; if not FRunning then begin if AutoReverse then FInverse := FSavedInverse; if AniThread <> nil then TAniThread(AniThread).RemoveAnimation(Self); DoFinish; end; end; procedure TAnimation.Start; var Control: IControl; SaveDuration: Single; begin if not FLoop then FTickCount := 0; if Supports(Parent, IControl, Control) and (not Control.Visible) then Exit; if AutoReverse then begin if Running then FInverse := FSavedInverse else FSavedInverse := FInverse; end; if (Abs(FDuration) < 0.001) or (Root = nil) or (csDesigning in ComponentState) then begin { immediate animation } SaveDuration := FDuration; try FDelayTime := 0; FDuration := 1; if FInverse then FTime := 0 else FTime := FDuration; FRunning := True; ProcessAnimation; DoProcess; FRunning := False; FTime := 0; DoFinish; finally FDuration := SaveDuration; end; end else begin FDelayTime := FDelay; FRunning := True; if FInverse then FTime := FDuration else FTime := 0; if FDelay = 0 then begin FirstFrame; ProcessAnimation; DoProcess; end; if AniThread = nil then FAniThread := TAniThread.Create; TAniThread(AniThread).AddAnimation(Self); if not AniThread.Enabled then Stop else FEnabled := True; end; end; procedure TAnimation.Stop; begin if not FRunning then Exit; if AniThread <> nil then TAniThread(AniThread).RemoveAnimation(Self); if AutoReverse then FInverse := FSavedInverse; if FInverse then FTime := 0 else FTime := FDuration; ProcessAnimation; DoProcess; FRunning := False; DoFinish; end; procedure TAnimation.StopAtCurrent; begin if not FRunning then Exit; if AniThread <> nil then TAniThread(AniThread).RemoveAnimation(Self); if AutoReverse then FInverse := FSavedInverse; if FInverse then FTime := 0 else FTime := FDuration; FRunning := False; FEnabled := False; DoFinish; end; procedure TAnimation.ParseTriggers(const AInstance: TFmxObject; Normal, Inverse: Boolean); var T: TRttiType; P: TRttiProperty; Line, Setter, Prop, Value: string; Trigger: TTriggerRec; begin if AInstance = nil then begin if FTriggerList <> nil then FreeAndNil(FTriggerList); if FInverseTriggerList <> nil then FreeAndNil(FInverseTriggerList); FTargetClass := nil; Exit; end; if ((Inverse and (FInverseTriggerList <> nil)) or not Inverse) and ((Normal and (FTriggerList <> nil)) or not Normal) then Exit; T := SharedContext.GetType(AInstance.ClassInfo); if T = nil then Exit; while Inverse do begin if FInverseTriggerList <> nil then Break else FInverseTriggerList := TList<TTriggerRec>.Create; Line := FTriggerInverse; Setter := GetToken(Line, ';'); while Setter <> '' do begin Prop := GetToken(Setter, '='); Value := Setter; P := T.GetProperty(Prop); if (P <> nil) and (P.PropertyType.TypeKind = tkEnumeration) then begin Trigger.Name := Prop; Trigger.Prop := P; Trigger.Value := StrToBoolDef(Value, True); FInverseTriggerList.Add(Trigger); end else begin FreeAndNil(FInverseTriggerList); Break; end; Setter := GetToken(Line, ';'); end; Break; end; while Normal do begin if FTriggerList <> nil then Break else FTriggerList := TList<TTriggerRec>.Create; Line := FTrigger; Setter := GetToken(Line, ';'); while Setter <> '' do begin Prop := GetToken(Setter, '='); Value := Setter; P := T.GetProperty(Prop); if (P <> nil) and (P.PropertyType.TypeKind = tkEnumeration) then begin Trigger.Name := Prop; Trigger.Prop := P; Trigger.Value := StrToBoolDef(Value, True); FTriggerList.Add(Trigger); end else begin FreeAndNil(FTriggerList); Break; end; Setter := GetToken(Line, ';'); end; Break; end; if (FInverseTriggerList <> nil) or (FTriggerList <> nil) then FTargetClass := AInstance.ClassType; end; procedure TAnimation.StartTrigger(const AInstance: TFmxObject; const ATrigger: string); var V: TValue; StartValue: Boolean; ContainsInTrigger, ContainsInTriggerInverse: Boolean; I: Integer; Trigger: TTriggerRec; begin if AInstance = nil then Exit; ContainsInTrigger := ContainsText(FTrigger, ATrigger); ContainsInTriggerInverse := ContainsText(FTriggerInverse, ATrigger); ParseTriggers(AInstance, ContainsInTrigger, ContainsInTriggerInverse); if not AInstance.InheritsFrom(FTargetClass) then Exit; if ContainsInTrigger or ContainsInTriggerInverse then begin if (FInverseTriggerList <> nil) and (FInverseTriggerList.Count > 0) and ContainsInTriggerInverse then begin StartValue := False; for I := 0 to FInverseTriggerList.Count - 1 do begin Trigger := FInverseTriggerList[I]; V := Trigger.Prop.GetValue(AInstance); StartValue := V.AsBoolean = Trigger.Value; if not StartValue then Break; end; if StartValue then begin Inverse := True; Start; Exit; end; end; if (FTriggerList <> nil) and (FTriggerList.Count > 0) and ContainsInTrigger then begin StartValue := False; for I := 0 to FTriggerList.Count - 1 do begin Trigger := FTriggerList[I]; V := Trigger.Prop.GetValue(AInstance); StartValue := V.AsBoolean = Trigger.Value; if not StartValue then Break; end; if StartValue then begin if FTriggerInverse <> '' then Inverse := False; Start; end; end; end; end; procedure TAnimation.StopTrigger(const AInstance: TFmxObject; const ATrigger: string); begin if AInstance = nil then Exit; if (FTriggerInverse <> '') and string(FTriggerInverse).ToLower.Contains(ATrigger.ToLower) then Stop; if (FTrigger <> '') and string(FTrigger).ToLower.Contains(ATrigger.ToLower) then Stop; end; class procedure TAnimation.Uninitialize; begin FreeAndNil(FAniThread); end; { TCustomPropertyAnimation } procedure TCustomPropertyAnimation.AssignTo(Dest: TPersistent); var DestAnimation: TCustomPropertyAnimation; begin if Dest Is TCustomPropertyAnimation then begin DestAnimation := TCustomPropertyAnimation(Dest); DestAnimation.PropertyName := PropertyName; end; inherited; end; function TCustomPropertyAnimation.FindProperty: Boolean; var Persistent: string; Comp: TFmxObject; I: Integer; T: TRttiType; P: TRttiProperty; Properties: TList<TRttiProperty>; begin Result := False; if (Parent <> nil) and (FPropertyName <> '') then begin if FInstance = nil then begin FInstance := Parent; FPath := FPropertyName; while FPath.Contains('.') do begin Persistent := GetToken(FPath, '.'); T := SharedContext.GetType(FInstance.ClassInfo); if T <> nil then begin P := T.GetProperty(Persistent); if (P <> nil) and (P.PropertyType.IsInstance) then FInstance := P.GetValue(FInstance).AsObject else if Parent <> nil then begin for I := 0 to Parent.ChildrenCount - 1 do if CompareText(Parent.Children[I].Name, Persistent) = 0 then begin Comp := Parent.Children[I]; T := SharedContext.GetType(Comp.ClassInfo); if T <> nil then begin P := T.GetProperty(FPath); if P <> nil then begin FInstance := Comp; Break; end; end; end; end; end; end; if FInstance <> nil then begin if not ClonePropertiesCache.TryGetValue(FInstance.ClassName, Properties) then begin Properties := TList<TRttiProperty>.Create; ClonePropertiesCache.Add(FInstance.ClassName, Properties); end; for P in Properties do if P.Name = FPath then begin FRttiProperty := P; Break; end; if FRttiProperty = nil then begin T := SharedContext.GetType(FInstance.ClassInfo); FRttiProperty := T.GetProperty(FPath); if FRttiProperty <> nil then Properties.Add(FRttiProperty); end; Result := FRttiProperty <> nil; end; end else Result := True; end; end; procedure TCustomPropertyAnimation.ParentChanged; begin inherited; FInstance := nil; end; procedure TCustomPropertyAnimation.SetPropertyName(const AValue: string); begin if not SameText(AValue, PropertyName) then FInstance := nil; FPropertyName := AValue; end; procedure TCustomPropertyAnimation.Start; begin if FindProperty then inherited; end; procedure TCustomPropertyAnimation.Stop; begin inherited; FInstance := nil; end; { TFloatAnimation } procedure TFloatAnimation.AssignTo(Dest: TPersistent); var DestAnimation: TFloatAnimation; begin if Dest is TFloatAnimation then begin DestAnimation := TFloatAnimation(Dest); DestAnimation.StartValue := StartValue; DestAnimation.StopValue := StopValue; DestAnimation.StartFromCurrent := StartFromCurrent; end; inherited; end; constructor TFloatAnimation.Create(AOwner: TComponent); begin inherited; Duration := 0.2; FStartFloat := 0; FStopFloat := 0; end; procedure TFloatAnimation.FirstFrame; var T: TRttiType; P: TRttiProperty; begin if StartFromCurrent then begin T := SharedContext.GetType(FInstance.ClassInfo); if T <> nil then begin P := T.GetProperty(FPath); if (P <> nil) and (P.PropertyType.TypeKind = tkFloat) then StartValue := P.GetValue(FInstance).AsExtended; end; end; end; procedure TFloatAnimation.ProcessAnimation; var T: TRttiType; P: TRttiProperty; begin if FInstance <> nil then begin T := SharedContext.GetType(FInstance.ClassInfo); if T <> nil then begin P := T.GetProperty(FPath); if (P <> nil) and (P.PropertyType.TypeKind = tkFloat) then P.SetValue(FInstance, InterpolateSingle(FStartFloat, FStopFloat, NormalizedTime)); end; end; end; { TIntAnimation } procedure TIntAnimation.AssignTo(Dest: TPersistent); var DestAnimation: TIntAnimation; begin if Dest is TIntAnimation then begin DestAnimation := TIntAnimation(Dest); DestAnimation.StartValue := StartValue; DestAnimation.StopValue := StopValue; DestAnimation.StartFromCurrent := StartFromCurrent; end; inherited; end; constructor TIntAnimation.Create(AOwner: TComponent); begin inherited; Duration := 0.2; FStartValue := 0; FStopValue := 0; end; procedure TIntAnimation.FirstFrame; var T: TRttiType; P: TRttiProperty; begin if StartFromCurrent then begin T := SharedContext.GetType(FInstance.ClassInfo); if T <> nil then begin P := T.GetProperty(FPath); if (P <> nil) and (P.PropertyType.TypeKind in [tkInteger, tkFloat]) then StartValue := Round(P.GetValue(FInstance).AsExtended); end; end; end; procedure TIntAnimation.ProcessAnimation; var T: TRttiType; P: TRttiProperty; begin if FInstance <> nil then begin T := SharedContext.GetType(FInstance.ClassInfo); if T <> nil then begin P := T.GetProperty(FPath); if (P <> nil) and (P.PropertyType.TypeKind in [tkInteger, tkFloat]) then P.SetValue(FInstance, Round(InterpolateSingle(FStartValue, FStopValue, NormalizedTime))); end; end; end; { TColorAnimation } procedure TColorAnimation.AssignTo(Dest: TPersistent); var DestAnimation: TColorAnimation; begin if Dest is TColorAnimation then begin DestAnimation := TColorAnimation(Dest); DestAnimation.StartValue := StartValue; DestAnimation.StopValue := StopValue; DestAnimation.StartFromCurrent := StartFromCurrent; end; inherited; end; constructor TColorAnimation.Create(AOwner: TComponent); begin inherited; Duration := 0.2; FStartColor := $FFFFFFFF; FStopColor := $FFFFFFFF; end; procedure TColorAnimation.FirstFrame; var T: TRttiType; P: TRttiProperty; begin if StartFromCurrent then begin T := SharedContext.GetType(FInstance.ClassInfo); if T <> nil then begin P := T.GetProperty(FPath); if (P <> nil) and (P.PropertyType.IsOrdinal) then StartValue := TAlphaColor(P.GetValue(FInstance).AsOrdinal); end; end; end; procedure TColorAnimation.ProcessAnimation; var T: TRttiType; P: TRttiProperty; begin if FInstance <> nil then begin T := SharedContext.GetType(FInstance.ClassInfo); if T <> nil then begin P := T.GetProperty(FPath); if (P <> nil) and (P.PropertyType.IsOrdinal) then P.SetValue(FInstance, InterpolateColor(FStartColor, FStopColor, NormalizedTime)); end; end; end; { TGradientAnimation } procedure TGradientAnimation.AssignTo(Dest: TPersistent); var DestAnimation: TGradientAnimation; begin if Dest is TGradientAnimation then begin DestAnimation := TGradientAnimation(Dest); DestAnimation.StartValue := StartValue; DestAnimation.StopValue := StopValue; DestAnimation.StartFromCurrent := StartFromCurrent; end; inherited; end; constructor TGradientAnimation.Create(AOwner: TComponent); begin inherited; Duration := 0.2; FStartGradient := TGradient.Create; FStopGradient := TGradient.Create; end; destructor TGradientAnimation.Destroy; begin FreeAndNil(FStartGradient); FreeAndNil(FStopGradient); inherited; end; procedure TGradientAnimation.FirstFrame; var T: TRttiType; P: TRttiProperty; begin if StartFromCurrent then begin T := SharedContext.GetType(FInstance.ClassInfo); if T <> nil then begin P := T.GetProperty(FPath); if (P <> nil) and (P.PropertyType.IsInstance) then StartValue := TGradient(P.GetValue(FInstance).AsObject); end; end; end; procedure TGradientAnimation.ProcessAnimation; var T: TRttiType; P: TRttiProperty; I: Integer; TargetGradientTmp: TGradient; begin if FInstance <> nil then begin T := SharedContext.GetType(FInstance.ClassInfo); if T <> nil then begin P := T.GetProperty(FPath); if (P <> nil) and P.PropertyType.IsInstance then begin TargetGradientTmp := TGradient(P.GetValue(FInstance).AsObject); for I := 0 to TargetGradientTmp.Points.Count - 1 do begin if (I < FStopGradient.Points.Count) and (I < FStartGradient.Points.Count) then TargetGradientTmp.Points[I].Color := FMX.Utils.InterpolateColor(FStartGradient.Points[I].Color, FStopGradient.Points[I].Color, NormalizedTime); end; TargetGradientTmp.Change; end; end; end; end; procedure TGradientAnimation.SetStartGradient(const Value: TGradient); begin FStartGradient.Assign(Value); end; procedure TGradientAnimation.SetStopGradient(const Value: TGradient); begin FStopGradient.Assign(Value); end; { TRectAnimation } procedure TRectAnimation.AssignTo(Dest: TPersistent); var DestAnimation: TRectAnimation; begin if Dest is TRectAnimation then begin DestAnimation := TRectAnimation(Dest); DestAnimation.StartValue := StartValue; DestAnimation.StopValue := StopValue; DestAnimation.StartFromCurrent := StartFromCurrent; end; inherited; end; constructor TRectAnimation.Create(AOwner: TComponent); begin inherited; Duration := 0.2; FStartRect := TBounds.Create(TRectF.Empty); FStopRect := TBounds.Create(TRectF.Empty); FCurrent := TBounds.Create(TRectF.Empty); end; destructor TRectAnimation.Destroy; begin FreeAndNil(FCurrent); FreeAndNil(FStartRect); FreeAndNil(FStopRect); inherited; end; procedure TRectAnimation.FirstFrame; begin if StartFromCurrent then begin if (FRttiProperty <> nil) and FRttiProperty.PropertyType.IsInstance then TBounds(FRttiProperty.GetValue(FInstance).AsObject).Assign(FCurrent); end; end; procedure TRectAnimation.ProcessAnimation; begin if FInstance <> nil then begin { calc value } FCurrent.Left := InterpolateSingle(FStartRect.Left, FStopRect.Left, NormalizedTime); FCurrent.Top := InterpolateSingle(FStartRect.Top, FStopRect.Top, NormalizedTime); FCurrent.Right := InterpolateSingle(FStartRect.Right, FStopRect.Right, NormalizedTime); FCurrent.Bottom := InterpolateSingle(FStartRect.Bottom, FStopRect.Bottom, NormalizedTime); if (FRttiProperty <> nil) and FRttiProperty.PropertyType.IsInstance then TBounds(FRttiProperty.GetValue(FInstance).AsObject).Assign(FCurrent); end; end; procedure TRectAnimation.SetStartRect(const Value: TBounds); begin FStartRect.Assign(Value); end; procedure TRectAnimation.SetStopRect(const Value: TBounds); begin FStopRect.Assign(Value); end; { TBitmapAnimation } procedure TBitmapAnimation.AssignTo(Dest: TPersistent); var DestAnimation: TBitmapAnimation; begin if Dest is TBitmapAnimation then begin DestAnimation := TBitmapAnimation(Dest); DestAnimation.StartValue := StartValue; DestAnimation.StopValue := StopValue; end; inherited; end; constructor TBitmapAnimation.Create(AOwner: TComponent); begin inherited; Duration := 0.2; FStartBitmap := TBitmap.Create; FStopBitmap := TBitmap.Create; end; destructor TBitmapAnimation.Destroy; begin FreeAndNil(FStartBitmap); FreeAndNil(FStopBitmap); inherited; end; procedure TBitmapAnimation.ProcessAnimation; var T: TRttiType; P: TRttiProperty; Value: TPersistent; Bitmap: TBitmap; begin if FInstance <> nil then begin T := SharedContext.GetType(FInstance.ClassInfo); if T <> nil then begin P := T.GetProperty(FPath); if (P <> nil) and (P.PropertyType.IsInstance) then begin Value := TPersistent(P.GetValue(FInstance).AsObject); if (Value <> nil) and (Value is TBitmap) then begin Bitmap := TBitmap(Value); if Inverse then begin { assign to start } Bitmap.SetSize(FStopBitmap.Width, FStopBitmap.Height); { draw final with alpha } if Bitmap.Canvas.BeginScene then try Bitmap.Canvas.Clear(0); Bitmap.Canvas.DrawBitmap(FStopBitmap, RectF(0, 0, Bitmap.Width, Bitmap.Height), RectF(0, 0, FStopBitmap.Width / Bitmap.BitmapScale, FStopBitmap.Height / Bitmap.BitmapScale), NormalizedTime); Bitmap.Canvas.DrawBitmap(FStartBitmap, RectF(0, 0, Bitmap.Width, Bitmap.Height), RectF(0, 0, FStartBitmap.Width / Bitmap.BitmapScale, FStartBitmap.Height / Bitmap.BitmapScale), 1 - NormalizedTime); finally Bitmap.Canvas.EndScene; end; end else begin { assign to start } Bitmap.SetSize(FStartBitmap.Width, FStartBitmap.Height); { draw final with alpha } if Bitmap.Canvas.BeginScene then try Bitmap.Canvas.Clear(0); Bitmap.Canvas.DrawBitmap(FStartBitmap, RectF(0, 0, Bitmap.Width, Bitmap.Height), RectF(0, 0, FStartBitmap.Width / Bitmap.BitmapScale, FStartBitmap.Height / Bitmap.BitmapScale), 1 - NormalizedTime); Bitmap.Canvas.DrawBitmap(FStopBitmap, RectF(0, 0, Bitmap.Width, Bitmap.Height), RectF(0, 0, FStopBitmap.Width / Bitmap.BitmapScale, FStopBitmap.Height / Bitmap.BitmapScale), NormalizedTime); finally Bitmap.Canvas.EndScene; end; end; end; end; end; end; end; procedure TBitmapAnimation.SetStartBitmap(Value: TBitmap); begin FStartBitmap.Assign(Value); end; procedure TBitmapAnimation.SetStopBitmap(Value: TBitmap); begin FStopBitmap.Assign(Value); end; { TBitmapListAnimation.TAnimationBitmap } procedure TBitmapListAnimation.TAnimationBitmap.ReadStyleLookup(Reader: TReader); begin if FAnimation <> nil then FAnimation.AnimationLookup := Reader.ReadString; end; { TBitmapListAnimation } procedure TBitmapListAnimation.AssignTo(Dest: TPersistent); var DestAnimation: TBitmapListAnimation; begin if Dest is TBitmapListAnimation then begin DestAnimation := TBitmapListAnimation(Dest); DestAnimation.AnimationBitmap := AnimationBitmap; DestAnimation.AnimationLookup := AnimationLookup; DestAnimation.AnimationCount := AnimationCount; DestAnimation.AnimationRowCount := AnimationRowCount; end; inherited; end; constructor TBitmapListAnimation.Create(AOwner: TComponent); begin inherited; Duration := 0.2; FAnimationBitmap := TAnimationBitmap.Create; TAnimationBitmap(FAnimationBitmap).FAnimation := Self; FAnimationCount := 1; FAnimationRowCount := 1; FLastAnimationStep := 0; end; destructor TBitmapListAnimation.Destroy; begin FreeAndNil(FAnimationBitmap); inherited; end; procedure TBitmapListAnimation.RefreshBitmap(const WorkBitmap: TBitmap); var ResourceObject: TFmxObject; BitmapObject: IBitmapObject; MultiResObject: IMultiResBitmapObject; Item: TCustomBitmapItem; begin if not AnimationLookup.IsEmpty then begin ResourceObject := FMX.Types.FindStyleResource(AnimationLookup); if Supports(ResourceObject, IMultiResBitmapObject, MultiResObject) and (WorkBitmap <> nil) then begin Item := MultiResObject.MultiResBitmap.ItemByScale(WorkBitmap.BitmapScale, False, False); if Item <> nil then begin AnimationBitmap.Assign(Item.Bitmap); Exit; end; end; if Supports(ResourceObject, IBitmapObject, BitmapObject) then AnimationBitmap.Assign(BitmapObject.Bitmap); end; end; procedure TBitmapListAnimation.ProcessAnimation; var T: TRttiType; P: TRttiProperty; Value: TObject; TopPos, LeftPos, CurrentIndex: Integer; NowValue: Single; SourceBitmap: TBitmap; WorkBitmap: TBitmap; AnimationColCount: Integer; begin if FInstance <> nil then begin T := SharedContext.GetType(FInstance.ClassInfo); if T <> nil then begin P := T.GetProperty(FPath); if (P <> nil) and (P.PropertyType.IsInstance) then begin Value := P.GetValue(FInstance).AsObject; if Value is TBitmap then WorkBitmap := TBitmap(Value) else WorkBitmap := nil; if WorkBitmap <> nil then begin if (FAnimationBitmap.BitmapScale <> WorkBitmap.BitmapScale) and (FAnimationLookup <> '') then RefreshBitmap(WorkBitmap); FAnimationBitmap.BitmapScale := WorkBitmap.BitmapScale; end; SourceBitmap := FAnimationBitmap; if (WorkBitmap <> nil) and not (SourceBitmap.IsEmpty) then begin NowValue := InterpolateSingle(0, FAnimationCount, NormalizedTime); if FAnimationCount mod FAnimationRowCount = 0 then AnimationColCount := FAnimationCount div FAnimationRowCount else AnimationColCount := FAnimationCount div FAnimationRowCount + 1; WorkBitmap.SetSize(SourceBitmap.Width div AnimationColCount, SourceBitmap.Height div FAnimationRowCount); CurrentIndex := Trunc(NowValue); if CurrentIndex > FAnimationCount - 1 then CurrentIndex := FAnimationCount - 1; LeftPos := (CurrentIndex mod AnimationColCount) * (SourceBitmap.Width div AnimationColCount); TopPos := (CurrentIndex div AnimationColCount) * (SourceBitmap.Height div AnimationRowCount); if WorkBitmap.Canvas.BeginScene then try WorkBitmap.Canvas.Clear(0); WorkBitmap.Canvas.DrawBitmap(SourceBitmap, TRectF.Create(LeftPos, TopPos, LeftPos + WorkBitmap.Width, TopPos + WorkBitmap.Height), TRectF.Create(0, 0, WorkBitmap.Width / WorkBitmap.BitmapScale, WorkBitmap.Height / WorkBitmap.BitmapScale), 1); finally WorkBitmap.Canvas.EndScene; end; end; end; end; end; end; procedure TBitmapListAnimation.SetAnimationBitmap(Value: TBitmap); begin FAnimationBitmap.Assign(Value); end; procedure TBitmapListAnimation.SetAnimationLookup(const Value: string); begin if FAnimationLookup <> Value then begin FAnimationLookup := Value; RefreshBitmap; end; end; procedure TBitmapListAnimation.SetAnimationRowCount(const Value: Integer); begin FAnimationRowCount := Value; if FAnimationRowCount < 1 then FAnimationRowCount := 1; end; { Key Animation } { TKey } procedure TKey.Assign(Source: TPersistent); begin if Source is TKey then FKey := TKey(Source).Key else inherited; end; procedure TKey.SetKey(const Value: Single); begin FKey := Value; if FKey < 0 then FKey := 0; if FKey > 1 then FKey := 1; end; { TKeys } function TKeys.FindKeys(const Time: Single; var Key1, Key2: TKey): Boolean; var I: Integer; begin Result := False; if Count < 2 then Exit; for I := 0 to Count - 2 do if (Time >= TKey(Items[I]).Key) and (Time <= TKey(Items[I + 1]).Key) then begin Result := True; Key1 := TKey(Items[I]); Key2 := TKey(Items[I + 1]); Exit; end; end; { TColorKeyAnimation } procedure TColorKeyAnimation.AssignTo(Dest: TPersistent); var DestAnimation: TColorKeyAnimation; begin if Dest is TColorKeyAnimation then begin DestAnimation := TColorKeyAnimation(Dest); DestAnimation.Keys := Keys; DestAnimation.StartFromCurrent := StartFromCurrent; end; inherited; end; constructor TColorKeyAnimation.Create(AOwner: TComponent); begin inherited; FKeys := TKeys.Create(TColorKey); end; destructor TColorKeyAnimation.Destroy; begin FreeAndNil(FKeys); inherited; end; procedure TColorKeyAnimation.FirstFrame; var T: TRttiType; P: TRttiProperty; begin if StartFromCurrent then begin T := SharedContext.GetType(FInstance.ClassInfo); if T <> nil then begin P := T.GetProperty(FPath); if (P <> nil) and P.PropertyType.IsOrdinal and (Keys.Count > 0) then TColorKey(Keys.Items[0]).Value := P.GetValue(FInstance).AsOrdinal; end; end; end; procedure TColorKeyAnimation.ProcessAnimation; var T: TRttiType; P: TRttiProperty; Key1, Key2: TKey; begin if FInstance <> nil then begin if FKeys.FindKeys(NormalizedTime, Key1, Key2) then begin if (TFloatKey(Key2).Key - TFloatKey(Key1).Key) = 0 then Exit; T := SharedContext.GetType(FInstance.ClassInfo); if T <> nil then begin P := T.GetProperty(FPath); if (P <> nil) and P.PropertyType.IsOrdinal then P.SetValue(FInstance, InterpolateColor(TColorKey(Key1).Value, TColorKey(Key2).Value, (NormalizedTime - TFloatKey(Key1).Key) / (TFloatKey(Key2).Key - TFloatKey(Key1).Key))); end; end; end; end; procedure TColorKeyAnimation.SetKeys(const Value: TKeys); begin FKeys.Assign(Value); end; { TFloatKeyAnimation } procedure TFloatKeyAnimation.AssignTo(Dest: TPersistent); var DestAnimation: TFloatKeyAnimation; begin if Dest is TFloatKeyAnimation then begin DestAnimation := TFloatKeyAnimation(Dest); DestAnimation.Keys := Keys; DestAnimation.StartFromCurrent := StartFromCurrent; end; inherited; end; constructor TFloatKeyAnimation.Create(AOwner: TComponent); begin inherited; FKeys := TKeys.Create(TFloatKey); end; destructor TFloatKeyAnimation.Destroy; begin FreeAndNil(FKeys); inherited; end; procedure TFloatKeyAnimation.FirstFrame; var T: TRttiType; P: TRttiProperty; begin if StartFromCurrent then begin T := SharedContext.GetType(FInstance.ClassInfo); if T <> nil then begin P := T.GetProperty(FPath); if (P <> nil) and P.PropertyType.IsOrdinal and (Keys.Count > 0) then TFloatKey(Keys.Items[0]).Value := P.GetValue(FInstance).AsExtended; end; end; end; procedure TFloatKeyAnimation.ProcessAnimation; var T: TRttiType; P: TRttiProperty; Key1, Key2: TKey; begin if FInstance <> nil then begin if FKeys.FindKeys(NormalizedTime, Key1, Key2) then begin if (TFloatKey(Key2).Key - TFloatKey(Key1).Key) = 0 then Exit; T := SharedContext.GetType(FInstance.ClassInfo); if T <> nil then begin P := T.GetProperty(FPath); if (P <> nil) and (P.PropertyType.TypeKind = tkFloat) then P.SetValue(FInstance, InterpolateSingle(TFloatKey(Key1).Value, TFloatKey(Key2).Value, (NormalizedTime - TFloatKey(Key1).Key) / (TFloatKey(Key2).Key - TFloatKey(Key1).Key))) else if (P <> nil) and P.PropertyType.IsOrdinal then P.SetValue(FInstance, Round(InterpolateSingle(TFloatKey(Key1).Value, TFloatKey(Key2).Value, (NormalizedTime - TFloatKey(Key1).Key) / (TFloatKey(Key2).Key - TFloatKey(Key1).Key)))); end; end; end; end; procedure TFloatKeyAnimation.SetKeys(const Value: TKeys); begin FKeys.Assign(Value); end; { TColorKey } procedure TColorKey.Assign(Source: TPersistent); begin if Source is TColorKey then FValue := TColorKey(Source).Value else inherited; end; { TTimerThread } constructor TTimerThread.Create; begin inherited; FEnabledEvent := TEvent.Create; Interval := 1; FEnabled := False; end; destructor TTimerThread.Destroy; begin FreeAndNil(FEnabledEvent); inherited; end; procedure TTimerThread.DoInterval; begin if Assigned(FTimerEvent) then FTimerEvent(Self); end; procedure TTimerThread.Execute; begin while not Terminated do begin Sleep(Interval); TThread.Synchronize(nil, procedure begin DoInterval; end); FEnabledEvent.WaitFor; end; end; procedure TTimerThread.SetEnabled(const Value: Boolean); begin if FEnabled <> Value then begin FEnabled := Value; if FEnabled then FEnabledEvent.SetEvent else FEnabledEvent.ResetEvent; end; end; procedure TTimerThread.SetInterval(const Value: Cardinal); begin FInterval := Max(Value, 1); end; { TThreadTimer } constructor TThreadTimer.Create(AOwner: TComponent); begin inherited; FThread := TTimerThread.Create; end; destructor TThreadTimer.Destroy; begin FreeAndNil(FThread); inherited; end; procedure TThreadTimer.SetEnabled(Value: Boolean); begin inherited; FThread.Enabled := Value; end; procedure TThreadTimer.SetInterval(Value: Cardinal); begin inherited; FThread.Interval := Value; end; procedure TThreadTimer.SetOnTimer(Value: TNotifyEvent); begin inherited; FThread.OnTimer := Value; end; procedure TThreadTimer.UpdateTimer; begin // Don't invoke inherited method, because we take care under alternative timer implementation with Thread. end; initialization RegisterFmxClasses([TColorAnimation, TGradientAnimation, TFloatAnimation, TIntAnimation, TRectAnimation, TBitmapAnimation, TBitmapListAnimation, TColorKeyAnimation, TFloatKeyAnimation]); TAnimation.AniFrameRate := TAnimation.DefaultAniFrameRate; finalization TAnimator.Uninitialize; TAnimation.Uninitialize; end.
28.602151
141
0.65154
85374369c72ac561183c75b2391a7ca35066d579
9,309
pas
Pascal
src/uanimatebackgound.pas
flutomax/ChladniPlate2
5684464979da9a6990874f3a9007d8791e12843c
[ "Zlib" ]
4
2022-02-16T15:49:50.000Z
2022-02-17T07:25:57.000Z
src/uanimatebackgound.pas
flutomax/ChladniPlate2
5684464979da9a6990874f3a9007d8791e12843c
[ "Zlib" ]
null
null
null
src/uanimatebackgound.pas
flutomax/ChladniPlate2
5684464979da9a6990874f3a9007d8791e12843c
[ "Zlib" ]
null
null
null
{ This file is part of the ChladniPlate2. See LICENSE.txt for more info. Copyright (c) 2022 by Vasily Makarov } unit uAnimateBackgound; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Controls, ExtCtrls, Forms, Graphics, LCLType, FPImage, GraphType, IntfGraphics; type TMatrix = array of array of double; { TMap } TMap = class(TFPPalette) public function ColorSmooth(const Value: double): TFPColor; end; TBackgoundStage = (bgsNone, bgsFadeIn, bgsFadeOut); { TAnimateBackgound } TAnimateBackgound = class(TComponent) private fRuleStr: string; fMatrix: TMatrix; fBuffer: TBitmap; fIntf: TLazIntfImage; fMap: TMap; fValMin: double; fValMax: double; fStep: integer; fCount: integer; fVariant: integer; fAlpha: word; fStage: TBackgoundStage; fOnDraw: TNotifyEvent; function CalcRule(const x, y: double): double; procedure DoNextStep(Sender: TObject; var Done: boolean); procedure NextVariant; procedure MakeMap; procedure MakeFrame; procedure MakeMatrix; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Start; procedure Stop; published property Buffer: TBitmap read fBuffer; property OnDraw: TNotifyEvent read fOnDraw write fOnDraw; end; implementation uses Math, StrUtils; const S_RULES: array[0..29] of string = ( 'BqWLRFPw', 'eyGdLaR', 'aQpObesKc', 'BwJc', 'TMOYaVslmGN', 'GIpmfmvplp', 'jGrpN', 'KA', 'RtI', 'xXYXOFHHYQW', 'pMRtmAe', 'wnXPVnBcQ', 'XN', 'hnGOVPGewe', 'Me', 'yVLHnQYw', 'NuTGXhl', 'Bg', 'Mel', 'ebsXCqyTf', 'mNDHBB', 'fhXNggmvDxn', 'FLmJeh', 'PmfsbtF', 'uJxUeQgQSYt', 'ffQ', 'WCEmOOYUb', 'Nt', 'LbMtBX', 'QMsAH'); function FMod(const a, b: double): double; inline; begin Result := a - b * Int(a / b); end; { TMap } function TMap.ColorSmooth(const Value: double): TFPColor; var n1, n2: byte; r: double; c1, c2: TFPColor; begin r := Frac(Value); n1 := EnsureRange(Trunc(Value), 0, Count - 1); n2 := EnsureRange(n1 + 1, 0, Count - 1); c1 := Color[n1]; c2 := Color[n2]; Result.red := Round(c1.red + ((c2.red - c1.red) * r)); Result.green := Round(c1.green + ((c2.green - c1.green) * r)); Result.blue := Round(c1.blue + ((c2.blue - c1.blue) * r)); Result.alpha := alphaOpaque; end; { TAnimateBackgound } constructor TAnimateBackgound.Create(AOwner: TComponent); var c: TWinControl; begin inherited Create(AOwner); if not (AOwner is TWinControl) then raise Exception.Create('Owner must be TWinControl only!'); c := TWinControl(AOwner); fVariant := -1; fCount := 0; fStep := 0; fStage := bgsFadeIn; fAlpha := alphaTransparent; SetLength(fMatrix, c.Width, c.Height); fBuffer := TBitmap.Create; fBuffer.SetSize(c.Width, c.Height); fIntf := fBuffer.CreateIntfImage; fIntf.FillPixels(colWhite); fMap := TMap.Create(256); MakeMap; NextVariant; MakeFrame; end; destructor TAnimateBackgound.Destroy; begin fMatrix := nil; fBuffer.Free; fIntf.Free; fMap.Free; inherited Destroy; end; procedure TAnimateBackgound.Start; begin Application.OnIdle := @DoNextStep; end; procedure TAnimateBackgound.Stop; begin Application.OnIdle := nil; end; function TAnimateBackgound.CalcRule(const x, y: double): double; function CheckZero(const a: double): double; begin if IsZero(a) then Result := 1E-7 * IfThen(a < 0, -1, 1) else Result := a; end; var i: integer; begin Result := 0.0; for i := 1 to Length(fRuleStr) do begin case fRuleStr[i] of 'A': Result := Result + sin(x * x + y * y); 'B': Result := Result + sin(x * x) * cos(y * y); 'C': Result := Result + sin(x / CheckZero(y)) * cos(x / CheckZero(y)); 'D': Result := Result + cos(x / CheckZero(y)); 'E': Result := Result + sin(y / CheckZero(x)); 'F': Result := Result + abs(y) - x; 'G': Result := Result + x + abs(y); 'H': Result := Result + abs(x); 'I': Result := Result + abs(y); 'J': Result := Result + abs(x) * abs(y); 'K': Result := Result + sin(x) * cos(y); 'L': Result := Result + sin(x * y) * cos(x * y); 'M': Result := Result + sin(sqr(abs(x))) - cos(sqr(abs(y))); 'N': Result := Result + sin(x * x - y * y); 'O': Result := Result + y - abs(x); 'P': Result := Result + abs(x) + y; 'Q': Result := Result + cos(x) * sin(y) * cos(x * y); 'R': Result := Result + sin(cos(x) * abs(y) * abs(y)); 'S': Result := Result + sin(x * x * x - y * y * y); 'T': Result := Result + sin(y * y * y) + sin(x * x * x); 'U': Result := Result + cos(y * y * y + x * x * x); 'V': Result := Result + cos(y * y * y) + cos(x * x * x); 'W': Result := Result + abs(y * 3); 'X': Result := Result + abs(x * 3); 'Y': Result := Result + sin(x * x / CheckZero(y) - y * y / CheckZero(x)); 'Z': Result := Result + cos(x * x / CheckZero(y)) + sin(y * y / CheckZero(x)); 'a': Result := Result + sin(x) + sin(x) + cos(y) + cos(y); 'b': Result := Result + cos(x) + cos(x) + sin(y) + sin(y); 'c': Result := Result + sin(x) + cos(x) + sin(y) + cos(y); 'd': Result := Result * cos(y) + sin(y) + cos(x) + sin(x); 'e': Result := Result - tan(cos(sqrt(x * y * x * y))); 'f': Result := Result * y - sin(x); 'g': Result := Result * x - cos(y); 'h': Result := Result * sqrt(abs(x) + abs(y)); 'i': Result := Result * sin(x * y * x) + cos(y * x * y); 'j': Result := Result + sin(x * x); 'k': Result := Result + sqr(cos(x) + sqr(x) * sin(y) + sqr(y)); 'l': Result := Result * sin(Result) * cos(x) * sin(x * y); 'm': Result := Result * sin(Result) * cos(y) * sin(x * y); 'n': Result := Result + sin(x + y * x * y + x * x); 'o': Result := Result + sin(y + x * y * x + y * y); 'p': Result := Result + abs(x * y + x * x + y * y); 'q': Result := Result + ((x + y) * y * x * sin(x) * cos(y)); 'r': Result := Result + ((x + y * x) + sin(x * y) + cos(y / CheckZero(x))); 's': Result := Result + sin(x * y + x) + cos(y * x + y); 't': Result := Result * cos(x + y) * sin(x + y) / 2; 'u': Result := Result + cos(sqr(x + y)) * y + sqr(cos(y) * sin(x)); 'v': Result := Result + sin(sqr(y + x)) * x + sqr(sin(x) * cos(y)); 'w': Result := Result + cos(x) * sin(x) + cos(y) * sin(y); 'x': Result := Result + sqr(sin(sqr(x) / CheckZero(sqr(y)))); 'y': Result := Result + sin(abs(cos(x)) + abs(sin(y))); 'z': Result := Result + sin(abs(cos(x + y)) + abs(cos(y * x * y))); end; end; end; procedure TAnimateBackgound.DoNextStep(Sender: TObject; var Done: boolean); const AlphaStep = 8192; AlphaStep2 = 4096; AlphaHi = alphaOpaque - AlphaStep; begin case fStage of bgsFadeIn: begin Inc(fAlpha, AlphaStep); if fAlpha >= AlphaHi then begin fAlpha := alphaOpaque; fStage := bgsNone; end; end; bgsFadeOut: begin if fAlpha > AlphaStep then Dec(fAlpha, AlphaStep) else Dec(fAlpha, AlphaStep2); if fAlpha <= AlphaStep2 then begin fAlpha := alphaTransparent; fStage := bgsFadeIn; NextVariant; end; end end; MakeFrame; Inc(fStep); if fStep >= 256 then begin fStep := 0; Inc(fCount); end; if fCount > 1 then begin fCount := 0; fStage := bgsFadeOut; end; Done := False; end; procedure TAnimateBackgound.NextVariant; var n: integer; begin // Always new variant! :^) repeat n := Random(High(S_RULES) + 1); until n <> fVariant; fRuleStr := S_RULES[n]; fVariant := n; MakeMatrix; end; procedure TAnimateBackgound.MakeMap; const k = 360 / 255; eHigh = 255; eLow = 239; repe = 7; var i, x, h: integer; v: double; begin h := eHigh - eLow; fMap.Clear; for i := 0 to 255 do begin v := repe * degtorad(k * i); v := 0.5 + Cos(v) * 0.5; x := eLow + Round(v * h); fMap.Add(TColorToFPColor(RGBToColor(x, x, x))); end; end; procedure TAnimateBackgound.MakeFrame; var i, j: integer; r, v, w: double; c: TFPColor; begin if fValMax - fValMin = 0 then Exit; r := 256 / (fValMax - fValMin); for j := 0 to fBuffer.Height - 1 do begin for i := 0 to fBuffer.Width - 1 do begin w := FMod(fStep + (fMatrix[i, j] - fValMin) * r, 256); c := fMap.ColorSmooth(w); c.alpha := fAlpha; fIntf.Colors[i, j] := AlphaBlend(colWhite, c); end; end; fBuffer.LoadFromIntfImage(fIntf); if Assigned(fOnDraw) then fOnDraw(self); end; procedure TAnimateBackgound.MakeMatrix; const edScale = 3.75; var xMin, xMax, yMin, yMax, xDelta, yDelta, x, y: double; i, j: integer; begin fValMin := MaxInt; fValMax := -MaxInt; xMin := -edScale; xMax := edScale; yMin := -edScale; yMax := edScale; xDelta := (xMax - xMin) / fBuffer.Width; yDelta := (yMax - yMin) / fBuffer.Height; for j := 0 to fBuffer.Height - 1 do begin y := yMax - j * yDelta; for i := 0 to fBuffer.Width - 1 do begin x := xMin + i * xDelta; fMatrix[i, j] := CalcRule(x, y); fValMin := Min(fValMin, fMatrix[i, j]); fValMax := Max(fValMax, fMatrix[i, j]); end; end; end; end.
26.29661
85
0.571597
476fc4099a479fcfb9f4934eb7bc800656f3af80
38,855
pas
Pascal
src/xampp-control-panel/uMain.pas
mnikolop/Thesis_project_CyberDoc
9a37fdd5a31de24cb902ee31ef19eb992faa1665
[ "Apache-2.0" ]
4
2018-04-20T07:27:13.000Z
2021-12-21T05:19:24.000Z
src/xampp-control-panel/uMain.pas
mnikolop/Thesis_project_CyberDoc
9a37fdd5a31de24cb902ee31ef19eb992faa1665
[ "Apache-2.0" ]
4
2020-06-22T12:31:31.000Z
2021-05-11T15:32:59.000Z
src/xampp-control-panel/uMain.pas
mnikolop/Thesis_project_CyberDoc
9a37fdd5a31de24cb902ee31ef19eb992faa1665
[ "Apache-2.0" ]
1
2019-11-24T08:43:35.000Z
2019-11-24T08:43:35.000Z
(* This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. Programmed by Steffen Strueber, Updates: 3.0.2: May 10th 2011, Steffen Strueber 3.0.3-3.2.1: hackattack142 *) unit uMain; interface uses GnuGettext, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, Buttons, uTools, uTomcat, uApache, uMySQL, uFileZilla, uMercury, uNetstat, uNetstatTable, Menus, IniFiles, AppEvnts, ImgList, JCLDebug, JCLSysInfo, uProcesses_new; type TfMain = class(TForm) imgXAMPP: TImage; lHeader: TLabel; bConfig: TBitBtn; bSCM: TBitBtn; gbModules: TGroupBox; bApacheAction: TBitBtn; bApacheAdmin: TBitBtn; bMySQLAction: TBitBtn; bMySQLAdmin: TBitBtn; bFileZillaAction: TBitBtn; bFileZillaAdmin: TBitBtn; bMercuryAction: TBitBtn; bMercuryAdmin: TBitBtn; sbMain: TStatusBar; bQuit: TBitBtn; bHelp: TBitBtn; bExplorer: TBitBtn; pApacheStatus: TPanel; TimerUpdateStatus: TTimer; TrayIcon: TTrayIcon; bNetstat: TBitBtn; puSystray: TPopupMenu; miShowHide: TMenuItem; miTerminate: TMenuItem; N1: TMenuItem; bApacheConfig: TBitBtn; lPIDs: TLabel; lPorts: TLabel; lApachePIDs: TLabel; bApacheLogs: TBitBtn; lApachePorts: TLabel; bMySQLConfig: TBitBtn; bMySQLLogs: TBitBtn; bFileZillaConfig: TBitBtn; bFileZillaLogs: TBitBtn; bMercuryConfig: TBitBtn; reLog: TRichEdit; lMySQLPIDs: TLabel; lMySQLPorts: TLabel; lFileZillaPorts: TLabel; lFileZillaPIDs: TLabel; lMercuryPorts: TLabel; lMercuryPIDs: TLabel; pMySQLStatus: TPanel; pFileZillaStatus: TPanel; pMercuryStatus: TPanel; ApplicationEvents: TApplicationEvents; ImageList: TImageList; bMySQLService: TBitBtn; bFileZillaService: TBitBtn; lServices: TLabel; lModules: TLabel; lActions: TLabel; bApacheService: TBitBtn; bMercurylogs: TBitBtn; puGeneral: TPopupMenu; lTomcatPorts: TLabel; lTomcatPIDs: TLabel; bTomcatAction: TBitBtn; bTomcatAdmin: TBitBtn; bTomcatConfig: TBitBtn; pTomcatStatus: TPanel; bTomcatLogs: TBitBtn; bTomcatService: TBitBtn; bMercuryService: TBitBtn; bXamppShell: TBitBtn; puLog: TPopupMenu; LogCopy: TMenuItem; LogSelectAll: TMenuItem; N2: TMenuItem; ApacheTray: TMenuItem; MySQLTray: TMenuItem; FileZillaTray: TMenuItem; MercuryTray: TMenuItem; TomcatTray: TMenuItem; TomcatTrayControl: TMenuItem; MercuryTrayControl: TMenuItem; FileZillaTrayControl: TMenuItem; MySQLTrayControl: TMenuItem; ApacheTrayControl: TMenuItem; TimerUpdateNetworking: TTimer; procedure FormCreate(Sender: TObject); procedure bApacheActionClick(Sender: TObject); procedure TimerUpdateStatusTimer(Sender: TObject); procedure TimerUpdateNetworkingTimer(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure bNetstatClick(Sender: TObject); procedure miTerminateClick(Sender: TObject); procedure bQuitClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure miShowHideClick(Sender: TObject); procedure TrayIconDblClick(Sender: TObject); procedure bExplorerClick(Sender: TObject); procedure bSCMClick(Sender: TObject); procedure bApacheAdminClick(Sender: TObject); procedure bApacheConfigClick(Sender: TObject); procedure miGeneralClick(Sender: TObject); procedure bConfigClick(Sender: TObject); procedure bApacheLogsClick(Sender: TObject); procedure bMySQLActionClick(Sender: TObject); procedure bMySQLAdminClick(Sender: TObject); procedure bMySQLConfigClick(Sender: TObject); procedure bMySQLLogsClick(Sender: TObject); procedure bFileZillaActionClick(Sender: TObject); procedure bFileZillaAdminClick(Sender: TObject); procedure bFileZillaConfigClick(Sender: TObject); procedure bFileZillaLogsClick(Sender: TObject); procedure bMercuryActionClick(Sender: TObject); procedure bMercuryAdminClick(Sender: TObject); procedure bMercuryConfigClick(Sender: TObject); procedure bHelpClick(Sender: TObject); procedure bApacheServiceClick(Sender: TObject); procedure bMySQLServiceClick(Sender: TObject); procedure bFileZillaServiceClick(Sender: TObject); procedure bMercuryServiceClick(Sender: TObject); procedure bMercurylogsClick(Sender: TObject); procedure bXamppShellClick(Sender: TObject); procedure bTomcatConfigClick(Sender: TObject); procedure bTomcatLogsClick(Sender: TObject); procedure bTomcatActionClick(Sender: TObject); procedure bTomcatAdminClick(Sender: TObject); procedure bTomcatServiceClick(Sender: TObject); procedure ApplicationEventsException(Sender: TObject; E: Exception); procedure LogCopyClick(Sender: TObject); procedure LogSelectAllClick(Sender: TObject); procedure ApacheTrayControlClick(Sender: TObject); procedure MySQLTrayControlClick(Sender: TObject); procedure FileZillaTrayControlClick(Sender: TObject); procedure MercuryTrayControlClick(Sender: TObject); procedure TomcatTrayControlClick(Sender: TObject); private Apache: tApache; MySQL: tMySQL; FileZilla: tFileZilla; Mercury: tMercury; Tomcat: tTomcat; WindowsShutdownInProgress: Boolean; procedure UpdateStatusAll; function TryGuessXamppVersion: string; procedure EditConfigLogs(ConfigFile: string); procedure GeneralPUClear; procedure GeneralPUAdd(text: string = ''; hint: string = ''; tag: integer = 0); procedure GeneralPUAddUser(text: string; hint: string = ''); procedure GeneralPUAddUserFromSL(sl: tStringList); procedure WMQueryEndSession(var Msg: TWMQueryEndSession); message WM_QueryEndSession; // detect Windows shutdown message procedure WriteLogToFile; procedure updateTimerStatus(enabled: Boolean); public procedure updateTimerNetworking(enabled: Boolean); procedure AddLog(module, log: string; LogType: tLogType = ltDefault); overload; procedure AddLog(log: string; LogType: tLogType = ltDefault); overload; procedure AdjustLogFont(Name: string; Size: integer); end; var fMain: TfMain; implementation uses uConfig, uHelp; {$R *.dfm} /////////////////////////////////////////// // APACHE FUNCTIONS /////////////////////////////////////////// procedure TfMain.bApacheServiceClick(Sender: TObject); var oldIsService: Boolean; begin oldIsService := Apache.isService; if Apache.isRunning then begin MessageDlg(_('Services cannot be installed or uninstalled while the service is running!'), mtError, [mbOk], 0); exit; end; if Apache.isService then begin if MessageDlg(Format(_('Click Yes to uninstall the %s service'), [Apache.ModuleName]), mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin updateTimerStatus(False); Apache.ServiceUnInstall; updateTimerStatus(True); end else exit; end else begin if MessageDlg(Format(_('Click Yes to install the %s service'), [Apache.ModuleName]), mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin updateTimerStatus(False); Apache.ServiceInstall; updateTimerStatus(True); end else exit; end; Apache.CheckIsService; if (oldIsService = Apache.isService) then begin Apache.AddLog(_('Service was NOT (un)installed!'), ltError); if (WinVersion.Major = 5) then // WinXP Apache.AddLog (_('One possible reason for failure: On windows security box you !!!MUST UNCHECK!!! the "Protect my computer and data from unauthorized program activity" checkbox!!!'), ltError); end else begin Apache.AddLog(_('Successful!')); end; end; procedure TfMain.bApacheActionClick(Sender: TObject); begin if Apache.isRunning then Apache.Stop else Apache.Start; end; procedure TfMain.bApacheAdminClick(Sender: TObject); begin Apache.Admin; end; procedure TfMain.bApacheConfigClick(Sender: TObject); begin GeneralPUClear; GeneralPUAdd('Apache (httpd.conf)', 'apache/conf/httpd.conf'); GeneralPUAdd('Apache (httpd-ssl.conf)', 'apache/conf/extra/httpd-ssl.conf'); GeneralPUAdd('Apache (httpd-xampp.conf)', 'apache/conf/extra/httpd-xampp.conf'); GeneralPUAdd('PHP (php.ini)', 'php/php.ini'); GeneralPUAdd('phpMyAdmin (config.inc.php)', 'phpMyAdmin/config.inc.php'); GeneralPUAddUserFromSL(Config.UserConfig.Apache); GeneralPUAdd(); GeneralPUAdd(_('<Browse>') + ' [Apache]', 'apache', 1); GeneralPUAdd(_('<Browse>') + ' [PHP]', 'php', 1); GeneralPUAdd(_('<Browse>') + ' [phpMyAdmin]', 'phpMyAdmin', 1); puGeneral.Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y); end; procedure TfMain.bApacheLogsClick(Sender: TObject); begin GeneralPUClear; GeneralPUAdd('Apache (access.log)', 'apache\logs\access.log'); GeneralPUAdd('Apache (error.log)', 'apache\logs\error.log'); GeneralPUAdd('PHP (php_error_log)', 'php\logs\php_error_log'); GeneralPUAddUserFromSL(Config.UserLogs.Apache); GeneralPUAdd(); GeneralPUAdd(_('<Browse>') + ' [Apache]', 'apache\logs', 1); GeneralPUAdd(_('<Browse>') + ' [PHP]', 'php\logs', 1); puGeneral.Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y); end; procedure TfMain.ApacheTrayControlClick(Sender: TObject); begin if Apache.isRunning then Apache.Stop else Apache.Start; end; /////////////////////////////////////////// // MYSQL FUNCTIONS /////////////////////////////////////////// procedure TfMain.bMySQLServiceClick(Sender: TObject); var oldIsService: Boolean; begin oldIsService := MySQL.isService; if MySQL.isRunning then begin MessageDlg(_('Services cannot be installed or uninstalled while the service is running!'), mtError, [mbOk], 0); exit; end; if MySQL.isService then begin if MessageDlg(Format(_('Click Yes to uninstall the %s service'), [MySQL.ModuleName]), mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin updateTimerStatus(False); MySQL.ServiceUnInstall; updateTimerStatus(True); end else exit; end else begin if MessageDlg(Format(_('Click Yes to install the %s service'), [MySQL.ModuleName]), mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin updateTimerStatus(False); MySQL.ServiceInstall; updateTimerStatus(True); end else exit; end; MySQL.CheckIsService; if (oldIsService = MySQL.isService) then begin MySQL.AddLog(_('Service was NOT (un)installed!'), ltError); if (WinVersion.Major = 5) then // WinXP MySQL.AddLog (_('One possible reason for failure: On windows security box you !!!MUST UNCHECK!!! the "Protect my computer and data from unauthorized program activity" checkbox!!!'), ltError); end else begin MySQL.AddLog(_('Successful!')); end; end; procedure TfMain.bMySQLActionClick(Sender: TObject); begin if MySQL.isRunning then MySQL.Stop else MySQL.Start; end; procedure TfMain.bMySQLAdminClick(Sender: TObject); begin MySQL.Admin; end; procedure TfMain.bMySQLConfigClick(Sender: TObject); begin GeneralPUClear; GeneralPUAdd('my.ini', 'mysql\bin\my.ini'); GeneralPUAddUserFromSL(Config.UserConfig.MySQL); GeneralPUAdd(); GeneralPUAdd(_('<Browse>'), 'mysql', 1); puGeneral.Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y); end; procedure TfMain.bMySQLLogsClick(Sender: TObject); begin GeneralPUClear; GeneralPUAdd('mysql_error.log', 'mysql\data\mysql_error.log'); GeneralPUAddUserFromSL(Config.UserLogs.MySQL); GeneralPUAdd(); GeneralPUAdd(_('<Browse>'), 'mysql\data', 1); puGeneral.Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y); end; procedure TfMain.MySQLTrayControlClick(Sender: TObject); begin if MySQL.isRunning then MySQL.Stop else MySQL.Start; end; /////////////////////////////////////////// // FILEZILLA FUNCTIONS /////////////////////////////////////////// procedure TfMain.bFileZillaServiceClick(Sender: TObject); var oldIsService: Boolean; begin oldIsService := FileZilla.isService; if FileZilla.isRunning then begin MessageDlg(_('Services cannot be installed or uninstalled while the service is running!'), mtError, [mbOk], 0); exit; end; if FileZilla.isService then begin if MessageDlg(Format(_('Click Yes to uninstall the %s service'), [FileZilla.ModuleName]), mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin updateTimerStatus(False); FileZilla.ServiceUnInstall; updateTimerStatus(True); end else exit; end else begin if MessageDlg(Format(_('Click Yes to install the %s service'), [FileZilla.ModuleName]), mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin updateTimerStatus(False); FileZilla.ServiceInstall; updateTimerStatus(True); end else exit; end; FileZilla.CheckIsService; if (oldIsService = FileZilla.isService) then begin FileZilla.AddLog(_('Service was NOT (un)installed!'), ltError); if (WinVersion.Major = 5) then // WinXP FileZilla.AddLog (_('One possible reason for failure: On windows security box you !!!MUST UNCHECK!!! the "Protect my computer and data from unauthorized program activity" checkbox!!!'), ltError); end else begin FileZilla.AddLog(_('Successful!')); end; end; procedure TfMain.bFileZillaActionClick(Sender: TObject); begin if FileZilla.isRunning then FileZilla.Stop else FileZilla.Start; end; procedure TfMain.bFileZillaAdminClick(Sender: TObject); begin FileZilla.Admin; end; procedure TfMain.bFileZillaConfigClick(Sender: TObject); begin GeneralPUClear; GeneralPUAdd('FileZilla Server.xml', 'FileZillaFTP\FileZilla Server.xml'); GeneralPUAddUserFromSL(Config.UserConfig.FileZilla); GeneralPUAdd(); GeneralPUAdd(_('<Browse>'), 'FileZillaFTP', 1); puGeneral.Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y); end; procedure TfMain.bFileZillaLogsClick(Sender: TObject); begin GeneralPUClear; GeneralPUAddUserFromSL(Config.UserLogs.FileZilla); if DirectoryExists(BaseDir + 'FileZillaFTP\Logs') then GeneralPUAdd(_('<Browse>'), 'FileZillaFTP\Logs', 1); puGeneral.Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y); end; procedure TfMain.FileZillaTrayControlClick(Sender: TObject); begin if FileZilla.isRunning then FileZilla.Stop else FileZilla.Start; end; /////////////////////////////////////////// // MERCURY FUNCTIONS /////////////////////////////////////////// procedure TfMain.bMercuryServiceClick(Sender: TObject); begin MessageDlg(_('Mercury cannot be run as service!'), mtError, [mbOk], 0); end; procedure TfMain.bMercuryActionClick(Sender: TObject); begin if Mercury.isRunning then Mercury.Stop else Mercury.Start; end; procedure TfMain.bMercuryAdminClick(Sender: TObject); begin Mercury.Admin; end; procedure TfMain.bMercuryConfigClick(Sender: TObject); begin GeneralPUClear; GeneralPUAdd('mercury.ini', 'MercuryMail\mercury.ini'); GeneralPUAddUserFromSL(Config.UserConfig.Mercury); GeneralPUAdd(); GeneralPUAdd(_('<Browse>'), 'MercuryMail', 1); puGeneral.Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y); end; procedure TfMain.bMercurylogsClick(Sender: TObject); begin GeneralPUClear; GeneralPUAddUserFromSL(Config.UserLogs.Mercury); GeneralPUAdd(_('<Browse>'), 'MercuryMail\LOGS', 1); puGeneral.Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y); end; procedure TfMain.MercuryTrayControlClick(Sender: TObject); begin if Mercury.isRunning then Mercury.Stop else Mercury.Start; end; /////////////////////////////////////////// // TOMCAT FUNCTIONS /////////////////////////////////////////// procedure TfMain.bTomcatServiceClick(Sender: TObject); var oldIsService: Boolean; begin oldIsService := Tomcat.isService; if Tomcat.isRunning then begin MessageDlg(_('Services cannot be installed or uninstalled while the service is running!'), mtError, [mbOk], 0); exit; end; if Tomcat.isService then begin if MessageDlg(Format(_('Click Yes to uninstall the %s service'), [Tomcat.ModuleName]), mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin updateTimerStatus(False); Tomcat.ServiceUnInstall; updateTimerStatus(True); end else exit; end else begin if MessageDlg(Format(_('Click Yes to install the %s service'), [Tomcat.ModuleName]), mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin updateTimerStatus(False); Tomcat.ServiceInstall; updateTimerStatus(True); end else exit; end; Tomcat.CheckIsService; if (oldIsService = Tomcat.isService) then begin Tomcat.AddLog(_('Service was NOT (un)installed!'), ltError); if (WinVersion.Major = 5) then // WinXP Tomcat.AddLog (_('One possible reason for failure: On windows security box you !!!MUST UNCHECK!!! the "Protect my computer and data from unauthorized program activity" checkbox!!!'), ltError); end else begin Tomcat.AddLog(_('Successful!')); end; end; procedure TfMain.bTomcatActionClick(Sender: TObject); begin if Tomcat.isRunning then Tomcat.Stop else Tomcat.Start; end; procedure TfMain.bTomcatAdminClick(Sender: TObject); begin Tomcat.Admin; end; procedure TfMain.bTomcatConfigClick(Sender: TObject); begin GeneralPUClear; GeneralPUAdd('server.xml', 'Tomcat\conf\server.xml'); GeneralPUAdd('tomcat-users.xml', 'Tomcat\conf\tomcat-users.xml'); GeneralPUAdd('web.xml', 'Tomcat\conf\web.xml'); GeneralPUAdd('context.xml', 'Tomcat\conf\context.xml'); GeneralPUAddUserFromSL(Config.UserConfig.Tomcat); GeneralPUAdd(); GeneralPUAdd(_('<Browse>'), 'Tomcat\conf', 1); puGeneral.Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y); end; procedure TfMain.bTomcatLogsClick(Sender: TObject); begin GeneralPUClear; GeneralPUAddUserFromSL(Config.UserLogs.Tomcat); GeneralPUAdd(); GeneralPUAdd(_('<Browse>'), 'tomcat\logs', 1); puGeneral.Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y); end; procedure TfMain.TomcatTrayControlClick(Sender: TObject); begin if Tomcat.isRunning then Tomcat.Stop else Tomcat.Start; end; /////////////////////////////////////////// // CONTROL PANEL FUNCTIONS /////////////////////////////////////////// procedure TfMain.bConfigClick(Sender: TObject); begin fConfig.Show; end; procedure TfMain.bNetstatClick(Sender: TObject); begin fNetStat.Show; fNetStat.RefreshTable(True); end; procedure TfMain.bXamppShellClick(Sender: TObject); const cBatchFileContents = '@ECHO OFF' + cr + '' + cr + 'GOTO weiter' + cr + ':setenv' + cr + 'SET "MIBDIRS=%~dp0php\extras\mibs"' + cr + 'SET "MIBDIRS=%MIBDIRS:\=/%"' + cr + 'SET "MYSQL_HOME=%~dp0mysql\bin"' + cr + 'SET "OPENSSL_CONF=%~dp0apache\bin\openssl.cnf"' + cr + 'SET "OPENSSL_CONF=%OPENSSL_CONF:\=/%"' + cr + 'SET "PHP_PEAR_SYSCONF_DIR=%~dp0php"' + cr + 'SET "PHP_PEAR_BIN_DIR=%~dp0php"' + cr + 'SET "PHP_PEAR_TEST_DIR=%~dp0php\tests"' + cr + 'SET "PHP_PEAR_WWW_DIR=%~dp0php\www"' + cr + 'SET "PHP_PEAR_CFG_DIR=%~dp0php\cfg"' + cr + 'SET "PHP_PEAR_DATA_DIR=%~dp0php\data"' + cr + 'SET "PHP_PEAR_DOC_DIR=%~dp0php\docs"' + cr + 'SET "PHP_PEAR_PHP_BIN=%~dp0php\php.exe"' + cr + 'SET "PHP_PEAR_INSTALL_DIR=%~dp0php\pear"' + cr + 'SET "PHPRC=%~dp0php"' + cr + 'SET "TMP=%~dp0tmp"' + cr + 'SET "PERL5LIB="' + cr + 'SET "Path=%~dp0;%~dp0php;%~dp0perl\site\bin;%~dp0perl\bin;%~dp0apache\bin;%~dp0mysql\bin;%~dp0FileZillaFTP;%~dp0MercuryMail;%~dp0sendmail;%~dp0webalizer;%~dp0tomcat\bin;%Path%"' + cr + 'GOTO :EOF' + cr + ':weiter' + cr + '' + cr + 'IF "%1" EQU "setenv" (' + cr + ' ECHO.' + cr + ' ECHO Setting environment for using XAMPP for Windows.' + cr + ' CALL :setenv' + cr + ') ELSE (' + cr + ' SETLOCAL' + cr + ' TITLE XAMPP for Windows' + cr + ' PROMPT %username%@%computername%$S$P$_#$S' + cr + ' START "" /B %COMSPEC% /K "%~f0" setenv' + cr + ')'; cFilename = 'xampp_shell.bat'; var ts: tStringList; batchfile: string; begin batchfile := BaseDir + cFilename; if not FileExists(batchfile) then begin if MessageDlg(Format(_('File "%s" not found. Should it be created now?'), [batchfile]), mtConfirmation, [mbYes, mbAbort], 0) <> mrYes then exit; ts := tStringList.Create; ts.text := cBatchFileContents; try ts.SaveToFile(batchfile); except on E: Exception do begin MessageDlg(_('Error') + ': ' + E.Message, mtError, [mbOk], 0); end; end; ts.Free; end; ExecuteFile(batchfile, '', '', SW_SHOW); end; procedure TfMain.bExplorerClick(Sender: TObject); var App: string; begin App := BaseDir; ExecuteFile(App, '', '', SW_SHOW); AddLog(Format(_('Executing "%s"'), [App])); end; procedure TfMain.bSCMClick(Sender: TObject); var App: string; begin App := 'services.msc'; ExecuteFile(App, '', '', SW_SHOW); AddLog(Format(_('Executing "%s"'), [App])); end; procedure TfMain.bHelpClick(Sender: TObject); begin fHelp.Show; end; procedure TfMain.bQuitClick(Sender: TObject); begin miTerminateClick(Sender); end; /////////////////////////////////////////// // LOG FUNCTIONS /////////////////////////////////////////// procedure TfMain.AddLog(module, log: string; LogType: tLogType = ltDefault); begin if (not Config.ShowDebug) and (LogType = ltDebug) or (LogType = ltDebugDetails) then exit; if (LogType = ltDebugDetails) and (Config.DebugLevel = 0) then exit; with reLog do begin SelStart := GetTextLen; SelAttributes.Color := clGray; SelText := TimeToStr(Now) + ' '; SelAttributes.Color := clBlack; SelText := '['; SelAttributes.Color := clBlue; SelText := module; SelAttributes.Color := clBlack; SelText := '] ' + #9; case LogType of ltDefault: SelAttributes.Color := clBlack; ltInfo: SelAttributes.Color := clBlue; ltError: SelAttributes.Color := clRed; ltDebug: SelAttributes.Color := clGray; ltDebugDetails: SelAttributes.Color := clSilver; end; SelText := log + #13; SendMessage(Handle, EM_SCROLLCARET, 0, 0); end; end; procedure TfMain.AddLog(log: string; LogType: tLogType = ltDefault); begin AddLog('main', log, LogType); end; procedure TfMain.WriteLogToFile; var exec_name: string; LogFileName: string; f: TextFile; i: integer; begin exec_name := ExtractFileName(Application.ExeName); while (length(exec_name) > 0) and (exec_name[length(exec_name)] <> '.') do exec_name := copy(exec_name, 1, length(exec_name) - 1); LogFileName := BaseDir + exec_name + 'log'; AssignFile(f, LogFileName); if FileExists(LogFileName) then Append(f) else Rewrite(f); for i := 0 to reLog.Lines.count - 1 do Writeln(f, reLog.Lines[i]); Writeln(f, ''); CloseFile(f); end; procedure TfMain.LogSelectAllClick(Sender: TObject); begin reLog.SelectAll; end; procedure TfMain.LogCopyClick(Sender: TObject); begin reLog.CopyToClipboard; end; procedure TfMain.AdjustLogFont(Name: string; Size: integer); begin reLog.Font.Name := Name; reLog.Font.Size := Size; end; /////////////////////////////////////////// // POPUP MENU FUNCTIONS /////////////////////////////////////////// procedure TfMain.GeneralPUAdd(text: string = ''; hint: string = ''; tag: integer = 0); var mi: TMenuItem; begin mi := TMenuItem.Create(puGeneral); mi.Caption := text; if text = '' then begin mi.Caption := '-'; end else begin mi.hint := hint; mi.tag := tag; mi.OnClick := miGeneralClick; end; puGeneral.Items.Add(mi); end; procedure TfMain.GeneralPUAddUser(text: string; hint: string = ''); var myCaption: TranslatedUnicodeString; mi, miMain: TMenuItem; begin myCaption := _('User defined'); miMain := puGeneral.Items.Find(myCaption); if miMain = nil then begin GeneralPUAdd(); miMain := TMenuItem.Create(puGeneral); miMain.Caption := myCaption; puGeneral.Items.Add(miMain); end; mi := TMenuItem.Create(miMain); mi.Caption := text; if hint <> '' then mi.hint := hint else mi.hint := text; mi.OnClick := miGeneralClick; miMain.Add(mi); end; procedure TfMain.GeneralPUAddUserFromSL(sl: tStringList); var i: integer; begin for i := 0 to sl.count - 1 do GeneralPUAddUser(sl[i]); end; procedure TfMain.GeneralPUClear; begin puGeneral.Items.Clear; end; procedure TfMain.miGeneralClick(Sender: TObject); var mi: TMenuItem; App: string; begin if not(Sender is TMenuItem) then exit; mi := Sender as TMenuItem; if mi.tag = 0 then EditConfigLogs(mi.hint); if mi.tag = 1 then begin App := BaseDir + mi.hint; ExecuteFile(App, '', '', SW_SHOW); AddLog(Format(_('Executing "%s"'), [App])); end; end; procedure TfMain.EditConfigLogs(ConfigFile: string); var App, Param: string; begin App := Config.EditorApp; Param := BaseDir + ConfigFile; AddLog(Format(_('Executing %s %s'), [App, Param]), ltDebug); ExecuteFile(App, Param, '', SW_SHOW); end; /////////////////////////////////////////// // FORM GENERAL FUNCTIONS /////////////////////////////////////////// procedure TfMain.updateTimerStatus(enabled: Boolean); begin TimerUpdateStatus.Enabled := enabled; end; procedure TfMain.updateTimerNetworking(enabled: Boolean); begin TimerUpdateNetworking.Enabled := enabled; end; procedure TfMain.miShowHideClick(Sender: TObject); begin if Visible then begin Hide; if fMain.WindowState = wsMinimized then fMain.WindowState := wsNormal; end else begin Show; if fMain.WindowState = wsMinimized then fMain.WindowState := wsNormal; Application.BringToFront; end; end; procedure TfMain.ApplicationEventsException(Sender: TObject; E: Exception); var ts: tStringList; i: integer; begin // GlobalAddLog(Format('Exception in thread: %d / %s', [Thread.ThreadID, JclDebugThreadList.ThreadClassNames[Thread.ThreadID]]),0,'LogException'); // Note: JclLastExceptStackList always returns list for *current* thread ID. To simplify getting the // stack of thread where an exception occured JclLastExceptStackList returns stack of the thread instead // of current thread when called *within* the JclDebugThreadList.OnSyncException handler. This is the // *only* exception to the behavior of JclLastExceptStackList described above. ts := tStringList.Create; AddLog('EXCEPTION', E.Message, ltError); JclLastExceptStackList.AddToStrings(ts, True, True, True); for i := 0 to ts.count - 1 do AddLog('EXCEPTION', ts[i], ltError); ts.Free; end; procedure TfMain.miTerminateClick(Sender: TObject); begin Closing := True; Application.ProcessMessages; Application.Terminate; end; procedure TfMain.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caHide; end; procedure TfMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if WindowsShutdownInProgress then begin CanClose := True; end else begin CanClose := false; Hide; end; end; procedure TfMain.FormCreate(Sender: TObject); var isAdmin: Boolean; xamppVersion: string; CCVersion: string; Bitness: string; OSVersionInfoEx: TOSVersionInfoEx; dirlist: TStringList; index: Integer; begin TranslateComponent(Self); if (Config.Minimized) then begin Hide; fMain.WindowState := wsMinimized; end; //ReportMemoryLeaksOnShutdown := true; BaseDir := LowerCase(ExtractFilePath(Application.ExeName)); GlobalProgramVersion := GlobalProgramVersion + ' ' + Config.Edition; reLog.PopupMenu := puLog; reLog.Font.Name := Config.LogSettings.Font; reLog.Font.Size := Config.LogSettings.FontSize; AddLog(_('Initializing Control Panel')); self.Left := Config.WindowSettings.Left; self.Top := Config.WindowSettings.Top; if (Config.WindowSettings.Width <> -1) then self.Width := Config.WindowSettings.Width; if (Config.WindowSettings.Height <> -1) then self.Height := Config.WindowSettings.Height; WindowsShutdownInProgress := false; if IsWindows64 then Bitness := '64-bit' else Bitness := '32-bit'; AddLog(Format(_('Windows Version: %s %s %s'), [GetWindowsProductString, GetWindowsServicePackVersionString, Bitness])); OSVersionInfoEx.dwOSVersionInfoSize := SizeOf(TOSVersionInfo); GetVersionEx(OSVersionInfoEx); if ((OSVersionInfoEx.dwMajorVersion = 5) and (OSVersionInfoEx.dwMinorVersion = 0)) or (OSVersionInfoEx.dwMajorVersion < 5) then AddLog(_('WARNING: Your Operating System is too old and is not supported'), ltError); xamppVersion := TryGuessXamppVersion; AddLog('XAMPP Version: ' + xamppVersion); if cCompileDate <> '' then CCVersion := GlobalProgramversion + Format(' [ Compiled: %s ]', [cCompileDate]) else CCVersion := GlobalProgramversion; AddLog('Control Panel Version: ' + CCVersion); Caption := 'XAMPP Control Panel v' + GlobalProgramversion + Format(' [ Compiled: %s ]', [cCompileDate]); lHeader.Caption := 'XAMPP Control Panel v' + GlobalProgramversion; isAdmin := IsWindowsAdmin; if isAdmin then begin AddLog(_('Running with Administrator rights - good!')); end else begin AddLog(_('You are not running with administrator rights! This will work for'), ltInfo); AddLog(_('most application stuff but whenever you do something with services'), ltInfo); AddLog(_('there will be a security dialogue or things will break! So think '), ltInfo); AddLog(_('about running this application with administrator rights!'), ltInfo); fmain.bApacheService.Enabled := false; fmain.bMySQLService.Enabled := false; fmain.bFileZillaService.Enabled := false; fmain.bTomcatService.Enabled := false; end; AddLog(Format(_('XAMPP Installation Directory: "%s"'), [BaseDir])); if LastDelimiter(' ', Trim(BaseDir)) <> 0 then AddLog(_('WARNING: Your install directory contains spaces. This may break programs/scripts'), ltInfo); if (LastDelimiter('(', Trim(BaseDir)) <> 0) or (LastDelimiter(')', Trim(BaseDir)) <> 0) or (LastDelimiter('!', Trim(BaseDir)) <> 0) or (LastDelimiter('@', Trim(BaseDir)) <> 0) or (LastDelimiter('#', Trim(BaseDir)) <> 0) or (LastDelimiter('$', Trim(BaseDir)) <> 0) or (LastDelimiter('%', Trim(BaseDir)) <> 0) or (LastDelimiter('^', Trim(BaseDir)) <> 0) or (LastDelimiter('&', Trim(BaseDir)) <> 0) or (LastDelimiter('*', Trim(BaseDir)) <> 0) or (LastDelimiter('<', Trim(BaseDir)) <> 0) or (LastDelimiter('>', Trim(BaseDir)) <> 0) or (LastDelimiter(',', Trim(BaseDir)) <> 0) or (LastDelimiter('?', Trim(BaseDir)) <> 0) or (LastDelimiter('[', Trim(BaseDir)) <> 0) or (LastDelimiter(']', Trim(BaseDir)) <> 0) or (LastDelimiter('{', Trim(BaseDir)) <> 0) or (LastDelimiter('}', Trim(BaseDir)) <> 0) or (LastDelimiter('=', Trim(BaseDir)) <> 0) or (LastDelimiter('+', Trim(BaseDir)) <> 0) or (LastDelimiter('`', Trim(BaseDir)) <> 0) or (LastDelimiter('~', Trim(BaseDir)) <> 0) or (LastDelimiter('|', Trim(BaseDir)) <> 0) then AddLog(_('WARNING: Your install directory contains special characters. This may break programs/scripts'), ltInfo); if BaseDir[length(BaseDir)] <> '\' then BaseDir := BaseDir + '\'; NetStatTable.UpdateTable; //Processes.Update; Processes.UpdateList; AddLog(_('Checking for prerequisites')); if Config.EnableChecks.Runtimes then begin dirlist := TStringList.Create; try GetSubDirectories(IncludeTrailingPathDelimiter(GetWinDir) + 'winsxs', dirlist); index := FindMatchText(dirlist, 'x86_microsoft.vc90.crt'); if index = -1 then begin AddLog(_('Required XAMPP prerequisite not found!'), ltError); AddLog(_('You do not appear to have the Microsoft Visual C++ 2008 Runtimes installed'), ltError); AddLog(_('This is required for XAMPP to fully function'), ltError); AddLog(_('http://www.microsoft.com/download/en/details.aspx?id=5582'), ltError); end else AddLog(_('All prerequisites found')); finally FreeAndNil(dirlist); end; end else begin AddLog(_('VC++ checking is disabled'), ltDebug); end; AddLog(_('Initializing Modules')); if Config.EnableModules.Apache then begin Apache := tApache.Create(bApacheService, pApacheStatus, lApachePIDs, lApachePorts, bApacheAction, bApacheAdmin); end else begin AddLog(Format(_('The %s module is disabled'),[Config.ModuleNames.Apache]), ltInfo); fmain.ApacheTray.Enabled := false; fmain.bApacheService.Enabled := false; fmain.bApacheAction.Enabled := false; fmain.bApacheAdmin.Enabled := false; fmain.bApacheConfig.Enabled := false; fmain.bApacheLogs.Enabled := false; end; if Config.EnableModules.MySQL then begin MySQL := tMySQL.Create(bMySQLService, pMySQLStatus, lMySQLPIDs, lMySQLPorts, bMySQLAction, bMySQLAdmin); end else begin AddLog(Format(_('The %s module is disabled'),[Config.ModuleNames.MySQL]), ltInfo); fmain.MySQLTray.Enabled := false; fmain.bMySQLService.Enabled := false; fmain.bMySQLAction.Enabled := false; fmain.bMySQLAdmin.Enabled := false; fmain.bMySQLConfig.Enabled := false; fmain.bMySQLLogs.Enabled := false; end; if Config.EnableModules.FileZilla then begin FileZilla := tFileZilla.Create(bFileZillaService, pFileZillaStatus, lFileZillaPIDs, lFileZillaPorts, bFileZillaAction, bFileZillaAdmin); end else begin AddLog(Format(_('The %s module is disabled'),[Config.ModuleNames.FileZilla]), ltInfo); fmain.FileZillaTray.Enabled := false; fmain.bFileZillaService.Enabled := false; fmain.bFileZillaAction.Enabled := false; fmain.bFileZillaAdmin.Enabled := false; fmain.bFileZillaConfig.Enabled := false; fmain.bFileZillaLogs.Enabled := false; end; if Config.EnableModules.Mercury then begin Mercury := tMercury.Create(bMercuryService, pMercuryStatus, lMercuryPIDs, lMercuryPorts, bMercuryAction, bMercuryAdmin); end else begin AddLog(Format(_('The %s module is disabled'),[Config.ModuleNames.Mercury]), ltInfo); fmain.MercuryTray.Enabled := false; fmain.bMercuryAction.Enabled := false; fmain.bMercuryAdmin.Enabled := false; fmain.bMercuryConfig.Enabled := false; fmain.bMercurylogs.Enabled := false; end; if Config.EnableModules.Tomcat then begin Tomcat := tTomcat.Create(bTomcatService, pTomcatStatus, lTomcatPIDs, lTomcatPorts, bTomcatAction, bTomcatAdmin); end else begin AddLog(Format(_('The %s module is disabled'),[Config.ModuleNames.Tomcat]), ltInfo); fmain.TomcatTray.Enabled := false; fmain.bTomcatService.Enabled := false; fmain.bTomcatAction.Enabled := false; fmain.bTomcatAdmin.Enabled := false; fmain.bTomcatConfig.Enabled := false; fmain.bTomcatLogs.Enabled := false; end; if Config.EnableModules.Apache then begin if Config.ASApache then begin Apache.AutoStart := True; AddLog(Format(_('Enabling autostart for module "%s"'), [Config.ModuleNames.Apache])); end; end; if Config.EnableModules.MySQL then begin if Config.ASMySQL then begin MySQL.AutoStart := True; AddLog(Format(_('Enabling autostart for module "%s"'), [Config.ModuleNames.MySQL])); end; end; if Config.EnableModules.FileZilla then begin if Config.ASFileZilla then begin FileZilla.AutoStart := True; AddLog(Format(_('Enabling autostart for module "%s"'), [Config.ModuleNames.FileZilla])); end; end; if Config.EnableModules.Mercury then begin if Config.ASMercury then begin Mercury.AutoStart := True; AddLog(Format(_('Enabling autostart for module "%s"'), [Config.ModuleNames.Mercury])); end; end; if Config.EnableModules.Tomcat then begin if Config.ASTomcat then begin Tomcat.AutoStart := True; AddLog(Format(_('Enabling autostart for module "%s"'), [Config.ModuleNames.Tomcat])); end; end; AddLog(_('Starting') + ' Check-Timer'); updateTimerStatus(True); updateTimerNetworking(True); AddLog(_('Control Panel Ready')); end; procedure TfMain.FormDestroy(Sender: TObject); begin AddLog(_('Deinitializing Modules')); if Config.EnableModules.Apache then begin Apache.Free; end; if Config.EnableModules.MySQL then begin MySQL.Free; end; if Config.EnableModules.FileZilla then begin FileZilla.Free; end; if Config.EnableModules.Mercury then begin Mercury.Free; end; if Config.EnableModules.Tomcat then begin Tomcat.Free end; AddLog(_('Deinitializing Control Panel')); Config.WindowSettings.Left := self.Left; Config.WindowSettings.Top := self.Top; Config.WindowSettings.Width := self.Width; Config.WindowSettings.Height := self.Height; SaveSettings; WriteLogToFile; end; procedure TfMain.TimerUpdateStatusTimer(Sender: TObject); begin UpdateStatusAll; end; procedure TfMain.TimerUpdateNetworkingTimer(Sender: TObject); begin AddLog(_('Updating Networking Table...'), ltDebugDetails); NetStatTable.UpdateTable; end; procedure TfMain.TrayIconDblClick(Sender: TObject); begin miShowHideClick(nil); end; function TfMain.TryGuessXamppVersion: string; var ts: tStringList; s: string; p: integer; begin result := '???'; ts := tStringList.Create; try ts.LoadFromFile(BaseDir + '\readme_de.txt'); if ts.count < 1 then exit; s := LowerCase(ts[0]); p := pos('version', s); if p = 0 then begin p := pos('portable', s); if p = 0 then exit; delete(s, 1, p + 8); p := pos(' ', s); if p = 0 then exit; result := copy(s, 1, p - 1) + ' Portable'; end else begin delete(s, 1, p + 7); p := pos(' ', s); if p = 0 then exit; result := copy(s, 1, p - 1); end; except end; ts.Free; end; procedure TfMain.UpdateStatusAll; begin //Processes.Update; Processes.UpdateList; // 1. Check Apache if Config.EnableModules.Apache then begin Apache.UpdateStatus; end; // 2. Check MySql if Config.EnableModules.MySQL then begin MySQL.UpdateStatus; end; // 3. Check Filezilla if Config.EnableModules.FileZilla then begin FileZilla.UpdateStatus; end; // 4. Check Mercury if Config.EnableModules.Mercury then begin Mercury.UpdateStatus; end; // 5. Check Tomcat if Config.EnableModules.Tomcat then begin Tomcat.UpdateStatus; end; end; procedure TfMain.WMQueryEndSession(var Msg: TWMQueryEndSession); begin WindowsShutdownInProgress := True; miTerminateClick(nil); inherited; end; end.
28.781481
182
0.688123
4709af66da404d9180f1d97d644822422e568f44
15,769
pas
Pascal
zlib_infcodes.pas
bashkirtsevich/gzip
46f8a12e09d365ae12b544117fd9476b809809a0
[ "Unlicense" ]
6
2020-10-10T09:03:17.000Z
2021-09-07T06:36:53.000Z
zlib_infcodes.pas
tina4stack/Pascal-gzip
46f8a12e09d365ae12b544117fd9476b809809a0
[ "Unlicense" ]
null
null
null
zlib_infcodes.pas
tina4stack/Pascal-gzip
46f8a12e09d365ae12b544117fd9476b809809a0
[ "Unlicense" ]
6
2020-05-04T21:44:08.000Z
2022-01-14T10:31:36.000Z
Unit zlib_InfCodes; { infcodes.c -- process literals and length/distance pairs Copyright (C) 1995-1998 Mark Adler Pascal tranlastion Copyright (C) 1998 by Jacques Nomssi Nzali For conditions of distribution and use, see copyright notice in readme.txt } interface {$I zlib_zconf.pp} uses {$IFNDEF FPC} windows, {$ENDIF} {$IFDEF STRUTILS_DEBUG} strutils, {$ENDIF} zlib_zutil, zlib_zbase; function inflate_codes_new (bl : uInt; bd : uInt; tl : pInflate_huft; td : pInflate_huft; var z : z_stream): pInflate_codes_state; function inflate_codes(var s : inflate_blocks_state; var z : z_stream; r : int) : int; procedure inflate_codes_free(c : pInflate_codes_state; var z : z_stream); implementation uses zlib_infutil, zlib_inffast; function inflate_codes_new (bl : uInt; bd : uInt; tl : pInflate_huft; td : pInflate_huft; var z : z_stream): pInflate_codes_state; var c : pInflate_codes_state; begin c := pInflate_codes_state( ZALLOC(z,1,sizeof(inflate_codes_state)) ); if (c <> Z_NULL) then begin c^.mode := START; c^.lbits := Byte(bl); c^.dbits := Byte(bd); c^.ltree := tl; c^.dtree := td; {$IFDEF STRUTILS_DEBUG} Tracev('inflate: codes new'); {$ENDIF} end; inflate_codes_new := c; end; function inflate_codes(var s : inflate_blocks_state; var z : z_stream; r : int) : int; var j : uInt; { temporary storage } t : pInflate_huft; { temporary pointer } e : uInt; { extra bits or operation } b : uLong; { bit buffer } k : uInt; { bits in bit buffer } p : pBytef; { input data pointer } n : uInt; { bytes available there } q : pBytef; { output window write pointer } m : uInt; { bytes to end of window or read pointer } f : pBytef; { pointer to copy strings from } var c : pInflate_codes_state; begin c := s.sub.decode.codes; { codes state } { copy input/output information to locals } p := z.next_in; n := z.avail_in; b := s.bitb; k := s.bitk; q := s.write; if ptr2int(q) < ptr2int(s.read) then m := uInt(ptr2int(s.read)-ptr2int(q)-1) else m := uInt(ptr2int(s.zend)-ptr2int(q)); { process input and output based on current state } while True do case (c^.mode) of { waiting for "i:"=input, "o:"=output, "x:"=nothing } START: { x: set up for LEN } begin {$ifndef SLOW} if (m >= 258) and (n >= 10) then begin {UPDATE} s.bitb := b; s.bitk := k; z.avail_in := n; Inc(z.total_in, ptr2int(p)-ptr2int(z.next_in)); z.next_in := p; s.write := q; r := inflate_fast(c^.lbits, c^.dbits, c^.ltree, c^.dtree, s, z); {LOAD} p := z.next_in; n := z.avail_in; b := s.bitb; k := s.bitk; q := s.write; if ptr2int(q) < ptr2int(s.read) then m := uInt(ptr2int(s.read)-ptr2int(q)-1) else m := uInt(ptr2int(s.zend)-ptr2int(q)); if (r <> Z_OK) then begin if (r = Z_STREAM_END) then c^.mode := WASH else c^.mode := BADCODE; continue; { break for switch-statement in C } end; end; {$endif} { not SLOW } c^.sub.code.need := c^.lbits; c^.sub.code.tree := c^.ltree; c^.mode := LEN; { falltrough } end; LEN: { i: get length/literal/eob next } begin j := c^.sub.code.need; {NEEDBITS(j);} while (k < j) do begin {NEEDBYTE;} if (n <> 0) then r :=Z_OK else begin {UPDATE} s.bitb := b; s.bitk := k; z.avail_in := n; Inc(z.total_in, ptr2int(p)-ptr2int(z.next_in)); z.next_in := p; s.write := q; inflate_codes := inflate_flush(s,z,r); exit; end; Dec(n); b := b or (uLong(p^) shl k); Inc(p); Inc(k, 8); end; t := c^.sub.code.tree; Inc(t, uInt(b) and inflate_mask[j]); {DUMPBITS(t^.bits);} b := b shr t^.bits; Dec(k, t^.bits); e := uInt(t^.exop); if (e = 0) then { literal } begin c^.sub.lit := t^.base; {$IFDEF STRUTILS_DEBUG} if (t^.base >= $20) and (t^.base < $7f) then Tracevv('inflate: literal '+char(t^.base)) else Tracevv('inflate: literal '+IntToStr(t^.base)); {$ENDIF} c^.mode := LIT; continue; { break switch statement } end; if (e and 16 <> 0) then { length } begin c^.sub.copy.get := e and 15; c^.len := t^.base; c^.mode := LENEXT; continue; { break C-switch statement } end; if (e and 64 = 0) then { next table } begin c^.sub.code.need := e; c^.sub.code.tree := @huft_ptr(t)^[t^.base]; continue; { break C-switch statement } end; if (e and 32 <> 0) then { end of block } begin {$IFDEF STRUTILS_DEBUG} Tracevv('inflate: end of block'); {$ENDIF} c^.mode := WASH; continue; { break C-switch statement } end; c^.mode := BADCODE; { invalid code } z.msg := 'invalid literal/length code'; r := Z_DATA_ERROR; {UPDATE} s.bitb := b; s.bitk := k; z.avail_in := n; Inc(z.total_in, ptr2int(p)-ptr2int(z.next_in)); z.next_in := p; s.write := q; inflate_codes := inflate_flush(s,z,r); exit; end; LENEXT: { i: getting length extra (have base) } begin j := c^.sub.copy.get; {NEEDBITS(j);} while (k < j) do begin {NEEDBYTE;} if (n <> 0) then r :=Z_OK else begin {UPDATE} s.bitb := b; s.bitk := k; z.avail_in := n; Inc(z.total_in, ptr2int(p)-ptr2int(z.next_in)); z.next_in := p; s.write := q; inflate_codes := inflate_flush(s,z,r); exit; end; Dec(n); b := b or (uLong(p^) shl k); Inc(p); Inc(k, 8); end; Inc(c^.len, uInt(b and inflate_mask[j])); {DUMPBITS(j);} b := b shr j; Dec(k, j); c^.sub.code.need := c^.dbits; c^.sub.code.tree := c^.dtree; {$IFDEF STRUTILS_DEBUG} Tracevv('inflate: length '+IntToStr(c^.len)); {$ENDIF} c^.mode := DIST; { falltrough } end; DIST: { i: get distance next } begin j := c^.sub.code.need; {NEEDBITS(j);} while (k < j) do begin {NEEDBYTE;} if (n <> 0) then r :=Z_OK else begin {UPDATE} s.bitb := b; s.bitk := k; z.avail_in := n; Inc(z.total_in, ptr2int(p)-ptr2int(z.next_in)); z.next_in := p; s.write := q; inflate_codes := inflate_flush(s,z,r); exit; end; Dec(n); b := b or (uLong(p^) shl k); Inc(p); Inc(k, 8); end; t := @huft_ptr(c^.sub.code.tree)^[uInt(b) and inflate_mask[j]]; {DUMPBITS(t^.bits);} b := b shr t^.bits; Dec(k, t^.bits); e := uInt(t^.exop); if (e and 16 <> 0) then { distance } begin c^.sub.copy.get := e and 15; c^.sub.copy.dist := t^.base; c^.mode := DISTEXT; continue; { break C-switch statement } end; if (e and 64 = 0) then { next table } begin c^.sub.code.need := e; c^.sub.code.tree := @huft_ptr(t)^[t^.base]; continue; { break C-switch statement } end; c^.mode := BADCODE; { invalid code } z.msg := 'invalid distance code'; r := Z_DATA_ERROR; {UPDATE} s.bitb := b; s.bitk := k; z.avail_in := n; Inc(z.total_in, ptr2int(p)-ptr2int(z.next_in)); z.next_in := p; s.write := q; inflate_codes := inflate_flush(s,z,r); exit; end; DISTEXT: { i: getting distance extra } begin j := c^.sub.copy.get; {NEEDBITS(j);} while (k < j) do begin {NEEDBYTE;} if (n <> 0) then r :=Z_OK else begin {UPDATE} s.bitb := b; s.bitk := k; z.avail_in := n; Inc(z.total_in, ptr2int(p)-ptr2int(z.next_in)); z.next_in := p; s.write := q; inflate_codes := inflate_flush(s,z,r); exit; end; Dec(n); b := b or (uLong(p^) shl k); Inc(p); Inc(k, 8); end; Inc(c^.sub.copy.dist, uInt(b) and inflate_mask[j]); {DUMPBITS(j);} b := b shr j; Dec(k, j); {$IFDEF STRUTILS_DEBUG} Tracevv('inflate: distance '+ IntToStr(c^.sub.copy.dist)); {$ENDIF} c^.mode := COPY; { falltrough } end; COPY: { o: copying bytes in window, waiting for space } begin f := q; Dec(f, c^.sub.copy.dist); if (uInt(ptr2int(q) - ptr2int(s.window)) < c^.sub.copy.dist) then begin f := s.zend; Dec(f, c^.sub.copy.dist - uInt(ptr2int(q) - ptr2int(s.window))); end; while (c^.len <> 0) do begin {NEEDOUT} if (m = 0) then begin {WRAP} if (q = s.zend) and (s.read <> s.window) then begin q := s.window; if ptr2int(q) < ptr2int(s.read) then m := uInt(ptr2int(s.read)-ptr2int(q)-1) else m := uInt(ptr2int(s.zend)-ptr2int(q)); end; if (m = 0) then begin {FLUSH} s.write := q; r := inflate_flush(s,z,r); q := s.write; if ptr2int(q) < ptr2int(s.read) then m := uInt(ptr2int(s.read)-ptr2int(q)-1) else m := uInt(ptr2int(s.zend)-ptr2int(q)); {WRAP} if (q = s.zend) and (s.read <> s.window) then begin q := s.window; if ptr2int(q) < ptr2int(s.read) then m := uInt(ptr2int(s.read)-ptr2int(q)-1) else m := uInt(ptr2int(s.zend)-ptr2int(q)); end; if (m = 0) then begin {UPDATE} s.bitb := b; s.bitk := k; z.avail_in := n; Inc(z.total_in, ptr2int(p)-ptr2int(z.next_in)); z.next_in := p; s.write := q; inflate_codes := inflate_flush(s,z,r); exit; end; end; end; r := Z_OK; {OUTBYTE( *f++)} q^ := f^; Inc(q); Inc(f); Dec(m); if (f = s.zend) then f := s.window; Dec(c^.len); end; c^.mode := START; { C-switch break; not needed } end; LIT: { o: got literal, waiting for output space } begin {NEEDOUT} if (m = 0) then begin {WRAP} if (q = s.zend) and (s.read <> s.window) then begin q := s.window; if ptr2int(q) < ptr2int(s.read) then m := uInt(ptr2int(s.read)-ptr2int(q)-1) else m := uInt(ptr2int(s.zend)-ptr2int(q)); end; if (m = 0) then begin {FLUSH} s.write := q; r := inflate_flush(s,z,r); q := s.write; if ptr2int(q) < ptr2int(s.read) then m := uInt(ptr2int(s.read)-ptr2int(q)-1) else m := uInt(ptr2int(s.zend)-ptr2int(q)); {WRAP} if (q = s.zend) and (s.read <> s.window) then begin q := s.window; if ptr2int(q) < ptr2int(s.read) then m := uInt(ptr2int(s.read)-ptr2int(q)-1) else m := uInt(ptr2int(s.zend)-ptr2int(q)); end; if (m = 0) then begin {UPDATE} s.bitb := b; s.bitk := k; z.avail_in := n; Inc(z.total_in, ptr2int(p)-ptr2int(z.next_in)); z.next_in := p; s.write := q; inflate_codes := inflate_flush(s,z,r); exit; end; end; end; r := Z_OK; {OUTBYTE(c^.sub.lit);} q^ := c^.sub.lit; Inc(q); Dec(m); c^.mode := START; {break;} end; WASH: { o: got eob, possibly more output } begin {$ifdef patch112} if (k > 7) then { return unused byte, if any } begin {$IFDEF STRUTILS_DEBUG} Assert(k < 16, 'inflate_codes grabbed too many bytes'); {$ENDIF} Dec(k, 8); Inc(n); Dec(p); { can always return one } end; {$endif} {FLUSH} s.write := q; r := inflate_flush(s,z,r); q := s.write; if ptr2int(q) < ptr2int(s.read) then m := uInt(ptr2int(s.read)-ptr2int(q)-1) else m := uInt(ptr2int(s.zend)-ptr2int(q)); if (s.read <> s.write) then begin {UPDATE} s.bitb := b; s.bitk := k; z.avail_in := n; Inc(z.total_in, ptr2int(p)-ptr2int(z.next_in)); z.next_in := p; s.write := q; inflate_codes := inflate_flush(s,z,r); exit; end; c^.mode := ZEND; { falltrough } end; ZEND: begin r := Z_STREAM_END; {UPDATE} s.bitb := b; s.bitk := k; z.avail_in := n; Inc(z.total_in, ptr2int(p)-ptr2int(z.next_in)); z.next_in := p; s.write := q; inflate_codes := inflate_flush(s,z,r); exit; end; BADCODE: { x: got error } begin r := Z_DATA_ERROR; {UPDATE} s.bitb := b; s.bitk := k; z.avail_in := n; Inc(z.total_in, ptr2int(p)-ptr2int(z.next_in)); z.next_in := p; s.write := q; inflate_codes := inflate_flush(s,z,r); exit; end; else begin r := Z_STREAM_ERROR; {UPDATE} s.bitb := b; s.bitk := k; z.avail_in := n; Inc(z.total_in, ptr2int(p)-ptr2int(z.next_in)); z.next_in := p; s.write := q; inflate_codes := inflate_flush(s,z,r); exit; end; end; {NEED_DUMMY_RETURN - Delphi2+ dumb compilers complain without this } inflate_codes := Z_STREAM_ERROR; end; procedure inflate_codes_free(c : pInflate_codes_state; var z : z_stream); begin ZFREE(z, c); {$IFDEF STRUTILS_DEBUG} Tracev('inflate: codes free'); {$ENDIF} end; end.
27.187931
77
0.444226
47a794f675c3843367115ba71e9ad2ef6dffa38b
2,940
dfm
Pascal
WebComponents/demos/vui-video/VCL/JsROVideo.Main.dfm
cybelesoft/virtualui
f0ba805563afc00546a1a1f9147721de45840ffb
[ "MIT" ]
11
2016-09-17T14:57:28.000Z
2022-03-16T21:30:44.000Z
WebComponents/demos/vui-video/VCL/JsROVideo.Main.dfm
cybelesoft/virtualui
f0ba805563afc00546a1a1f9147721de45840ffb
[ "MIT" ]
3
2021-11-29T09:16:36.000Z
2022-02-01T22:23:04.000Z
WebComponents/demos/vui-video/VCL/JsROVideo.Main.dfm
cybelesoft/virtualui
f0ba805563afc00546a1a1f9147721de45840ffb
[ "MIT" ]
10
2016-10-26T16:49:50.000Z
2021-12-01T15:23:44.000Z
object Form5: TForm5 Left = 0 Top = 0 Caption = 'Form5' ClientHeight = 464 ClientWidth = 684 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False OnCreate = FormCreate DesignSize = ( 684 464) PixelsPerInch = 96 TextHeight = 13 object Label1: TLabel Left = 8 Top = 18 Width = 23 Height = 13 Caption = 'URL:' end object cbUrl: TComboBox Left = 56 Top = 15 Width = 562 Height = 21 Style = csDropDownList Anchors = [akLeft, akTop, akRight] TabOrder = 0 Items.Strings = ( 'http://www.sample-videos.com/video/mp4/480/big_buck_bunny_480p_2' + 'mb.mp4' 'http://download.openbricks.org/sample/H264/big_buck_bunny_1080p_' + 'H264_AAC_25fps_7200K.MP4' 'http://download.openbricks.org/sample/H264/big_buck_bunny_1080p_' + 'H264_AAC_25fps_7200K_short.MP4' 'http://download.openbricks.org/sample/H264/h264_Linkin_Park-Leav' + 'e_Out_All_The_Rest.mp4' 'http://download.wavetlan.com/SVV/Media/HTTP/H264/Talkinghead_Med' + 'ia/H264_test1_Talkinghead_mp4_480x360.mp4' 'http://download.wavetlan.com/SVV/Media/HTTP/H264/Talkinghead_Med' + 'ia/H264_test3_Talkingheadclipped_mp4_480x360.mp4') end object bGo: TButton Left = 624 Top = 13 Width = 52 Height = 25 Anchors = [akTop, akRight] Caption = 'Go' TabOrder = 1 OnClick = bGoClick end object Panel1: TPanel Left = 8 Top = 118 Width = 668 Height = 338 Anchors = [akLeft, akTop, akRight, akBottom] Caption = 'Panel1' TabOrder = 2 end object GroupBox1: TGroupBox Left = 8 Top = 42 Width = 668 Height = 81 Anchors = [akLeft, akTop, akRight] TabOrder = 3 DesignSize = ( 668 81) object Label2: TLabel Left = 240 Top = 22 Width = 35 Height = 13 Caption = 'Status:' end object lblStatus: TLabel Left = 296 Top = 22 Width = 353 Height = 19 Anchors = [akLeft, akTop, akRight] AutoSize = False end object TrackBar1: TTrackBar Left = 8 Top = 48 Width = 641 Height = 25 Anchors = [akLeft, akTop, akRight] Max = 100 TabOrder = 0 OnChange = TrackBar1Change end object bPlay: TButton Left = 24 Top = 17 Width = 70 Height = 25 Caption = 'Play' TabOrder = 1 OnClick = bPlayClick end object bStop: TButton Left = 100 Top = 17 Width = 70 Height = 25 Caption = 'Stop' TabOrder = 2 OnClick = bStopClick end end end
22.790698
77
0.560884
f1d4ccabc99e13d08eba802c2739af75d0b15efb
309,853
pas
Pascal
Borland/CBuilder5/Source/Vcl/system.pas
TrevorDArcyEvans/DivingMagpieSoftware
7ffcfef653b110e514d5db735d11be0aae9953ec
[ "MIT" ]
1
2021-05-27T10:27:25.000Z
2021-05-27T10:27:25.000Z
Borland/CBuilder5/Source/Vcl/system.pas
TrevorDArcyEvans/Diving-Magpie-Software
7ffcfef653b110e514d5db735d11be0aae9953ec
[ "MIT" ]
null
null
null
Borland/CBuilder5/Source/Vcl/system.pas
TrevorDArcyEvans/Diving-Magpie-Software
7ffcfef653b110e514d5db735d11be0aae9953ec
[ "MIT" ]
null
null
null
{*******************************************************} { } { Borland Delphi Runtime Library } { System Unit } { } { Copyright (C) 1988,99 Inprise Corporation } { } {*******************************************************} unit System; { Predefined constants, types, procedures, } { and functions (such as True, Integer, or } { Writeln) do not have actual declarations.} { Instead they are built into the compiler } { and are treated as if they were declared } { at the beginning of the System unit. } {$H+,I-,S-} { L- should never be specified. The IDE needs to find debug hook (through the C++ compiler sometimes) for integrated debugging to function properly. ILINK will generate debug info for DebugHook if the object module has not been compiled with debug info. ILINK will not generate debug info for DebugHook if the object module has been compiled with debug info. Thus, the Pascal compiler must be responsible for generating the debug information for that symbol when a debug-enabled object file is produced. } interface const { Variant type codes (wtypes.h) } varEmpty = $0000; { vt_empty } varNull = $0001; { vt_null } varSmallint = $0002; { vt_i2 } varInteger = $0003; { vt_i4 } varSingle = $0004; { vt_r4 } varDouble = $0005; { vt_r8 } varCurrency = $0006; { vt_cy } varDate = $0007; { vt_date } varOleStr = $0008; { vt_bstr } varDispatch = $0009; { vt_dispatch } varError = $000A; { vt_error } varBoolean = $000B; { vt_bool } varVariant = $000C; { vt_variant } varUnknown = $000D; { vt_unknown } { vt_decimal $e } { undefined $f } { vt_i1 $10 } varByte = $0011; { vt_ui1 } { vt_ui2 $12 } { vt_ui4 $13 } { vt_i8 $14 } { if adding new items, update varLast, BaseTypeMap and OpTypeMap } varStrArg = $0048; { vt_clsid } varString = $0100; { Pascal string; not OLE compatible } varAny = $0101; varTypeMask = $0FFF; varArray = $2000; varByRef = $4000; { TVarRec.VType values } vtInteger = 0; vtBoolean = 1; vtChar = 2; vtExtended = 3; vtString = 4; vtPointer = 5; vtPChar = 6; vtObject = 7; vtClass = 8; vtWideChar = 9; vtPWideChar = 10; vtAnsiString = 11; vtCurrency = 12; vtVariant = 13; vtInterface = 14; vtWideString = 15; vtInt64 = 16; { Virtual method table entries } vmtSelfPtr = -76; vmtIntfTable = -72; vmtAutoTable = -68; vmtInitTable = -64; vmtTypeInfo = -60; vmtFieldTable = -56; vmtMethodTable = -52; vmtDynamicTable = -48; vmtClassName = -44; vmtInstanceSize = -40; vmtParent = -36; vmtSafeCallException = -32; vmtAfterConstruction = -28; vmtBeforeDestruction = -24; vmtDispatch = -20; vmtDefaultHandler = -16; vmtNewInstance = -12; vmtFreeInstance = -8; vmtDestroy = -4; vmtQueryInterface = 0; vmtAddRef = 4; vmtRelease = 8; vmtCreateObject = 12; type TObject = class; TClass = class of TObject; {$EXTERNALSYM HRESULT} HRESULT = type Longint; { from WTYPES.H } {$EXTERNALSYM IUnknown} {$EXTERNALSYM IDispatch} PGUID = ^TGUID; TGUID = packed record D1: LongWord; D2: Word; D3: Word; D4: array[0..7] of Byte; end; PInterfaceEntry = ^TInterfaceEntry; TInterfaceEntry = packed record IID: TGUID; VTable: Pointer; IOffset: Integer; ImplGetter: Integer; end; PInterfaceTable = ^TInterfaceTable; TInterfaceTable = packed record EntryCount: Integer; Entries: array[0..9999] of TInterfaceEntry; end; TObject = class constructor Create; procedure Free; class function InitInstance(Instance: Pointer): TObject; procedure CleanupInstance; function ClassType: TClass; class function ClassName: ShortString; class function ClassNameIs(const Name: string): Boolean; class function ClassParent: TClass; class function ClassInfo: Pointer; class function InstanceSize: Longint; class function InheritsFrom(AClass: TClass): Boolean; class function MethodAddress(const Name: ShortString): Pointer; class function MethodName(Address: Pointer): ShortString; function FieldAddress(const Name: ShortString): Pointer; function GetInterface(const IID: TGUID; out Obj): Boolean; class function GetInterfaceEntry(const IID: TGUID): PInterfaceEntry; class function GetInterfaceTable: PInterfaceTable; function SafeCallException(ExceptObject: TObject; ExceptAddr: Pointer): HResult; virtual; procedure AfterConstruction; virtual; procedure BeforeDestruction; virtual; procedure Dispatch(var Message); virtual; procedure DefaultHandler(var Message); virtual; class function NewInstance: TObject; virtual; procedure FreeInstance; virtual; destructor Destroy; virtual; end; IUnknown = interface ['{00000000-0000-0000-C000-000000000046}'] function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; end; IDispatch = interface(IUnknown) ['{00020400-0000-0000-C000-000000000046}'] function GetTypeInfoCount(out Count: Integer): HResult; stdcall; function GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; stdcall; function GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; stdcall; function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; stdcall; end; TInterfacedObject = class(TObject, IUnknown) protected FRefCount: Integer; function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; public procedure AfterConstruction; override; procedure BeforeDestruction; override; class function NewInstance: TObject; override; property RefCount: Integer read FRefCount; end; TInterfacedClass = class of TInterfacedObject; TVarArrayBound = packed record ElementCount: Integer; LowBound: Integer; end; PVarArray = ^TVarArray; TVarArray = packed record DimCount: Word; Flags: Word; ElementSize: Integer; LockCount: Integer; Data: Pointer; Bounds: array[0..255] of TVarArrayBound; end; PVarData = ^TVarData; TVarData = packed record VType: Word; Reserved1, Reserved2, Reserved3: Word; case Integer of varSmallint: (VSmallint: Smallint); varInteger: (VInteger: Integer); varSingle: (VSingle: Single); varDouble: (VDouble: Double); varCurrency: (VCurrency: Currency); varDate: (VDate: Double); varOleStr: (VOleStr: PWideChar); varDispatch: (VDispatch: Pointer); varError: (VError: LongWord); varBoolean: (VBoolean: WordBool); varUnknown: (VUnknown: Pointer); varByte: (VByte: Byte); varString: (VString: Pointer); varAny: (VAny: Pointer); varArray: (VArray: PVarArray); varByRef: (VPointer: Pointer); end; PShortString = ^ShortString; PAnsiString = ^AnsiString; PWideString = ^WideString; PString = PAnsiString; PExtended = ^Extended; PCurrency = ^Currency; PVariant = ^Variant; POleVariant = ^OleVariant; PInt64 = ^Int64; TDateTime = type Double; PDateTime = ^TDateTime; PVarRec = ^TVarRec; TVarRec = record { do not pack this record; it is compiler-generated } case Byte of vtInteger: (VInteger: Integer; VType: Byte); vtBoolean: (VBoolean: Boolean); vtChar: (VChar: Char); vtExtended: (VExtended: PExtended); vtString: (VString: PShortString); vtPointer: (VPointer: Pointer); vtPChar: (VPChar: PChar); vtObject: (VObject: TObject); vtClass: (VClass: TClass); vtWideChar: (VWideChar: WideChar); vtPWideChar: (VPWideChar: PWideChar); vtAnsiString: (VAnsiString: Pointer); vtCurrency: (VCurrency: PCurrency); vtVariant: (VVariant: PVariant); vtInterface: (VInterface: Pointer); vtWideString: (VWideString: Pointer); vtInt64: (VInt64: PInt64); end; PMemoryManager = ^TMemoryManager; TMemoryManager = record GetMem: function(Size: Integer): Pointer; FreeMem: function(P: Pointer): Integer; ReallocMem: function(P: Pointer; Size: Integer): Pointer; end; THeapStatus = record TotalAddrSpace: Cardinal; TotalUncommitted: Cardinal; TotalCommitted: Cardinal; TotalAllocated: Cardinal; TotalFree: Cardinal; FreeSmall: Cardinal; FreeBig: Cardinal; Unused: Cardinal; Overhead: Cardinal; HeapErrorCode: Cardinal; end; PackageUnitEntry = packed record Init, FInit : procedure; end; { Compiler generated table to be processed sequentially to init & finit all package units } { Init: 0..Max-1; Final: Last Initialized..0 } UnitEntryTable = array [0..9999999] of PackageUnitEntry; PUnitEntryTable = ^UnitEntryTable; PackageInfoTable = packed record UnitCount : Integer; { number of entries in UnitInfo array; always > 0 } UnitInfo : PUnitEntryTable; end; PackageInfo = ^PackageInfoTable; { Each package exports a '@GetPackageInfoTable' which can be used to retrieve } { the table which contains compiler generated information about the package DLL } GetPackageInfoTable = function : PackageInfo; function RaiseList: Pointer; { Stack of current exception objects } function SetRaiseList(NewPtr: Pointer): Pointer; { returns previous value } procedure SetInOutRes(NewValue: Integer); var ExceptProc: Pointer; { Unhandled exception handler } ErrorProc: Pointer; { Error handler procedure } ExceptClsProc: Pointer; { Map an OS Exception to a Delphi class reference } ExceptObjProc: Pointer; { Map an OS Exception to a Delphi class instance } ExceptionClass: TClass; { Exception base class (must be Exception) } SafeCallErrorProc: Pointer; { Safecall error handler } AssertErrorProc: Pointer; { Assertion error handler } AbstractErrorProc: Pointer; { Abstract method error handler } HPrevInst: LongWord; { Handle of previous instance - HPrevInst cannot be tested for multiple instances in Win32} MainInstance: LongWord; { Handle of the main(.EXE) HInstance } MainThreadID: LongWord; { ThreadID of thread that module was initialized in } IsLibrary: Boolean; { True if module is a DLL } CmdShow: Integer; { CmdShow parameter for CreateWindow } CmdLine: PChar; { Command line pointer } InitProc: Pointer; { Last installed initialization procedure } ExitCode: Integer; { Program result } ExitProc: Pointer; { Last installed exit procedure } ErrorAddr: Pointer; { Address of run-time error } RandSeed: Longint; { Base for random number generator } IsConsole: Boolean; { True if compiled as console app } IsMultiThread: Boolean; { True if more than one thread } FileMode: Byte; { Standard mode for opening files } Test8086: Byte; { Will always be 2 (386 or later) } Test8087: Byte; { Will always be 3 (387 or later) } TestFDIV: Shortint; { -1: Flawed Pentium, 0: Not determined, 1: Ok } Input: Text; { Standard input } Output: Text; { Standard output } ClearAnyProc: Pointer; { Handler clearing a varAny } ChangeAnyProc: Pointer; { Handler to change any to variant } RefAnyProc: Pointer; { Handler to add a reference to an varAny } var Default8087CW: Word = $1332;{ Default 8087 control word. FPU control register is set to this value. CAUTION: Setting this to an invalid value could cause unpredictable behavior. } HeapAllocFlags: Word = 2; { Heap allocation flags, gmem_Moveable } DebugHook: Byte = 0; { 1 to notify debugger of non-Delphi exceptions >1 to notify debugger of exception unwinding } JITEnable: Byte = 0; { 1 to call UnhandledExceptionFilter if the exception is not a Pascal exception. >1 to call UnhandledExceptionFilter for all exceptions } NoErrMsg: Boolean = False; { True causes the base RTL to not display the message box when a run-time error occurs } var Unassigned: Variant; { Unassigned standard constant } Null: Variant; { Null standard constant } EmptyParam: OleVariant; { "Empty parameter" standard constant which can be passed as an optional parameter on a dual interface. } AllocMemCount: Integer; { Number of allocated memory blocks } AllocMemSize: Integer; { Total size of allocated memory blocks } { Memory manager support } procedure GetMemoryManager(var MemMgr: TMemoryManager); procedure SetMemoryManager(const MemMgr: TMemoryManager); function IsMemoryManagerSet: Boolean; function SysGetMem(Size: Integer): Pointer; function SysFreeMem(P: Pointer): Integer; function SysReallocMem(P: Pointer; Size: Integer): Pointer; function GetHeapStatus: THeapStatus; { Thread support } type TThreadFunc = function(Parameter: Pointer): Integer; function BeginThread(SecurityAttributes: Pointer; StackSize: LongWord; ThreadFunc: TThreadFunc; Parameter: Pointer; CreationFlags: LongWord; var ThreadId: LongWord): Integer; procedure EndThread(ExitCode: Integer); { Standard procedures and functions } procedure _ChDir(const S: string); procedure __Flush(var F: Text); procedure _LGetDir(D: Byte; var S: string); procedure _SGetDir(D: Byte; var S: ShortString); function IOResult: Integer; procedure _MkDir(const S: string); procedure Move(const Source; var Dest; Count: Integer); function ParamCount: Integer; function ParamStr(Index: Integer): string; procedure Randomize; procedure _RmDir(const S: string); function UpCase(Ch: Char): Char; { Control 8087 control word } procedure Set8087CW(NewCW: Word); { Wide character support procedures and functions } function WideCharToString(Source: PWideChar): string; function WideCharLenToString(Source: PWideChar; SourceLen: Integer): string; procedure WideCharToStrVar(Source: PWideChar; var Dest: string); procedure WideCharLenToStrVar(Source: PWideChar; SourceLen: Integer; var Dest: string); function StringToWideChar(const Source: string; Dest: PWideChar; DestSize: Integer): PWideChar; { OLE string support procedures and functions } function OleStrToString(Source: PWideChar): string; procedure OleStrToStrVar(Source: PWideChar; var Dest: string); function StringToOleStr(const Source: string): PWideChar; { Variant support procedures and functions } procedure _VarClear(var V : Variant); procedure _VarCopy(var Dest : Variant; const Source: Variant); procedure _VarCast(var Dest : Variant; const Source: Variant; VarType: Integer); procedure _VarCastOle(var Dest : Variant; const Source: Variant; VarType: Integer); procedure VarCopyNoInd(var Dest: Variant; const Source: Variant); function VarType(const V: Variant): Integer; function VarAsType(const V: Variant; VarType: Integer): Variant; function VarIsEmpty(const V: Variant): Boolean; function VarIsNull(const V: Variant): Boolean; function VarToStr(const V: Variant): string; function VarFromDateTime(DateTime: TDateTime): Variant; function VarToDateTime(const V: Variant): TDateTime; { Variant array support procedures and functions } function VarArrayCreate(const Bounds: array of Integer; VarType: Integer): Variant; function VarArrayOf(const Values: array of Variant): Variant; procedure _VarArrayRedim(var A : Variant; HighBound: Integer); function VarArrayDimCount(const A: Variant): Integer; function VarArrayLowBound(const A: Variant; Dim: Integer): Integer; function VarArrayHighBound(const A: Variant; Dim: Integer): Integer; function VarArrayLock(const A: Variant): Pointer; procedure VarArrayUnlock(const A: Variant); function VarArrayRef(const A: Variant): Variant; function VarIsArray(const A: Variant): Boolean; { Variant IDispatch call support } procedure _DispInvokeError; var VarDispProc: Pointer = @_DispInvokeError; DispCallByIDProc: Pointer = @_DispInvokeError; { Package/Module registration and unregistration } type PLibModule = ^TLibModule; TLibModule = record Next: PLibModule; Instance: LongWord; CodeInstance: LongWord; DataInstance: LongWord; ResInstance: LongWord; Reserved: Integer; end; TEnumModuleFunc = function (HInstance: Integer; Data: Pointer): Boolean; {$EXTERNALSYM TEnumModuleFunc} TEnumModuleFuncLW = function (HInstance: LongWord; Data: Pointer): Boolean; {$EXTERNALSYM TEnumModuleFuncLW} TModuleUnloadProc = procedure (HInstance: Integer); {$EXTERNALSYM TModuleUnloadProc} TModuleUnloadProcLW = procedure (HInstance: LongWord); {$EXTERNALSYM TModuleUnloadProcLW} PModuleUnloadRec = ^TModuleUnloadRec; TModuleUnloadRec = record Next: PModuleUnloadRec; Proc: TModuleUnloadProcLW; end; var LibModuleList: PLibModule = nil; ModuleUnloadList: PModuleUnloadRec = nil; procedure RegisterModule(LibModule: PLibModule); procedure UnregisterModule(LibModule: PLibModule); function FindHInstance(Address: Pointer): LongWord; function FindClassHInstance(ClassType: TClass): LongWord; function FindResourceHInstance(Instance: LongWord): LongWord; function LoadResourceModule(ModuleName: PChar): LongWord; procedure EnumModules(Func: TEnumModuleFunc; Data: Pointer); overload; procedure EnumResourceModules(Func: TEnumModuleFunc; Data: Pointer); overload; procedure EnumModules(Func: TEnumModuleFuncLW; Data: Pointer); overload; procedure EnumResourceModules(Func: TEnumModuleFuncLW; Data: Pointer); overload; procedure AddModuleUnloadProc(Proc: TModuleUnloadProc); overload; procedure RemoveModuleUnloadProc(Proc: TModuleUnloadProc); overload; procedure AddModuleUnloadProc(Proc: TModuleUnloadProcLW); overload; procedure RemoveModuleUnloadProc(Proc: TModuleUnloadProcLW); overload; { ResString support function/record } type PResStringRec = ^TResStringRec; TResStringRec = packed record Module: ^Longint; Identifier: Integer; end; function LoadResString(ResStringRec: PResStringRec): string; { Procedures and functions that need compiler magic } procedure _COS; procedure _EXP; procedure _INT; procedure _SIN; procedure _FRAC; procedure _ROUND; procedure _TRUNC; procedure _AbstractError; procedure _Assert(const Message, Filename: AnsiString; LineNumber: Integer); procedure _Append; procedure _Assign(var T: Text; S: ShortString); procedure _BlockRead; procedure _BlockWrite; procedure _Close; procedure _PStrCat; procedure _PStrNCat; procedure _PStrCpy; procedure _PStrNCpy; procedure _EofFile; procedure _EofText; procedure _Eoln; procedure _Erase; procedure _FilePos; procedure _FileSize; procedure _FillChar; procedure _FreeMem; procedure _GetMem; procedure _ReallocMem; procedure _Halt; procedure _Halt0; procedure _Mark; procedure _PStrCmp; procedure _AStrCmp; procedure _RandInt; procedure _RandExt; procedure _ReadRec; procedure _ReadChar; procedure _ReadLong; procedure _ReadString; procedure _ReadCString; procedure _ReadLString; procedure _ReadExt; procedure _ReadLn; procedure _Rename; procedure _Release; procedure _ResetText(var T: Text); procedure _ResetFile; procedure _RewritText(var T: Text); procedure _RewritFile; procedure _RunError; procedure _Run0Error; procedure _Seek; procedure _SeekEof; procedure _SeekEoln; procedure _SetTextBuf; procedure _StrLong; procedure _Str0Long; procedure _Truncate; procedure _ValLong; procedure _WriteRec; procedure _WriteChar; procedure _Write0Char; procedure _WriteBool; procedure _Write0Bool; procedure _WriteLong; procedure _Write0Long; procedure _WriteString; procedure _Write0String; procedure _WriteCString; procedure _Write0CString; procedure _WriteLString; procedure _Write0LString; function _WriteVariant(var T: Text; const V: Variant; Width: Integer): Pointer; function _Write0Variant(var T: Text; const V: Variant): Pointer; procedure _Write2Ext; procedure _Write1Ext; procedure _Write0Ext; procedure _WriteLn; procedure __CToPasStr; procedure __CLenToPasStr; procedure __ArrayToPasStr; procedure __PasToCStr; procedure __IOTest; procedure _Flush(var F: Text); procedure _SetElem; procedure _SetRange; procedure _SetEq; procedure _SetLe; procedure _SetIntersect; procedure _SetIntersect3; { BEG only } procedure _SetUnion; procedure _SetUnion3; { BEG only } procedure _SetSub; procedure _SetSub3; { BEG only } procedure _SetExpand; procedure _Str2Ext; procedure _Str0Ext; procedure _Str1Ext; procedure _ValExt; procedure _Pow10; procedure _Real2Ext; procedure _Ext2Real; procedure _ObjSetup; procedure _ObjCopy; procedure _Fail; procedure _BoundErr; procedure _IntOver; procedure _StartExe; procedure _StartLib; procedure _PackageLoad (const Table : PackageInfo); procedure _PackageUnload(const Table : PackageInfo); procedure _InitResStrings; procedure _InitResStringImports; procedure _InitImports; procedure _InitWideStrings; procedure _ClassCreate; procedure _ClassDestroy; procedure _AfterConstruction; procedure _BeforeDestruction; procedure _IsClass; procedure _AsClass; procedure _RaiseExcept; procedure _RaiseAgain; procedure _DoneExcept; procedure _TryFinallyExit; procedure _CallDynaInst; procedure _CallDynaClass; procedure _FindDynaInst; procedure _FindDynaClass; procedure _LStrClr(var S: AnsiString); procedure _LStrArrayClr{var str: AnsiString; cnt: longint}; procedure _LStrAsg{var dest: AnsiString; source: AnsiString}; procedure _LStrLAsg{var dest: AnsiString; source: AnsiString}; procedure _LStrFromPCharLen(var Dest: AnsiString; Source: PAnsiChar; Length: Integer); procedure _LStrFromPWCharLen(var Dest: AnsiString; Source: PWideChar; Length: Integer); procedure _LStrFromChar(var Dest: AnsiString; Source: AnsiChar); procedure _LStrFromWChar(var Dest: AnsiString; Source: WideChar); procedure _LStrFromPChar(var Dest: AnsiString; Source: PAnsiChar); procedure _LStrFromPWChar(var Dest: AnsiString; Source: PWideChar); procedure _LStrFromString(var Dest: AnsiString; const Source: ShortString); procedure _LStrFromArray(var Dest: AnsiString; Source: PAnsiChar; Length: Integer); procedure _LStrFromWArray(var Dest: AnsiString; Source: PWideChar; Length: Integer); procedure _LStrFromWStr(var Dest: AnsiString; const Source: WideString); procedure _LStrToString{(var Dest: ShortString; const Source: AnsiString; MaxLen: Integer)}; function _LStrLen{str: AnsiString}: Longint; procedure _LStrCat{var dest: AnsiString; source: AnsiString}; procedure _LStrCat3{var dest:AnsiString; source1: AnsiString; source2: AnsiString}; procedure _LStrCatN{var dest:AnsiString; argCnt: Integer; ...}; procedure _LStrCmp{left: AnsiString; right: AnsiString}; procedure _LStrAddRef{str: AnsiString}; procedure _LStrToPChar{str: AnsiString): PChar}; procedure _Copy{ s : ShortString; index, count : Integer ) : ShortString}; procedure _Delete{ var s : openstring; index, count : Integer }; procedure _Insert{ source : ShortString; var s : openstring; index : Integer }; procedure _Pos{ substr : ShortString; s : ShortString ) : Integer}; procedure _SetLength{var s: ShortString; newLength: Integer}; procedure _SetString{var s: ShortString: buffer: PChar; len: Integer}; procedure UniqueString(var str: string); procedure _NewAnsiString{length: Longint}; { for debugger purposes only } procedure _LStrCopy { const s : AnsiString; index, count : Integer) : AnsiString}; procedure _LStrDelete{ var s : AnsiString; index, count : Integer }; procedure _LStrInsert{ const source : AnsiString; var s : AnsiString; index : Integer }; procedure _LStrPos{ const substr : AnsiString; const s : AnsiString ) : Integer}; procedure _LStrSetLength{ var str: AnsiString; newLength: Integer}; procedure _LStrOfChar{ c: Char; count: Integer): AnsiString }; procedure _WStrClr(var S: WideString); procedure _WStrArrayClr(var StrArray; Count: Integer); procedure _WStrAsg(var Dest: WideString; const Source: WideString); procedure _WStrFromPCharLen(var Dest: WideString; Source: PAnsiChar; Length: Integer); procedure _WStrFromPWCharLen(var Dest: WideString; Source: PWideChar; Length: Integer); procedure _WStrFromChar(var Dest: WideString; Source: AnsiChar); procedure _WStrFromWChar(var Dest: WideString; Source: WideChar); procedure _WStrFromPChar(var Dest: WideString; Source: PAnsiChar); procedure _WStrFromPWChar(var Dest: WideString; Source: PWideChar); procedure _WStrFromString(var Dest: WideString; const Source: ShortString); procedure _WStrFromArray(var Dest: WideString; Source: PAnsiChar; Length: Integer); procedure _WStrFromWArray(var Dest: WideString; Source: PWideChar; Length: Integer); procedure _WStrFromLStr(var Dest: WideString; const Source: AnsiString); procedure _WStrToString(Dest: PShortString; const Source: WideString; MaxLen: Integer); function _WStrToPWChar(const S: WideString): PWideChar; function _WStrLen(const S: WideString): Integer; procedure _WStrCat(var Dest: WideString; const Source: WideString); procedure _WStrCat3(var Dest: WideString; const Source1, Source2: WideString); procedure _WStrCatN{var dest:WideString; argCnt: Integer; ...}; procedure _WStrCmp{left: WideString; right: WideString}; function _NewWideString(Length: Integer): PWideChar; function _WStrCopy(const S: WideString; Index, Count: Integer): WideString; procedure _WStrDelete(var S: WideString; Index, Count: Integer); procedure _WStrInsert(const Source: WideString; var Dest: WideString; Index: Integer); procedure _WStrPos{ const substr : WideString; const s : WideString ) : Integer}; procedure _WStrSetLength(var S: WideString; NewLength: Integer); function _WStrOfWChar(Ch: WideChar; Count: Integer): WideString; procedure _WStrAddRef{var str: WideString}; procedure _Initialize; procedure _InitializeArray; procedure _InitializeRecord; procedure _Finalize; procedure _FinalizeArray; procedure _FinalizeRecord; procedure _AddRef; procedure _AddRefArray; procedure _AddRefRecord; procedure _CopyArray; procedure _CopyRecord; procedure _CopyObject; procedure _New; procedure _Dispose; procedure _DispInvoke; cdecl; procedure _IntfDispCall; cdecl; procedure _IntfVarCall; cdecl; procedure _VarToInt; procedure _VarToBool; procedure _VarToReal; procedure _VarToCurr; procedure _VarToPStr(var S; const V: Variant); procedure _VarToLStr(var S: string; const V: Variant); procedure _VarToWStr(var S: WideString; const V: Variant); procedure _VarToIntf(var Unknown: IUnknown; const V: Variant); procedure _VarToDisp(var Dispatch: IDispatch; const V: Variant); procedure _VarToDynArray(var DynArray: Pointer; const V: Variant; TypeInfo: Pointer); procedure _VarFromInt; procedure _VarFromBool; procedure _VarFromReal; procedure _VarFromTDateTime; procedure _VarFromCurr; procedure _VarFromPStr(var V: Variant; const Value: ShortString); procedure _VarFromLStr(var V: Variant; const Value: string); procedure _VarFromWStr(var V: Variant; const Value: WideString); procedure _VarFromIntf(var V: Variant; const Value: IUnknown); procedure _VarFromDisp(var V: Variant; const Value: IDispatch); procedure _VarFromDynArray(var V: Variant; const DynArray: Pointer; TypeInfo: Pointer); procedure _OleVarFromPStr(var V: OleVariant; const Value: ShortString); procedure _OleVarFromLStr(var V: OleVariant; const Value: string); procedure _OleVarFromVar(var V: OleVariant; const Value: Variant); procedure _VarAdd; procedure _VarSub; procedure _VarMul; procedure _VarDiv; procedure _VarMod; procedure _VarAnd; procedure _VarOr; procedure _VarXor; procedure _VarShl; procedure _VarShr; procedure _VarRDiv; procedure _VarCmp; procedure _VarNeg; procedure _VarNot; procedure _VarCopyNoInd; procedure _VarClr; procedure _VarAddRef; { 64-bit Integer helper routines } procedure __llmul; procedure __lldiv; procedure __lludiv; procedure __llmod; procedure __llmulo; procedure __lldivo; procedure __llmodo; procedure __llumod; procedure __llshl; procedure __llushr; procedure _WriteInt64; procedure _Write0Int64; procedure _ReadInt64; function _StrInt64(val: Int64; width: Integer): ShortString; function _Str0Int64(val: Int64): ShortString; function _ValInt64(const s: AnsiString; var code: Integer): Int64; { Dynamic array helper functions } procedure _DynArrayHigh; procedure _DynArrayClear(var a: Pointer; typeInfo: Pointer); procedure _DynArrayLength; procedure _DynArraySetLength; procedure _DynArrayCopy(a: Pointer; typeInfo: Pointer; var Result: Pointer); procedure _DynArrayCopyRange(a: Pointer; typeInfo: Pointer; index, count : Integer; var Result: Pointer); procedure _DynArrayAsg; procedure _DynArrayAddRef; procedure DynArrayToVariant(var V: Variant; const DynArray: Pointer; TypeInfo: Pointer); procedure DynArrayFromVariant(var DynArray: Pointer; const V: Variant; TypeInfo: Pointer); procedure _IntfClear(var Dest: IUnknown); procedure _IntfCopy(var Dest: IUnknown; const Source: IUnknown); procedure _IntfCast(var Dest: IUnknown; const Source: IUnknown; const IID: TGUID); procedure _IntfAddRef(const Dest: IUnknown); function _VarArrayGet(var A: Variant; IndexCount: Integer; Indices: Integer): Variant; cdecl; procedure _VarArrayPut(var A: Variant; const Value: Variant; IndexCount: Integer; Indices: Integer); cdecl; procedure _HandleAnyException; procedure _HandleOnException; procedure _HandleFinally; procedure _HandleAutoException; procedure _FSafeDivide; procedure _FSafeDivideR; procedure _CheckAutoResult; procedure FPower10; procedure TextStart; function CompToDouble(acomp: Comp): Double; cdecl; procedure DoubleToComp(adouble: Double; var result: Comp); cdecl; function CompToCurrency(acomp: Comp): Currency; cdecl; procedure CurrencyToComp(acurrency: Currency; var result: Comp); cdecl; function GetMemory(Size: Integer): Pointer; cdecl; function FreeMemory(P: Pointer): Integer; cdecl; function ReallocMemory(P: Pointer; Size: Integer): Pointer; cdecl; (* =================================================================== *) implementation uses SysInit; { Internal runtime error codes } const reOutOfMemory = 1; reInvalidPtr = 2; reDivByZero = 3; reRangeError = 4; reIntOverflow = 5; reInvalidOp = 6; reZeroDivide = 7; reOverflow = 8; reUnderflow = 9; reInvalidCast = 10; reAccessViolation = 11; reStackOverflow = 12; reControlBreak = 13; rePrivInstruction = 14; reVarTypeCast = 15; reVarInvalidOp = 16; reVarDispatch = 17; reVarArrayCreate = 18; reVarNotArray = 19; reVarArrayBounds = 20; reAssertionFailed = 21; reExternalException = 22; { not used here; in SysUtils } reIntfCastError = 23; reSafeCallError = 24; { this procedure should be at the very beginning of the } { text segment. it is only used by _RunError to find } { start address of the text segment so a nice error } { location can be shown. } procedure TextStart; begin end; { ----------------------------------------------------- } { NT Calls necessary for the .asm files } { ----------------------------------------------------- } type PMemInfo = ^TMemInfo; TMemInfo = packed record BaseAddress: Pointer; AllocationBase: Pointer; AllocationProtect: Longint; RegionSize: Longint; State: Longint; Protect: Longint; Type_9 : Longint; end; PStartupInfo = ^TStartupInfo; TStartupInfo = record cb: Longint; lpReserved: Pointer; lpDesktop: Pointer; lpTitle: Pointer; dwX: Longint; dwY: Longint; dwXSize: Longint; dwYSize: Longint; dwXCountChars: Longint; dwYCountChars: Longint; dwFillAttribute: Longint; dwFlags: Longint; wShowWindow: Word; cbReserved2: Word; lpReserved2: ^Byte; hStdInput: Integer; hStdOutput: Integer; hStdError: Integer; end; TWin32FindData = packed record dwFileAttributes: Integer; ftCreationTime: Int64; ftLastAccessTime: Int64; ftLastWriteTime: Int64; nFileSizeHigh: Integer; nFileSizeLow: Integer; dwReserved0: Integer; dwReserved1: Integer; cFileName: array[0..259] of Char; cAlternateFileName: array[0..13] of Char; end; const advapi32 = 'advapi32.dll'; kernel = 'kernel32.dll'; user = 'user32.dll'; oleaut = 'oleaut32.dll'; procedure CloseHandle; external kernel name 'CloseHandle'; procedure CreateFileA; external kernel name 'CreateFileA'; procedure DeleteFileA; external kernel name 'DeleteFileA'; procedure GetFileType; external kernel name 'GetFileType'; procedure GetSystemTime; external kernel name 'GetSystemTime'; procedure GetFileSize; external kernel name 'GetFileSize'; procedure GetStdHandle; external kernel name 'GetStdHandle'; //procedure GetStartupInfo; external kernel name 'GetStartupInfo'; procedure MoveFileA; external kernel name 'MoveFileA'; procedure RaiseException; external kernel name 'RaiseException'; procedure ReadFile; external kernel name 'ReadFile'; procedure RtlUnwind; external kernel name 'RtlUnwind'; procedure SetEndOfFile; external kernel name 'SetEndOfFile'; procedure SetFilePointer; external kernel name 'SetFilePointer'; procedure UnhandledExceptionFilter; external kernel name 'UnhandledExceptionFilter'; procedure WriteFile; external kernel name 'WriteFile'; function CharNext(lpsz: PChar): PChar; stdcall; external user name 'CharNextA'; function CreateThread(SecurityAttributes: Pointer; StackSize: LongWord; ThreadFunc: TThreadFunc; Parameter: Pointer; CreationFlags: LongWord; var ThreadId: LongWord): Integer; stdcall; external kernel name 'CreateThread'; procedure ExitThread(ExitCode: Integer); stdcall; external kernel name 'ExitThread'; procedure ExitProcess(ExitCode: Integer); stdcall; external kernel name 'ExitProcess'; procedure MessageBox(Wnd: Integer; Text: PChar; Caption: PChar; Typ: Integer); stdcall; external user name 'MessageBoxA'; function CreateDirectory(PathName: PChar; Attr: Integer): WordBool; stdcall; external kernel name 'CreateDirectoryA'; function FindClose(FindFile: Integer): LongBool; stdcall; external kernel name 'FindClose'; function FindFirstFile(FileName: PChar; var FindFileData: TWIN32FindData): Integer; stdcall; external kernel name 'FindFirstFileA'; function FreeLibrary(ModuleHandle: Longint): LongBool; stdcall; external kernel name 'FreeLibrary'; function GetCommandLine: PChar; stdcall; external kernel name 'GetCommandLineA'; function GetCurrentDirectory(BufSize: Integer; Buffer: PChar): Integer; stdcall; external kernel name 'GetCurrentDirectoryA'; function GetLastError: Integer; stdcall; external kernel name 'GetLastError'; function GetLocaleInfo(Locale: Longint; LCType: Longint; lpLCData: PChar; cchData: Integer): Integer; stdcall; external kernel name 'GetLocaleInfoA'; function GetModuleFileName(Module: Integer; Filename: PChar; Size: Integer): Integer; stdcall; external kernel name 'GetModuleFileNameA'; function GetModuleHandle(ModuleName: PChar): Integer; stdcall; external kernel name 'GetModuleHandleA'; function GetProcAddress(Module: Integer; ProcName: PChar): Pointer; stdcall; external kernel name 'GetProcAddress'; procedure GetStartupInfo(var lpStartupInfo: TStartupInfo); stdcall; external kernel name 'GetStartupInfoA'; function GetThreadLocale: Longint; stdcall; external kernel name 'GetThreadLocale'; function LoadLibraryEx(LibName: PChar; hFile: Longint; Flags: Longint): Longint; stdcall; external kernel name 'LoadLibraryExA'; function LoadString(Instance: Longint; IDent: Integer; Buffer: PChar; Size: Integer): Integer; stdcall; external user name 'LoadStringA'; {function lstrcat(lpString1, lpString2: PChar): PChar; stdcall; external kernel name 'lstrcatA';} function lstrcpy(lpString1, lpString2: PChar): PChar; stdcall; external kernel name 'lstrcpyA'; function lstrcpyn(lpString1, lpString2: PChar; iMaxLength: Integer): PChar; stdcall; external kernel name 'lstrcpynA'; function lstrlen(lpString: PChar): Integer; stdcall; external kernel name 'lstrlenA'; function MultiByteToWideChar(CodePage, Flags: Integer; MBStr: PChar; MBCount: Integer; WCStr: PWideChar; WCCount: Integer): Integer; stdcall; external kernel name 'MultiByteToWideChar'; function RegCloseKey(hKey: Integer): Longint; stdcall; external advapi32 name 'RegCloseKey'; function RegOpenKeyEx(hKey: LongWord; lpSubKey: PChar; ulOptions, samDesired: LongWord; var phkResult: LongWord): Longint; stdcall; external advapi32 name 'RegOpenKeyExA'; function RegQueryValueEx(hKey: LongWord; lpValueName: PChar; lpReserved: Pointer; lpType: Pointer; lpData: PChar; lpcbData: Pointer): Integer; stdcall; external advapi32 name 'RegQueryValueExA'; function RemoveDirectory(PathName: PChar): WordBool; stdcall; external kernel name 'RemoveDirectoryA'; function SetCurrentDirectory(PathName: PChar): WordBool; stdcall; external kernel name 'SetCurrentDirectoryA'; function WideCharToMultiByte(CodePage, Flags: Integer; WCStr: PWideChar; WCCount: Integer; MBStr: PChar; MBCount: Integer; DefaultChar: PChar; UsedDefaultChar: Pointer): Integer; stdcall; external kernel name 'WideCharToMultiByte'; function VirtualQuery(lpAddress: Pointer; var lpBuffer: TMemInfo; dwLength: Longint): Longint; stdcall; external kernel name 'VirtualQuery'; //function SysAllocString(P: PWideChar): PWideChar; stdcall; // external oleaut name 'SysAllocString'; function SysAllocStringLen(P: PWideChar; Len: Integer): PWideChar; stdcall; external oleaut name 'SysAllocStringLen'; function SysReAllocStringLen(var S: WideString; P: PWideChar; Len: Integer): LongBool; stdcall; external oleaut name 'SysReAllocStringLen'; procedure SysFreeString(const S: WideString); stdcall; external oleaut name 'SysFreeString'; function SysStringLen(const S: WideString): Integer; stdcall; external oleaut name 'SysStringLen'; //procedure VariantInit(var V: Variant); stdcall; // external oleaut name 'VariantInit'; function VariantClear(var V: Variant): Integer; stdcall; external oleaut name 'VariantClear'; function VariantCopy(var Dest: Variant; const Source: Variant): Integer; stdcall; external oleaut name 'VariantCopy'; function VariantCopyInd(var Dest: Variant; const Source: Variant): Integer; stdcall; external oleaut name 'VariantCopyInd'; //function VariantChangeType(var Dest: Variant; const Source: Variant; // Flags: Word; VarType: Word): Integer; stdcall; // external oleaut name 'VariantChangeType'; function VariantChangeTypeEx(var Dest: Variant; const Source: Variant; LCID: Integer; Flags: Word; VarType: Word): Integer; stdcall; external oleaut name 'VariantChangeTypeEx'; function SafeArrayCreate(VarType, DimCount: Integer; const Bounds): PVarArray; stdcall; external oleaut name 'SafeArrayCreate'; function SafeArrayRedim(VarArray: PVarArray; var NewBound: TVarArrayBound): Integer; stdcall; external oleaut name 'SafeArrayRedim'; function SafeArrayGetLBound(VarArray: PVarArray; Dim: Integer; var LBound: Integer): Integer; stdcall; external oleaut name 'SafeArrayGetLBound'; function SafeArrayGetUBound(VarArray: PVarArray; Dim: Integer; var UBound: Integer): Integer; stdcall; external oleaut name 'SafeArrayGetUBound'; function SafeArrayAccessData(VarArray: PVarArray; var Data: Pointer): Integer; stdcall; external oleaut name 'SafeArrayAccessData'; function SafeArrayUnaccessData(VarArray: PVarArray): Integer; stdcall; external oleaut name 'SafeArrayUnaccessData'; function SafeArrayGetElement(VarArray: PVarArray; Indices, Data: Pointer): Integer; stdcall; external oleaut name 'SafeArrayGetElement'; function SafeArrayPtrOfIndex(VarArray: PVarArray; Indices: Pointer; var pvData: Pointer): HResult; stdcall; external oleaut name 'SafeArrayPtrOfIndex'; function SafeArrayPutElement(VarArray: PVarArray; Indices, Data: Pointer): Integer; stdcall; external oleaut name 'SafeArrayPutElement'; function InterlockedIncrement(var Addend: Integer): Integer; stdcall; external kernel name 'InterlockedIncrement'; function InterlockedDecrement(var Addend: Integer): Integer; stdcall; external kernel name 'InterlockedDecrement'; function GetCmdShow: Integer; var SI: TStartupInfo; begin Result := 10; { SW_SHOWDEFAULT } GetStartupInfo(SI); if SI.dwFlags and 1 <> 0 then { STARTF_USESHOWWINDOW } Result := SI.wShowWindow; end; { ----------------------------------------------------- } { Memory manager } { ----------------------------------------------------- } procedure Error(errorCode: Byte); forward; {$I GETMEM.INC } var MemoryManager: TMemoryManager = ( GetMem: SysGetMem; FreeMem: SysFreeMem; ReallocMem: SysReallocMem); procedure _GetMem; asm TEST EAX,EAX JE @@1 CALL MemoryManager.GetMem OR EAX,EAX JE @@2 @@1: RET @@2: MOV AL,reOutOfMemory JMP Error end; procedure _FreeMem; asm TEST EAX,EAX JE @@1 CALL MemoryManager.FreeMem OR EAX,EAX JNE @@2 @@1: RET @@2: MOV AL,reInvalidPtr JMP Error end; procedure _ReallocMem; asm MOV ECX,[EAX] TEST ECX,ECX JE @@alloc TEST EDX,EDX JE @@free @@resize: PUSH EAX MOV EAX,ECX CALL MemoryManager.ReallocMem POP ECX OR EAX,EAX JE @@allocError MOV [ECX],EAX RET @@freeError: MOV AL,reInvalidPtr JMP Error @@free: MOV [EAX],EDX MOV EAX,ECX CALL MemoryManager.FreeMem OR EAX,EAX JNE @@freeError RET @@allocError: MOV AL,reOutOfMemory JMP Error @@alloc: TEST EDX,EDX JE @@exit PUSH EAX MOV EAX,EDX CALL MemoryManager.GetMem POP ECX OR EAX,EAX JE @@allocError MOV [ECX],EAX @@exit: end; procedure GetMemoryManager(var MemMgr: TMemoryManager); begin MemMgr := MemoryManager; end; procedure SetMemoryManager(const MemMgr: TMemoryManager); begin MemoryManager := MemMgr; end; function IsMemoryManagerSet: Boolean; begin with MemoryManager do Result := (@GetMem <> @SysGetMem) or (@FreeMem <> @SysFreeMem) or (@ReallocMem <> @SysReallocMem); end; threadvar RaiseListPtr: pointer; InOutRes: Integer; function RaiseList: Pointer; asm CALL SysInit.@GetTLS MOV EAX, [EAX].RaiseListPtr end; function SetRaiseList(NewPtr: Pointer): Pointer; asm MOV ECX, EAX CALL SysInit.@GetTLS MOV EDX, [EAX].RaiseListPtr MOV [EAX].RaiseListPtr, ECX MOV EAX, EDX end; { ----------------------------------------------------- } { local functions & procedures of the system unit } { ----------------------------------------------------- } procedure Error(errorCode: Byte); asm AND EAX,127 MOV ECX,ErrorProc TEST ECX,ECX JE @@term POP EDX CALL ECX @@term: DEC EAX MOV AL,byte ptr @@errorTable[EAX] JNS @@skip CALL SysInit.@GetTLS MOV EAX,[EAX].InOutRes @@skip: JMP _RunError @@errorTable: DB 203 { reOutOfMemory } DB 204 { reInvalidPtr } DB 200 { reDivByZero } DB 201 { reRangeError } { 210 abstract error } DB 215 { reIntOverflow } DB 207 { reInvalidOp } DB 200 { reZeroDivide } DB 205 { reOverflow } DB 206 { reUnderflow } DB 219 { reInvalidCast } DB 216 { Access violation } DB 202 { Stack overflow } DB 217 { Control-C } DB 218 { Privileged instruction } DB 220 { Invalid variant type cast } DB 221 { Invalid variant operation } DB 222 { No variant method call dispatcher } DB 223 { Cannot create variant array } DB 224 { Variant does not contain an array } DB 225 { Variant array bounds error } { 226 thread init failure } DB 227 { reAssertionFailed } DB 0 { reExternalException not used here; in SysUtils } DB 228 { reIntfCastError } DB 229 { reSafeCallError } end; procedure __IOTest; asm PUSH EAX PUSH EDX PUSH ECX CALL SysInit.@GetTLS CMP [EAX].InOutRes,0 POP ECX POP EDX POP EAX JNE @error RET @error: XOR EAX,EAX JMP Error end; procedure SetInOutRes; asm PUSH EAX CALL SysInit.@GetTLS POP [EAX].InOutRes end; procedure InOutError; asm CALL GetLastError JMP SetInOutRes end; procedure _ChDir(const S: string); begin if not SetCurrentDirectory(PChar(S)) then InOutError; end; procedure _Copy{ s : ShortString; index, count : Integer ) : ShortString}; asm { ->EAX Source string } { EDX index } { ECX count } { [ESP+4] Pointer to result string } PUSH ESI PUSH EDI MOV ESI,EAX MOV EDI,[ESP+8+4] XOR EAX,EAX OR AL,[ESI] JZ @@srcEmpty { limit index to satisfy 1 <= index <= Length(src) } TEST EDX,EDX JLE @@smallInx CMP EDX,EAX JG @@bigInx @@cont1: { limit count to satisfy 0 <= count <= Length(src) - index + 1 } SUB EAX,EDX { calculate Length(src) - index + 1 } INC EAX TEST ECX,ECX JL @@smallCount CMP ECX,EAX JG @@bigCount @@cont2: ADD ESI,EDX MOV [EDI],CL INC EDI REP MOVSB JMP @@exit @@smallInx: MOV EDX,1 JMP @@cont1 @@bigInx: { MOV EDX,EAX JMP @@cont1 } @@smallCount: XOR ECX,ECX JMP @@cont2 @@bigCount: MOV ECX,EAX JMP @@cont2 @@srcEmpty: MOV [EDI],AL @@exit: POP EDI POP ESI RET 4 end; procedure _Delete{ var s : openstring; index, count : Integer }; asm { ->EAX Pointer to s } { EDX index } { ECX count } PUSH ESI PUSH EDI MOV EDI,EAX XOR EAX,EAX MOV AL,[EDI] { if index not in [1 .. Length(s)] do nothing } TEST EDX,EDX JLE @@exit CMP EDX,EAX JG @@exit { limit count to [0 .. Length(s) - index + 1] } TEST ECX,ECX JLE @@exit SUB EAX,EDX { calculate Length(s) - index + 1 } INC EAX CMP ECX,EAX JLE @@1 MOV ECX,EAX @@1: SUB [EDI],CL { reduce Length(s) by count } ADD EDI,EDX { point EDI to first char to be deleted } LEA ESI,[EDI+ECX] { point ESI to first char to be preserved } SUB EAX,ECX { #chars = Length(s) - index + 1 - count } MOV ECX,EAX REP MOVSB @@exit: POP EDI POP ESI end; procedure __Flush( var f : Text ); external; { Assign } procedure _Flush( var f : Text ); external; { Assign } procedure _LGetDir(D: Byte; var S: string); var Drive: array[0..3] of Char; DirBuf, SaveBuf: array[0..259] of Char; begin if D <> 0 then begin Drive[0] := Chr(D + Ord('A') - 1); Drive[1] := ':'; Drive[2] := #0; GetCurrentDirectory(SizeOf(SaveBuf), SaveBuf); SetCurrentDirectory(Drive); end; GetCurrentDirectory(SizeOf(DirBuf), DirBuf); if D <> 0 then SetCurrentDirectory(SaveBuf); S := DirBuf; end; procedure _SGetDir(D: Byte; var S: ShortString); var L: string; begin GetDir(D, L); S := L; end; procedure _Insert{ source : ShortString; var s : openstring; index : Integer }; asm { ->EAX Pointer to source string } { EDX Pointer to destination string } { ECX Length of destination string } { [ESP+4] Index } PUSH EBX PUSH ESI PUSH EDI PUSH ECX MOV ECX,[ESP+16+4] SUB ESP,512 { VAR buf: ARRAY [0..511] of Char } MOV EBX,EDX { save pointer to s for later } MOV ESI,EDX XOR EDX,EDX MOV DL,[ESI] INC ESI { limit index to [1 .. Length(s)+1] } INC EDX TEST ECX,ECX JLE @@smallInx CMP ECX,EDX JG @@bigInx @@cont1: DEC EDX { EDX = Length(s) } { EAX = Pointer to src } { ESI = EBX = Pointer to s } { ECX = Index } { copy index-1 chars from s to buf } MOV EDI,ESP DEC ECX SUB EDX,ECX { EDX = remaining length of s } REP MOVSB { copy Length(src) chars from src to buf } XCHG EAX,ESI { save pointer into s, point ESI to src } MOV CL,[ESI] { ECX = Length(src) (ECX was zero after rep) } INC ESI REP MOVSB { copy remaining chars of s to buf } MOV ESI,EAX { restore pointer into s } MOV ECX,EDX { copy remaining bytes of s } REP MOVSB { calculate total chars in buf } SUB EDI,ESP { length = bufPtr - buf } MOV ECX,[ESP+512] { ECX = Min(length, destLength) } { MOV ECX,[EBP-16] }{ ECX = Min(length, destLength) } CMP ECX,EDI JB @@1 MOV ECX,EDI @@1: MOV EDI,EBX { Point EDI to s } MOV ESI,ESP { Point ESI to buf } MOV [EDI],CL { Store length in s } INC EDI REP MOVSB { Copy length chars to s } JMP @@exit @@smallInx: MOV ECX,1 JMP @@cont1 @@bigInx: MOV ECX,EDX JMP @@cont1 @@exit: ADD ESP,512+4 POP EDI POP ESI POP EBX RET 4 end; function IOResult: Integer; asm CALL SysInit.@GetTLS XOR EDX,EDX MOV ECX,[EAX].InOutRes MOV [EAX].InOutRes,EDX MOV EAX,ECX end; procedure _MkDir(const S: string); begin if not CreateDirectory(PChar(S), 0) then InOutError; end; procedure Move( const Source; var Dest; count : Integer ); asm { ->EAX Pointer to source } { EDX Pointer to destination } { ECX Count } PUSH ESI PUSH EDI MOV ESI,EAX MOV EDI,EDX MOV EAX,ECX CMP EDI,ESI JA @@down JE @@exit SAR ECX,2 { copy count DIV 4 dwords } JS @@exit REP MOVSD MOV ECX,EAX AND ECX,03H REP MOVSB { copy count MOD 4 bytes } JMP @@exit @@down: LEA ESI,[ESI+ECX-4] { point ESI to last dword of source } LEA EDI,[EDI+ECX-4] { point EDI to last dword of dest } SAR ECX,2 { copy count DIV 4 dwords } JS @@exit STD REP MOVSD MOV ECX,EAX AND ECX,03H { copy count MOD 4 bytes } ADD ESI,4-1 { point to last byte of rest } ADD EDI,4-1 REP MOVSB CLD @@exit: POP EDI POP ESI end; function GetParamStr(P: PChar; var Param: string): PChar; var Len: Integer; Buffer: array[0..4095] of Char; begin while True do begin while (P[0] <> #0) and (P[0] <= ' ') do Inc(P); if (P[0] = '"') and (P[1] = '"') then Inc(P, 2) else Break; end; Len := 0; while (P[0] > ' ') and (Len < SizeOf(Buffer)) do if P[0] = '"' then begin Inc(P); while (P[0] <> #0) and (P[0] <> '"') do begin Buffer[Len] := P[0]; Inc(Len); Inc(P); end; if P[0] <> #0 then Inc(P); end else begin Buffer[Len] := P[0]; Inc(Len); Inc(P); end; SetString(Param, Buffer, Len); Result := P; end; function ParamCount: Integer; var P: PChar; S: string; begin P := GetParamStr(GetCommandLine, S); Result := 0; while True do begin P := GetParamStr(P, S); if S = '' then Break; Inc(Result); end; end; function ParamStr(Index: Integer): string; var P: PChar; Buffer: array[0..260] of Char; begin if Index = 0 then SetString(Result, Buffer, GetModuleFileName(0, Buffer, SizeOf(Buffer))) else begin P := GetCommandLine; while True do begin P := GetParamStr(P, Result); if (Index = 0) or (Result = '') then Break; Dec(Index); end; end; end; procedure _Pos{ substr : ShortString; s : ShortString ) : Integer}; asm { ->EAX Pointer to substr } { EDX Pointer to string } { <-EAX Position of substr in s or 0 } PUSH EBX PUSH ESI PUSH EDI MOV ESI,EAX { Point ESI to substr } MOV EDI,EDX { Point EDI to s } XOR ECX,ECX { ECX = Length(s) } MOV CL,[EDI] INC EDI { Point EDI to first char of s } PUSH EDI { remember s position to calculate index } XOR EDX,EDX { EDX = Length(substr) } MOV DL,[ESI] INC ESI { Point ESI to first char of substr } DEC EDX { EDX = Length(substr) - 1 } JS @@fail { < 0 ? return 0 } MOV AL,[ESI] { AL = first char of substr } INC ESI { Point ESI to 2'nd char of substr } SUB ECX,EDX { #positions in s to look at } { = Length(s) - Length(substr) + 1 } JLE @@fail @@loop: REPNE SCASB JNE @@fail MOV EBX,ECX { save outer loop counter } PUSH ESI { save outer loop substr pointer } PUSH EDI { save outer loop s pointer } MOV ECX,EDX REPE CMPSB POP EDI { restore outer loop s pointer } POP ESI { restore outer loop substr pointer } JE @@found MOV ECX,EBX { restore outer loop counter } JMP @@loop @@fail: POP EDX { get rid of saved s pointer } XOR EAX,EAX JMP @@exit @@found: POP EDX { restore pointer to first char of s } MOV EAX,EDI { EDI points of char after match } SUB EAX,EDX { the difference is the correct index } @@exit: POP EDI POP ESI POP EBX end; procedure _SetLength{var s: ShortString; newLength: Integer}; asm { -> EAX pointer to string } { EDX new length } MOV [EAX],DL { should also fill new space, parameter should be openstring } end; procedure _SetString{var s: ShortString: buffer: PChar; len: Integer}; asm { -> EAX pointer to string } { EDX pointer to buffer } { ECX len } MOV [EAX],CL TEST EDX,EDX JE @@noMove XCHG EAX,EDX INC EDX CALL Move @@noMove: end; procedure Randomize; var systemTime : record wYear : Word; wMonth : Word; wDayOfWeek : Word; wDay : Word; wHour : Word; wMinute : Word; wSecond : Word; wMilliSeconds: Word; reserved : array [0..7] of char; end; asm LEA EAX,systemTime PUSH EAX CALL GetSystemTime MOVZX EAX,systemTime.wHour IMUL EAX,60 ADD AX,systemTime.wMinute { sum = hours * 60 + minutes } IMUL EAX,60 XOR EDX,EDX MOV DX,systemTime.wSecond ADD EAX,EDX { sum = sum * 60 + seconds } IMUL EAX,1000 MOV DX,systemTime.wMilliSeconds ADD EAX,EDX { sum = sum * 1000 + milliseconds } MOV RandSeed,EAX end; procedure _RmDir(const S: string); begin if not RemoveDirectory(PChar(S)) then InOutError; end; function UpCase( ch : Char ) : Char; asm { -> AL Character } { <- AL Result } CMP AL,'a' JB @@exit CMP AL,'z' JA @@exit SUB AL,'a' - 'A' @@exit: end; procedure Set8087CW(NewCW: Word); asm MOV Default8087CW,AX FNCLEX // don't raise pending exceptions enabled by the new flags FLDCW Default8087CW end; { ----------------------------------------------------- } { functions & procedures that need compiler magic } { ----------------------------------------------------- } const cwChop : Word = $1F32; procedure _COS; asm FCOS FNSTSW AX SAHF JP @@outOfRange RET @@outOfRange: FSTP st(0) { for now, return 0. result would } FLDZ { have little significance anyway } end; procedure _EXP; asm { e**x = 2**(x*log2(e)) } FLDL2E { y := x*log2e; } FMUL FLD ST(0) { i := round(y); } FRNDINT FSUB ST(1), ST { f := y - i; } FXCH ST(1) { z := 2**f } F2XM1 FLD1 FADD FSCALE { result := z * 2**i } FSTP ST(1) end; procedure _INT; asm SUB ESP,4 FSTCW [ESP] FWAIT FLDCW cwChop FRNDINT FWAIT FLDCW [ESP] ADD ESP,4 end; procedure _SIN; asm FSIN FNSTSW AX SAHF JP @@outOfRange RET @@outOfRange: FSTP st(0) { for now, return 0. result would } FLDZ { have little significance anyway } end; procedure _FRAC; asm FLD ST(0) SUB ESP,4 FSTCW [ESP] FWAIT FLDCW cwChop FRNDINT FWAIT FLDCW [ESP] ADD ESP,4 FSUB end; procedure _ROUND; asm { -> FST(0) Extended argument } { <- EDX:EAX Result } SUB ESP,8 FISTP qword ptr [ESP] FWAIT POP EAX POP EDX end; procedure _TRUNC; asm { -> FST(0) Extended argument } { <- EDX:EAX Result } SUB ESP,12 FSTCW [ESP] FWAIT FLDCW cwChop FISTP qword ptr [ESP+4] FWAIT FLDCW [ESP] POP ECX POP EAX POP EDX end; procedure _AbstractError; asm CMP AbstractErrorProc, 0 JE @@NoAbstErrProc CALL AbstractErrorProc @@NoAbstErrProc: MOV EAX,210 JMP _RunError end; procedure _Append; external; { OpenText} procedure _Assign(var t: text; s: ShortString); external; {$L Assign } procedure _BlockRead; external; {$L BlockRea} procedure _BlockWrite; external; {$L BlockWri} procedure _Close; external; {$L Close } procedure _PStrCat; asm { ->EAX = Pointer to destination string } { EDX = Pointer to source string } PUSH ESI PUSH EDI { load dest len into EAX } MOV EDI,EAX XOR EAX,EAX MOV AL,[EDI] { load source address in ESI, source len in ECX } MOV ESI,EDX XOR ECX,ECX MOV CL,[ESI] INC ESI { calculate final length in DL and store it in the destination } MOV DL,AL ADD DL,CL JC @@trunc @@cont: MOV [EDI],DL { calculate final dest address } INC EDI ADD EDI,EAX { do the copy } REP MOVSB { done } POP EDI POP ESI RET @@trunc: INC DL { DL = #chars to truncate } SUB CL,DL { CL = source len - #chars to truncate } MOV DL,255 { DL = maximum length } JMP @@cont end; procedure _PStrNCat; asm { ->EAX = Pointer to destination string } { EDX = Pointer to source string } { CL = max length of result (allocated size of dest - 1) } PUSH ESI PUSH EDI { load dest len into EAX } MOV EDI,EAX XOR EAX,EAX MOV AL,[EDI] { load source address in ESI, source len in EDX } MOV ESI,EDX XOR EDX,EDX MOV DL,[ESI] INC ESI { calculate final length in AL and store it in the destination } ADD AL,DL JC @@trunc CMP AL,CL JA @@trunc @@cont: MOV ECX,EDX MOV DL,[EDI] MOV [EDI],AL { calculate final dest address } INC EDI ADD EDI,EDX { do the copy } REP MOVSB @@done: POP EDI POP ESI RET @@trunc: { CL = maxlen } MOV AL,CL { AL = final length = maxlen } SUB CL,[EDI] { CL = length to copy = maxlen - destlen } JBE @@done MOV DL,CL JMP @@cont end; procedure _PStrCpy; asm { ->EAX = Pointer to dest string } { EDX = Pointer to source string } XOR ECX,ECX PUSH ESI PUSH EDI MOV CL,[EDX] MOV EDI,EAX INC ECX { we must copy len+1 bytes } MOV ESI,EDX MOV EAX,ECX SHR ECX,2 AND EAX,3 REP MOVSD MOV ECX,EAX REP MOVSB POP EDI POP ESI end; procedure _PStrNCpy; asm { ->EAX = Pointer to dest string } { EDX = Pointer to source string } { CL = Maximum length to copy (allocated size of dest - 1) } PUSH ESI PUSH EDI MOV EDI,EAX XOR EAX,EAX MOV ESI,EDX MOV AL,[EDX] CMP AL,CL JA @@trunc INC EAX MOV ECX,EAX AND EAX,3 SHR ECX,2 REP MOVSD MOV ECX,EAX REP MOVSB POP EDI POP ESI RET @@trunc: MOV [EDI],CL { result length is maxLen } INC ESI { advance pointers } INC EDI AND ECX,0FFH { should be cheaper than MOVZX } REP MOVSB { copy maxLen bytes } POP EDI POP ESI end; procedure _PStrCmp; asm { ->EAX = Pointer to left string } { EDX = Pointer to right string } PUSH EBX PUSH ESI PUSH EDI MOV ESI,EAX MOV EDI,EDX XOR EAX,EAX XOR EDX,EDX MOV AL,[ESI] MOV DL,[EDI] INC ESI INC EDI SUB EAX,EDX { eax = len1 - len2 } JA @@skip1 ADD EDX,EAX { edx = len2 + (len1 - len2) = len1 } @@skip1: PUSH EDX SHR EDX,2 JE @@cmpRest @@longLoop: MOV ECX,[ESI] MOV EBX,[EDI] CMP ECX,EBX JNE @@misMatch DEC EDX JE @@cmpRestP4 MOV ECX,[ESI+4] MOV EBX,[EDI+4] CMP ECX,EBX JNE @@misMatch ADD ESI,8 ADD EDI,8 DEC EDX JNE @@longLoop JMP @@cmpRest @@cmpRestP4: ADD ESI,4 ADD EDI,4 @@cmpRest: POP EDX AND EDX,3 JE @@equal MOV CL,[ESI] CMP CL,[EDI] JNE @@exit DEC EDX JE @@equal MOV CL,[ESI+1] CMP CL,[EDI+1] JNE @@exit DEC EDX JE @@equal MOV CL,[ESI+2] CMP CL,[EDI+2] JNE @@exit @@equal: ADD EAX,EAX JMP @@exit @@misMatch: POP EDX CMP CL,BL JNE @@exit CMP CH,BH JNE @@exit SHR ECX,16 SHR EBX,16 CMP CL,BL JNE @@exit CMP CH,BH @@exit: POP EDI POP ESI POP EBX end; procedure _AStrCmp; asm { ->EAX = Pointer to left string } { EDX = Pointer to right string } { ECX = Number of chars to compare} PUSH EBX PUSH ESI PUSH ECX MOV ESI,ECX SHR ESI,2 JE @@cmpRest @@longLoop: MOV ECX,[EAX] MOV EBX,[EDX] CMP ECX,EBX JNE @@misMatch DEC ESI JE @@cmpRestP4 MOV ECX,[EAX+4] MOV EBX,[EDX+4] CMP ECX,EBX JNE @@misMatch ADD EAX,8 ADD EDX,8 DEC ESI JNE @@longLoop JMP @@cmpRest @@cmpRestp4: ADD EAX,4 ADD EDX,4 @@cmpRest: POP ESI AND ESI,3 JE @@exit MOV CL,[EAX] CMP CL,[EDX] JNE @@exit DEC ESI JE @@equal MOV CL,[EAX+1] CMP CL,[EDX+1] JNE @@exit DEC ESI JE @@equal MOV CL,[EAX+2] CMP CL,[EDX+2] JNE @@exit @@equal: XOR EAX,EAX JMP @@exit @@misMatch: POP ESI CMP CL,BL JNE @@exit CMP CH,BH JNE @@exit SHR ECX,16 SHR EBX,16 CMP CL,BL JNE @@exit CMP CH,BH @@exit: POP ESI POP EBX end; procedure _EofFile; external; {$L EofFile } procedure _EofText; external; {$L EofText } procedure _Eoln; external; {$L Eoln } procedure _Erase; external; {$L Erase } procedure _FSafeDivide; external; {$L FDIV } procedure _FSafeDivideR; external; { FDIV } procedure _FilePos; external; {$L FilePos } procedure _FileSize; external; {$L FileSize} procedure _FillChar; asm { ->EAX Pointer to destination } { EDX count } { CL value } PUSH EDI MOV EDI,EAX { Point EDI to destination } MOV CH,CL { Fill EAX with value repeated 4 times } MOV EAX,ECX SHL EAX,16 MOV AX,CX MOV ECX,EDX SAR ECX,2 JS @@exit REP STOSD { Fill count DIV 4 dwords } MOV ECX,EDX AND ECX,3 REP STOSB { Fill count MOD 4 bytes } @@exit: POP EDI end; procedure _Mark; begin Error(reInvalidPtr); end; procedure _RandInt; asm { ->EAX Range } { <-EAX Result } IMUL EDX,RandSeed,08088405H INC EDX MOV RandSeed,EDX MUL EDX MOV EAX,EDX end; procedure _RandExt; const two2neg32: double = ((1.0/$10000) / $10000); // 2^-32 asm { FUNCTION _RandExt: Extended; } IMUL EDX,RandSeed,08088405H INC EDX MOV RandSeed,EDX FLD two2neg32 PUSH 0 PUSH EDX FILD qword ptr [ESP] ADD ESP,8 FMULP ST(1), ST(0) end; procedure _ReadRec; external; {$L ReadRec } procedure _ReadChar; external; {$L ReadChar} procedure _ReadLong; external; {$L ReadLong} procedure _ReadString; external; {$L ReadStri} procedure _ReadCString; external; { ReadStri} procedure _ReadExt; external; {$L ReadExt } procedure _ReadLn; external; {$L ReadLn } procedure _Rename; external; {$L Rename } procedure _Release; begin Error(reInvalidPtr); end; procedure _ResetText(var t: text); external; {$L OpenText} procedure _ResetFile; external; {$L OpenFile} procedure _RewritText(var t: text); external; { OpenText} procedure _RewritFile; external; { OpenFile} procedure _Seek; external; {$L Seek } procedure _SeekEof; external; {$L SeekEof } procedure _SeekEoln; external; {$L SeekEoln} procedure _SetTextBuf; external; {$L SetTextB} procedure _StrLong; asm { PROCEDURE _StrLong( val: Longint; width: Longint; VAR s: ShortString ); ->EAX Value EDX Width ECX Pointer to string } PUSH EBX { VAR i: Longint; } PUSH ESI { VAR sign : Longint; } PUSH EDI PUSH EDX { store width on the stack } SUB ESP,20 { VAR a: array [0..19] of Char; } MOV EDI,ECX MOV ESI,EAX { sign := val } CDQ { val := Abs(val); canned sequence } XOR EAX,EDX SUB EAX,EDX MOV ECX,10 XOR EBX,EBX { i := 0; } @@repeat1: { repeat } XOR EDX,EDX { a[i] := Chr( val MOD 10 + Ord('0') );} DIV ECX { val := val DIV 10; } ADD EDX,'0' MOV [ESP+EBX],DL INC EBX { i := i + 1; } TEST EAX,EAX { until val = 0; } JNZ @@repeat1 TEST ESI,ESI JGE @@2 MOV byte ptr [ESP+EBX],'-' INC EBX @@2: MOV [EDI],BL { s^++ := Chr(i); } INC EDI MOV ECX,[ESP+20] { spaceCnt := width - i; } CMP ECX,255 JLE @@3 MOV ECX,255 @@3: SUB ECX,EBX JLE @@repeat2 { for k := 1 to spaceCnt do s^++ := ' '; } ADD [EDI-1],CL MOV AL,' ' REP STOSB @@repeat2: { repeat } MOV AL,[ESP+EBX-1] { s^ := a[i-1]; } MOV [EDI],AL INC EDI { s := s + 1 } DEC EBX { i := i - 1; } JNZ @@repeat2 { until i = 0; } ADD ESP,20+4 POP EDI POP ESI POP EBX end; procedure _Str0Long; asm { ->EAX Value } { EDX Pointer to string } MOV ECX,EDX XOR EDX,EDX JMP _StrLong end; procedure _Truncate; external; {$L Truncate} procedure _ValLong; asm { FUNCTION _ValLong( s: AnsiString; VAR code: Integer ) : Longint; } { ->EAX Pointer to string } { EDX Pointer to code result } { <-EAX Result } PUSH EBX PUSH ESI PUSH EDI MOV ESI,EAX PUSH EAX { save for the error case } TEST EAX,EAX JE @@empty XOR EAX,EAX XOR EBX,EBX MOV EDI,07FFFFFFFH / 10 { limit } @@blankLoop: MOV BL,[ESI] INC ESI CMP BL,' ' JE @@blankLoop @@endBlanks: MOV CH,0 CMP BL,'-' JE @@minus CMP BL,'+' JE @@plus CMP BL,'$' JE @@dollar CMP BL, 'x' JE @@dollar CMP BL, 'X' JE @@dollar CMP BL, '0' JNE @@firstDigit MOV BL, [ESI] INC ESI CMP BL, 'x' JE @@dollar CMP BL, 'X' JE @@dollar TEST BL, BL JE @@endDigits JMP @@digLoop @@firstDigit: TEST BL,BL JE @@error @@digLoop: SUB BL,'0' CMP BL,9 JA @@error CMP EAX,EDI { value > limit ? } JA @@overFlow LEA EAX,[EAX+EAX*4] ADD EAX,EAX ADD EAX,EBX { fortunately, we can't have a carry } MOV BL,[ESI] INC ESI TEST BL,BL JNE @@digLoop @@endDigits: DEC CH JE @@negate TEST EAX,EAX JL @@overFlow @@successExit: POP ECX { saved copy of string pointer } XOR ESI,ESI { signal no error to caller } @@exit: MOV [EDX],ESI POP EDI POP ESI POP EBX RET @@empty: INC ESI JMP @@error @@negate: NEG EAX JLE @@successExit JS @@successExit { to handle 2**31 correctly, where the negate overflows } @@error: @@overFlow: POP EBX SUB ESI,EBX JMP @@exit @@minus: INC CH @@plus: MOV BL,[ESI] INC ESI JMP @@firstDigit @@dollar: MOV EDI,0FFFFFFFH MOV BL,[ESI] INC ESI TEST BL,BL JZ @@empty @@hDigLoop: CMP BL,'a' JB @@upper SUB BL,'a' - 'A' @@upper: SUB BL,'0' CMP BL,9 JBE @@digOk SUB BL,'A' - '0' CMP BL,5 JA @@error ADD BL,10 @@digOk: CMP EAX,EDI JA @@overFlow SHL EAX,4 ADD EAX,EBX MOV BL,[ESI] INC ESI TEST BL,BL JNE @@hDigLoop JMP @@successExit end; procedure _WriteRec; external; {$L WriteRec} procedure _WriteChar; external; { WriteStr} procedure _Write0Char; external; { WriteStr} procedure _WriteBool; asm { PROCEDURE _WriteBool( VAR t: Text; val: Boolean; width: Longint); } { ->EAX Pointer to file record } { DL Boolean value } { ECX Field width } TEST DL,DL JE @@false MOV EDX,offset @trueString JMP _WriteString @@false: MOV EDX,offset @falseString JMP _WriteString @trueString: db 4,'TRUE' @falseString: db 5,'FALSE' end; procedure _Write0Bool; asm { PROCEDURE _Write0Bool( VAR t: Text; val: Boolean); } { ->EAX Pointer to file record } { DL Boolean value } XOR ECX,ECX JMP _WriteBool end; procedure _WriteLong; asm { PROCEDURE _WriteLong( VAR t: Text; val: Longint; with: Longint); } { ->EAX Pointer to file record } { EDX Value } { ECX Field width } SUB ESP,32 { VAR s: String[31]; } PUSH EAX PUSH ECX MOV EAX,EDX { Str( val : 0, s ); } XOR EDX,EDX CMP ECX,31 JG @@1 MOV EDX,ECX @@1: LEA ECX,[ESP+8] CALL _StrLong POP ECX POP EAX MOV EDX,ESP { Write( t, s : width );} CALL _WriteString ADD ESP,32 end; procedure _Write0Long; asm { PROCEDURE _Write0Long( VAR t: Text; val: Longint); } { ->EAX Pointer to file record } { EDX Value } XOR ECX,ECX JMP _WriteLong end; procedure _WriteString; external; {$L WriteStr} procedure _Write0String; external; { WriteStr} procedure _WriteCString; external; { WriteStr} procedure _Write0CString; external; { WriteStr} procedure _WriteBytes; external; { WriteStr} procedure _WriteSpaces; external; { WriteStr} procedure _Write2Ext; asm { PROCEDURE _Write2Ext( VAR t: Text; val: Extended; width, prec: Longint); ->EAX Pointer to file record [ESP+4] Extended value EDX Field width ECX precision (<0: scientific, >= 0: fixed point) } FLD tbyte ptr [ESP+4] { load value } SUB ESP,256 { VAR s: String; } PUSH EAX PUSH EDX { Str( val, width, prec, s ); } SUB ESP,12 FSTP tbyte ptr [ESP] { pass value } MOV EAX,EDX { pass field width } MOV EDX,ECX { pass precision } LEA ECX,[ESP+8+12] { pass destination string } CALL _Str2Ext { Write( t, s, width ); } POP ECX { pass width } POP EAX { pass text } MOV EDX,ESP { pass string } CALL _WriteString ADD ESP,256 RET 12 end; procedure _Write1Ext; asm { PROCEDURE _Write1Ext( VAR t: Text; val: Extended; width: Longint); -> EAX Pointer to file record [ESP+4] Extended value EDX Field width } OR ECX,-1 JMP _Write2Ext end; procedure _Write0Ext; asm { PROCEDURE _Write0Ext( VAR t: Text; val: Extended); ->EAX Pointer to file record [ESP+4] Extended value } MOV EDX,23 { field width } OR ECX,-1 JMP _Write2Ext end; procedure _WriteLn; external; { WriteStr} procedure __CToPasStr; asm { ->EAX Pointer to destination } { EDX Pointer to source } PUSH EAX { save destination } MOV CL,255 @@loop: MOV CH,[EDX] { ch = *src++; } INC EDX TEST CH,CH { if (ch == 0) break } JE @@endLoop INC EAX { *++dest = ch; } MOV [EAX],CH DEC CL JNE @@loop @@endLoop: POP EDX SUB EAX,EDX MOV [EDX],AL end; procedure __CLenToPasStr; asm { ->EAX Pointer to destination } { EDX Pointer to source } { ECX cnt } PUSH EBX PUSH EAX { save destination } CMP ECX,255 JBE @@loop MOV ECX,255 @@loop: MOV BL,[EDX] { ch = *src++; } INC EDX TEST BL,BL { if (ch == 0) break } JE @@endLoop INC EAX { *++dest = ch; } MOV [EAX],BL DEC ECX { while (--cnt != 0) } JNZ @@loop @@endLoop: POP EDX SUB EAX,EDX MOV [EDX],AL POP EBX end; procedure __ArrayToPasStr; asm { ->EAX Pointer to destination } { EDX Pointer to source } { ECX cnt } XCHG EAX,EDX { limit the length to 255 } CMP ECX,255 JBE @@skip MOV ECX,255 @@skip: MOV [EDX],CL { copy the source to destination + 1 } INC EDX JMP Move end; procedure __PasToCStr; asm { ->EAX Pointer to source } { EDX Pointer to destination } PUSH ESI PUSH EDI MOV ESI,EAX MOV EDI,EDX XOR ECX,ECX MOV CL,[ESI] INC ESI REP MOVSB MOV byte ptr [EDI],CL { Append terminator: CL is zero here } POP EDI POP ESI end; procedure _SetElem; asm { PROCEDURE _SetElem( VAR d: SET; elem, size: Byte); } { EAX = dest address } { DL = element number } { CL = size of set } PUSH EBX PUSH EDI MOV EDI,EAX XOR EBX,EBX { zero extend set size into ebx } MOV BL,CL MOV ECX,EBX { and use it for the fill } XOR EAX,EAX { for zero fill } REP STOSB SUB EDI,EBX { point edi at beginning of set again } INC EAX { eax is still zero - make it 1 } MOV CL,DL ROL AL,CL { generate a mask } SHR ECX,3 { generate the index } CMP ECX,EBX { if index >= siz then exit } JAE @@exit OR [EDI+ECX],AL{ set bit } @@exit: POP EDI POP EBX end; procedure _SetRange; asm { PROCEDURE _SetRange( lo, hi, size: Byte; VAR d: SET ); } { ->AL low limit of range } { DL high limit of range } { ECX Pointer to set } { AH size of set } PUSH EBX PUSH ESI PUSH EDI XOR EBX,EBX { EBX = set size } MOV BL,AH MOVZX ESI,AL { ESI = low zero extended } MOVZX EDX,DL { EDX = high zero extended } MOV EDI,ECX { clear the set } MOV ECX,EBX XOR EAX,EAX REP STOSB { prepare for setting the bits } SUB EDI,EBX { point EDI at start of set } SHL EBX,3 { EBX = highest bit in set + 1 } CMP EDX,EBX JB @@inrange LEA EDX,[EBX-1] { ECX = highest bit in set } @@inrange: CMP ESI,EDX { if lo > hi then exit; } JA @@exit DEC EAX { loMask = 0xff << (lo & 7) } MOV ECX,ESI AND CL,07H SHL AL,CL SHR ESI,3 { loIndex = lo >> 3; } MOV CL,DL { hiMask = 0xff >> (7 - (hi & 7)); } NOT CL AND CL,07 SHR AH,CL SHR EDX,3 { hiIndex = hi >> 3; } ADD EDI,ESI { point EDI to set[loIndex] } MOV ECX,EDX SUB ECX,ESI { if ((inxDiff = (hiIndex - loIndex)) == 0) } JNE @@else AND AL,AH { set[loIndex] = hiMask & loMask; } MOV [EDI],AL JMP @@exit @@else: STOSB { set[loIndex++] = loMask; } DEC ECX MOV AL,0FFH { while (loIndex < hiIndex) } REP STOSB { set[loIndex++] = 0xff; } MOV [EDI],AH { set[hiIndex] = hiMask; } @@exit: POP EDI POP ESI POP EBX end; procedure _SetEq; asm { FUNCTION _SetEq( CONST l, r: Set; size: Byte): ConditionCode; } { EAX = left operand } { EDX = right operand } { CL = size of set } PUSH ESI PUSH EDI MOV ESI,EAX MOV EDI,EDX AND ECX,0FFH REP CMPSB POP EDI POP ESI end; procedure _SetLe; asm { FUNCTION _SetLe( CONST l, r: Set; size: Byte): ConditionCode; } { EAX = left operand } { EDX = right operand } { CL = size of set (>0 && <= 32) } @@loop: MOV CH,[EDX] NOT CH AND CH,[EAX] JNE @@exit INC EDX INC EAX DEC CL JNZ @@loop @@exit: end; procedure _SetIntersect; asm { PROCEDURE _SetIntersect( VAR dest: Set; CONST src: Set; size: Byte);} { EAX = destination operand } { EDX = source operand } { CL = size of set (0 < size <= 32) } @@loop: MOV CH,[EDX] INC EDX AND [EAX],CH INC EAX DEC CL JNZ @@loop end; procedure _SetIntersect3; asm { PROCEDURE _SetIntersect3( VAR dest: Set; CONST src: Set; size: Longint; src2: Set);} { EAX = destination operand } { EDX = source operand } { ECX = size of set (0 < size <= 32) } { [ESP+4] = 2nd source operand } PUSH EBX PUSH ESI MOV ESI,[ESP+8+4] @@loop: MOV BL,[EDX+ECX-1] AND BL,[ESI+ECX-1] MOV [EAX+ECX-1],BL DEC ECX JNZ @@loop POP ESI POP EBX end; procedure _SetUnion; asm { PROCEDURE _SetUnion( VAR dest: Set; CONST src: Set; size: Byte); } { EAX = destination operand } { EDX = source operand } { CL = size of set (0 < size <= 32) } @@loop: MOV CH,[EDX] INC EDX OR [EAX],CH INC EAX DEC CL JNZ @@loop end; procedure _SetUnion3; asm { PROCEDURE _SetUnion3( VAR dest: Set; CONST src: Set; size: Longint; src2: Set);} { EAX = destination operand } { EDX = source operand } { ECX = size of set (0 < size <= 32) } { [ESP+4] = 2nd source operand } PUSH EBX PUSH ESI MOV ESI,[ESP+8+4] @@loop: MOV BL,[EDX+ECX-1] OR BL,[ESI+ECX-1] MOV [EAX+ECX-1],BL DEC ECX JNZ @@loop POP ESI POP EBX end; procedure _SetSub; asm { PROCEDURE _SetSub( VAR dest: Set; CONST src: Set; size: Byte); } { EAX = destination operand } { EDX = source operand } { CL = size of set (0 < size <= 32) } @@loop: MOV CH,[EDX] NOT CH INC EDX AND [EAX],CH INC EAX DEC CL JNZ @@loop end; procedure _SetSub3; asm { PROCEDURE _SetSub3( VAR dest: Set; CONST src: Set; size: Longint; src2: Set);} { EAX = destination operand } { EDX = source operand } { ECX = size of set (0 < size <= 32) } { [ESP+4] = 2nd source operand } PUSH EBX PUSH ESI MOV ESI,[ESP+8+4] @@loop: MOV BL,[ESI+ECX-1] NOT BL AND BL,[EDX+ECX-1] MOV [EAX+ECX-1],BL DEC ECX JNZ @@loop POP ESI POP EBX end; procedure _SetExpand; asm { PROCEDURE _SetExpand( CONST src: Set; VAR dest: Set; lo, hi: Byte); } { ->EAX Pointer to source (packed set) } { EDX Pointer to destination (expanded set) } { CH high byte of source } { CL low byte of source } { algorithm: } { clear low bytes } { copy high-low+1 bytes } { clear 31-high bytes } PUSH ESI PUSH EDI MOV ESI,EAX MOV EDI,EDX MOV EDX,ECX { save low, high in dl, dh } XOR ECX,ECX XOR EAX,EAX MOV CL,DL { clear low bytes } REP STOSB MOV CL,DH { copy high - low bytes } SUB CL,DL REP MOVSB MOV CL,32 { copy 32 - high bytes } SUB CL,DH REP STOSB POP EDI POP ESI end; procedure _Str2Ext; external; {$L StrExt } procedure _Str0Ext; external; { StrExt } procedure _Str1Ext; external; { StrExt } procedure _ValExt; external; {$L ValExt } procedure _Pow10; external; {$L Pow10 } procedure FPower10; external; { Pow10 } procedure _Real2Ext; external; {$L Real2Ext} procedure _Ext2Real; external; {$L Ext2Real} const ovtInstanceSize = -8; { Offset of instance size in OBJECTs } ovtVmtPtrOffs = -4; procedure _ObjSetup; asm { FUNCTION _ObjSetup( self: ^OBJECT; vmt: ^VMT): ^OBJECT; } { ->EAX Pointer to self (possibly nil) } { EDX Pointer to vmt (possibly nil) } { <-EAX Pointer to self } { EDX <> 0: an object was allocated } { Z-Flag Set: failure, Cleared: Success } CMP EDX,1 { is vmt = 0, indicating a call } JAE @@skip1 { from a constructor? } RET { return immediately with Z-flag cleared } @@skip1: PUSH ECX TEST EAX,EAX { is self already allocated? } JNE @@noAlloc MOV EAX,[EDX].ovtInstanceSize TEST EAX,EAX JE @@zeroSize PUSH EDX CALL MemoryManager.GetMem POP EDX TEST EAX,EAX JZ @@fail { Zero fill the memory } PUSH EDI MOV ECX,[EDX].ovtInstanceSize MOV EDI,EAX PUSH EAX XOR EAX,EAX SHR ECX,2 REP STOSD MOV ECX,[EDX].ovtInstanceSize AND ECX,3 REP STOSB POP EAX POP EDI MOV ECX,[EDX].ovtVmtPtrOffs TEST ECX,ECX JL @@skip MOV [EAX+ECX],EDX { store vmt in object at this offset } @@skip: TEST EAX,EAX { clear zero flag } POP ECX RET @@fail: XOR EDX,EDX POP ECX RET @@zeroSize: XOR EDX,EDX CMP EAX,1 { clear zero flag - we were successful (kind of) } POP ECX RET @@noAlloc: MOV ECX,[EDX].ovtVmtPtrOffs TEST ECX,ECX JL @@exit MOV [EAX+ECX],EDX { store vmt in object at this offset } @@exit: XOR EDX,EDX { clear allocated flag } TEST EAX,EAX { clear zero flag } POP ECX end; procedure _ObjCopy; asm { PROCEDURE _ObjCopy( dest, src: ^OBJECT; vmtPtrOff: Longint); } { ->EAX Pointer to destination } { EDX Pointer to source } { ECX Offset of vmt in those objects. } PUSH EBX PUSH ESI PUSH EDI MOV ESI,EDX MOV EDI,EAX LEA EAX,[EDI+ECX] { remember pointer to dest vmt pointer } MOV EDX,[EAX] { fetch dest vmt pointer } MOV EBX,[EDX].ovtInstanceSize MOV ECX,EBX { copy size DIV 4 dwords } SHR ECX,2 REP MOVSD MOV ECX,EBX { copy size MOD 4 bytes } AND ECX,3 REP MOVSB MOV [EAX],EDX { restore dest vmt } POP EDI POP ESI POP EBX end; procedure _Fail; asm { FUNCTION _Fail( self: ^OBJECT; allocFlag:Longint): ^OBJECT; } { ->EAX Pointer to self (possibly nil) } { EDX <> 0: Object must be deallocated } { <-EAX Nil } TEST EDX,EDX JE @@exit { if no object was allocated, return } CALL _FreeMem @@exit: XOR EAX,EAX end; function GetKeyboardType(nTypeFlag: Integer): Integer; stdcall; external user name 'GetKeyboardType'; function _isNECWindows: Boolean; var KbSubType: Integer; begin Result := False; if GetKeyboardType(0) = $7 then begin KbSubType := GetKeyboardType(1) and $FF00; if (KbSubType = $0D00) or (KbSubType = $0400) then Result := True; end; end; procedure _FpuMaskInit; const HKEY_LOCAL_MACHINE = $80000002; KEY_QUERY_VALUE = $00000001; REG_DWORD = 4; FPUMASKKEY = 'SOFTWARE\Borland\Delphi\RTL'; FPUMASKNAME = 'FPUMaskValue'; var phkResult: LongWord; lpData, DataSize: Longint; begin lpData := Default8087CW; if RegOpenKeyEx(HKEY_LOCAL_MACHINE, FPUMASKKEY, 0, KEY_QUERY_VALUE, phkResult) = 0 then try DataSize := Sizeof(lpData); RegQueryValueEx(phkResult, FPUMASKNAME, nil, nil, @lpData, @DataSize); finally RegCloseKey(phkResult); end; Default8087CW := (Default8087CW and $ffc0) or (lpData and $3f); end; procedure _FpuInit; //const cwDefault: Word = $1332 { $133F}; asm FNINIT FWAIT FLDCW Default8087CW end; procedure _BoundErr; asm MOV AL,reRangeError JMP Error end; procedure _IntOver; asm MOV AL,reIntOverflow JMP Error end; function TObject.ClassType: TClass; asm mov eax,[eax] end; class function TObject.ClassName: ShortString; asm { -> EAX VMT } { EDX Pointer to result string } PUSH ESI PUSH EDI MOV EDI,EDX MOV ESI,[EAX].vmtClassName XOR ECX,ECX MOV CL,[ESI] INC ECX REP MOVSB POP EDI POP ESI end; class function TObject.ClassNameIs(const Name: string): Boolean; asm PUSH EBX XOR EBX,EBX OR EDX,EDX JE @@exit MOV EAX,[EAX].vmtClassName XOR ECX,ECX MOV CL,[EAX] CMP ECX,[EDX-4] JNE @@exit DEC EDX @@loop: MOV BH,[EAX+ECX] XOR BH,[EDX+ECX] AND BH,0DFH JNE @@exit DEC ECX JNE @@loop INC EBX @@exit: MOV AL,BL POP EBX end; class function TObject.ClassParent: TClass; asm MOV EAX,[EAX].vmtParent TEST EAX,EAX JE @@exit MOV EAX,[EAX] @@exit: end; class function TObject.NewInstance: TObject; asm PUSH EAX MOV EAX,[EAX].vmtInstanceSize CALL _GetMem MOV EDX,EAX POP EAX JMP TObject.InitInstance end; procedure TObject.FreeInstance; asm PUSH EBX PUSH ESI MOV EBX,EAX MOV ESI,EAX @@loop: MOV ESI,[ESI] MOV EDX,[ESI].vmtInitTable MOV ESI,[ESI].vmtParent TEST EDX,EDX JE @@skip CALL _FinalizeRecord MOV EAX,EBX @@skip: TEST ESI,ESI JNE @@loop CALL _FreeMem POP ESI POP EBX end; class function TObject.InstanceSize: Longint; asm MOV EAX,[EAX].vmtInstanceSize end; constructor TObject.Create; begin end; destructor TObject.Destroy; begin end; procedure TObject.Free; asm TEST EAX,EAX JE @@exit MOV ECX,[EAX] MOV DL,1 CALL dword ptr [ECX].vmtDestroy @@exit: end; class function TObject.InitInstance(Instance: Pointer): TObject; asm PUSH EBX PUSH ESI PUSH EDI MOV EBX,EAX MOV EDI,EDX STOSD MOV ECX,[EBX].vmtInstanceSize XOR EAX,EAX PUSH ECX SHR ECX,2 DEC ECX REP STOSD POP ECX AND ECX,3 REP STOSB MOV EAX,EDX MOV EDX,ESP @@0: MOV ECX,[EBX].vmtIntfTable TEST ECX,ECX JE @@1 PUSH ECX @@1: MOV EBX,[EBX].vmtParent TEST EBX,EBX JE @@2 MOV EBX,[EBX] JMP @@0 @@2: CMP ESP,EDX JE @@5 @@3: POP EBX MOV ECX,[EBX].TInterfaceTable.EntryCount ADD EBX,4 @@4: MOV ESI,[EBX].TInterfaceEntry.VTable TEST ESI,ESI JE @@4a MOV EDI,[EBX].TInterfaceEntry.IOffset MOV [EAX+EDI],ESI @@4a: ADD EBX,TYPE TInterfaceEntry DEC ECX JNE @@4 CMP ESP,EDX JNE @@3 @@5: POP EDI POP ESI POP EBX end; procedure TObject.CleanupInstance; asm PUSH EBX PUSH ESI MOV EBX,EAX MOV ESI,EAX @@loop: MOV ESI,[ESI] MOV EDX,[ESI].vmtInitTable MOV ESI,[ESI].vmtParent TEST EDX,EDX JE @@skip CALL _FinalizeRecord MOV EAX,EBX @@skip: TEST ESI,ESI JNE @@loop POP ESI POP EBX end; function InvokeImplGetter(Self: TObject; ImplGetter: Integer): IUnknown; asm XCHG EDX,ECX CMP ECX,$FF000000 JAE @@isField CMP ECX,$FE000000 JB @@isStaticMethod { the GetProc is a virtual method } MOVSX ECX,CX { sign extend slot offs } ADD ECX,[EAX] { vmt + slotoffs } JMP dword ptr [ECX] { call vmt[slot] } @@isStaticMethod: JMP ECX @@isField: AND ECX,$00FFFFFF ADD ECX,EAX MOV EAX,EDX MOV EDX,[ECX] JMP _IntfCopy end; function TObject.GetInterface(const IID: TGUID; out Obj): Boolean; var InterfaceEntry: PInterfaceEntry; begin InterfaceEntry := GetInterfaceEntry(IID); if InterfaceEntry <> nil then begin if InterfaceEntry^.IOffset <> 0 then Pointer(Obj) := Pointer(Integer(Self) + InterfaceEntry^.IOffset) else IUnknown(Obj) := InvokeImplGetter(Self, InterfaceEntry^.ImplGetter); if Pointer(Obj) <> nil then begin if InterfaceEntry^.IOffset <> 0 then IUnknown(Obj)._AddRef; Result := True; end else Result := False; end else begin Pointer(Obj) := nil; Result := False; end; end; class function TObject.GetInterfaceEntry(const IID: TGUID): PInterfaceEntry; asm PUSH EBX PUSH ESI MOV EBX,EAX @@1: MOV EAX,[EBX].vmtIntfTable TEST EAX,EAX JE @@4 MOV ECX,[EAX].TInterfaceTable.EntryCount ADD EAX,4 @@2: MOV ESI,[EDX].Integer[0] CMP ESI,[EAX].TInterfaceEntry.IID.Integer[0] JNE @@3 MOV ESI,[EDX].Integer[4] CMP ESI,[EAX].TInterfaceEntry.IID.Integer[4] JNE @@3 MOV ESI,[EDX].Integer[8] CMP ESI,[EAX].TInterfaceEntry.IID.Integer[8] JNE @@3 MOV ESI,[EDX].Integer[12] CMP ESI,[EAX].TInterfaceEntry.IID.Integer[12] JE @@5 @@3: ADD EAX,type TInterfaceEntry DEC ECX JNE @@2 @@4: MOV EBX,[EBX].vmtParent TEST EBX,EBX JE @@4a MOV EBX,[EBX] JMP @@1 @@4a: XOR EAX,EAX @@5: POP ESI POP EBX end; class function TObject.GetInterfaceTable: PInterfaceTable; asm MOV EAX,[EAX].vmtIntfTable end; procedure _IsClass; asm { -> EAX left operand (class) } { EDX VMT of right operand } { <- AL left is derived from right } TEST EAX,EAX JE @@exit @@loop: MOV EAX,[EAX] CMP EAX,EDX JE @@success MOV EAX,[EAX].vmtParent TEST EAX,EAX JNE @@loop JMP @@exit @@success: MOV AL,1 @@exit: end; procedure _AsClass; asm { -> EAX left operand (class) } { EDX VMT of right operand } { <- EAX if left is derived from right, else runtime error } TEST EAX,EAX JE @@exit MOV ECX,EAX @@loop: MOV ECX,[ECX] CMP ECX,EDX JE @@exit MOV ECX,[ECX].vmtParent TEST ECX,ECX JNE @@loop { do runtime error } MOV AL,reInvalidCast JMP Error @@exit: end; procedure GetDynaMethod; { function GetDynaMethod(vmt: TClass; selector: Smallint) : Pointer; } asm { -> EAX vmt of class } { BX dynamic method index } { <- EBX pointer to routine } { ZF = 0 if found } { trashes: EAX, ECX } PUSH EDI XCHG EAX,EBX JMP @@haveVMT @@outerLoop: MOV EBX,[EBX] @@haveVMT: MOV EDI,[EBX].vmtDynamicTable TEST EDI,EDI JE @@parent MOVZX ECX,word ptr [EDI] PUSH ECX ADD EDI,2 REPNE SCASW JE @@found POP ECX @@parent: MOV EBX,[EBX].vmtParent TEST EBX,EBX JNE @@outerLoop JMP @@exit @@found: POP EAX ADD EAX,EAX SUB EAX,ECX { this will always clear the Z-flag ! } MOV EBX,[EDI+EAX*2-4] @@exit: POP EDI end; procedure _CallDynaInst; asm PUSH EAX PUSH ECX MOV EAX,[EAX] CALL GetDynaMethod POP ECX POP EAX JE @@Abstract JMP EBX @@Abstract: POP ECX JMP _AbstractError end; procedure _CallDynaClass; asm PUSH EAX PUSH ECX CALL GetDynaMethod POP ECX POP EAX JE @@Abstract JMP EBX @@Abstract: POP ECX JMP _AbstractError end; procedure _FindDynaInst; asm PUSH EBX MOV EBX,EDX MOV EAX,[EAX] CALL GetDynaMethod MOV EAX,EBX POP EBX JNE @@exit POP ECX JMP _AbstractError @@exit: end; procedure _FindDynaClass; asm PUSH EBX MOV EBX,EDX CALL GetDynaMethod MOV EAX,EBX POP EBX JNE @@exit POP ECX JMP _AbstractError @@exit: end; class function TObject.InheritsFrom(AClass: TClass): Boolean; asm { -> EAX Pointer to our class } { EDX Pointer to AClass } { <- AL Boolean result } JMP @@haveVMT @@loop: MOV EAX,[EAX] @@haveVMT: CMP EAX,EDX JE @@success MOV EAX,[EAX].vmtParent TEST EAX,EAX JNE @@loop JMP @@exit @@success: MOV AL,1 @@exit: end; class function TObject.ClassInfo: Pointer; asm MOV EAX,[EAX].vmtTypeInfo end; function TObject.SafeCallException(ExceptObject: TObject; ExceptAddr: Pointer): HResult; begin Result := HResult($8000FFFF); { E_UNEXPECTED } end; procedure TObject.DefaultHandler(var Message); begin end; procedure TObject.AfterConstruction; begin end; procedure TObject.BeforeDestruction; begin end; procedure TObject.Dispatch(var Message); asm PUSH EBX MOV BX,[EDX] OR BX,BX JE @@default CMP BX,0C000H JAE @@default PUSH EAX MOV EAX,[EAX] CALL GetDynaMethod POP EAX JE @@default MOV ECX,EBX POP EBX JMP ECX @@default: POP EBX MOV ECX,[EAX] JMP dword ptr [ECX].vmtDefaultHandler end; class function TObject.MethodAddress(const Name: ShortString): Pointer; asm { -> EAX Pointer to class } { EDX Pointer to name } PUSH EBX PUSH ESI PUSH EDI XOR ECX,ECX XOR EDI,EDI MOV BL,[EDX] JMP @@haveVMT @@outer: { upper 16 bits of ECX are 0 ! } MOV EAX,[EAX] @@haveVMT: MOV ESI,[EAX].vmtMethodTable TEST ESI,ESI JE @@parent MOV DI,[ESI] { EDI := method count } ADD ESI,2 @@inner: { upper 16 bits of ECX are 0 ! } MOV CL,[ESI+6] { compare length of strings } CMP CL,BL JE @@cmpChar @@cont: { upper 16 bits of ECX are 0 ! } MOV CX,[ESI] { fetch length of method desc } ADD ESI,ECX { point ESI to next method } DEC EDI JNZ @@inner @@parent: MOV EAX,[EAX].vmtParent { fetch parent vmt } TEST EAX,EAX JNE @@outer JMP @@exit { return NIL } @@notEqual: MOV BL,[EDX] { restore BL to length of name } JMP @@cont @@cmpChar: { upper 16 bits of ECX are 0 ! } MOV CH,0 { upper 24 bits of ECX are 0 ! } @@cmpCharLoop: MOV BL,[ESI+ECX+6] { case insensitive string cmp } XOR BL,[EDX+ECX+0] { last char is compared first } AND BL,$DF JNE @@notEqual DEC ECX { ECX serves as counter } JNZ @@cmpCharLoop { found it } MOV EAX,[ESI+2] @@exit: POP EDI POP ESI POP EBX end; class function TObject.MethodName(Address: Pointer): ShortString; asm { -> EAX Pointer to class } { EDX Address } { ECX Pointer to result } PUSH EBX PUSH ESI PUSH EDI MOV EDI,ECX XOR EBX,EBX XOR ECX,ECX JMP @@haveVMT @@outer: MOV EAX,[EAX] @@haveVMT: MOV ESI,[EAX].vmtMethodTable { fetch pointer to method table } TEST ESI,ESI JE @@parent MOV CX,[ESI] ADD ESI,2 @@inner: CMP EDX,[ESI+2] JE @@found MOV BX,[ESI] ADD ESI,EBX DEC ECX JNZ @@inner @@parent: MOV EAX,[EAX].vmtParent TEST EAX,EAX JNE @@outer MOV [EDI],AL JMP @@exit @@found: ADD ESI,6 XOR ECX,ECX MOV CL,[ESI] INC ECX REP MOVSB @@exit: POP EDI POP ESI POP EBX end; function TObject.FieldAddress(const Name: ShortString): Pointer; asm { -> EAX Pointer to instance } { EDX Pointer to name } PUSH EBX PUSH ESI PUSH EDI XOR ECX,ECX XOR EDI,EDI MOV BL,[EDX] PUSH EAX { save instance pointer } @@outer: MOV EAX,[EAX] { fetch class pointer } MOV ESI,[EAX].vmtFieldTable TEST ESI,ESI JE @@parent MOV DI,[ESI] { fetch count of fields } ADD ESI,6 @@inner: MOV CL,[ESI+6] { compare string lengths } CMP CL,BL JE @@cmpChar @@cont: LEA ESI,[ESI+ECX+7] { point ESI to next field } DEC EDI JNZ @@inner @@parent: MOV EAX,[EAX].vmtParent { fetch parent VMT } TEST EAX,EAX JNE @@outer POP EDX { forget instance, return Nil } JMP @@exit @@notEqual: MOV BL,[EDX] { restore BL to length of name } MOV CL,[ESI+6] { ECX := length of field name } JMP @@cont @@cmpChar: MOV BL,[ESI+ECX+6] { case insensitive string cmp } XOR BL,[EDX+ECX+0] { starting with last char } AND BL,$DF JNE @@notEqual DEC ECX { ECX serves as counter } JNZ @@cmpChar { found it } MOV EAX,[ESI] { result is field offset plus ... } POP EDX ADD EAX,EDX { instance pointer } @@exit: POP EDI POP ESI POP EBX end; const { copied from xx.h } cContinuable = 0; cNonContinuable = 1; cUnwinding = 2; cUnwindingForExit = 4; cUnwindInProgress = cUnwinding or cUnwindingForExit; cDelphiException = $0EEDFADE; cDelphiReRaise = $0EEDFADF; cDelphiExcept = $0EEDFAE0; cDelphiFinally = $0EEDFAE1; cDelphiTerminate = $0EEDFAE2; cDelphiUnhandled = $0EEDFAE3; cNonDelphiException = $0EEDFAE4; cDelphiExitFinally = $0EEDFAE5; cCppException = $0EEFFACE; { used by BCB } EXCEPTION_CONTINUE_SEARCH = 0; EXCEPTION_EXECUTE_HANDLER = 1; EXCEPTION_CONTINUE_EXECUTION = -1; type JmpInstruction = packed record opCode: Byte; distance: Longint; end; TExcDescEntry = record vTable: Pointer; handler: Pointer; end; PExcDesc = ^TExcDesc; TExcDesc = packed record jmp: JmpInstruction; case Integer of 0: (instructions: array [0..0] of Byte); 1{...}: (cnt: Integer; excTab: array [0..0{cnt-1}] of TExcDescEntry); end; PExcFrame = ^TExcFrame; TExcFrame = record next: PExcFrame; desc: PExcDesc; hEBP: Pointer; case Integer of 0: ( ); 1: ( ConstructedObject: Pointer ); 2: ( SelfOfMethod: Pointer ); end; PExceptionRecord = ^TExceptionRecord; TExceptionRecord = record ExceptionCode : LongWord; ExceptionFlags : LongWord; OuterException : PExceptionRecord; ExceptionAddress : Pointer; NumberParameters : Longint; case {IsOsException:} Boolean of True: (ExceptionInformation : array [0..14] of Longint); False: (ExceptAddr: Pointer; ExceptObject: Pointer); end; PRaiseFrame = ^TRaiseFrame; TRaiseFrame = packed record NextRaise: PRaiseFrame; ExceptAddr: Pointer; ExceptObject: TObject; ExceptionRecord: PExceptionRecord; end; procedure _ClassCreate; asm { -> EAX = pointer to VMT } { <- EAX = pointer to instance } PUSH EDX PUSH ECX PUSH EBX TEST DL,DL JL @@noAlloc CALL dword ptr [EAX].vmtNewInstance @@noAlloc: XOR EDX,EDX LEA ECX,[ESP+16] MOV EBX,FS:[EDX] MOV [ECX].TExcFrame.next,EBX MOV [ECX].TExcFrame.hEBP,EBP MOV [ECX].TExcFrame.desc,offset @desc MOV [ECX].TexcFrame.ConstructedObject,EAX { trick: remember copy to instance } MOV FS:[EDX],ECX POP EBX POP ECX POP EDX RET @desc: JMP _HandleAnyException { destroy the object } MOV EAX,[ESP+8+9*4] MOV EAX,[EAX].TExcFrame.ConstructedObject TEST EAX,EAX JE @@skip MOV ECX,[EAX] MOV DL,$81 PUSH EAX CALL dword ptr [ECX].vmtDestroy POP EAX CALL _ClassDestroy @@skip: { reraise the exception } CALL _RaiseAgain end; procedure _ClassDestroy; asm MOV EDX,[EAX] CALL dword ptr [EDX].vmtFreeInstance end; procedure _AfterConstruction; asm { -> EAX = pointer to instance } PUSH EAX MOV EDX,[EAX] CALL dword ptr [EDX].vmtAfterConstruction POP EAX end; procedure _BeforeDestruction; asm { -> EAX = pointer to instance } { DL = dealloc flag } TEST DL,DL JG @@outerMost RET @@outerMost: PUSH EAX PUSH EDX MOV EDX,[EAX] CALL dword ptr [EDX].vmtBeforeDestruction POP EDX POP EAX end; { The following NotifyXXXX routines are used to "raise" special exceptions as a signaling mechanism to an interested debugger. If the debugger sets the DebugHook flag to 1 or 2, then all exception processing is tracked by raising these special exceptions. The debugger *MUST* respond to the debug event with DBG_CONTINE so that normal processing will occur. } { tell the debugger that the next raise is a re-raise of the current non-Delphi exception } procedure NotifyReRaise; asm CMP BYTE PTR DebugHook,1 JBE @@1 PUSH 0 PUSH 0 PUSH cContinuable PUSH cDelphiReRaise CALL RaiseException @@1: end; { tell the debugger about the raise of a non-Delphi exception } procedure NotifyNonDelphiException; asm CMP BYTE PTR DebugHook,0 JE @@1 PUSH EAX PUSH EAX PUSH EDX PUSH ESP PUSH 2 PUSH cContinuable PUSH cNonDelphiException CALL RaiseException ADD ESP,8 POP EAX @@1: end; { Tell the debugger where the handler for the current exception is located } procedure NotifyExcept; asm PUSH ESP PUSH 1 PUSH cContinuable PUSH cDelphiExcept { our magic exception code } CALL RaiseException ADD ESP,4 POP EAX end; procedure NotifyOnExcept; asm CMP BYTE PTR DebugHook,1 JBE @@1 PUSH EAX PUSH [EBX].TExcDescEntry.handler JMP NotifyExcept @@1: end; procedure NotifyAnyExcept; asm CMP BYTE PTR DebugHook,1 JBE @@1 PUSH EAX PUSH EBX JMP NotifyExcept @@1: end; procedure CheckJmp; asm TEST ECX,ECX JE @@3 MOV EAX,[ECX + 1] CMP BYTE PTR [ECX],0E9H { near jmp } JE @@1 CMP BYTE PTR [ECX],0EBH { short jmp } JNE @@3 MOVSX EAX,AL INC ECX INC ECX JMP @@2 @@1: ADD ECX,5 @@2: ADD ECX,EAX @@3: end; { Notify debugger of a finally during an exception unwind } procedure NotifyExceptFinally; asm CMP BYTE PTR DebugHook,1 JBE @@1 PUSH EAX PUSH EDX PUSH ECX CALL CheckJmp PUSH ECX PUSH ESP { pass pointer to arguments } PUSH 1 { there is 1 argument } PUSH cContinuable { continuable execution } PUSH cDelphiFinally { our magic exception code } CALL RaiseException POP ECX POP ECX POP EDX POP EAX @@1: end; { Tell the debugger that the current exception is handled and cleaned up. Also indicate where execution is about to resume. } procedure NotifyTerminate; asm CMP BYTE PTR DebugHook,1 JBE @@1 PUSH EDX PUSH ESP PUSH 1 PUSH cContinuable PUSH cDelphiTerminate { our magic exception code } CALL RaiseException POP EDX @@1: end; { Tell the debugger that there was no handler found for the current execption and we are about to go to the default handler } procedure NotifyUnhandled; asm PUSH EAX PUSH EDX CMP BYTE PTR DebugHook,1 JBE @@1 PUSH ESP PUSH 2 PUSH cContinuable PUSH cDelphiUnhandled CALL RaiseException @@1: POP EDX POP EAX end; procedure _HandleAnyException; asm { -> [ESP+ 4] excPtr: PExceptionRecord } { [ESP+ 8] errPtr: PExcFrame } { [ESP+12] ctxPtr: Pointer } { [ESP+16] dspPtr: Pointer } { <- EAX return value - always one } MOV EAX,[ESP+4] TEST [EAX].TExceptionRecord.ExceptionFlags,cUnwindInProgress JNE @@exit CMP [EAX].TExceptionRecord.ExceptionCode,cDelphiException MOV EDX,[EAX].TExceptionRecord.ExceptObject MOV ECX,[EAX].TExceptionRecord.ExceptAddr JE @@DelphiException CLD CALL _FpuInit MOV EDX,ExceptObjProc TEST EDX,EDX JE @@exit CALL EDX TEST EAX,EAX JE @@exit MOV EDX,[ESP+12] MOV ECX,[ESP+4] CMP [ECX].TExceptionRecord.ExceptionCode,cCppException JE @@CppException CALL NotifyNonDelphiException CMP BYTE PTR JITEnable,0 JBE @@CppException CMP BYTE PTR DebugHook,0 JA @@CppException { Do not JIT if debugging } LEA ECX,[ESP+4] PUSH EAX PUSH ECX CALL UnhandledExceptionFilter CMP EAX,EXCEPTION_CONTINUE_SEARCH POP EAX JE @@exit MOV EDX,EAX MOV EAX,[ESP+4] MOV ECX,[EAX].TExceptionRecord.ExceptionAddress JMP @@GoUnwind @@CppException: MOV EDX,EAX MOV EAX,[ESP+4] MOV ECX,[EAX].TExceptionRecord.ExceptionAddress @@DelphiException: CMP BYTE PTR JITEnable,1 JBE @@GoUnwind CMP BYTE PTR DebugHook,0 { Do not JIT if debugging } JA @@GoUnwind PUSH EAX LEA EAX,[ESP+8] PUSH EDX PUSH ECX PUSH EAX CALL UnhandledExceptionFilter CMP EAX,EXCEPTION_CONTINUE_SEARCH POP ECX POP EDX POP EAX JE @@exit @@GoUnwind: OR [EAX].TExceptionRecord.ExceptionFlags,cUnwinding PUSH EBX XOR EBX,EBX PUSH ESI PUSH EDI PUSH EBP MOV EBX,FS:[EBX] PUSH EBX { Save pointer to topmost frame } PUSH EAX { Save OS exception pointer } PUSH EDX { Save exception object } PUSH ECX { Save exception address } MOV EDX,[ESP+8+8*4] PUSH 0 PUSH EAX PUSH offset @@returnAddress PUSH EDX CALL RtlUnwind @@returnAddress: MOV EDI,[ESP+8+8*4] { Make the RaiseList entry on the stack } CALL SysInit.@GetTLS PUSH [EAX].RaiseListPtr MOV [EAX].RaiseListPtr,ESP MOV EBP,[EDI].TExcFrame.hEBP MOV EBX,[EDI].TExcFrame.desc MOV [EDI].TExcFrame.desc,offset @@exceptFinally ADD EBX,TExcDesc.instructions CALL NotifyAnyExcept JMP EBX @@exceptFinally: JMP _HandleFinally @@destroyExcept: { we come here if an exception handler has thrown yet another exception } { we need to destroy the exception object and pop the raise list. } CALL SysInit.@GetTLS MOV ECX,[EAX].RaiseListPtr MOV EDX,[ECX].TRaiseFrame.NextRaise MOV [EAX].RaiseListPtr,EDX MOV EAX,[ECX].TRaiseFrame.ExceptObject JMP TObject.Free @@exit: MOV EAX,1 end; procedure _HandleOnException; asm { -> [ESP+ 4] excPtr: PExceptionRecord } { [ESP+ 8] errPtr: PExcFrame } { [ESP+12] ctxPtr: Pointer } { [ESP+16] dspPtr: Pointer } { <- EAX return value - always one } MOV EAX,[ESP+4] TEST [EAX].TExceptionRecord.ExceptionFlags,cUnwindInProgress JNE @@exit CMP [EAX].TExceptionRecord.ExceptionCode,cDelphiException JE @@DelphiException CLD CALL _FpuInit MOV EDX,ExceptClsProc TEST EDX,EDX JE @@exit CALL EDX TEST EAX,EAX JNE @@common JMP @@exit @@DelphiException: MOV EAX,[EAX].TExceptionRecord.ExceptObject MOV EAX,[EAX] { load vtable of exception object } @@common: MOV EDX,[ESP+8] PUSH EBX PUSH ESI PUSH EDI PUSH EBP MOV ECX,[EDX].TExcFrame.desc MOV EBX,[ECX].TExcDesc.cnt LEA ESI,[ECX].TExcDesc.excTab { point ECX to exc descriptor table } MOV EBP,EAX { load vtable of exception object } @@innerLoop: MOV EAX,[ESI].TExcDescEntry.vTable TEST EAX,EAX { catch all clause? } JE @@doHandler { yes: go execute handler } MOV EDI,EBP { load vtable of exception object } JMP @@haveVMT @@vtLoop: MOV EDI,[EDI] @@haveVMT: MOV EAX,[EAX] CMP EAX,EDI JE @@doHandler MOV ECX,[EAX].vmtInstanceSize CMP ECX,[EDI].vmtInstanceSize JNE @@parent MOV EAX,[EAX].vmtClassName MOV EDX,[EDI].vmtClassName XOR ECX,ECX MOV CL,[EAX] CMP CL,[EDX] JNE @@parent INC EAX INC EDX CALL _AStrCmp JE @@doHandler @@parent: MOV EDI,[EDI].vmtParent { load vtable of parent } MOV EAX,[ESI].TExcDescEntry.vTable TEST EDI,EDI JNE @@vtLoop ADD ESI,8 DEC EBX JNZ @@innerLoop POP EBP POP EDI POP ESI POP EBX JMP @@exit @@doHandler: MOV EAX,[ESP+4+4*4] CMP [EAX].TExceptionRecord.ExceptionCode,cDelphiException MOV EDX,[EAX].TExceptionRecord.ExceptObject MOV ECX,[EAX].TExceptionRecord.ExceptAddr JE @@haveObject CALL ExceptObjProc MOV EDX,[ESP+12+4*4] CALL NotifyNonDelphiException CMP BYTE PTR JITEnable,0 JBE @@NoJIT CMP BYTE PTR DebugHook,0 JA @@noJIT { Do not JIT if debugging } LEA ECX,[ESP+4] PUSH EAX PUSH ECX CALL UnhandledExceptionFilter CMP EAX,EXCEPTION_CONTINUE_SEARCH POP EAX JE @@exit @@noJIT: MOV EDX,EAX MOV EAX,[ESP+4+4*4] MOV ECX,[EAX].TExceptionRecord.ExceptionAddress JMP @@GoUnwind @@haveObject: CMP BYTE PTR JITEnable,1 JBE @@GoUnwind CMP BYTE PTR DebugHook,0 JA @@GoUnwind PUSH EAX LEA EAX,[ESP+8] PUSH EDX PUSH ECX PUSH EAX CALL UnhandledExceptionFilter CMP EAX,EXCEPTION_CONTINUE_SEARCH POP ECX POP EDX POP EAX JE @@exit @@GoUnwind: XOR EBX,EBX MOV EBX,FS:[EBX] PUSH EBX { Save topmost frame } PUSH EAX { Save exception record } PUSH EDX { Save exception object } PUSH ECX { Save exception address } MOV EDX,[ESP+8+8*4] OR [EAX].TExceptionRecord.ExceptionFlags,cUnwinding PUSH ESI { Save handler entry } PUSH 0 PUSH EAX PUSH offset @@returnAddress PUSH EDX CALL RtlUnwind @@returnAddress: POP EBX { Restore handler entry } MOV EDI,[ESP+8+8*4] { Make the RaiseList entry on the stack } CALL SysInit.@GetTLS PUSH [EAX].RaiseListPtr MOV [EAX].RaiseListPtr,ESP MOV EBP,[EDI].TExcFrame.hEBP MOV [EDI].TExcFrame.desc,offset @@exceptFinally MOV EAX,[ESP].TRaiseFrame.ExceptObject CALL NotifyOnExcept JMP [EBX].TExcDescEntry.handler @@exceptFinally: JMP _HandleFinally @@destroyExcept: { we come here if an exception handler has thrown yet another exception } { we need to destroy the exception object and pop the raise list. } CALL SysInit.@GetTLS MOV ECX,[EAX].RaiseListPtr MOV EDX,[ECX].TRaiseFrame.NextRaise MOV [EAX].RaiseListPtr,EDX MOV EAX,[ECX].TRaiseFrame.ExceptObject JMP TObject.Free @@exit: MOV EAX,1 end; procedure _HandleFinally; asm { -> [ESP+ 4] excPtr: PExceptionRecord } { [ESP+ 8] errPtr: PExcFrame } { [ESP+12] ctxPtr: Pointer } { [ESP+16] dspPtr: Pointer } { <- EAX return value - always one } MOV EAX,[ESP+4] MOV EDX,[ESP+8] TEST [EAX].TExceptionRecord.ExceptionFlags,cUnwindInProgress JE @@exit MOV ECX,[EDX].TExcFrame.desc MOV [EDX].TExcFrame.desc,offset @@exit PUSH EBX PUSH ESI PUSH EDI PUSH EBP MOV EBP,[EDX].TExcFrame.hEBP ADD ECX,TExcDesc.instructions CALL NotifyExceptFinally CALL ECX POP EBP POP EDI POP ESI POP EBX @@exit: MOV EAX,1 end; procedure _HandleAutoException; asm { -> [ESP+ 4] excPtr: PExceptionRecord } { [ESP+ 8] errPtr: PExcFrame } { [ESP+12] ctxPtr: Pointer } { [ESP+16] dspPtr: Pointer } { <- EAX return value - always one } MOV EAX,[ESP+4] TEST [EAX].TExceptionRecord.ExceptionFlags,cUnwindInProgress JNE @@exit CMP [EAX].TExceptionRecord.ExceptionCode,cDelphiException CLD CALL _FpuInit JE @@DelphiException CMP BYTE PTR JITEnable,0 JBE @@DelphiException CMP BYTE PTR DebugHook,0 JA @@DelphiException @@DoUnhandled: LEA EAX,[ESP+4] PUSH EAX CALL UnhandledExceptionFilter CMP EAX,EXCEPTION_CONTINUE_SEARCH JE @@exit MOV EAX,[ESP+4] JMP @@GoUnwind @@DelphiException: CMP BYTE PTR JITEnable,1 JBE @@GoUnwind CMP BYTE PTR DebugHook,0 JA @@GoUnwind JMP @@DoUnhandled @@GoUnwind: OR [EAX].TExceptionRecord.ExceptionFlags,cUnwinding PUSH ESI PUSH EDI PUSH EBP MOV EDX,[ESP+8+3*4] PUSH 0 PUSH EAX PUSH offset @@returnAddress PUSH EDX CALL RtlUnwind @@returnAddress: POP EBP POP EDI POP ESI MOV EAX,[ESP+4] MOV EBX,8000FFFFH CMP [EAX].TExceptionRecord.ExceptionCode,cDelphiException JNE @@done MOV EDX,[EAX].TExceptionRecord.ExceptObject MOV ECX,[EAX].TExceptionRecord.ExceptAddr MOV EAX,[ESP+8] MOV EAX,[EAX].TExcFrame.SelfOfMethod MOV EBX,[EAX] CALL [EBX].vmtSafeCallException.Pointer MOV EBX,EAX MOV EAX,[ESP+4] MOV EAX,[EAX].TExceptionRecord.ExceptObject CALL TObject.Free @@done: XOR EAX,EAX MOV ESP,[ESP+8] POP ECX MOV FS:[EAX],ECX POP EDX POP EBP LEA EDX,[EDX].TExcDesc.instructions POP ECX JMP EDX @@exit: MOV EAX,1 end; procedure _RaiseExcept; asm { When making changes to the way Delphi Exceptions are raised, } { please realize that the C++ Exception handling code reraises } { some exceptions as Delphi Exceptions. Of course we want to } { keep exception raising compatible between Delphi and C++, so } { when you make changes here, consult with the relevant C++ } { exception handling engineer. The C++ code is in xx.cpp, in } { the RTL sources, in function tossAnException. } { -> EAX Pointer to exception object } { [ESP] Error address } POP EDX PUSH ESP PUSH EBP PUSH EDI PUSH ESI PUSH EBX PUSH EAX { pass class argument } PUSH EDX { pass address argument } PUSH ESP { pass pointer to arguments } PUSH 7 { there are seven arguments } PUSH cNonContinuable { we can't continue execution } PUSH cDelphiException { our magic exception code } PUSH EDX { pass the user's return address } JMP RaiseException end; procedure _RaiseAgain; asm { -> [ESP ] return address to user program } { [ESP+ 4 ] raise list entry (4 dwords) } { [ESP+ 4+ 4*4] saved topmost frame } { [ESP+ 4+ 5*4] saved registers (4 dwords) } { [ESP+ 4+ 9*4] return address to OS } { -> [ESP+ 4+10*4] excPtr: PExceptionRecord } { [ESP+ 8+10*4] errPtr: PExcFrame } { Point the error handler of the exception frame to something harmless } MOV EAX,[ESP+8+10*4] MOV [EAX].TExcFrame.desc,offset @@exit { Pop the RaiseList } CALL SysInit.@GetTLS MOV EDX,[EAX].RaiseListPtr MOV ECX,[EDX].TRaiseFrame.NextRaise MOV [EAX].RaiseListPtr,ECX { Destroy any objects created for non-delphi exceptions } MOV EAX,[EDX].TRaiseFrame.ExceptionRecord AND [EAX].TExceptionRecord.ExceptionFlags,NOT cUnwinding CMP [EAX].TExceptionRecord.ExceptionCode,cDelphiException JE @@delphiException MOV EAX,[EDX].TRaiseFrame.ExceptObject CALL TObject.Free CALL NotifyReRaise @@delphiException: XOR EAX,EAX ADD ESP,5*4 MOV EDX,FS:[EAX] POP ECX MOV EDX,[EDX].TExcFrame.next MOV [ECX].TExcFrame.next,EDX POP EBP POP EDI POP ESI POP EBX @@exit: MOV EAX,1 end; procedure _DoneExcept; asm { -> [ESP+ 4+10*4] excPtr: PExceptionRecord } { [ESP+ 8+10*4] errPtr: PExcFrame } { Pop the RaiseList } CALL SysInit.@GetTLS MOV EDX,[EAX].RaiseListPtr MOV ECX,[EDX].TRaiseFrame.NextRaise MOV [EAX].RaiseListPtr,ECX { Destroy exception object } MOV EAX,[EDX].TRaiseFrame.ExceptObject CALL TObject.Free POP EDX MOV ESP,[ESP+8+9*4] XOR EAX,EAX POP ECX MOV FS:[EAX],ECX POP EAX POP EBP CALL NotifyTerminate JMP EDX end; procedure _TryFinallyExit; asm XOR EDX,EDX MOV ECX,[ESP+4].TExcFrame.desc MOV EAX,[ESP+4].TExcFrame.next ADD ECX,TExcDesc.instructions MOV FS:[EDX],EAX CALL ECX @@1: RET 12 end; type PInitContext = ^TInitContext; TInitContext = record OuterContext: PInitContext; { saved InitContext } ExcFrame: PExcFrame; { bottom exc handler } InitTable: PackageInfo; { unit init info } InitCount: Integer; { how far we got } Module: PLibModule; { ptr to module desc } DLLSaveEBP: Pointer; { saved regs for DLLs } DLLSaveEBX: Pointer; { saved regs for DLLs } DLLSaveESI: Pointer; { saved regs for DLLs } DLLSaveEDI: Pointer; { saved regs for DLLs } DLLInitState: Byte; ExitProcessTLS: procedure; { Shutdown for TLS } end; var InitContext: TInitContext; procedure RunErrorAt(ErrCode: Integer; ErrorAddr: Pointer); asm MOV [ESP],ErrorAddr JMP _RunError end; procedure MapToRunError(P: PExceptionRecord); stdcall; const STATUS_ACCESS_VIOLATION = $C0000005; STATUS_ARRAY_BOUNDS_EXCEEDED = $C000008C; STATUS_FLOAT_DENORMAL_OPERAND = $C000008D; STATUS_FLOAT_DIVIDE_BY_ZERO = $C000008E; STATUS_FLOAT_INEXACT_RESULT = $C000008F; STATUS_FLOAT_INVALID_OPERATION = $C0000090; STATUS_FLOAT_OVERFLOW = $C0000091; STATUS_FLOAT_STACK_CHECK = $C0000092; STATUS_FLOAT_UNDERFLOW = $C0000093; STATUS_INTEGER_DIVIDE_BY_ZERO = $C0000094; STATUS_INTEGER_OVERFLOW = $C0000095; STATUS_PRIVILEGED_INSTRUCTION = $C0000096; STATUS_STACK_OVERFLOW = $C00000FD; STATUS_CONTROL_C_EXIT = $C000013A; var ErrCode: Byte; begin case P.ExceptionCode of STATUS_INTEGER_DIVIDE_BY_ZERO: ErrCode := 200; STATUS_ARRAY_BOUNDS_EXCEEDED: ErrCode := 201; STATUS_FLOAT_OVERFLOW: ErrCode := 205; STATUS_FLOAT_INEXACT_RESULT, STATUS_FLOAT_INVALID_OPERATION, STATUS_FLOAT_STACK_CHECK: ErrCode := 207; STATUS_FLOAT_DIVIDE_BY_ZERO: ErrCode := 200; STATUS_INTEGER_OVERFLOW: ErrCode := 215; STATUS_FLOAT_UNDERFLOW, STATUS_FLOAT_DENORMAL_OPERAND: ErrCode := 206; STATUS_ACCESS_VIOLATION: ErrCode := 216; STATUS_PRIVILEGED_INSTRUCTION: ErrCode := 218; STATUS_CONTROL_C_EXIT: ErrCode := 217; STATUS_STACK_OVERFLOW: ErrCode := 202; else ErrCode := 255; end; RunErrorAt(ErrCode, P.ExceptionAddress); end; procedure _ExceptionHandler; asm MOV EAX,[ESP+4] TEST [EAX].TExceptionRecord.ExceptionFlags,cUnwindInProgress JNE @@exit CMP BYTE PTR DebugHook,0 JA @@ExecuteHandler LEA EAX,[ESP+4] PUSH EAX CALL UnhandledExceptionFilter CMP EAX,EXCEPTION_CONTINUE_SEARCH JNE @@ExecuteHandler JMP @@exit // MOV EAX,1 // RET @@ExecuteHandler: MOV EAX,[ESP+4] CLD CALL _FpuInit MOV EDX,[ESP+8] PUSH 0 PUSH EAX PUSH offset @@returnAddress PUSH EDX CALL RtlUnwind @@returnAddress: MOV EBX,[ESP+4] CMP [EBX].TExceptionRecord.ExceptionCode,cDelphiException MOV EDX,[EBX].TExceptionRecord.ExceptAddr MOV EAX,[EBX].TExceptionRecord.ExceptObject JE @@DelphiException2 MOV EDX,ExceptObjProc TEST EDX,EDX JE MapToRunError MOV EAX,EBX CALL EDX TEST EAX,EAX JE MapToRunError MOV EDX,[EBX].TExceptionRecord.ExceptionAddress @@DelphiException2: CALL NotifyUnhandled MOV ECX,ExceptProc TEST ECX,ECX JE @@noExceptProc CALL ECX { call ExceptProc(ExceptObject, ExceptAddr) } @@noExceptProc: MOV ECX,[ESP+4] MOV EAX,217 MOV EDX,[ECX].TExceptionRecord.ExceptAddr MOV [ESP],EDX JMP _RunError @@exit: XOR EAX,EAX end; procedure SetExceptionHandler; asm XOR EDX,EDX { using [EDX] saves some space over [0] } LEA EAX,[EBP-12] MOV ECX,FS:[EDX] { ECX := head of chain } MOV FS:[EDX],EAX { head of chain := @exRegRec } MOV [EAX].TExcFrame.next,ECX MOV [EAX].TExcFrame.desc,offset _ExceptionHandler MOV [EAX].TExcFrame.hEBP,EBP MOV InitContext.ExcFrame,EAX end; procedure UnsetExceptionHandler; asm XOR EDX,EDX MOV EAX,InitContext.ExcFrame MOV ECX,FS:[EDX] { ECX := head of chain } CMP EAX,ECX { simple case: our record is first } JNE @@search MOV EAX,[EAX] { head of chain := exRegRec.next } MOV FS:[EDX],EAX JMP @@exit @@loop: MOV ECX,[ECX] @@search: CMP ECX,-1 { at end of list? } JE @@exit { yes - didn't find it } CMP [ECX],EAX { is it the next one on the list? } JNE @@loop { no - look at next one on list } @@unlink: { yes - unlink our record } MOV EAX,[EAX] { get next record on list } MOV [ECX],EAX { unlink our record } @@exit: end; procedure FInitUnits; var Count: Integer; Table: PUnitEntryTable; P: procedure; begin if InitContext.InitTable = nil then exit; Count := InitContext.InitCount; Table := InitContext.InitTable^.UnitInfo; try while Count > 0 do begin Dec(Count); InitContext.InitCount := Count; P := Table^[Count].FInit; if Assigned(P) then P; end; except FInitUnits; { try to finalize the others } raise; end; end; procedure InitUnits; var Count, I: Integer; Table: PUnitEntryTable; P: procedure; begin if InitContext.InitTable = nil then exit; Count := InitContext.InitTable^.UnitCount; I := 0; Table := InitContext.InitTable^.UnitInfo; try while I < Count do begin P := Table^[I].Init; Inc(I); InitContext.InitCount := I; if Assigned(P) then P; end; except FInitUnits; raise; end; end; procedure _PackageLoad(const Table : PackageInfo); var SavedContext: TInitContext; begin SavedContext := InitContext; InitContext.DLLInitState := 0; InitContext.InitTable := Table; InitContext.InitCount := 0; InitContext.OuterContext := @SavedContext; try InitUnits; finally InitContext := SavedContext; end; end; procedure _PackageUnload(const Table : PackageInfo); var SavedContext: TInitContext; begin SavedContext := InitContext; InitContext.DLLInitState := 0; InitContext.InitTable := Table; InitContext.InitCount := Table^.UnitCount; InitContext.OuterContext := @SavedContext; try FInitUnits; finally InitContext := SavedContext; end; end; procedure _StartExe; asm { -> EAX InitTable } { EDX Module } MOV InitContext.InitTable,EAX XOR EAX,EAX MOV InitContext.InitCount,EAX MOV InitContext.Module,EDX MOV EAX,[EDX].TLibModule.Instance MOV MainInstance,EAX CALL SetExceptionHandler MOV IsLibrary,0 CALL InitUnits; end; procedure _StartLib; asm { -> EAX InitTable } { EDX Module } { ECX InitTLS } { [ESP+4] DllProc } { [EBP+8] HInst } { [EBP+12] Reason } { Push some desperately needed registers } PUSH ECX PUSH ESI PUSH EDI { Save the current init context into the stackframe of our caller } MOV ESI,offset InitContext LEA EDI,[EBP- (type TExcFrame) - (type TInitContext)] MOV ECX,(type TInitContext)/4 REP MOVSD { Setup the current InitContext } POP InitContext.DLLSaveEDI POP InitContext.DLLSaveESI MOV InitContext.DLLSaveEBP,EBP MOV InitContext.DLLSaveEBX,EBX MOV InitContext.InitTable,EAX MOV InitContext.Module,EDX LEA ECX,[EBP- (type TExcFrame) - (type TInitContext)] MOV InitContext.OuterContext,ECX XOR ECX,ECX CMP dword ptr [EBP+12],0 JNE @@notShutDown MOV ECX,[EAX].PackageInfoTable.UnitCount @@notShutDown: MOV InitContext.InitCount,ECX CALL SetExceptionHandler MOV EAX,[EBP+12] INC EAX MOV InitContext.DLLInitState,AL DEC EAX { Init any needed TLS } POP ECX MOV EDX,[ECX] MOV InitContext.ExitProcessTLS,EDX JE @@noTLSproc CALL dword ptr [ECX+EAX*4] @@noTLSproc: { Call any DllProc } MOV EDX,[ESP+4] TEST EDX,EDX JE @@noDllProc MOV EAX,[EBP+12] CALL EDX @@noDllProc: { Set IsLibrary if there was no exe yet } CMP MainInstance,0 JNE @@haveExe MOV IsLibrary,1 FNSTCW Default8087CW // save host exe's FPU preferences @@haveExe: MOV EAX,[EBP+12] DEC EAX JNE _Halt0 CALL InitUnits RET 4 end; procedure _InitResStrings; asm { -> EAX Pointer to init table } { record } { cnt: Integer; } { tab: array [1..cnt] record } { variableAddress: Pointer; } { resStringAddress: Pointer; } { end; } { end; } PUSH EBX PUSH ESI MOV EBX,[EAX] LEA ESI,[EAX+4] @@loop: MOV EAX,[ESI+4] { load resStringAddress } MOV EDX,[ESI] { load variableAddress } CALL LoadResString ADD ESI,8 DEC EBX JNZ @@loop POP ESI POP EBX end; procedure _InitResStringImports; asm { -> EAX Pointer to init table } { record } { cnt: Integer; } { tab: array [1..cnt] record } { variableAddress: Pointer; } { resStringAddress: ^Pointer; } { end; } { end; } PUSH EBX PUSH ESI MOV EBX,[EAX] LEA ESI,[EAX+4] @@loop: MOV EAX,[ESI+4] { load address of import } MOV EDX,[ESI] { load address of variable } MOV EAX,[EAX] { load contents of import } CALL LoadResString ADD ESI,8 DEC EBX JNZ @@loop POP ESI POP EBX end; procedure _InitImports; asm { -> EAX Pointer to init table } { record } { cnt: Integer; } { tab: array [1..cnt] record } { variableAddress: Pointer; } { sourceAddress: ^Pointer; } { sourceOffset: Longint; } { end; } { end; } PUSH EBX PUSH ESI MOV EBX,[EAX] LEA ESI,[EAX+4] @@loop: MOV EAX,[ESI+4] { load address of import } MOV EDX,[ESI] { load address of variable } MOV ECX,[ESI+8] { load offset } MOV EAX,[EAX] { load contents of import } ADD EAX,ECX { calc address of variable } MOV [EDX],EAX { store result } ADD ESI,12 DEC EBX JNZ @@loop POP ESI POP EBX end; procedure _InitWideStrings; asm { -> EAX Pointer to init table } { record } { cnt: Integer; } { tab: array [1..cnt] record } { variableAddress: Pointer; } { stringAddress: ^Pointer; } { end; } { end; } PUSH EBX PUSH ESI MOV EBX,[EAX] LEA ESI,[EAX+4] @@loop: MOV EDX,[ESI+4] { load address of string } MOV EAX,[ESI] { load address of variable } CALL _WStrAsg ADD ESI,8 DEC EBX JNZ @@loop POP ESI POP EBX end; var runErrMsg: array[0..29] of Char = 'Runtime error at 00000000'#0; // columns: 0123456789012345678901234567890 errCaption: array[0..5] of Char = 'Error'#0; procedure MakeErrorMessage; const dig : array [0..15] of Char = '0123456789ABCDEF'; asm PUSH EBX MOV EAX,ExitCode MOV EBX,offset runErrMsg + 16 MOV ECX,10 @@digLoop: XOR EDX,EDX DIV ECX ADD DL,'0' MOV [EBX],DL DEC EBX TEST EAX,EAX JNZ @@digLoop MOV EAX,ErrorAddr CALL FindHInstance MOV EDX, ErrorAddr XCHG EAX, EDX SUB EAX, EDX { EAX <=> offset from start of code for HINSTANCE } MOV EBX,offset runErrMsg + 28 @@hdigLoop: MOV EDX,EAX AND EDX,0FH MOV DL,byte ptr dig[EDX] MOV [EBX],DL DEC EBX SHR EAX,4 JNE @@hdigLoop POP EBX end; procedure ExitDll; asm { Restore the InitContext } MOV EDI,offset InitContext MOV EBX,InitContext.DLLSaveEBX MOV EBP,InitContext.DLLSaveEBP PUSH [EDI].TInitContext.DLLSaveESI PUSH [EDI].TInitContext.DLLSaveEDI MOV ESI,[EDI].TInitContext.OuterContext MOV ECX,(type TInitContext)/4 REP MOVSD POP EDI POP ESI { Return False if ExitCode <> 0, and set ExitCode to 0 } XOR EAX,EAX XCHG EAX,ExitCode NEG EAX SBB EAX,EAX INC EAX LEAVE RET 12 end; procedure _Halt0; var P: procedure; begin if InitContext.DLLInitState = 0 then while ExitProc <> nil do begin @P := ExitProc; ExitProc := nil; P; end; { If there was some kind of runtime error, alert the user } if ErrorAddr <> nil then begin MakeErrorMessage; if IsConsole then WriteLn(PChar(@runErrMsg)) else if not NoErrMsg then MessageBox(0, runErrMsg, errCaption, 0); ErrorAddr := nil; end; { This loop exists because we might be nested in PackageLoad calls when } { Halt got called. We need to unwind these contexts. } while True do begin { If we are a library, and we are starting up fine, there are no units to finalize } if (InitContext.DLLInitState = 2) and (ExitCode = 0) then InitContext.InitCount := 0; { Undo any unit initializations accomplished so far } FInitUnits; if (InitContext.DLLInitState <= 1) or (ExitCode <> 0) then if InitContext.Module <> nil then with InitContext do begin UnregisterModule(Module); if Module.ResInstance <> Module.Instance then FreeLibrary(Module.ResInstance); end; UnsetExceptionHandler; if InitContext.DllInitState = 1 then InitContext.ExitProcessTLS; if InitContext.DllInitState <> 0 then ExitDll; if InitContext.OuterContext = nil then ExitProcess(ExitCode); InitContext := InitContext.OuterContext^ end; asm db 'Portions Copyright (c) 1983,99 Borland',0 end; end; procedure _Halt; asm MOV ExitCode,EAX JMP _Halt0 end; procedure _Run0Error; asm XOR EAX,EAX JMP _RunError end; procedure _RunError; asm POP ErrorAddr JMP _Halt end; procedure _Assert(const Message, Filename: AnsiString; LineNumber: Integer); asm CMP AssertErrorProc,0 JE @@1 PUSH [ESP].Pointer CALL AssertErrorProc RET @@1: MOV AL,reAssertionFailed JMP Error end; type PThreadRec = ^TThreadRec; TThreadRec = record Func: TThreadFunc; Parameter: Pointer; end; function ThreadWrapper(Parameter: Pointer): Integer; stdcall; asm CALL _FpuInit XOR ECX,ECX PUSH EBP PUSH offset _ExceptionHandler MOV EDX,FS:[ECX] PUSH EDX MOV EAX,Parameter MOV FS:[ECX],ESP MOV ECX,[EAX].TThreadRec.Parameter MOV EDX,[EAX].TThreadRec.Func PUSH ECX PUSH EDX CALL _FreeMem POP EDX POP EAX CALL EDX XOR EDX,EDX POP ECX MOV FS:[EDX],ECX POP ECX POP EBP end; function BeginThread(SecurityAttributes: Pointer; StackSize: LongWord; ThreadFunc: TThreadFunc; Parameter: Pointer; CreationFlags: LongWord; var ThreadId: LongWord): Integer; var P: PThreadRec; begin New(P); P.Func := ThreadFunc; P.Parameter := Parameter; IsMultiThread := TRUE; Result := CreateThread(SecurityAttributes, StackSize, @ThreadWrapper, P, CreationFlags, ThreadID); end; procedure EndThread(ExitCode: Integer); begin ExitThread(ExitCode); end; type StrRec = packed record allocSiz: Longint; refCnt: Longint; length: Longint; end; const skew = sizeof(StrRec); rOff = sizeof(StrRec) - sizeof(Longint); { refCnt offset } overHead = sizeof(StrRec) + 1; procedure _LStrClr(var S: AnsiString); asm { -> EAX pointer to str } MOV EDX,[EAX] { fetch str } TEST EDX,EDX { if nil, nothing to do } JE @@done MOV dword ptr [EAX],0 { clear str } MOV ECX,[EDX-skew].StrRec.refCnt { fetch refCnt } DEC ECX { if < 0: literal str } JL @@done LOCK DEC [EDX-skew].StrRec.refCnt { threadsafe dec refCount } JNE @@done PUSH EAX LEA EAX,[EDX-skew].StrRec.refCnt { if refCnt now zero, deallocate} CALL _FreeMem POP EAX @@done: end; procedure _LStrArrayClr{var str: AnsiString; cnt: longint}; asm { -> EAX pointer to str } { EDX cnt } PUSH EBX PUSH ESI MOV EBX,EAX MOV ESI,EDX @@loop: MOV EDX,[EBX] { fetch str } TEST EDX,EDX { if nil, nothing to do } JE @@doneEntry MOV dword ptr [EBX],0 { clear str } MOV ECX,[EDX-skew].StrRec.refCnt { fetch refCnt } DEC ECX { if < 0: literal str } JL @@doneEntry LOCK DEC [EDX-skew].StrRec.refCnt { threadsafe dec refCount } JNE @@doneEntry LEA EAX,[EDX-skew].StrRec.refCnt { if refCnt now zero, deallocate} CALL _FreeMem @@doneEntry: ADD EBX,4 DEC ESI JNE @@loop POP ESI POP EBX end; { 99.03.11 This function is used when assigning to global variables. Literals are copied to prevent a situation where a dynamically allocated DLL or package assigns a literal to a variable and then is unloaded -- thereby causing the string memory (in the code segment of the DLL) to be removed -- and therefore leaving the global variable pointing to invalid memory. } procedure _LStrAsg{var dest: AnsiString; source: AnsiString}; asm { -> EAX pointer to dest str } { -> EDX pointer to source str } TEST EDX,EDX { have a source? } JE @@2 { no -> jump } MOV ECX,[EDX-skew].StrRec.refCnt INC ECX JG @@1 { literal string -> jump not taken } PUSH EAX PUSH EDX MOV EAX,[EDX-skew].StrRec.length CALL _NewAnsiString MOV EDX,EAX POP EAX PUSH EDX MOV ECX,[EAX-skew].StrRec.length CALL Move POP EDX POP EAX JMP @@2 @@1: LOCK INC [EDX-skew].StrRec.refCnt @@2: XCHG EDX,[EAX] TEST EDX,EDX JE @@3 MOV ECX,[EDX-skew].StrRec.refCnt DEC ECX JL @@3 LOCK DEC [EDX-skew].StrRec.refCnt JNE @@3 LEA EAX,[EDX-skew].StrRec.refCnt CALL _FreeMem @@3: end; procedure _LStrLAsg{var dest: AnsiString; source: AnsiString}; asm { -> EAX pointer to dest } { EDX source } TEST EDX,EDX JE @@sourceDone { bump up the ref count of the source } MOV ECX,[EDX-skew].StrRec.refCnt INC ECX JLE @@sourceDone { literal assignment -> jump taken } LOCK INC [EDX-skew].StrRec.refCnt @@sourceDone: { we need to release whatever the dest is pointing to } XCHG EDX,[EAX] { fetch str } TEST EDX,EDX { if nil, nothing to do } JE @@done MOV ECX,[EDX-skew].StrRec.refCnt { fetch refCnt } DEC ECX { if < 0: literal str } JL @@done LOCK DEC [EDX-skew].StrRec.refCnt { threadsafe dec refCount } JNE @@done LEA EAX,[EDX-skew].StrRec.refCnt { if refCnt now zero, deallocate} CALL _FreeMem @@done: end; procedure _NewAnsiString{length: Longint}; asm { -> EAX length } { <- EAX pointer to new string } TEST EAX,EAX JLE @@null PUSH EAX ADD EAX,rOff+1 CALL _GetMem ADD EAX,rOff POP EDX MOV [EAX-skew].StrRec.length,EDX MOV [EAX-skew].StrRec.refCnt,1 MOV byte ptr [EAX+EDX],0 RET @@null: XOR EAX,EAX end; procedure _LStrFromPCharLen(var Dest: AnsiString; Source: PAnsiChar; Length: Integer); asm { -> EAX pointer to dest } { EDX source } { ECX length } PUSH EBX PUSH ESI PUSH EDI MOV EBX,EAX MOV ESI,EDX MOV EDI,ECX { allocate new string } MOV EAX,EDI CALL _NewAnsiString MOV ECX,EDI MOV EDI,EAX TEST ESI,ESI JE @@noMove MOV EDX,EAX MOV EAX,ESI CALL Move { assign the result to dest } @@noMove: MOV EAX,EBX CALL _LStrClr MOV [EBX],EDI POP EDI POP ESI POP EBX end; procedure _LStrFromPWCharLen(var Dest: AnsiString; Source: PWideChar; Length: Integer); var DestLen: Integer; Buffer: array[0..2047] of Char; begin if Length <= 0 then begin _LStrClr(Dest); Exit; end; if Length < SizeOf(Buffer) div 2 then begin DestLen := WideCharToMultiByte(0, 0, Source, Length, Buffer, SizeOf(Buffer), nil, nil); if DestLen > 0 then begin _LStrFromPCharLen(Dest, Buffer, DestLen); Exit; end; end; DestLen := WideCharToMultiByte(0, 0, Source, Length, nil, 0, nil, nil); _LStrFromPCharLen(Dest, nil, DestLen); WideCharToMultiByte(0, 0, Source, Length, Pointer(Dest), DestLen, nil, nil); end; procedure _LStrFromChar(var Dest: AnsiString; Source: AnsiChar); asm PUSH EDX MOV EDX,ESP MOV ECX,1 CALL _LStrFromPCharLen POP EDX end; procedure _LStrFromWChar(var Dest: AnsiString; Source: WideChar); asm PUSH EDX MOV EDX,ESP MOV ECX,1 CALL _LStrFromPWCharLen POP EDX end; procedure _LStrFromPChar(var Dest: AnsiString; Source: PAnsiChar); asm XOR ECX,ECX TEST EDX,EDX JE @@5 PUSH EDX @@0: CMP CL,[EDX+0] JE @@4 CMP CL,[EDX+1] JE @@3 CMP CL,[EDX+2] JE @@2 CMP CL,[EDX+3] JE @@1 ADD EDX,4 JMP @@0 @@1: INC EDX @@2: INC EDX @@3: INC EDX @@4: MOV ECX,EDX POP EDX SUB ECX,EDX @@5: JMP _LStrFromPCharLen end; procedure _LStrFromPWChar(var Dest: AnsiString; Source: PWideChar); asm XOR ECX,ECX TEST EDX,EDX JE @@5 PUSH EDX @@0: CMP CX,[EDX+0] JE @@4 CMP CX,[EDX+2] JE @@3 CMP CX,[EDX+4] JE @@2 CMP CX,[EDX+6] JE @@1 ADD EDX,8 JMP @@0 @@1: ADD EDX,2 @@2: ADD EDX,2 @@3: ADD EDX,2 @@4: MOV ECX,EDX POP EDX SUB ECX,EDX SHR ECX,1 @@5: JMP _LStrFromPWCharLen end; procedure _LStrFromString(var Dest: AnsiString; const Source: ShortString); asm XOR ECX,ECX MOV CL,[EDX] INC EDX JMP _LStrFromPCharLen end; procedure _LStrFromArray(var Dest: AnsiString; Source: PAnsiChar; Length: Integer); asm PUSH EDI PUSH EAX PUSH ECX MOV EDI,EDX XOR EAX,EAX REPNE SCASB JNE @@1 NOT ECX @@1: POP EAX ADD ECX,EAX POP EAX POP EDI JMP _LStrFromPCharLen end; procedure _LStrFromWArray(var Dest: AnsiString; Source: PWideChar; Length: Integer); asm PUSH EDI PUSH EAX PUSH ECX MOV EDI,EDX XOR EAX,EAX REPNE SCASW JNE @@1 NOT ECX @@1: POP EAX ADD ECX,EAX POP EAX POP EDI JMP _LStrFromPWCharLen end; procedure _LStrFromWStr(var Dest: AnsiString; const Source: WideString); asm { -> EAX pointer to dest } { EDX pointer to WideString data } XOR ECX,ECX TEST EDX,EDX JE @@1 MOV ECX,[EDX-4] SHR ECX,1 @@1: JMP _LStrFromPWCharLen end; procedure _LStrToString{(var Dest: ShortString; const Source: AnsiString; MaxLen: Integer)}; asm { -> EAX pointer to result } { EDX AnsiString s } { ECX length of result } PUSH EBX TEST EDX,EDX JE @@empty MOV EBX,[EDX-skew].StrRec.length TEST EBX,EBX JE @@empty CMP ECX,EBX JL @@truncate MOV ECX,EBX @@truncate: MOV [EAX],CL INC EAX XCHG EAX,EDX CALL Move JMP @@exit @@empty: MOV byte ptr [EAX],0 @@exit: POP EBX end; function _LStrLen{str: AnsiString}: Longint; asm { -> EAX str } TEST EAX,EAX JE @@done MOV EAX,[EAX-skew].StrRec.length; @@done: end; procedure _LStrCat{var dest: AnsiString; source: AnsiString}; asm { -> EAX pointer to dest } { EDX source } TEST EDX,EDX JE @@exit MOV ECX,[EAX] TEST ECX,ECX JE _LStrAsg PUSH EBX PUSH ESI PUSH EDI MOV EBX,EAX MOV ESI,EDX MOV EDI,[ECX-skew].StrRec.length MOV EDX,[ESI-skew].StrRec.length ADD EDX,EDI CMP ESI,ECX JE @@appendSelf CALL _LStrSetLength MOV EAX,ESI MOV ECX,[ESI-skew].StrRec.length @@appendStr: MOV EDX,[EBX] ADD EDX,EDI CALL Move POP EDI POP ESI POP EBX RET @@appendSelf: CALL _LStrSetLength MOV EAX,[EBX] MOV ECX,EDI JMP @@appendStr @@exit: end; procedure _LStrCat3{var dest:AnsiString; source1: AnsiString; source2: AnsiString}; asm { ->EAX = Pointer to dest } { EDX = source1 } { ECX = source2 } TEST EDX,EDX JE @@assignSource2 TEST ECX,ECX JE _LStrAsg CMP EDX,[EAX] JE @@appendToDest CMP ECX,[EAX] JE @@theHardWay PUSH EAX PUSH ECX CALL _LStrAsg POP EDX POP EAX JMP _LStrCat @@theHardWay: PUSH EBX PUSH ESI PUSH EDI MOV EBX,EDX MOV ESI,ECX PUSH EAX MOV EAX,[EBX-skew].StrRec.length ADD EAX,[ESI-skew].StrRec.length CALL _NewAnsiString MOV EDI,EAX MOV EDX,EAX MOV EAX,EBX MOV ECX,[EBX-skew].StrRec.length CALL Move MOV EDX,EDI MOV EAX,ESI MOV ECX,[ESI-skew].StrRec.length ADD EDX,[EBX-skew].StrRec.length CALL Move POP EAX MOV EDX,EDI TEST EDI,EDI JE @@skip DEC [EDI-skew].StrRec.refCnt // EDI = local temp str @@skip: CALL _LStrAsg POP EDI POP ESI POP EBX JMP @@exit @@assignSource2: MOV EDX,ECX JMP _LStrAsg @@appendToDest: MOV EDX,ECX JMP _LStrCat @@exit: end; procedure _LStrCatN{var dest:AnsiString; argCnt: Integer; ...}; asm { ->EAX = Pointer to dest } { EDX = number of args (>= 3) } { [ESP+4], [ESP+8], ... crgCnt AnsiString arguments } PUSH EBX PUSH ESI PUSH EDX PUSH EAX MOV EBX,EDX XOR EAX,EAX @@loop1: MOV ECX,[ESP+EDX*4+4*4] TEST ECX,ECX JE @@1 ADD EAX,[ECX-skew].StrRec.length @@1: DEC EDX JNE @@loop1 CALL _NewAnsiString PUSH EAX MOV ESI,EAX @@loop2: MOV EAX,[ESP+EBX*4+5*4] MOV EDX,ESI TEST EAX,EAX JE @@2 MOV ECX,[EAX-skew].StrRec.length ADD ESI,ECX CALL Move @@2: DEC EBX JNE @@loop2 POP EDX POP EAX TEST EDX,EDX JE @@skip DEC [EDX-skew].StrRec.refCnt // EDX = local temp str @@skip: CALL _LStrAsg POP EDX POP ESI POP EBX POP EAX LEA ESP,[ESP+EDX*4] JMP EAX end; procedure _LStrCmp{left: AnsiString; right: AnsiString}; asm { ->EAX = Pointer to left string } { EDX = Pointer to right string } PUSH EBX PUSH ESI PUSH EDI MOV ESI,EAX MOV EDI,EDX CMP EAX,EDX JE @@exit TEST ESI,ESI JE @@str1null TEST EDI,EDI JE @@str2null MOV EAX,[ESI-skew].StrRec.length MOV EDX,[EDI-skew].StrRec.length SUB EAX,EDX { eax = len1 - len2 } JA @@skip1 ADD EDX,EAX { edx = len2 + (len1 - len2) = len1 } @@skip1: PUSH EDX SHR EDX,2 JE @@cmpRest @@longLoop: MOV ECX,[ESI] MOV EBX,[EDI] CMP ECX,EBX JNE @@misMatch DEC EDX JE @@cmpRestP4 MOV ECX,[ESI+4] MOV EBX,[EDI+4] CMP ECX,EBX JNE @@misMatch ADD ESI,8 ADD EDI,8 DEC EDX JNE @@longLoop JMP @@cmpRest @@cmpRestP4: ADD ESI,4 ADD EDI,4 @@cmpRest: POP EDX AND EDX,3 JE @@equal MOV ECX,[ESI] MOV EBX,[EDI] CMP CL,BL JNE @@exit DEC EDX JE @@equal CMP CH,BH JNE @@exit DEC EDX JE @@equal AND EBX,$00FF0000 AND ECX,$00FF0000 CMP ECX,EBX JNE @@exit @@equal: ADD EAX,EAX JMP @@exit @@str1null: MOV EDX,[EDI-skew].StrRec.length SUB EAX,EDX JMP @@exit @@str2null: MOV EAX,[ESI-skew].StrRec.length SUB EAX,EDX JMP @@exit @@misMatch: POP EDX CMP CL,BL JNE @@exit CMP CH,BH JNE @@exit SHR ECX,16 SHR EBX,16 CMP CL,BL JNE @@exit CMP CH,BH @@exit: POP EDI POP ESI POP EBX end; procedure _LStrAddRef{str: AnsiString}; asm { -> EAX str } TEST EAX,EAX JE @@exit MOV EDX,[EAX-skew].StrRec.refCnt INC EDX JLE @@exit LOCK INC [EAX-skew].StrRec.refCnt @@exit: end; procedure _LStrToPChar{str: AnsiString): PChar}; asm { -> EAX pointer to str } { <- EAX pointer to PChar } TEST EAX,EAX JE @@handle0 RET @@zeroByte: DB 0 @@handle0: MOV EAX,offset @@zeroByte end; procedure UniqueString(var str: string); asm { -> EAX pointer to str } { <- EAX pointer to unique copy } MOV EDX,[EAX] TEST EDX,EDX JE @@exit MOV ECX,[EDX-skew].StrRec.refCnt DEC ECX JE @@exit PUSH EBX MOV EBX,EAX MOV EAX,[EDX-skew].StrRec.length CALL _NewAnsiString MOV EDX,EAX MOV EAX,[EBX] MOV [EBX],EDX MOV ECX,[EAX-skew].StrRec.refCnt DEC ECX JL @@skip LOCK DEC [EAX-skew].StrRec.refCnt @@skip: MOV ECX,[EAX-skew].StrRec.length CALL Move MOV EDX,[EBX] POP EBX @@exit: MOV EAX,EDX end; procedure _LStrCopy{ const s : AnsiString; index, count : Integer) : AnsiString}; asm { ->EAX Source string } { EDX index } { ECX count } { [ESP+4] Pointer to result string } PUSH EBX TEST EAX,EAX JE @@srcEmpty MOV EBX,[EAX-skew].StrRec.length TEST EBX,EBX JE @@srcEmpty { make index 0-based and limit to 0 <= index < Length(src) } DEC EDX JL @@smallInx CMP EDX,EBX JGE @@bigInx @@cont1: { limit count to satisfy 0 <= count <= Length(src) - index } SUB EBX,EDX { calculate Length(src) - index } TEST ECX,ECX JL @@smallCount CMP ECX,EBX JG @@bigCount @@cont2: ADD EDX,EAX MOV EAX,[ESP+4+4] CALL _LStrFromPCharLen JMP @@exit @@smallInx: XOR EDX,EDX JMP @@cont1 @@bigCount: MOV ECX,EBX JMP @@cont2 @@bigInx: @@smallCount: @@srcEmpty: MOV EAX,[ESP+4+4] CALL _LStrClr @@exit: POP EBX RET 4 end; procedure _LStrDelete{ var s : AnsiString; index, count : Integer }; asm { ->EAX Pointer to s } { EDX index } { ECX count } PUSH EBX PUSH ESI PUSH EDI MOV EBX,EAX MOV ESI,EDX MOV EDI,ECX CALL UniqueString MOV EDX,[EBX] TEST EDX,EDX { source already empty: nothing to do } JE @@exit MOV ECX,[EDX-skew].StrRec.length { make index 0-based, if not in [0 .. Length(s)-1] do nothing } DEC ESI JL @@exit CMP ESI,ECX JGE @@exit { limit count to [0 .. Length(s) - index] } TEST EDI,EDI JLE @@exit SUB ECX,ESI { ECX = Length(s) - index } CMP EDI,ECX JLE @@1 MOV EDI,ECX @@1: { move length - index - count characters from s+index+count to s+index } SUB ECX,EDI { ECX = Length(s) - index - count } ADD EDX,ESI { EDX = s+index } LEA EAX,[EDX+EDI] { EAX = s+index+count } CALL Move { set length(s) to length(s) - count } MOV EDX,[EBX] MOV EAX,EBX MOV EDX,[EDX-skew].StrRec.length SUB EDX,EDI CALL _LStrSetLength @@exit: POP EDI POP ESI POP EBX end; procedure _LStrInsert{ const source : AnsiString; var s : AnsiString; index : Integer }; asm { -> EAX source string } { EDX pointer to destination string } { ECX index } TEST EAX,EAX JE @@nothingToDo PUSH EBX PUSH ESI PUSH EDI PUSH EBP MOV EBX,EAX MOV ESI,EDX MOV EDI,ECX { make index 0-based and limit to 0 <= index <= Length(s) } MOV EDX,[EDX] PUSH EDX TEST EDX,EDX JE @@sIsNull MOV EDX,[EDX-skew].StrRec.length @@sIsNull: DEC EDI JGE @@indexNotLow XOR EDI,EDI @@indexNotLow: CMP EDI,EDX JLE @@indexNotHigh MOV EDI,EDX @@indexNotHigh: MOV EBP,[EBX-skew].StrRec.length { set length of result to length(source) + length(s) } MOV EAX,ESI ADD EDX,EBP CALL _LStrSetLength POP EAX CMP EAX,EBX JNE @@notInsertSelf MOV EBX,[ESI] @@notInsertSelf: { move length(s) - length(source) - index chars from s+index to s+index+length(source) } MOV EAX,[ESI] { EAX = s } LEA EDX,[EDI+EBP] { EDX = index + length(source) } MOV ECX,[EAX-skew].StrRec.length SUB ECX,EDX { ECX = length(s) - length(source) - index } ADD EDX,EAX { EDX = s + index + length(source) } ADD EAX,EDI { EAX = s + index } CALL Move { copy length(source) chars from source to s+index } MOV EAX,EBX MOV EDX,[ESI] MOV ECX,EBP ADD EDX,EDI CALL Move @@exit: POP EBP POP EDI POP ESI POP EBX @@nothingToDo: end; procedure _LStrPos{ const substr : AnsiString; const s : AnsiString ) : Integer}; asm { ->EAX Pointer to substr } { EDX Pointer to string } { <-EAX Position of substr in s or 0 } TEST EAX,EAX JE @@noWork TEST EDX,EDX JE @@stringEmpty PUSH EBX PUSH ESI PUSH EDI MOV ESI,EAX { Point ESI to substr } MOV EDI,EDX { Point EDI to s } MOV ECX,[EDI-skew].StrRec.length { ECX = Length(s) } PUSH EDI { remember s position to calculate index } MOV EDX,[ESI-skew].StrRec.length { EDX = Length(substr) } DEC EDX { EDX = Length(substr) - 1 } JS @@fail { < 0 ? return 0 } MOV AL,[ESI] { AL = first char of substr } INC ESI { Point ESI to 2'nd char of substr } SUB ECX,EDX { #positions in s to look at } { = Length(s) - Length(substr) + 1 } JLE @@fail @@loop: REPNE SCASB JNE @@fail MOV EBX,ECX { save outer loop counter } PUSH ESI { save outer loop substr pointer } PUSH EDI { save outer loop s pointer } MOV ECX,EDX REPE CMPSB POP EDI { restore outer loop s pointer } POP ESI { restore outer loop substr pointer } JE @@found MOV ECX,EBX { restore outer loop counter } JMP @@loop @@fail: POP EDX { get rid of saved s pointer } XOR EAX,EAX JMP @@exit @@stringEmpty: XOR EAX,EAX JMP @@noWork @@found: POP EDX { restore pointer to first char of s } MOV EAX,EDI { EDI points of char after match } SUB EAX,EDX { the difference is the correct index } @@exit: POP EDI POP ESI POP EBX @@noWork: end; procedure _LStrSetLength{ var str: AnsiString; newLength: Integer}; asm { -> EAX Pointer to str } { EDX new length } PUSH EBX PUSH ESI PUSH EDI MOV EBX,EAX MOV ESI,EDX XOR EDI,EDI TEST EDX,EDX JE @@setString MOV EAX,[EBX] TEST EAX,EAX JE @@copyString CMP [EAX-skew].StrRec.refCnt,1 JNE @@copyString SUB EAX,rOff ADD EDX,rOff+1 PUSH EAX MOV EAX,ESP CALL _ReallocMem POP EAX ADD EAX,rOff MOV [EBX],EAX MOV [EAX-skew].StrRec.length,ESI MOV BYTE PTR [EAX+ESI],0 JMP @@exit @@copyString: MOV EAX,EDX CALL _NewAnsiString MOV EDI,EAX MOV EAX,[EBX] TEST EAX,EAX JE @@setString MOV EDX,EDI MOV ECX,[EAX-skew].StrRec.length CMP ECX,ESI JL @@moveString MOV ECX,ESI @@moveString: CALL Move @@setString: MOV EAX,EBX CALL _LStrClr MOV [EBX],EDI @@exit: POP EDI POP ESI POP EBX end; procedure _LStrOfChar{ c: Char; count: Integer): AnsiString }; asm { -> AL c } { EDX count } { ECX result } PUSH EBX PUSH ESI PUSH EDI MOV EBX,EAX MOV ESI,EDX MOV EDI,ECX MOV EAX,ECX CALL _LStrClr TEST ESI,ESI JLE @@exit MOV EAX,ESI CALL _NewAnsiString MOV [EDI],EAX MOV EDX,ESI MOV CL,BL CALL _FillChar @@exit: POP EDI POP ESI POP EBX end; procedure _Write0LString{ VAR t: Text; s: AnsiString }; asm { -> EAX Pointer to text record } { EDX Pointer to AnsiString } XOR ECX,ECX JMP _WriteLString end; procedure _WriteLString{ VAR t: Text; s: AnsiString; width: Longint }; asm { -> EAX Pointer to text record } { EDX Pointer to AnsiString } { ECX Field width } PUSH EBX MOV EBX,EDX MOV EDX,ECX XOR ECX,ECX TEST EBX,EBX JE @@skip MOV ECX,[EBX-skew].StrRec.length SUB EDX,ECX @@skip: PUSH ECX CALL _WriteSpaces POP ECX MOV EDX,EBX POP EBX JMP _WriteBytes end; procedure _ReadLString{var t: Text; var str: AnsiString}; asm { -> EAX pointer to Text } { EDX pointer to AnsiString } PUSH EBX PUSH ESI MOV EBX,EAX MOV ESI,EDX MOV EAX,EDX CALL _LStrClr SUB ESP,256 MOV EAX,EBX MOV EDX,ESP MOV ECX,255 CALL _ReadString MOV EAX,ESI MOV EDX,ESP CALL _LStrFromString CMP byte ptr [ESP],255 JNE @@exit @@loop: MOV EAX,EBX MOV EDX,ESP MOV ECX,255 CALL _ReadString MOV EDX,ESP PUSH 0 MOV EAX,ESP CALL _LStrFromString MOV EAX,ESI MOV EDX,[ESP] CALL _LStrCat MOV EAX,ESP CALL _LStrClr POP EAX CMP byte ptr [ESP],255 JE @@loop @@exit: ADD ESP,256 POP ESI POP EBX end; procedure WStrError; asm MOV AL,reOutOfMemory JMP Error end; procedure WStrSet(var S: WideString; P: PWideChar); asm MOV ECX,[EAX] MOV [EAX],EDX TEST ECX,ECX JE @@1 PUSH ECX CALL SysFreeString @@1: end; procedure _WStrClr(var S: WideString); asm { -> EAX Pointer to WideString } MOV EDX,[EAX] TEST EDX,EDX JE @@1 MOV DWORD PTR [EAX],0 PUSH EAX PUSH EDX CALL SysFreeString POP EAX @@1: end; procedure _WStrArrayClr(var StrArray; Count: Integer); asm PUSH EBX PUSH ESI MOV EBX,EAX MOV ESI,EDX @@1: MOV EAX,[EBX] TEST EAX,EAX JE @@2 MOV DWORD PTR [EBX],0 PUSH EAX CALL SysFreeString @@2: ADD EBX,4 DEC ESI JNE @@1 POP ESI POP EBX end; procedure _WStrAsg(var Dest: WideString; const Source: WideString); asm { -> EAX Pointer to WideString } { EDX Pointer to data } TEST EDX,EDX JE _WStrClr MOV ECX,[EDX-4] SHR ECX,1 JE _WStrClr PUSH ECX PUSH EDX PUSH EAX CALL SysReAllocStringLen TEST EAX,EAX JE WStrError end; procedure _WStrFromPCharLen(var Dest: WideString; Source: PAnsiChar; Length: Integer); var DestLen: Integer; Buffer: array[0..1023] of WideChar; begin if Length <= 0 then begin _WStrClr(Dest); Exit; end; if Length < SizeOf(Buffer) div 2 then begin DestLen := MultiByteToWideChar(0, 0, Source, Length, Buffer, SizeOf(Buffer) div 2); if DestLen > 0 then begin _WStrFromPWCharLen(Dest, Buffer, DestLen); Exit; end; end; DestLen := MultiByteToWideChar(0, 0, Source, Length, nil, 0); _WStrFromPWCharLen(Dest, nil, DestLen); MultiByteToWideChar(0, 0, Source, Length, Pointer(Dest), DestLen); end; procedure _WStrFromPWCharLen(var Dest: WideString; Source: PWideChar; Length: Integer); asm { -> EAX Pointer to WideString (dest) } { EDX Pointer to characters (source) } { ECX number of characters (not bytes) } TEST ECX,ECX JE _WStrClr PUSH EAX PUSH ECX PUSH EDX CALL SysAllocStringLen TEST EAX,EAX JE WStrError POP EDX PUSH [EDX].PWideChar MOV [EDX],EAX CALL SysFreeString end; procedure _WStrFromChar(var Dest: WideString; Source: AnsiChar); asm PUSH EDX MOV EDX,ESP MOV ECX,1 CALL _WStrFromPCharLen POP EDX end; procedure _WStrFromWChar(var Dest: WideString; Source: WideChar); asm { -> EAX Pointer to WideString (dest) } { EDX character (source) } PUSH EDX MOV EDX,ESP MOV ECX,1 CALL _WStrFromPWCharLen POP EDX end; procedure _WStrFromPChar(var Dest: WideString; Source: PAnsiChar); asm { -> EAX Pointer to WideString (dest) } { EDX Pointer to character (source) } XOR ECX,ECX TEST EDX,EDX JE @@5 PUSH EDX @@0: CMP CL,[EDX+0] JE @@4 CMP CL,[EDX+1] JE @@3 CMP CL,[EDX+2] JE @@2 CMP CL,[EDX+3] JE @@1 ADD EDX,4 JMP @@0 @@1: INC EDX @@2: INC EDX @@3: INC EDX @@4: MOV ECX,EDX POP EDX SUB ECX,EDX @@5: JMP _WStrFromPCharLen end; procedure _WStrFromPWChar(var Dest: WideString; Source: PWideChar); asm { -> EAX Pointer to WideString (dest) } { EDX Pointer to character (source) } XOR ECX,ECX TEST EDX,EDX JE @@5 PUSH EDX @@0: CMP CX,[EDX+0] JE @@4 CMP CX,[EDX+2] JE @@3 CMP CX,[EDX+4] JE @@2 CMP CX,[EDX+6] JE @@1 ADD EDX,8 JMP @@0 @@1: ADD EDX,2 @@2: ADD EDX,2 @@3: ADD EDX,2 @@4: MOV ECX,EDX POP EDX SUB ECX,EDX SHR ECX,1 @@5: JMP _WStrFromPWCharLen end; procedure _WStrFromString(var Dest: WideString; const Source: ShortString); asm XOR ECX,ECX MOV CL,[EDX] INC EDX JMP _WStrFromPCharLen end; procedure _WStrFromArray(var Dest: WideString; Source: PAnsiChar; Length: Integer); asm PUSH EDI PUSH EAX PUSH ECX MOV EDI,EDX XOR EAX,EAX REPNE SCASB JNE @@1 NOT ECX @@1: POP EAX ADD ECX,EAX POP EAX POP EDI JMP _WStrFromPCharLen end; procedure _WStrFromWArray(var Dest: WideString; Source: PWideChar; Length: Integer); asm PUSH EDI PUSH EAX PUSH ECX MOV EDI,EDX XOR EAX,EAX REPNE SCASW JNE @@1 NOT ECX @@1: POP EAX ADD ECX,EAX POP EAX POP EDI JMP _WStrFromPWCharLen end; procedure _WStrFromLStr(var Dest: WideString; const Source: AnsiString); asm XOR ECX,ECX TEST EDX,EDX JE @@1 MOV ECX,[EDX-4] @@1: JMP _WStrFromPCharLen end; procedure _WStrToString(Dest: PShortString; const Source: WideString; MaxLen: Integer); var SourceLen, DestLen: Integer; Buffer: array[0..511] of Char; begin SourceLen := Length(Source); if SourceLen >= 255 then SourceLen := 255; if SourceLen = 0 then DestLen := 0 else begin DestLen := WideCharToMultiByte(0, 0, Pointer(Source), SourceLen, Buffer, SizeOf(Buffer), nil, nil); if DestLen > MaxLen then DestLen := MaxLen; end; Dest^[0] := Chr(DestLen); if DestLen > 0 then Move(Buffer, Dest^[1], DestLen); end; function _WStrToPWChar(const S: WideString): PWideChar; asm TEST EAX,EAX JE @@1 RET NOP @@0: DW 0 @@1: MOV EAX,OFFSET @@0 end; function _WStrLen(const S: WideString): Integer; asm { -> EAX Pointer to WideString data } TEST EAX,EAX JE @@1 MOV EAX,[EAX-4] SHR EAX,1 @@1: end; procedure _WStrCat(var Dest: WideString; const Source: WideString); var DestLen, SourceLen: Integer; NewStr: PWideChar; begin SourceLen := Length(Source); if SourceLen <> 0 then begin DestLen := Length(Dest); NewStr := _NewWideString(DestLen + SourceLen); if DestLen > 0 then Move(Pointer(Dest)^, NewStr^, DestLen * 2); Move(Pointer(Source)^, NewStr[DestLen], SourceLen * 2); WStrSet(Dest, NewStr); end; end; procedure _WStrCat3(var Dest: WideString; const Source1, Source2: WideString); var Source1Len, Source2Len: Integer; NewStr: PWideChar; begin Source1Len := Length(Source1); Source2Len := Length(Source2); if (Source1Len <> 0) or (Source2Len <> 0) then begin NewStr := _NewWideString(Source1Len + Source2Len); Move(Pointer(Source1)^, Pointer(NewStr)^, Source1Len * 2); Move(Pointer(Source2)^, NewStr[Source1Len], Source2Len * 2); WStrSet(Dest, NewStr); end; end; procedure _WStrCatN{var Dest: WideString; ArgCnt: Integer; ...}; asm { ->EAX = Pointer to dest } { EDX = number of args (>= 3) } { [ESP+4], [ESP+8], ... crgCnt WideString arguments } PUSH EBX PUSH ESI PUSH EDX PUSH EAX MOV EBX,EDX XOR EAX,EAX @@loop1: MOV ECX,[ESP+EDX*4+4*4] TEST ECX,ECX JE @@1 ADD EAX,[ECX-4] @@1: DEC EDX JNE @@loop1 SHR EAX,1 CALL _NewWideString PUSH EAX MOV ESI,EAX @@loop2: MOV EAX,[ESP+EBX*4+5*4] MOV EDX,ESI TEST EAX,EAX JE @@2 MOV ECX,[EAX-4] ADD ESI,ECX CALL Move @@2: DEC EBX JNE @@loop2 POP EDX POP EAX CALL WStrSet POP EDX POP ESI POP EBX POP EAX LEA ESP,[ESP+EDX*4] JMP EAX end; procedure _WStrCmp{left: WideString; right: WideString}; asm { ->EAX = Pointer to left string } { EDX = Pointer to right string } PUSH EBX PUSH ESI PUSH EDI MOV ESI,EAX MOV EDI,EDX CMP EAX,EDX JE @@exit TEST ESI,ESI JE @@str1null TEST EDI,EDI JE @@str2null MOV EAX,[ESI-4] MOV EDX,[EDI-4] SUB EAX,EDX { eax = len1 - len2 } JA @@skip1 ADD EDX,EAX { edx = len2 + (len1 - len2) = len1 } @@skip1: PUSH EDX SHR EDX,2 JE @@cmpRest @@longLoop: MOV ECX,[ESI] MOV EBX,[EDI] CMP ECX,EBX JNE @@misMatch DEC EDX JE @@cmpRestP4 MOV ECX,[ESI+4] MOV EBX,[EDI+4] CMP ECX,EBX JNE @@misMatch ADD ESI,8 ADD EDI,8 DEC EDX JNE @@longLoop JMP @@cmpRest @@cmpRestP4: ADD ESI,4 ADD EDI,4 @@cmpRest: POP EDX AND EDX,2 JE @@equal MOV CX,[ESI] MOV BX,[EDI] CMP CX,BX JNE @@exit @@equal: ADD EAX,EAX JMP @@exit @@str1null: MOV EDX,[EDI-4] SUB EAX,EDX JMP @@exit @@str2null: MOV EAX,[ESI-4] SUB EAX,EDX JMP @@exit @@misMatch: POP EDX CMP CX,BX JNE @@exit SHR ECX,16 SHR EBX,16 CMP CX,BX @@exit: POP EDI POP ESI POP EBX end; function _NewWideString(Length: Integer): PWideChar; asm TEST EAX,EAX JE @@1 PUSH EAX PUSH 0 CALL SysAllocStringLen TEST EAX,EAX JE WStrError @@1: end; function _WStrCopy(const S: WideString; Index, Count: Integer): WideString; var L, N: Integer; begin L := Length(S); if Index < 1 then Index := 0 else begin Dec(Index); if Index > L then Index := L; end; if Count < 0 then N := 0 else begin N := L - Index; if N > Count then N := Count; end; _WStrFromPWCharLen(Result, PWideChar(Pointer(S)) + Index, N); end; procedure _WStrDelete(var S: WideString; Index, Count: Integer); var L, N: Integer; NewStr: PWideChar; begin L := Length(S); if (L > 0) and (Index >= 1) and (Index <= L) and (Count > 0) then begin Dec(Index); N := L - Index - Count; if N < 0 then N := 0; if (Index = 0) and (N = 0) then NewStr := nil else begin NewStr := _NewWideString(Index + N); if Index > 0 then Move(Pointer(S)^, NewStr^, Index * 2); if N > 0 then Move(PWideChar(Pointer(S))[L - N], NewStr[Index], N * 2); end; WStrSet(S, NewStr); end; end; procedure _WStrInsert(const Source: WideString; var Dest: WideString; Index: Integer); var SourceLen, DestLen: Integer; NewStr: PWideChar; begin SourceLen := Length(Source); if SourceLen > 0 then begin DestLen := Length(Dest); if Index < 1 then Index := 0 else begin Dec(Index); if Index > DestLen then Index := DestLen; end; NewStr := _NewWideString(DestLen + SourceLen); if Index > 0 then Move(Pointer(Dest)^, NewStr^, Index * 2); Move(Pointer(Source)^, NewStr[Index], SourceLen * 2); if Index < DestLen then Move(PWideChar(Pointer(Dest))[Index], NewStr[Index + SourceLen], (DestLen - Index) * 2); WStrSet(Dest, NewStr); end; end; procedure _WStrPos{ const substr : WideString; const s : WideString ) : Integer}; asm { ->EAX Pointer to substr } { EDX Pointer to string } { <-EAX Position of substr in s or 0 } TEST EAX,EAX JE @@noWork TEST EDX,EDX JE @@stringEmpty PUSH EBX PUSH ESI PUSH EDI MOV ESI,EAX { Point ESI to substr } MOV EDI,EDX { Point EDI to s } MOV ECX,[EDI-4] { ECX = Length(s) } SHR ECX,1 PUSH EDI { remember s position to calculate index } MOV EDX,[ESI-4] { EDX = Length(substr) } SHR EDX,1 DEC EDX { EDX = Length(substr) - 1 } JS @@fail { < 0 ? return 0 } MOV AX,[ESI] { AL = first char of substr } ADD ESI,2 { Point ESI to 2'nd char of substr } SUB ECX,EDX { #positions in s to look at } { = Length(s) - Length(substr) + 1 } JLE @@fail @@loop: REPNE SCASW JNE @@fail MOV EBX,ECX { save outer loop counter } PUSH ESI { save outer loop substr pointer } PUSH EDI { save outer loop s pointer } MOV ECX,EDX REPE CMPSW POP EDI { restore outer loop s pointer } POP ESI { restore outer loop substr pointer } JE @@found MOV ECX,EBX { restore outer loop counter } JMP @@loop @@fail: POP EDX { get rid of saved s pointer } XOR EAX,EAX JMP @@exit @@stringEmpty: XOR EAX,EAX JMP @@noWork @@found: POP EDX { restore pointer to first char of s } MOV EAX,EDI { EDI points of char after match } SUB EAX,EDX { the difference is the correct index } SHR EAX,1 @@exit: POP EDI POP ESI POP EBX @@noWork: end; procedure _WStrSetLength(var S: WideString; NewLength: Integer); var NewStr: PWideChar; Count: Integer; begin NewStr := nil; if NewLength > 0 then begin NewStr := _NewWideString(NewLength); Count := Length(S); if Count > 0 then begin if Count > NewLength then Count := NewLength; Move(Pointer(S)^, NewStr^, Count * 2); end; end; WStrSet(S, NewStr); end; function _WStrOfWChar(Ch: WideChar; Count: Integer): WideString; var P: PWideChar; begin _WStrFromPWCharLen(Result, nil, Count); P := Pointer(Result); while Count > 0 do begin Dec(Count); P[Count] := Ch; end; end; procedure _WStrAddRef{var str: WideString}; asm MOV EDX,[EAX] TEST EDX,EDX JE @@1 PUSH EAX MOV ECX,[EDX-4] SHR ECX,1 PUSH ECX PUSH EDX CALL SysAllocStringLen POP EDX TEST EAX,EAX JE WStrError MOV [EDX],EAX @@1: end; procedure _InitializeRecord{ p: Pointer; typeInfo: Pointer }; asm { -> EAX pointer to record to be initialized } { EDX pointer to type info } XOR ECX,ECX PUSH EBX MOV CL,[EDX+1] { type name length } PUSH ESI PUSH EDI MOV EBX,EAX LEA ESI,[EDX+ECX+2+8] { address of destructable fields } MOV EDI,[EDX+ECX+2+4] { number of destructable fields } @@loop: MOV EDX,[ESI] MOV EAX,[ESI+4] ADD EAX,EBX MOV EDX,[EDX] CALL _Initialize ADD ESI,8 DEC EDI JG @@loop POP EDI POP ESI POP EBX end; const tkLString = 10; tkWString = 11; tkVariant = 12; tkArray = 13; tkRecord = 14; tkInterface = 15; tkDynArray = 17; procedure _InitializeArray{ p: Pointer; typeInfo: Pointer; elemCount: Longint}; asm { -> EAX pointer to data to be initialized } { EDX pointer to type info describing data } { ECX number of elements of that type } PUSH EBX PUSH ESI PUSH EDI MOV EBX,EAX MOV ESI,EDX MOV EDI,ECX XOR EDX,EDX MOV AL,[ESI] MOV DL,[ESI+1] XOR ECX,ECX CMP AL,tkLString JE @@LString CMP AL,tkWString JE @@WString CMP AL,tkVariant JE @@Variant CMP AL,tkArray JE @@Array CMP AL,tkRecord JE @@Record CMP AL,tkInterface JE @@Interface CMP AL,tkDynArray JE @@DynArray MOV AL,reInvalidPtr POP EDI POP ESI POP EBX JMP Error @@LString: @@WString: @@Interface: @@DynArray: MOV [EBX],ECX ADD EBX,4 DEC EDI JG @@LString JMP @@exit @@Variant: MOV [EBX ],ECX MOV [EBX+ 4],ECX MOV [EBX+ 8],ECX MOV [EBX+12],ECX ADD EBX,16 DEC EDI JG @@Variant JMP @@exit @@Array: PUSH EBP MOV EBP,EDX @@ArrayLoop: MOV EDX,[ESI+EBP+2+8] MOV EAX,EBX ADD EBX,[ESI+EBP+2] MOV ECX,[ESI+EBP+2+4] MOV EDX,[EDX] CALL _InitializeArray DEC EDI JG @@ArrayLoop POP EBP JMP @@exit @@Record: PUSH EBP MOV EBP,EDX @@RecordLoop: MOV EAX,EBX ADD EBX,[ESI+EBP+2] MOV EDX,ESI CALL _InitializeRecord DEC EDI JG @@RecordLoop POP EBP @@exit: POP EDI POP ESI POP EBX end; procedure _Initialize{ p: Pointer; typeInfo: Pointer}; asm MOV ECX,1 JMP _InitializeArray end; procedure _FinalizeRecord{ p: Pointer; typeInfo: Pointer }; asm { -> EAX pointer to record to be finalized } { EDX pointer to type info } XOR ECX,ECX PUSH EBX MOV CL,[EDX+1] PUSH ESI PUSH EDI MOV EBX,EAX LEA ESI,[EDX+ECX+2+8] MOV EDI,[EDX+ECX+2+4] @@loop: MOV EDX,[ESI] MOV EAX,[ESI+4] ADD EAX,EBX MOV EDX,[EDX] CALL _Finalize ADD ESI,8 DEC EDI JG @@loop MOV EAX,EBX POP EDI POP ESI POP EBX end; procedure _FinalizeArray{ p: Pointer; typeInfo: Pointer; elemCount: Longint}; asm { -> EAX pointer to data to be finalized } { EDX pointer to type info describing data } { ECX number of elements of that type } CMP ECX, 0 { no array -> nop } JE @@zerolength PUSH EAX PUSH EBX PUSH ESI PUSH EDI MOV EBX,EAX MOV ESI,EDX MOV EDI,ECX XOR EDX,EDX MOV AL,[ESI] MOV DL,[ESI+1] CMP AL,tkLString JE @@LString CMP AL,tkWString JE @@WString CMP AL,tkVariant JE @@Variant CMP AL,tkArray JE @@Array CMP AL,tkRecord JE @@Record CMP AL,tkInterface JE @@Interface CMP AL,tkDynArray JE @@DynArray POP EDI POP ESI POP EBX POP EAX MOV AL,reInvalidPtr JMP Error @@LString: CMP ECX,1 MOV EAX,EBX JG @@LStringArray CALL _LStrClr JMP @@exit @@LStringArray: MOV EDX,ECX CALL _LStrArrayClr JMP @@exit @@WString: CMP ECX,1 MOV EAX,EBX JG @@WStringArray CALL _WStrClr JMP @@exit @@WStringArray: MOV EDX,ECX CALL _WStrArrayClr JMP @@exit @@Variant: MOV EAX,EBX ADD EBX,16 CALL _VarClr DEC EDI JG @@Variant JMP @@exit @@Array: PUSH EBP MOV EBP,EDX @@ArrayLoop: MOV EDX,[ESI+EBP+2+8] MOV EAX,EBX ADD EBX,[ESI+EBP+2] MOV ECX,[ESI+EBP+2+4] MOV EDX,[EDX] CALL _FinalizeArray DEC EDI JG @@ArrayLoop POP EBP JMP @@exit @@Record: PUSH EBP MOV EBP,EDX @@RecordLoop: { inv: EDI = number of array elements to finalize } MOV EAX,EBX ADD EBX,[ESI+EBP+2] MOV EDX,ESI CALL _FinalizeRecord DEC EDI JG @@RecordLoop POP EBP JMP @@exit @@Interface: MOV EAX,EBX ADD EBX,4 CALL _IntfClear DEC EDI JG @@Interface JMP @@exit @@DynArray: MOV EAX,EBX MOV EDX,ESI ADD EBX,4 CALL _DynArrayClear DEC EDI JG @@DynArray @@exit: POP EDI POP ESI POP EBX POP EAX @@zerolength: end; procedure _Finalize{ p: Pointer; typeInfo: Pointer}; asm MOV ECX,1 JMP _FinalizeArray end; procedure _AddRefRecord{ p: Pointer; typeInfo: Pointer }; asm { -> EAX pointer to record to be referenced } { EDX pointer to type info } XOR ECX,ECX PUSH EBX MOV CL,[EDX+1] PUSH ESI PUSH EDI MOV EBX,EAX LEA ESI,[EDX+ECX+2+8] MOV EDI,[EDX+ECX+2+4] @@loop: MOV EDX,[ESI] MOV EAX,[ESI+4] ADD EAX,EBX MOV EDX,[EDX] CALL _AddRef ADD ESI,8 DEC EDI JG @@loop POP EDI POP ESI POP EBX end; procedure _AddRefArray{ p: Pointer; typeInfo: Pointer; elemCount: Longint}; asm { -> EAX pointer to data to be referenced } { EDX pointer to type info describing data } { ECX number of elements of that type } PUSH EBX PUSH ESI PUSH EDI MOV EBX,EAX MOV ESI,EDX MOV EDI,ECX XOR EDX,EDX MOV AL,[ESI] MOV DL,[ESI+1] CMP AL,tkLString JE @@LString CMP AL,tkWString JE @@WString CMP AL,tkVariant JE @@Variant CMP AL,tkArray JE @@Array CMP AL,tkRecord JE @@Record CMP AL,tkInterface JE @@Interface CMP AL,tkDynArray JE @@DynArray MOV AL,reInvalidPtr POP EDI POP ESI POP EBX JMP Error @@LString: MOV EAX,[EBX] ADD EBX,4 CALL _LStrAddRef DEC EDI JG @@LString JMP @@exit @@WString: MOV EAX,EBX ADD EBX,4 CALL _WStrAddRef DEC EDI JG @@WString JMP @@exit @@Variant: MOV EAX,EBX ADD EBX,16 CALL _VarAddRef DEC EDI JG @@Variant JMP @@exit @@Array: PUSH EBP MOV EBP,EDX @@ArrayLoop: MOV EDX,[ESI+EBP+2+8] MOV EAX,EBX ADD EBX,[ESI+EBP+2] MOV ECX,[ESI+EBP+2+4] MOV EDX,[EDX] CALL _AddRefArray DEC EDI JG @@ArrayLoop POP EBP JMP @@exit @@Record: PUSH EBP MOV EBP,EDX @@RecordLoop: MOV EAX,EBX ADD EBX,[ESI+EBP+2] MOV EDX,ESI CALL _AddRefRecord DEC EDI JG @@RecordLoop POP EBP JMP @@exit @@Interface: MOV EAX,[EBX] ADD EBX,4 CALL _IntfAddRef DEC EDI JG @@Interface JMP @@exit @@DynArray: MOV EAX,[EBX] ADD EBX,4 CALL _DynArrayAddRef DEC EDI JG @@DynArray @@exit: POP EDI POP ESI POP EBX end; procedure _AddRef{ p: Pointer; typeInfo: Pointer}; asm MOV ECX,1 JMP _AddRefArray end; procedure _CopyRecord{ dest, source, typeInfo: Pointer }; asm { -> EAX pointer to dest } { EDX pointer to source } { ECX pointer to typeInfo } PUSH EBX PUSH ESI PUSH EDI PUSH EBP MOV EBX,EAX MOV ESI,EDX XOR EAX,EAX MOV AL,[ECX+1] LEA EDI,[ECX+EAX+2+8] MOV EBP,[EDI-4] XOR EAX,EAX MOV ECX,[EDI-8] PUSH ECX @@loop: MOV ECX,[EDI+4] SUB ECX,EAX JLE @@nomove1 MOV EDX,EAX ADD EAX,ESI ADD EDX,EBX CALL Move @@noMove1: MOV EAX,[EDI+4] MOV EDX,[EDI] MOV EDX,[EDX] MOV CL,[EDX] CMP CL,tkLString JE @@LString CMP CL,tkWString JE @@WString CMP CL,tkVariant JE @@Variant CMP CL,tkArray JE @@Array CMP CL,tkRecord JE @@Record CMP CL,tkInterface JE @@Interface CMP CL,tkDynArray JE @@DynArray MOV AL,reInvalidPtr POP EBP POP EDI POP ESI POP EBX JMP Error @@LString: MOV EDX,[ESI+EAX] ADD EAX,EBX CALL _LStrAsg MOV EAX,4 JMP @@common @@WString: MOV EDX,[ESI+EAX] ADD EAX,EBX CALL _WStrAsg MOV EAX,4 JMP @@common @@Variant: LEA EDX,[ESI+EAX] ADD EAX,EBX CALL _VarCopy MOV EAX,16 JMP @@common @@Array: XOR ECX,ECX MOV CL,[EDX+1] PUSH dword ptr [EDX+ECX+2] PUSH dword ptr [EDX+ECX+2+4] MOV ECX,[EDX+ECX+2+8] MOV ECX,[ECX] LEA EDX,[ESI+EAX] ADD EAX,EBX CALL _CopyArray POP EAX JMP @@common @@Record: XOR ECX,ECX MOV CL,[EDX+1] MOV ECX,[EDX+ECX+2] PUSH ECX MOV ECX,EDX LEA EDX,[ESI+EAX] ADD EAX,EBX CALL _CopyRecord POP EAX JMP @@common @@Interface: MOV EDX,[ESI+EAX] ADD EAX,EBX CALL _IntfCopy MOV EAX,4 JMP @@common @@DynArray: MOV ECX,EDX MOV EDX,[ESI+EAX] ADD EAX,EBX CALL _DynArrayAsg MOV EAX,4 @@common: ADD EAX,[EDI+4] ADD EDI,8 DEC EBP JNZ @@loop POP ECX SUB ECX,EAX JLE @@noMove2 LEA EDX,[EBX+EAX] ADD EAX,ESI CALL Move @@noMove2: POP EBP POP EDI POP ESI POP EBX end; procedure _CopyObject{ dest, source: Pointer; vmtPtrOffs: Longint; typeInfo: Pointer }; asm { -> EAX pointer to dest } { EDX pointer to source } { ECX offset of vmt in object } { [ESP+4] pointer to typeInfo } ADD ECX,EAX { pointer to dest vmt } PUSH dword ptr [ECX] { save dest vmt } PUSH ECX MOV ECX,[ESP+4+4+4] CALL _CopyRecord POP ECX POP dword ptr [ECX] { restore dest vmt } RET 4 end; procedure _CopyArray{ dest, source, typeInfo: Pointer; cnt: Integer }; asm { -> EAX pointer to dest } { EDX pointer to source } { ECX pointer to typeInfo } { [ESP+4] count } PUSH EBX PUSH ESI PUSH EDI PUSH EBP MOV EBX,EAX MOV ESI,EDX MOV EDI,ECX MOV EBP,[ESP+4+4*4] MOV CL,[EDI] CMP CL,tkLString JE @@LString CMP CL,tkWString JE @@WString CMP CL,tkVariant JE @@Variant CMP CL,tkArray JE @@Array CMP CL,tkRecord JE @@Record CMP CL,tkInterface JE @@Interface CMP CL,tkDynArray JE @@DynArray MOV AL,reInvalidPtr POP EBP POP EDI POP ESI POP EBX JMP Error @@LString: MOV EAX,EBX MOV EDX,[ESI] CALL _LStrAsg ADD EBX,4 ADD ESI,4 DEC EBP JNE @@LString JMP @@exit @@WString: MOV EAX,EBX MOV EDX,[ESI] CALL _WStrAsg ADD EBX,4 ADD ESI,4 DEC EBP JNE @@WString JMP @@exit @@Variant: MOV EAX,EBX MOV EDX,ESI CALL _VarCopy ADD EBX,16 ADD ESI,16 DEC EBP JNE @@Variant JMP @@exit @@Array: XOR ECX,ECX MOV CL,[EDI+1] LEA EDI,[EDI+ECX+2] @@ArrayLoop: MOV EAX,EBX MOV EDX,ESI MOV ECX,[EDI+8] PUSH dword ptr [EDI+4] CALL _CopyArray ADD EBX,[EDI] ADD ESI,[EDI] DEC EBP JNE @@ArrayLoop JMP @@exit @@Record: MOV EAX,EBX MOV EDX,ESI MOV ECX,EDI CALL _CopyRecord XOR EAX,EAX MOV AL,[EDI+1] ADD EBX,[EDI+EAX+2] ADD ESI,[EDI+EAX+2] DEC EBP JNE @@Record JMP @@exit @@Interface: MOV EAX,EBX MOV EDX,[ESI] CALL _IntfCopy ADD EBX,4 ADD ESI,4 DEC EBP JNE @@Interface JMP @@exit @@DynArray: MOV EAX,EBX MOV EDX,[ESI] MOV ECX,EDI CALL _DynArrayAsg ADD EBX,4 ADD ESI,4 DEC EBP JNE @@DynArray @@exit: POP EBP POP EDI POP ESI POP EBX RET 4 end; procedure _New{ size: Longint; typeInfo: Pointer}; asm { -> EAX size of object to allocate } { EDX pointer to typeInfo } PUSH EDX CALL _GetMem POP EDX TEST EAX,EAX JE @@exit PUSH EAX CALL _Initialize POP EAX @@exit: end; procedure _Dispose{ p: Pointer; typeInfo: Pointer}; asm { -> EAX Pointer to object to be disposed } { EDX Pointer to type info } PUSH EAX CALL _Finalize POP EAX CALL _FreeMem end; { ----------------------------------------------------- } { Wide character support } { ----------------------------------------------------- } function WideCharToString(Source: PWideChar): string; begin WideCharToStrVar(Source, Result); end; function WideCharLenToString(Source: PWideChar; SourceLen: Integer): string; begin WideCharLenToStrVar(Source, SourceLen, Result); end; procedure WideCharToStrVar(Source: PWideChar; var Dest: string); var SourceLen: Integer; begin SourceLen := 0; while Source[SourceLen] <> #0 do Inc(SourceLen); WideCharLenToStrVar(Source, SourceLen, Dest); end; procedure WideCharLenToStrVar(Source: PWideChar; SourceLen: Integer; var Dest: string); var DestLen: Integer; Buffer: array[0..2047] of Char; begin if SourceLen = 0 then Dest := '' else if SourceLen < SizeOf(Buffer) div 2 then SetString(Dest, Buffer, WideCharToMultiByte(0, 0, Source, SourceLen, Buffer, SizeOf(Buffer), nil, nil)) else begin DestLen := WideCharToMultiByte(0, 0, Source, SourceLen, nil, 0, nil, nil); SetString(Dest, nil, DestLen); WideCharToMultiByte(0, 0, Source, SourceLen, Pointer(Dest), DestLen, nil, nil); end; end; function StringToWideChar(const Source: string; Dest: PWideChar; DestSize: Integer): PWideChar; begin Dest[MultiByteToWideChar(0, 0, PChar(Source), Length(Source), Dest, DestSize - 1)] := #0; Result := Dest; end; { ----------------------------------------------------- } { OLE string support } { ----------------------------------------------------- } function OleStrToString(Source: PWideChar): string; begin OleStrToStrVar(Source, Result); end; procedure OleStrToStrVar(Source: PWideChar; var Dest: string); begin WideCharLenToStrVar(Source, SysStringLen(WideString(Pointer(Source))), Dest); end; function StringToOleStr(const Source: string): PWideChar; var SourceLen, ResultLen: Integer; Buffer: array[0..1023] of WideChar; begin SourceLen := Length(Source); if Length(Source) < SizeOf(Buffer) div 2 then Result := SysAllocStringLen(Buffer, MultiByteToWideChar(0, 0, PChar(Source), SourceLen, Buffer, SizeOf(Buffer) div 2)) else begin ResultLen := MultiByteToWideChar(0, 0, Pointer(Source), SourceLen, nil, 0); Result := SysAllocStringLen(nil, ResultLen); MultiByteToWideChar(0, 0, Pointer(Source), SourceLen, Result, ResultLen); end; end; { ----------------------------------------------------- } { Variant support } { ----------------------------------------------------- } type TBaseType = (btErr, btNul, btInt, btFlt, btCur, btStr, btBol, btDat); const varLast = varByte; const BaseTypeMap: array[0..varLast] of TBaseType = ( btErr, { varEmpty } btNul, { varNull } btInt, { varSmallint } btInt, { varInteger } btFlt, { varSingle } btFlt, { varDouble } btCur, { varCurrency } btDat, { varDate } btStr, { varOleStr } btErr, { varDispatch } btErr, { varError } btBol, { varBoolean } btErr, { varVariant } btErr, { varUnknown } btErr, { vt_decimal } btErr, { undefined } btErr, { vt_i1 } btInt); { varByte } const OpTypeMap: array[TBaseType, TBaseType] of TBaseType = ( (btErr, btErr, btErr, btErr, btErr, btErr, btErr, btErr), (btErr, btNul, btNul, btNul, btNul, btNul, btNul, btNul), (btErr, btNul, btInt, btFlt, btCur, btFlt, btInt, btDat), (btErr, btNul, btFlt, btFlt, btCur, btFlt, btFlt, btDat), (btErr, btNul, btCur, btCur, btCur, btCur, btCur, btDat), (btErr, btNul, btFlt, btFlt, btCur, btStr, btBol, btDat), (btErr, btNul, btInt, btFlt, btCur, btBol, btBol, btDat), (btErr, btNul, btDat, btDat, btDat, btDat, btDat, btDat)); const C10000: Single = 10000; const opAdd = 0; opSub = 1; opMul = 2; opDvd = 3; opDiv = 4; opMod = 5; opShl = 6; opShr = 7; opAnd = 8; opOr = 9; opXor = 10; procedure _DispInvoke; asm { -> [ESP+4] Pointer to result or nil } { [ESP+8] Pointer to variant } { [ESP+12] Pointer to call descriptor } { [ESP+16] Additional parameters, if any } JMP VarDispProc end; procedure _DispInvokeError; asm MOV AL,reVarDispatch JMP Error end; procedure VarCastError; asm MOV AL,reVarTypeCast JMP Error end; procedure VarInvalidOp; asm MOV AL,reVarInvalidOp JMP Error end; procedure _VarClear(var V : Variant); asm XOR EDX,EDX MOV DX,[EAX].TVarData.VType TEST EDX,varByRef JNE @@2 CMP EDX,varOleStr JB @@2 CMP EDX,varString JE @@1 CMP EDX,varAny JNE @@3 JMP [ClearAnyProc] @@1: MOV [EAX].TVarData.VType,varEmpty ADD EAX,OFFSET TVarData.VString JMP _LStrClr @@2: MOV [EAX].TVarData.VType,varEmpty RET @@3: PUSH EAX CALL VariantClear end; procedure _VarCopy(var Dest : Variant; const Source: Variant); asm CMP EAX,EDX JE @@9 CMP [EAX].TVarData.VType,varOleStr JB @@3 PUSH EAX PUSH EDX CMP [EAX].TVarData.VType,varString JE @@1 CMP [EAX].TVarData.VType,varAny JE @@0 PUSH EAX CALL VariantClear JMP @@2 @@0: CALL [ClearAnyProc] JMP @@2 @@1: ADD EAX,OFFSET TVarData.VString CALL _LStrClr @@2: POP EDX POP EAX @@3: CMP [EDX].TVarData.VType,varOleStr JAE @@5 @@4: MOV ECX,[EDX] MOV [EAX],ECX MOV ECX,[EDX+8] MOV [EAX+8],ECX MOV ECX,[EDX+12] MOV [EAX+12],ECX RET @@5: CMP [EDX].TVarData.VType,varString JE @@6 CMP [EDX].TVarData.VType,varAny JNE @@8 PUSH EAX CALL @@4 POP EAX JMP [RefAnyProc] @@6: MOV EDX,[EDX].TVarData.VString OR EDX,EDX JE @@7 MOV ECX,[EDX-skew].StrRec.refCnt INC ECX JLE @@7 LOCK INC [EDX-skew].StrRec.refCnt @@7: MOV [EAX].TVarData.VType,varString MOV [EAX].TVarData.VString,EDX RET @@8: MOV [EAX].TVarData.VType,varEmpty PUSH EDX PUSH EAX CALL VariantCopyInd OR EAX,EAX JNE VarInvalidOp @@9: end; procedure VarCopyNoInd(var Dest: Variant; const Source: Variant); asm CMP EAX,EDX JE @@9 CMP [EAX].TVarData.VType,varOleStr JB @@3 PUSH EAX PUSH EDX CMP [EAX].TVarData.VType,varString JE @@1 CMP [EAX].TVarData.VType,varAny JE @@0 PUSH EAX CALL VariantClear JMP @@2 @@0: CALL [ClearAnyProc] JMP @@2 @@1: ADD EAX,OFFSET TVarData.VString CALL _LStrClr @@2: POP EDX POP EAX @@3: CMP [EDX].TVarData.VType,varOleStr JAE @@5 @@4: MOV ECX,[EDX] MOV [EAX],ECX MOV ECX,[EDX+8] MOV [EAX+8],ECX MOV ECX,[EDX+12] MOV [EAX+12],ECX RET @@5: CMP [EDX].TVarData.VType,varString JNE @@6 CMP [EDX].TVarData.VType,varAny JNE @@8 CALL @@4 JMP [RefAnyProc] @@6: MOV EDX,[EDX].TVarData.VString OR EDX,EDX JE @@7 MOV ECX,[EDX-skew].StrRec.refCnt INC ECX JLE @@7 LOCK INC [EDX-skew].StrRec.refCnt @@7: MOV [EAX].TVarData.VType,varString MOV [EAX].TVarData.VString,EDX RET @@8: MOV [EAX].TVarData.VType,varEmpty PUSH EDX PUSH EAX CALL VariantCopy @@9: end; type TAnyProc = procedure (var V: Variant); procedure VarChangeType(var Dest: Variant; const Source: Variant; DestType: Word); forward; procedure AnyChangeType(var Dest: Variant; Source: Variant; DestType: Word); begin TAnyProc(ChangeAnyProc)(Source); VarChangeType(Dest, Source, DestType); end; procedure VarChangeType(var Dest: Variant; const Source: Variant; DestType: Word); type TVarMem = array[0..3] of Integer; function ChangeSourceAny(var Dest: Variant; const Source: Variant; DestType: Word): Boolean; begin Result := False; if TVarData(Source).VType = varAny then begin AnyChangeType(Dest, Source, DestType); Result := True; end; end; var Temp: TVarData; begin case TVarData(Dest).VType of varString: begin if not ChangeSourceAny(Dest, Source, DestType) then begin Temp.VType := varEmpty; if VariantChangeTypeEx(Variant(Temp), Source, $400, 0, DestType) <> 0 then VarCastError; _VarClear(Dest); TVarMem(Dest)[0] := TVarMem(Temp)[0]; TVarMem(Dest)[2] := TVarMem(Temp)[2]; TVarMem(Dest)[3] := TVarMem(Temp)[3]; end; end; varAny: AnyChangeType(Dest, Source, DestType); else if not ChangeSourceAny(Dest, Source, DestType) then if VariantChangeTypeEx(Dest, Source, $400, 0, DestType) <> 0 then VarCastError; end; end; procedure VarOleStrToString(var Dest: Variant; const Source: Variant); var StringPtr: Pointer; begin StringPtr := nil; OleStrToStrVar(TVarData(Source).VOleStr, string(StringPtr)); _VarClear(Dest); TVarData(Dest).VType := varString; TVarData(Dest).VString := StringPtr; end; procedure VarStringToOleStr(var Dest: Variant; const Source: Variant); var OleStrPtr: PWideChar; begin OleStrPtr := StringToOleStr(string(TVarData(Source).VString)); _VarClear(Dest); TVarData(Dest).VType := varOleStr; TVarData(Dest).VOleStr := OleStrPtr; end; procedure _VarCast(var Dest : Variant; const Source: Variant; VarType: Integer); var SourceType, DestType: Word; Temp: TVarData; begin SourceType := TVarData(Source).VType; DestType := Word(VarType); if SourceType = DestType then _VarCopy(Dest, Source) else if SourceType = varString then if DestType = varOleStr then VarStringToOleStr(Variant(Dest), Source) else begin Temp.VType := varEmpty; VarStringToOleStr(Variant(Temp), Source); try VarChangeType(Variant(Dest), Variant(Temp), DestType); finally _VarClear(PVariant(@Temp)^); end; end else if (DestType = varString) and (SourceType <> varAny) then if SourceType = varOleStr then VarOleStrToString(Variant(Dest), Source) else begin Temp.VType := varEmpty; VarChangeType(Variant(Temp), Source, varOleStr); try VarOleStrToString(Variant(Dest), Variant(Temp)); finally _VarClear(Variant(Temp)); end; end else VarChangeType(Variant(Dest), Source, DestType); end; (* VarCast when the destination is OleVariant *) procedure _VarCastOle(var Dest : Variant; const Source: Variant; VarType: Integer); begin if (VarType = varString) or (VarType = varAny) then VarCastError else _VarCast(Dest, Source, VarType); end; procedure _VarToInt; asm XOR EDX,EDX MOV DX,[EAX].TVarData.VType CMP EDX,varInteger JE @@0 CMP EDX,varSmallint JE @@1 CMP EDX,varByte JE @@2 CMP EDX,varDouble JE @@5 CMP EDX,varSingle JE @@4 CMP EDX,varCurrency JE @@3 SUB ESP,16 MOV [ESP].TVarData.VType,varEmpty MOV EDX,EAX MOV EAX,ESP MOV ECX,varInteger CALL _VarCast MOV EAX,[ESP].TVarData.VInteger ADD ESP,16 RET @@0: MOV EAX,[EAX].TVarData.VInteger RET @@1: MOVSX EAX,[EAX].TVarData.VSmallint RET @@2: MOVZX EAX,[EAX].TVarData.VByte RET @@3: FILD [EAX].TVarData.VCurrency FDIV C10000 JMP @@6 @@4: FLD [EAX].TVarData.VSingle JMP @@6 @@5: FLD [EAX].TVarData.VDouble @@6: PUSH EAX FISTP DWORD PTR [ESP] FWAIT POP EAX end; procedure _VarToBool; asm CMP [EAX].TVarData.VType,varBoolean JE @@1 SUB ESP,16 MOV [ESP].TVarData.VType,varEmpty MOV EDX,EAX MOV EAX,ESP MOV ECX,varBoolean CALL _VarCast MOV AX,[ESP].TVarData.VBoolean ADD ESP,16 JMP @@2 @@1: MOV AX,[EAX].TVarData.VBoolean @@2: NEG AX SBB EAX,EAX NEG EAX end; procedure _VarToReal; asm XOR EDX,EDX MOV DX,[EAX].TVarData.VType CMP EDX,varDouble JE @@1 CMP EDX,varSingle JE @@2 CMP EDX,varCurrency JE @@3 CMP EDX,varInteger JE @@4 CMP EDX,varSmallint JE @@5 CMP EDX,varDate JE @@1 SUB ESP,16 MOV [ESP].TVarData.VType,varEmpty MOV EDX,EAX MOV EAX,ESP MOV ECX,varDouble CALL _VarCast FLD [ESP].TVarData.VDouble ADD ESP,16 RET @@1: FLD [EAX].TVarData.VDouble RET @@2: FLD [EAX].TVarData.VSingle RET @@3: FILD [EAX].TVarData.VCurrency FDIV C10000 RET @@4: FILD [EAX].TVarData.VInteger RET @@5: FILD [EAX].TVarData.VSmallint end; procedure _VarToCurr; asm XOR EDX,EDX MOV DX,[EAX].TVarData.VType CMP EDX,varCurrency JE @@1 CMP EDX,varDouble JE @@2 CMP EDX,varSingle JE @@3 CMP EDX,varInteger JE @@4 CMP EDX,varSmallint JE @@5 SUB ESP,16 MOV [ESP].TVarData.VType,varEmpty MOV EDX,EAX MOV EAX,ESP MOV ECX,varCurrency CALL _VarCast FILD [ESP].TVarData.VCurrency ADD ESP,16 RET @@1: FILD [EAX].TVarData.VCurrency RET @@2: FLD [EAX].TVarData.VDouble JMP @@6 @@3: FLD [EAX].TVarData.VSingle JMP @@6 @@4: FILD [EAX].TVarData.VInteger JMP @@6 @@5: FILD [EAX].TVarData.VSmallint @@6: FMUL C10000 end; procedure _VarToPStr(var S; const V: Variant); var Temp: string; begin _VarToLStr(Temp, V); ShortString(S) := Temp; end; procedure _VarToLStr(var S: string; const V: Variant); asm { -> EAX: destination string } { EDX: source variant } { <- none } CMP [EDX].TVarData.VType,varString JNE @@1 MOV EDX,[EDX].TVarData.VString JMP _LStrAsg @@1: PUSH EBX MOV EBX,EAX SUB ESP,16 MOV [ESP].TVarData.VType,varEmpty MOV EAX,ESP MOV ECX,varString CALL _VarCast MOV EAX,EBX CALL _LStrClr MOV EAX,[ESP].TVarData.VString MOV [EBX],EAX ADD ESP,16 POP EBX end; procedure _VarToWStr(var S: WideString; const V: Variant); asm CMP [EDX].TVarData.VType,varOleStr JNE @@1 MOV EDX,[EDX].TVarData.VOleStr JMP _WStrAsg @@1: PUSH EBX MOV EBX,EAX SUB ESP,16 MOV [ESP].TVarData.VType,varEmpty MOV EAX,ESP MOV ECX,varOleStr CALL _VarCast MOV EAX,EBX MOV EDX,[ESP].TVarData.VOleStr CALL WStrSet ADD ESP,16 POP EBX end; procedure AnyToIntf(var Unknown: IUnknown; V: Variant); begin TAnyProc(ChangeAnyProc)(V); if TVarData(V).VType <> varUnknown then VarCastError; Unknown := IUnknown(TVarData(V).VUnknown); end; procedure _VarToIntf(var Unknown: IUnknown; const V: Variant); asm CMP [EDX].TVarData.VType,varEmpty JE _IntfClear CMP [EDX].TVarData.VType,varUnknown JE @@2 CMP [EDX].TVarData.VType,varDispatch JE @@2 CMP [EDX].TVarData.VType,varUnknown+varByRef JE @@1 CMP [EDX].TVarData.VType,varDispatch+varByRef JE @@1 CMP [EDX].TVarData.VType,varAny JNE VarCastError JMP AnyToIntf @@0: CALL _VarClear ADD ESP,16 JMP VarCastError @@1: MOV EDX,[EDX].TVarData.VPointer MOV EDX,[EDX] JMP _IntfCopy @@2: MOV EDX,[EDX].TVarData.VUnknown JMP _IntfCopy end; procedure _VarToDisp(var Dispatch: IDispatch; const V: Variant); asm CMP [EDX].TVarData.VType,varEmpty JE _IntfClear CMP [EDX].TVarData.VType,varDispatch JE @@1 CMP [EDX].TVarData.VType,varDispatch+varByRef JNE VarCastError MOV EDX,[EDX].TVarData.VPointer MOV EDX,[EDX] JMP _IntfCopy @@1: MOV EDX,[EDX].TVarData.VDispatch JMP _IntfCopy end; procedure _VarToDynArray(var DynArray: Pointer; const V: Variant; TypeInfo: Pointer); asm CALL DynArrayFromVariant OR EAX, EAX JNZ @@1 JMP VarCastError @@1: end; procedure _VarFromInt; asm CMP [EAX].TVarData.VType,varOleStr JB @@1 PUSH EAX PUSH EDX CALL _VarClear POP EDX POP EAX @@1: MOV [EAX].TVarData.VType,varInteger MOV [EAX].TVarData.VInteger,EDX end; procedure _VarFromBool; asm CMP [EAX].TVarData.VType,varOleStr JB @@1 PUSH EAX PUSH EDX CALL _VarClear POP EDX POP EAX @@1: MOV [EAX].TVarData.VType,varBoolean NEG DL SBB EDX,EDX MOV [EAX].TVarData.VBoolean,DX end; procedure _VarFromReal; asm CMP [EAX].TVarData.VType,varOleStr JB @@1 PUSH EAX CALL _VarClear POP EAX @@1: MOV [EAX].TVarData.VType,varDouble FSTP [EAX].TVarData.VDouble FWAIT end; procedure _VarFromTDateTime; asm CMP [EAX].TVarData.VType,varOleStr JB @@1 PUSH EAX CALL _VarClear POP EAX @@1: MOV [EAX].TVarData.VType,varDate FSTP [EAX].TVarData.VDouble FWAIT end; procedure _VarFromCurr; asm CMP [EAX].TVarData.VType,varOleStr JB @@1 PUSH EAX CALL _VarClear POP EAX @@1: MOV [EAX].TVarData.VType,varCurrency FISTP [EAX].TVarData.VCurrency FWAIT end; procedure _VarFromPStr(var V: Variant; const Value: ShortString); begin _VarFromLStr(V, Value); end; procedure _VarFromLStr(var V: Variant; const Value: string); asm CMP [EAX].TVarData.VType,varOleStr JB @@1 PUSH EAX PUSH EDX CALL _VarClear POP EDX POP EAX @@1: TEST EDX,EDX JE @@3 MOV ECX,[EDX-skew].StrRec.refCnt INC ECX JLE @@2 LOCK INC [EDX-skew].StrRec.refCnt JMP @@3 @@2: PUSH EAX PUSH EDX MOV EAX,[EDX-skew].StrRec.length CALL _NewAnsiString MOV EDX,EAX POP EAX PUSH EDX MOV ECX,[EDX-skew].StrRec.length CALL Move POP EDX POP EAX @@3: MOV [EAX].TVarData.VType,varString MOV [EAX].TVarData.VString,EDX end; procedure _VarFromWStr(var V: Variant; const Value: WideString); asm PUSH EAX CMP [EAX].TVarData.VType,varOleStr JB @@1 PUSH EDX CALL _VarClear POP EDX @@1: XOR EAX,EAX TEST EDX,EDX JE @@2 MOV EAX,[EDX-4] SHR EAX,1 JE @@2 PUSH EAX PUSH EDX CALL SysAllocStringLen TEST EAX,EAX JE WStrError @@2: POP EDX MOV [EDX].TVarData.VType,varOleStr MOV [EDX].TVarData.VOleStr,EAX end; procedure _VarFromIntf(var V: Variant; const Value: IUnknown); asm CMP [EAX].TVarData.VType,varOleStr JB @@1 PUSH EAX PUSH EDX CALL _VarClear POP EDX POP EAX @@1: MOV [EAX].TVarData.VType,varUnknown MOV [EAX].TVarData.VUnknown,EDX TEST EDX,EDX JE @@2 PUSH EDX MOV EAX,[EDX] CALL [EAX].vmtAddRef.Pointer @@2: end; procedure _VarFromDisp(var V: Variant; const Value: IDispatch); asm CMP [EAX].TVarData.VType,varOleStr JB @@1 PUSH EAX PUSH EDX CALL _VarClear POP EDX POP EAX @@1: MOV [EAX].TVarData.VType,varDispatch MOV [EAX].TVarData.VDispatch,EDX TEST EDX,EDX JE @@2 PUSH EDX MOV EAX,[EDX] CALL [EAX].vmtAddRef.Pointer @@2: end; procedure _VarFromDynArray(var V: Variant; const DynArray: Pointer; TypeInfo: Pointer); asm PUSH EAX CALL DynArrayToVariant POP EAX CMP [EAX].TVarData.VType,varEmpty JNE @@1 JMP VarCastError @@1: end; procedure _OleVarFromPStr(var V: OleVariant; const Value: ShortString); begin _OleVarFromLStr(V, Value); end; procedure _OleVarFromLStr(var V: OleVariant; const Value: string); asm CMP [EAX].TVarData.VType,varOleStr JB @@1 PUSH EAX PUSH EDX CALL _VarClear POP EDX POP EAX @@1: MOV [EAX].TVarData.VType,varOleStr ADD EAX,TVarData.VOleStr XOR ECX,ECX MOV [EAX],ECX JMP _WStrFromLStr end; procedure OleVarFromAny(var V: OleVariant; Value: Variant); begin TAnyProc(ChangeAnyProc)(Value); V := Value; end; procedure _OleVarFromVar(var V: OleVariant; const Value: Variant); asm CMP [EDX].TVarData.VType,varAny JE OleVarFromAny CMP [EDX].TVarData.VType,varString JNE _VarCopy CMP [EAX].TVarData.VType,varOleStr JB @@1 PUSH EAX PUSH EDX CALL _VarClear POP EDX POP EAX @@1: MOV [EAX].TVarData.VType,varOleStr ADD EAX,TVarData.VOleStr ADD EDX,TVarData.VString XOR ECX,ECX MOV EDX,[EDX] MOV [EAX],ECX JMP _WStrFromLStr @@2: end; procedure VarStrCat(var Dest: Variant; const Source: Variant); begin if TVarData(Dest).VType = varString then Dest := string(Dest) + string(Source) else Dest := WideString(Dest) + WideString(Source); end; procedure VarOp(var Dest: Variant; const Source: Variant; OpCode: Integer); forward; procedure AnyOp(var Dest: Variant; Source: Variant; OpCode: Integer); begin if TVarData(Dest).VType = varAny then TAnyProc(ChangeAnyProc)(Dest); if TVarData(Source).VType = varAny then TAnyProc(ChangeAnyProc)(Source); VarOp(Dest, Source, OpCode); end; procedure VarOp(var Dest: Variant; const Source: Variant; OpCode: Integer); asm PUSH EBX PUSH ESI PUSH EDI MOV EDI,EAX MOV ESI,EDX MOV EBX,ECX MOV EAX,[EDI].TVarData.VType.Integer MOV EDX,[ESI].TVarData.VType.Integer AND EAX,varTypeMask AND EDX,varTypeMask CMP EAX,varLast JBE @@1 CMP EAX,varString JNE @@4 MOV EAX,varOleStr @@1: CMP EDX,varLast JBE @@2 CMP EDX,varString JNE @@3 MOV EDX,varOleStr @@2: MOV AL,BaseTypeMap.Byte[EAX] MOV DL,BaseTypeMap.Byte[EDX] MOVZX ECX,OpTypeMap.Byte[EAX*8+EDX] CALL @VarOpTable.Pointer[ECX*4] POP EDI POP ESI POP EBX RET @@3: MOV EAX,EDX @@4: CMP EAX,varAny JNE @InvalidOp POP EDI POP ESI POP EBX JMP AnyOp @VarOpTable: DD @VarOpError DD @VarOpNull DD @VarOpInteger DD @VarOpReal DD @VarOpCurr DD @VarOpString DD @VarOpBoolean DD @VarOpDate @VarOpError: POP EAX @InvalidOp: POP EDI POP ESI POP EBX JMP VarInvalidOp @VarOpNull: MOV EAX,EDI CALL _VarClear MOV [EDI].TVarData.VType,varNull RET @VarOpInteger: CMP BL,opDvd JE @RealOp @IntegerOp: MOV EAX,ESI CALL _VarToInt PUSH EAX MOV EAX,EDI CALL _VarToInt POP EDX CALL @IntegerOpTable.Pointer[EBX*4] MOV EDX,EAX MOV EAX,EDI JMP _VarFromInt @IntegerOpTable: DD @IntegerAdd DD @IntegerSub DD @IntegerMul DD 0 DD @IntegerDiv DD @IntegerMod DD @IntegerShl DD @IntegerShr DD @IntegerAnd DD @IntegerOr DD @IntegerXor @IntegerAdd: ADD EAX,EDX JO @IntToRealOp RET @IntegerSub: SUB EAX,EDX JO @IntToRealOp RET @IntegerMul: IMUL EDX JO @IntToRealOp RET @IntegerDiv: MOV ECX,EDX CDQ IDIV ECX RET @IntegerMod: MOV ECX,EDX CDQ IDIV ECX MOV EAX,EDX RET @IntegerShl: MOV ECX,EDX SHL EAX,CL RET @IntegerShr: MOV ECX,EDX SHR EAX,CL RET @IntegerAnd: AND EAX,EDX RET @IntegerOr: OR EAX,EDX RET @IntegerXor: XOR EAX,EDX RET @IntToRealOp: POP EAX JMP @RealOp @VarOpReal: CMP BL,opDiv JAE @IntegerOp @RealOp: MOV EAX,ESI CALL _VarToReal SUB ESP,12 FSTP TBYTE PTR [ESP] MOV EAX,EDI CALL _VarToReal FLD TBYTE PTR [ESP] ADD ESP,12 CALL @RealOpTable.Pointer[EBX*4] @RealResult: MOV EAX,EDI JMP _VarFromReal @VarOpCurr: CMP BL,opDiv JAE @IntegerOp CMP BL,opMul JAE @CurrMulDvd MOV EAX,ESI CALL _VarToCurr SUB ESP,12 FSTP TBYTE PTR [ESP] MOV EAX,EDI CALL _VarToCurr FLD TBYTE PTR [ESP] ADD ESP,12 CALL @RealOpTable.Pointer[EBX*4] @CurrResult: MOV EAX,EDI JMP _VarFromCurr @CurrMulDvd: CMP DL,btCur JE @CurrOpCurr MOV EAX,ESI CALL _VarToReal FILD [EDI].TVarData.VCurrency FXCH CALL @RealOpTable.Pointer[EBX*4] JMP @CurrResult @CurrOpCurr: CMP BL,opDvd JE @CurrDvdCurr CMP AL,btCur JE @CurrMulCurr MOV EAX,EDI CALL _VarToReal FILD [ESI].TVarData.VCurrency FMUL JMP @CurrResult @CurrMulCurr: FILD [EDI].TVarData.VCurrency FILD [ESI].TVarData.VCurrency FMUL FDIV C10000 JMP @CurrResult @CurrDvdCurr: MOV EAX,EDI CALL _VarToCurr FILD [ESI].TVarData.VCurrency FDIV JMP @RealResult @RealOpTable: DD @RealAdd DD @RealSub DD @RealMul DD @RealDvd @RealAdd: FADD RET @RealSub: FSUB RET @RealMul: FMUL RET @RealDvd: FDIV RET @VarOpString: CMP BL,opAdd JNE @VarOpReal MOV EAX,EDI MOV EDX,ESI JMP VarStrCat @VarOpBoolean: CMP BL,opAnd JB @VarOpReal MOV EAX,ESI CALL _VarToBool PUSH EAX MOV EAX,EDI CALL _VarToBool POP EDX CALL @IntegerOpTable.Pointer[EBX*4] MOV EDX,EAX MOV EAX,EDI JMP _VarFromBool @VarOpDate: CMP BL,opSub JA @VarOpReal JB @DateOp MOV AH,DL CMP AX,btDat+btDat*256 JE @RealOp @DateOp: CALL @RealOp MOV [EDI].TVarData.VType,varDate RET end; procedure _VarAdd; asm MOV ECX,opAdd JMP VarOp end; procedure _VarSub; asm MOV ECX,opSub JMP VarOp end; procedure _VarMul; asm MOV ECX,opMul JMP VarOp end; procedure _VarDiv; asm MOV ECX,opDiv JMP VarOp end; procedure _VarMod; asm MOV ECX,opMod JMP VarOp end; procedure _VarAnd; asm MOV ECX,opAnd JMP VarOp end; procedure _VarOr; asm MOV ECX,opOr JMP VarOp end; procedure _VarXor; asm MOV ECX,opXor JMP VarOp end; procedure _VarShl; asm MOV ECX,opShl JMP VarOp end; procedure _VarShr; asm MOV ECX,opShr JMP VarOp end; procedure _VarRDiv; asm MOV ECX,opDvd JMP VarOp end; function VarCompareString(const S1, S2: string): Integer; asm PUSH ESI PUSH EDI MOV ESI,EAX MOV EDI,EDX OR EAX,EAX JE @@1 MOV EAX,[EAX-4] @@1: OR EDX,EDX JE @@2 MOV EDX,[EDX-4] @@2: MOV ECX,EAX CMP ECX,EDX JBE @@3 MOV ECX,EDX @@3: CMP ECX,ECX REPE CMPSB JE @@4 MOVZX EAX,BYTE PTR [ESI-1] MOVZX EDX,BYTE PTR [EDI-1] @@4: SUB EAX,EDX POP EDI POP ESI end; function VarCmpStr(const V1, V2: Variant): Integer; begin Result := VarCompareString(V1, V2); end; function AnyCmp(var Dest: Variant; const Source: Variant): Integer; var Temp: Variant; P: ^Variant; begin asm PUSH Dest end; P := @Source; if TVarData(Dest).VType = varAny then TAnyProc(ChangeAnyProc)(Dest); if TVarData(Source).VType = varAny then begin Temp := Source; TAnyProc(ChangeAnyProc)(Temp); P := @Temp; end; asm MOV EDX,P POP EAX CALL _VarCmp PUSHF POP EAX MOV Result,EAX end; end; procedure _VarCmp; asm PUSH ESI PUSH EDI MOV EDI,EAX MOV ESI,EDX MOV EAX,[EDI].TVarData.VType.Integer MOV EDX,[ESI].TVarData.VType.Integer AND EAX,varTypeMask AND EDX,varTypeMask CMP EAX,varLast JBE @@1 CMP EAX,varString JNE @@4 MOV EAX,varOleStr @@1: CMP EDX,varLast JBE @@2 CMP EDX,varString JNE @@3 MOV EDX,varOleStr @@2: MOV AL,BaseTypeMap.Byte[EAX] MOV DL,BaseTypeMap.Byte[EDX] MOVZX ECX,OpTypeMap.Byte[EAX*8+EDX] JMP @VarCmpTable.Pointer[ECX*4] @@3: MOV EAX,EDX @@4: CMP EAX,varAny JNE @VarCmpError POP EDI POP ESI CALL AnyCmp PUSH EAX POPF RET @VarCmpTable: DD @VarCmpError DD @VarCmpNull DD @VarCmpInteger DD @VarCmpReal DD @VarCmpCurr DD @VarCmpString DD @VarCmpBoolean DD @VarCmpDate @VarCmpError: POP EDI POP ESI JMP VarInvalidOp @VarCmpNull: CMP AL,DL JMP @Exit @VarCmpInteger: MOV EAX,ESI CALL _VarToInt XCHG EAX,EDI CALL _VarToInt CMP EAX,EDI JMP @Exit @VarCmpReal: @VarCmpDate: MOV EAX,EDI CALL _VarToReal SUB ESP,12 FSTP TBYTE PTR [ESP] MOV EAX,ESI CALL _VarToReal FLD TBYTE PTR [ESP] ADD ESP,12 @RealCmp: FCOMPP FNSTSW AX MOV AL,AH { Move CF into SF } AND AX,4001H ROR AL,1 OR AH,AL SAHF JMP @Exit @VarCmpCurr: MOV EAX,EDI CALL _VarToCurr SUB ESP,12 FSTP TBYTE PTR [ESP] MOV EAX,ESI CALL _VarToCurr FLD TBYTE PTR [ESP] ADD ESP,12 JMP @RealCmp @VarCmpString: MOV EAX,EDI MOV EDX,ESI CALL VarCmpStr CMP EAX,0 JMP @Exit @VarCmpBoolean: MOV EAX,ESI CALL _VarToBool XCHG EAX,EDI CALL _VarToBool MOV EDX,EDI CMP AL,DL @Exit: POP EDI POP ESI end; procedure _VarNeg; asm MOV EDX,[EAX].TVarData.VType.Integer AND EDX,varTypeMask CMP EDX,varLast JBE @@1 CMP EDX,varString JNE @VarNegError MOV EDX,varOleStr @@1: MOV DL,BaseTypeMap.Byte[EDX] JMP @VarNegTable.Pointer[EDX*4] @@2: CMP EAX,varAny JNE @VarNegError PUSH EAX CALL [ChangeAnyProc] POP EAX JMP _VarNeg @VarNegTable: DD @VarNegError DD @VarNegNull DD @VarNegInteger DD @VarNegReal DD @VarNegCurr DD @VarNegReal DD @VarNegInteger DD @VarNegDate @VarNegError: JMP VarInvalidOp @VarNegNull: RET @VarNegInteger: PUSH EAX CALL _VarToInt NEG EAX MOV EDX,EAX POP EAX JMP _VarFromInt @VarNegReal: PUSH EAX CALL _VarToReal FCHS POP EAX JMP _VarFromReal @VarNegCurr: FILD [EAX].TVarData.VCurrency FCHS FISTP [EAX].TVarData.VCurrency FWAIT RET @VarNegDate: FLD [EAX].TVarData.VDate FCHS FSTP [EAX].TVarData.VDate FWAIT end; procedure _VarNot; asm MOV EDX,[EAX].TVarData.VType.Integer AND EDX,varTypeMask JE @@2 CMP EDX,varBoolean JE @@3 CMP EDX,varNull JE @@4 CMP EDX,varLast JBE @@1 CMP EDX,varString JE @@1 CMP EAX,varAny JNE @@2 PUSH EAX CALL [ChangeAnyProc] POP EAX JMP _VarNot @@1: PUSH EAX CALL _VarToInt NOT EAX MOV EDX,EAX POP EAX JMP _VarFromInt @@2: JMP VarInvalidOp @@3: MOV DX,[EAX].TVarData.VBoolean NEG DX SBB EDX,EDX NOT EDX MOV [EAX].TVarData.VBoolean,DX @@4: end; procedure _VarCopyNoInd; asm JMP VarCopyNoInd end; procedure _VarClr; asm PUSH EAX CALL _VarClear POP EAX end; procedure _VarAddRef; asm CMP [EAX].TVarData.VType,varOleStr JB @@1 PUSH [EAX].Integer[12] PUSH [EAX].Integer[8] PUSH [EAX].Integer[4] PUSH [EAX].Integer[0] MOV [EAX].TVarData.VType,varEmpty MOV EDX,ESP CALL _VarCopy ADD ESP,16 @@1: end; function VarType(const V: Variant): Integer; asm MOVZX EAX,[EAX].TVarData.VType end; function VarAsType(const V: Variant; VarType: Integer): Variant; begin _VarCast(Result, V, VarType); end; function VarIsEmpty(const V: Variant): Boolean; begin with TVarData(V) do Result := (VType = varEmpty) or ((VType = varDispatch) or (VType = varUnknown)) and (VDispatch = nil); end; function VarIsNull(const V: Variant): Boolean; begin Result := TVarData(V).VType = varNull; end; function VarToStr(const V: Variant): string; begin if TVarData(V).VType <> varNull then Result := V else Result := ''; end; function VarFromDateTime(DateTime: TDateTime): Variant; begin _VarClear(Result); TVarData(Result).VType := varDate; TVarData(Result).VDate := DateTime; end; function VarToDateTime(const V: Variant): TDateTime; var Temp: TVarData; begin Temp.VType := varEmpty; _VarCast(Variant(Temp), V, varDate); Result := Temp.VDate; end; function _WriteVariant(var T: Text; const V: Variant; Width: Integer): Pointer; var S: string; begin if TVarData(V).VType >= varSmallint then S := V; Write(T, S: Width); Result := @T; end; function _Write0Variant(var T: Text; const V: Variant): Pointer; begin Result := _WriteVariant(T, V, 0); end; { ----------------------------------------------------- } { Variant array support } { ----------------------------------------------------- } function VarArrayCreate(const Bounds: array of Integer; VarType: Integer): Variant; var I, DimCount: Integer; VarArrayRef: PVarArray; VarBounds: array[0..63] of TVarArrayBound; begin if not Odd(High(Bounds)) or (High(Bounds) > 127) then Error(reVarArrayCreate); DimCount := (High(Bounds) + 1) div 2; for I := 0 to DimCount - 1 do with VarBounds[I] do begin LowBound := Bounds[I * 2]; ElementCount := Bounds[I * 2 + 1] - LowBound + 1; end; VarArrayRef := SafeArrayCreate(VarType, DimCount, VarBounds); if VarArrayRef = nil then Error(reVarArrayCreate); _VarClear(Result); TVarData(Result).VType := VarType or varArray; TVarData(Result).VArray := VarArrayRef; end; function VarArrayOf(const Values: array of Variant): Variant; var I: Integer; begin Result := VarArrayCreate([0, High(Values)], varVariant); for I := 0 to High(Values) do Result[I] := Values[I]; end; procedure _VarArrayRedim(var A : Variant; HighBound: Integer); var VarBound: TVarArrayBound; begin if (TVarData(A).VType and (varArray or varByRef)) <> varArray then Error(reVarNotArray); with TVarData(A).VArray^ do VarBound.LowBound := Bounds[DimCount - 1].LowBound; VarBound.ElementCount := HighBound - VarBound.LowBound + 1; if SafeArrayRedim(TVarData(A).VArray, VarBound) <> 0 then Error(reVarArrayCreate); end; function GetVarArray(const A: Variant): PVarArray; begin if TVarData(A).VType and varArray = 0 then Error(reVarNotArray); if TVarData(A).VType and varByRef <> 0 then Result := PVarArray(TVarData(A).VPointer^) else Result := TVarData(A).VArray; end; function VarArrayDimCount(const A: Variant): Integer; begin if TVarData(A).VType and varArray <> 0 then Result := GetVarArray(A)^.DimCount else Result := 0; end; function VarArrayLowBound(const A: Variant; Dim: Integer): Integer; begin if SafeArrayGetLBound(GetVarArray(A), Dim, Result) <> 0 then Error(reVarArrayBounds); end; function VarArrayHighBound(const A: Variant; Dim: Integer): Integer; begin if SafeArrayGetUBound(GetVarArray(A), Dim, Result) <> 0 then Error(reVarArrayBounds); end; function VarArrayLock(const A: Variant): Pointer; begin if SafeArrayAccessData(GetVarArray(A), Result) <> 0 then Error(reVarNotArray); end; procedure VarArrayUnlock(const A: Variant); begin if SafeArrayUnaccessData(GetVarArray(A)) <> 0 then Error(reVarNotArray); end; function VarArrayRef(const A: Variant): Variant; begin if TVarData(A).VType and varArray = 0 then Error(reVarNotArray); _VarClear(Result); TVarData(Result).VType := TVarData(A).VType or varByRef; if TVarData(A).VType and varByRef <> 0 then TVarData(Result).VPointer := TVarData(A).VPointer else TVarData(Result).VPointer := @TVarData(A).VArray; end; function VarIsArray(const A: Variant): Boolean; begin Result := TVarData(A).VType and varArray <> 0; end; function _VarArrayGet(var A: Variant; IndexCount: Integer; Indices: Integer): Variant; cdecl; var VarArrayPtr: PVarArray; VarType: Integer; P: Pointer; begin if TVarData(A).VType and varArray = 0 then Error(reVarNotArray); VarArrayPtr := GetVarArray(A); if VarArrayPtr^.DimCount <> IndexCount then Error(reVarArrayBounds); VarType := TVarData(A).VType and varTypeMask; _VarClear(Result); if VarType = varVariant then begin if SafeArrayPtrOfIndex(VarArrayPtr, @Indices, P) <> 0 then Error(reVarArrayBounds); Result := PVariant(P)^; end else begin if SafeArrayGetElement(VarArrayPtr, @Indices, @TVarData(Result).VPointer) <> 0 then Error(reVarArrayBounds); TVarData(Result).VType := VarType; end; end; procedure _VarArrayPut(var A: Variant; const Value: Variant; IndexCount: Integer; Indices: Integer); cdecl; type TAnyPutArrayProc = procedure (var A: Variant; const Value: Variant; Index: Integer); var VarArrayPtr: PVarArray; VarType: Integer; P: Pointer; Temp: TVarData; begin if TVarData(A).VType and varArray = 0 then Error(reVarNotArray); VarArrayPtr := GetVarArray(A); if VarArrayPtr^.DimCount <> IndexCount then Error(reVarArrayBounds); VarType := TVarData(A).VType and varTypeMask; if (VarType = varVariant) and (TVarData(Value).VType <> varString) then begin if SafeArrayPtrOfIndex(VarArrayPtr, @Indices, P) <> 0 then Error(reVarArrayBounds); PVariant(P)^ := Value; end else begin Temp.VType := varEmpty; try if VarType = varVariant then begin VarStringToOleStr(Variant(Temp), Value); P := @Temp; end else begin _VarCast(Variant(Temp), Value, VarType); case VarType of varOleStr, varDispatch, varUnknown: P := Temp.VPointer; else P := @Temp.VPointer; end; end; if SafeArrayPutElement(VarArrayPtr, @Indices, P) <> 0 then Error(reVarArrayBounds); finally _VarClear(Variant(Temp)); end; end; end; function VarArrayGet(const A: Variant; const Indices: array of Integer): Variant; asm { ->EAX Pointer to A } { EDX Pointer to Indices } { ECX High bound of Indices } { [EBP+8] Pointer to result } PUSH EBX MOV EBX,ECX INC EBX JLE @@endLoop @@loop: PUSH [EDX+ECX*4].Integer DEC ECX JNS @@loop @@endLoop: PUSH EBX PUSH EAX MOV EAX,[EBP+8] PUSH EAX CALL _VarArrayGet LEA ESP,[ESP+EBX*4+3*4] POP EBX end; procedure VarArrayPut(var A: Variant; const Value: Variant; const Indices: array of Integer); asm { ->EAX Pointer to A } { EDX Pointer to Value } { ECX Pointer to Indices } { [EBP+8] High bound of Indices } PUSH EBX MOV EBX,[EBP+8] TEST EBX,EBX JS @@endLoop @@loop: PUSH [ECX+EBX*4].Integer DEC EBX JNS @@loop @@endLoop: MOV EBX,[EBP+8] INC EBX PUSH EBX PUSH EDX PUSH EAX CALL _VarArrayPut LEA ESP,[ESP+EBX*4+3*4] POP EBX end; { 64-bit Integer helper routines - recycling C++ RTL routines } procedure __llmul; external; {$L _LL } procedure __lldiv; external; { _LL } procedure __llmod; external; { _LL } procedure __llmulo; external; { _LL (overflow version) } procedure __lldivo; external; { _LL (overflow version) } procedure __llmodo; external; { _LL (overflow version) } procedure __llshl; external; { _LL } procedure __llushr; external; { _LL } procedure __llumod; external; { _LL } procedure __lludiv; external; { _LL } function _StrInt64(val: Int64; width: Integer): ShortString; var d: array[0..31] of Char; { need 19 digits and a sign } i, k: Integer; sign: Boolean; spaces: Integer; begin { Produce an ASCII representation of the number in reverse order } i := 0; sign := val < 0; repeat d[i] := Chr( Abs(val mod 10) + Ord('0') ); Inc(i); val := val div 10; until val = 0; if sign then begin d[i] := '-'; Inc(i); end; { Fill the Result with the appropriate number of blanks } if width > 255 then width := 255; k := 1; spaces := width - i; while k <= spaces do begin Result[k] := ' '; Inc(k); end; { Fill the Result with the number } while i > 0 do begin Dec(i); Result[k] := d[i]; Inc(k); end; { Result is k-1 characters long } SetLength(Result, k-1); end; function _Str0Int64(val: Int64): ShortString; begin Result := _StrInt64(val, 0); end; procedure _WriteInt64; asm { PROCEDURE _WriteInt64( VAR t: Text; val: Int64; with: Longint); } { ->EAX Pointer to file record } { [ESP+4] Value } { EDX Field width } SUB ESP,32 { VAR s: String[31]; } PUSH EAX PUSH EDX PUSH dword ptr [ESP+8+32+8] { Str( val : 0, s ); } PUSH dword ptr [ESP+8+32+8] XOR EAX,EAX LEA EDX,[ESP+8+8] CALL _StrInt64 POP ECX POP EAX MOV EDX,ESP { Write( t, s : width );} CALL _WriteString ADD ESP,32 RET 8 end; procedure _Write0Int64; asm { PROCEDURE _Write0Long( VAR t: Text; val: Longint); } { ->EAX Pointer to file record } { EDX Value } XOR EDX,EDX JMP _WriteInt64 end; procedure _ReadInt64; external; {$L ReadInt64 } function _ValInt64(const s: AnsiString; var code: Integer): Int64; var i: Integer; dig: Integer; sign: Boolean; empty: Boolean; begin i := 1; dig := 0; Result := 0; if s = '' then begin code := i; exit; end; while s[i] = ' ' do Inc(i); sign := False; if s[i] = '-' then begin sign := True; Inc(i); end else if s[i] = '+' then Inc(i); empty := True; if (s[i] = '$') or (s[i] = '0') and (Upcase(s[i+1]) = 'X') then begin if s[i] = '0' then Inc(i); Inc(i); while True do begin case s[i] of '0'..'9': dig := Ord(s[i]) - Ord('0'); 'A'..'F': dig := Ord(s[i]) - (Ord('A') - 10); 'a'..'f': dig := Ord(s[i]) - (Ord('a') - 10); else break; end; if (Result < 0) or (Result > $0FFFFFFFFFFFFFFF) then break; Result := Result shl 4 + dig; Inc(i); empty := False; end; if sign then Result := - Result; end else begin while True do begin case s[i] of '0'..'9': dig := Ord(s[i]) - Ord('0'); else break; end; if (Result < 0) or (Result > $7FFFFFFFFFFFFFFF div 10) then break; Result := Result*10 + dig; Inc(i); empty := False; end; if sign then Result := - Result; if (Result <> 0) and (sign <> (Result < 0)) then Dec(i); end; if (s[i] <> #0) or empty then code := i else code := 0; end; procedure _DynArrayLength; asm { FUNCTION _DynArrayLength(const a: array of ...): Longint; } { ->EAX Pointer to array or nil } { <-EAX High bound of array + 1 or 0 } TEST EAX,EAX JZ @@skip MOV EAX,[EAX-4] @@skip: end; procedure _DynArrayHigh; asm { FUNCTION _DynArrayHigh(const a: array of ...): Longint; } { ->EAX Pointer to array or nil } { <-EAX High bound of array or -1 } CALL _DynArrayLength DEC EAX end; type PLongint = ^Longint; PointerArray = array [0..512*1024*1024 -2] of Pointer; PPointerArray = ^PointerArray; PDynArrayTypeInfo = ^TDynArrayTypeInfo; TDynArrayTypeInfo = packed record kind: Byte; name: string[0]; elSize: Longint; elType: ^PDynArrayTypeInfo; varType: Integer; end; procedure CopyArray(dest, source, typeInfo: Pointer; cnt: Integer); asm PUSH dword ptr [EBP+8] CALL _CopyArray end; procedure FinalizeArray(p, typeInfo: Pointer; cnt: Integer); asm JMP _FinalizeArray end; procedure DynArrayClear(var a: Pointer; typeInfo: Pointer); asm CALL _DynArrayClear end; procedure DynArraySetLength(var a: Pointer; typeInfo: PDynArrayTypeInfo; dimCnt: Longint; lengthVec: PLongint); var i: Integer; newLength, oldLength, minLength: Longint; elSize: Longint; neededSize: Longint; p, pp: Pointer; begin p := a; // Fetch the new length of the array in this dimension, and the old length newLength := PLongint(lengthVec)^; if newLength <= 0 then begin if newLength < 0 then Error(reRangeError); DynArrayClear(a, typeInfo); exit; end; oldLength := 0; if p <> nil then begin Dec(PLongint(p)); oldLength := PLongint(p)^; Dec(PLongint(p)); end; // Calculate the needed size of the heap object Inc(PChar(typeInfo), Length(typeInfo.name)); elSize := typeInfo.elSize; if typeInfo.elType <> nil then typeInfo := typeInfo.elType^ else typeInfo := nil; neededSize := newLength*elSize; if neededSize div newLength <> elSize then Error(reRangeError); Inc(neededSize, Sizeof(Longint)*2); // If the heap object isn't shared (ref count = 1), just resize it. Otherwise, we make a copy if (p = nil) or (PLongint(p)^ = 1) then begin pp := p; if (newLength < oldLength) and (typeInfo <> nil) then FinalizeArray(PChar(p) + Sizeof(Longint)*2 + newLength*elSize, typeInfo, oldLength - newLength); ReallocMem(pp, neededSize); p := pp; end else begin Dec(PLongint(p)^); GetMem(p, neededSize); minLength := oldLength; if minLength > newLength then minLength := newLength; if typeInfo <> nil then begin FillChar((PChar(p) + Sizeof(Longint)*2)^, minLength*elSize, 0); CopyArray(PChar(p) + Sizeof(Longint)*2, a, typeInfo, minLength) end else Move(PChar(a)^, (PChar(p) + Sizeof(Longint)*2)^, minLength*elSize); end; // The heap object will now have a ref count of 1 and the new length PLongint(p)^ := 1; Inc(PLongint(p)); PLongint(p)^ := newLength; Inc(PLongint(p)); // Set the new memory to all zero bits FillChar((PChar(p) + elSize * oldLength)^, elSize * (newLength - oldLength), 0); // Take care of the inner dimensions, if any if dimCnt > 1 then begin Inc(lengthVec); Dec(dimCnt); for i := 0 to newLength-1 do DynArraySetLength(PPointerArray(p)[i], typeInfo, dimCnt, lengthVec); end; a := p; end; procedure _DynArraySetLength; asm { PROCEDURE _DynArraySetLength(var a: dynarray; typeInfo: PDynArrayTypeInfo; dimCnt: Longint; lengthVec: ^Longint) } { ->EAX Pointer to dynamic array (= pointer to pointer to heap object) } { EDX Pointer to type info for the dynamic array } { ECX number of dimensions } { [ESP+4] dimensions } PUSH ESP ADD dword ptr [ESP],4 CALL DynArraySetLength end; procedure _DynArrayCopy(a: Pointer; typeInfo: Pointer; var Result: Pointer); begin if a <> nil then _DynArrayCopyRange(a, typeInfo, 0, PLongint(PChar(a)-4)^, Result); end; procedure _DynArrayCopyRange(a: Pointer; typeInfo: Pointer; index, count : Integer; var Result: Pointer); var arrayLength: Integer; elSize: Integer; typeInf: PDynArrayTypeInfo; p: Pointer; begin p := nil; if a <> nil then begin typeInf := typeInfo; // Limit index and count to values within the array if index < 0 then begin Inc(count, index); index := 0; end; arrayLength := PLongint(PChar(a)-4)^; if index > arrayLength then index := arrayLength; if count > arrayLength - index then count := arrayLength - index; if count < 0 then count := 0; if count > 0 then begin // Figure out the size and type descriptor of the element type Inc(PChar(typeInf), Length(typeInf.name)); elSize := typeInf.elSize; if typeInf.elType <> nil then typeInf := typeInf.elType^ else typeInf := nil; // Allocate the amount of memory needed GetMem(p, count*elSize + Sizeof(Longint)*2); // The reference count of the new array is 1, the length is count PLongint(p)^ := 1; Inc(PLongint(p)); PLongint(p)^ := count; Inc(PLongint(p)); Inc(PChar(a), index*elSize); // If the element type needs destruction, we must copy each element, // otherwise we can just copy the bits if count > 0 then begin if typeInf <> nil then begin FillChar(p^, count*elSize, 0); CopyArray(p, a, typeInf, count) end else Move(a^, p^, count*elSize); end; end; end; DynArrayClear(Result, typeInfo); Result := p; end; procedure _DynArrayClear; asm { ->EAX Pointer to dynamic array (Pointer to pointer to heap object } { EDX Pointer to type info } { Nothing to do if Pointer to heap object is nil } MOV ECX,[EAX] TEST ECX,ECX JE @@exit { Set the variable to be finalized to nil } MOV dword ptr [EAX],0 { Decrement ref count. Nothing to do if not zero now. } LOCK DEC dword ptr [ECX-8] JNE @@exit { Save the source - we're supposed to return it } PUSH EAX MOV EAX,ECX { Fetch the type descriptor of the elements } XOR ECX,ECX MOV CL,[EDX].TDynArrayTypeInfo.name; MOV EDX,[EDX+ECX].TDynArrayTypeInfo.elType; { If it's non-nil, finalize the elements } TEST EDX,EDX JE @@noFinalize MOV ECX,[EAX-4] TEST ECX,ECX JE @@noFinalize MOV EDX,[EDX] CALL _FinalizeArray @@noFinalize: { Now deallocate the array } SUB EAX,8 CALL _FreeMem POP EAX @@exit: end; procedure _DynArrayAsg; asm { ->EAX Pointer to destination (pointer to pointer to heap object } { EDX source (pointer to heap object } { ECX Pointer to rtti describing dynamic array } PUSH EBX MOV EBX,[EAX] { Increment ref count of source if non-nil } TEST EDX,EDX JE @@skipInc LOCK INC dword ptr [EDX-8] @@skipInc: { Dec ref count of destination - if it becomes 0, clear dest } TEST EBX,EBX JE @@skipClear LOCK DEC dword ptr[EBX-8] JNZ @@skipClear PUSH EAX PUSH EDX MOV EDX,ECX INC dword ptr[EBX-8] CALL _DynArrayClear POP EDX POP EAX @@skipClear: { Finally store source into destination } MOV [EAX],EDX POP EBX end; procedure _DynArrayAddRef; asm { ->EAX Pointer to heap object } TEST EAX,EAX JE @@exit LOCK INC dword ptr [EAX-8] @@exit: end; function DynArrayIndex(const P: Pointer; const Indices: array of Integer; const TypInfo: Pointer): Pointer; asm { ->EAX P } { EDX Pointer to Indices } { ECX High bound of Indices } { [EBP+8] TypInfo } PUSH EBX PUSH ESI PUSH EDI PUSH EBP MOV ESI,EDX MOV EDI,[EBP+8] MOV EBP,EAX XOR EBX,EBX { for i := 0 to High(Indices) do } TEST ECX,ECX JGE @@start @@loop: MOV EBP,[EBP] @@start: XOR EAX,EAX MOV AL,[EDI].TDynArrayTypeInfo.name ADD EDI,EAX MOV EAX,[ESI+EBX*4] { P := P + Indices[i]*TypInfo.elSize } MUL [EDI].TDynArrayTypeInfo.elSize MOV EDI,[EDI].TDynArrayTypeInfo.elType TEST EDI,EDI JE @@skip MOV EDI,[EDI] @@skip: ADD EBP,EAX INC EBX CMP EBX,ECX JLE @@loop @@loopEnd: MOV EAX,EBP POP EBP POP EDI POP ESI POP EBX end; type TBoundArray = array of Integer; PPointer = ^Pointer; { Returns the DynArrayTypeInfo of the Element Type of the specified DynArrayTypeInfo } function DynArrayElTypeInfo(typeInfo: PDynArrayTypeInfo): PDynArrayTypeInfo; begin Result := nil; if typeInfo <> nil then begin Inc(PChar(typeInfo), Length(typeInfo.name)); if typeInfo.elType <> nil then Result := typeInfo.elType^; end; end; { Returns # of dimemsions of the DynArray described by the specified DynArrayTypeInfo} function DynArrayDim(typeInfo: PDynArrayTypeInfo): Integer; begin Result := 0; while (typeInfo <> nil) and (typeInfo.kind = tkDynArray) do begin Inc(Result); typeInfo := DynArrayElTypeInfo(typeInfo); end; end; { Returns size of the Dynamic Array} function DynArraySize(a: Pointer): Integer; asm TEST EAX, EAX JZ @@exit MOV EAX, [EAX-4] @@exit: end; // Returns whether array is rectangular function IsDynArrayRectangular(const DynArray: Pointer; typeInfo: PDynArrayTypeInfo): Boolean; var Dim, I, J, Size, SubSize: Integer; P: Pointer; begin // Assume we have a rectangular array Result := True; P := DynArray; Dim := DynArrayDim(typeInfo); {NOTE: Start at 1. Don't need to test the first dimension - it's rectangular by definition} for I := 1 to dim-1 do begin if P <> nil then begin { Get size of this dimension } Size := DynArraySize(P); { Get Size of first sub. dimension } SubSize := DynArraySize(PPointerArray(P)[0]); { Walk through every dimension making sure they all have the same size} for J := 1 to Size-1 do if DynArraySize(PPointerArray(P)[J]) <> SubSize then begin Result := False; Exit; end; { Point to next dimension} P := PPointerArray(P)[0]; end; end; end; // Returns Bounds of a DynamicArray in a format usable for creating a Variant. // i.e. The format of the bounds returns contains pairs of lo and hi bounds where // lo is always 0, and hi is the size dimension of the array-1. function DynArrayVariantBounds(const DynArray: Pointer; typeInfo: PDynArrayTypeInfo): TBoundArray; var Dim, I: Integer; P: Pointer; begin P := DynArray; Dim := DynArrayDim(typeInfo); SetLength(Result, Dim*2); I := 0; while I < dim*2 do begin Result[I] := 0; // Always use 0 as low-bound in low/high pair Inc(I); if P <> nil then begin Result[I] := DynArraySize(P)-1; // Adjust for 0-base low-bound P := PPointerArray(p)[0]; // Assume rectangular arrays end; Inc(I); end; end; // Returns Bounds of Dynamic array as an array of integer containing the 'high' of each dimension function DynArrayBounds(const DynArray: Pointer; typeInfo: PDynArrayTypeInfo): TBoundArray; var Dim, I: Integer; P: Pointer; begin P := DynArray; Dim := DynArrayDim(typeInfo); SetLength(Result, Dim); for I := 0 to dim-1 do if P <> nil then begin Result[I] := DynArraySize(P)-1; P := PPointerArray(P)[0]; // Assume rectangular arrays end; end; // The dynamicArrayTypeInformation contains the VariantType of the element type // when the kind == tkDynArray. This function returns that VariantType. function DynArrayVarType(typeInfo: PDynArrayTypeInfo): Integer; begin Result := varNull; if (typeInfo <> nil) and (typeInfo.Kind = tkDynArray) then begin Inc(PChar(typeInfo), Length(typeInfo.name)); Result := typeInfo.varType; end; { NOTE: DECL.H and SYSTEM.PAS have different values for varString } if Result = $48 then Result := varString; end; type IntegerArray = array[0..$effffff] of Integer; PIntegerArray = ^IntegerArray; PSmallInt = ^SmallInt; PInteger = ^Integer; PSingle = ^Single; PDouble = ^Double; PDate = ^Double; PDispatch = ^IDispatch; PPDispatch = ^PDispatch; PError = ^LongWord; PWordBool = ^WordBool; PUnknown = ^IUnknown; PPUnknown = ^PUnknown; PByte = ^Byte; PPWideChar = ^PWideChar; { Decrements to next lower index - Returns True if successful } { Indices: Indices to be decremented } { Bounds : High bounds of each dimension } function DecIndices(var Indices: TBoundArray; const Bounds: TBoundArray): Boolean; var I, J: Integer; begin { Find out if we're done: all at zeroes } Result := False; for I := Low(Indices) to High(Indices) do if Indices[I] <> 0 then begin Result := True; break; end; if not Result then Exit; { Two arrays must be of same length } Assert(Length(Indices) = Length(Bounds)); { Find index of item to tweak } for I := High(Indices) downto Low(Bounds) do begin // If not reach zero, dec and bail out if Indices[I] <> 0 then begin Dec(Indices[I]); Exit; end else begin J := I; while Indices[J] = 0 do begin // Restore high bound when we've reached zero on a particular dimension Indices[J] := Bounds[J]; // Move to higher dimension Dec(J); Assert(J >= 0); end; Dec(Indices[J]); Exit; end; end; end; // Copy Contents of Dynamic Array to Variant // NOTE: The Dynamic array must be rectangular // The Dynamic array must contain items whose type is Automation compatible // In case of failure, the function returns with a Variant of type VT_EMPTY. procedure DynArrayToVariant(var V: Variant; const DynArray: Pointer; TypeInfo: Pointer); var VarBounds, Bounds, Indices: TBoundArray; DAVarType, VVarType, DynDim: Integer; PDAData: Pointer; Value: Variant; begin VarBounds := nil; Bounds := nil; { This resets the Variant to VT_EMPTY - flag which is used to determine whether the } { the cast to Variant succeeded or not } VarClear(V); { Get variantType code from DynArrayTypeInfo } DAVarType := DynArrayVarType(PDynArrayTypeInfo(TypeInfo)); { Validate the Variant Type } if ((DAVarType > varNull) and (DAVarType <= varByte)) or (DAVarType = varString) then begin {NOTE: Map varString to varOleStr for SafeArrayCreate call } if DAVarType = varString then VVarType := varOleStr else VVarType := DAVarType; { Get dimension of Dynamic Array } DynDim := DynarrayDim(PDynArrayTypeInfo(TypeInfo)); { If more than one dimension, make sure we're dealing with a rectangular array } if DynDim > 1 then if not IsDynArrayRectangular(DynArray, PDynArrayTypeInfo(TypeInfo)) then Exit; { Get Variant-style Bounds (lo/hi pair) of Dynamic Array } VarBounds := DynArrayVariantBounds(DynArray, TypeInfo); { Get DynArray Bounds } Bounds := DynArrayBounds(DynArray, TypeInfo); Indices:= Copy(Bounds); { Create Variant of SAFEARRAY } V := VarArrayCreate(VarBounds, VVarType); Assert(VarArrayDimCount(V) = DynDim); repeat PDAData := DynArrayIndex(DynArray, Indices, TypeInfo); if PDAData <> nil then begin case DAVarType of varSmallInt: Value := PSmallInt(PDAData)^; varInteger: Value := PInteger(PDAData)^; varSingle: value := PSingle(PDAData)^; varDouble: value := PDouble(PDAData)^; varCurrency: Value := PCurrency(PDAData)^; varDate: Value := PDouble(PDAData)^; varOleStr: Value := PWideString(PDAData)^; varDispatch: Value := PDispatch(PDAData)^; varError: Value := PError(PDAData)^; varBoolean: Value := PWordBool(PDAData)^; varVariant: Value := PVariant(PDAData)^; varUnknown: Value := PUnknown(PDAData)^; varByte: Value := PByte(PDAData)^; varString: Value := PString(PDAData)^; else VarClear(Value); end; { case } VarArrayPut(V, Value, Indices); end; until not DecIndices(Indices, Bounds); end; end; // Copies data from the Variant to the DynamicArray procedure DynArrayFromVariant(var DynArray: Pointer; const V: Variant; TypeInfo: Pointer); var DADimCount, VDimCount : Integer; DAVarType, I: Integer; lengthVec: PLongInt; Bounds, Indices: TBoundArray; Value: Variant; PDAData: Pointer; begin { Get Variant information } VDimCount:= VarArrayDimCount(V); { Allocate vector for lengths } GetMem(lengthVec, VDimCount * sizeof(Integer)); { Initialize lengths - NOTE: VarArrayxxxxBound are 1-based.} for I := 0 to VDimCount-1 do PIntegerArray(lengthVec)[I]:= (VarArrayHighBound(V, I+1) - VarArrayLowBound(V, I+1)) + 1; { Set Length of DynArray } DynArraySetLength(DynArray, PDynArrayTypeInfo(TypeInfo), VDimCount, lengthVec); { Get DynArray information } DADimCount:= DynArrayDim(PDynArrayTypeInfo(TypeInfo)); DAVarType := DynArrayVarType(PDynArrayTypeInfo(TypeInfo)); Assert(VDimCount = DADimCount); { Get DynArray Bounds } Bounds := DynArrayBounds(DynArray, TypeInfo); Indices:= Copy(Bounds); { Copy data over} repeat Value := VarArrayGet(V, Indices); PDAData := DynArrayIndex(DynArray, Indices, TypeInfo); case DAVarType of varSmallInt: PSmallInt(PDAData)^ := Value; varInteger: PInteger(PDAData)^ := Value; varSingle: PSingle(PDAData)^ := Value; varDouble: PDouble(PDAData)^ := Value; varCurrency: PCurrency(PDAData)^ := Value; varDate: PDouble(PDAData)^ := Value; varOleStr: PWideString(PDAData)^ := Value; varDispatch: PDispatch(PDAData)^ := Value; varError: PError(PDAData)^ := Value; varBoolean: PWordBool(PDAData)^ := Value; varVariant: PVariant(PDAData)^ := Value; varUnknown: PUnknown(PDAData)^ := value; varByte: PByte(PDAData)^ := Value; varString: PString(PDAData)^ := Value; end; { case } until not DecIndices(Indices, Bounds); { Free vector of lengths } FreeMem(lengthVec); end; { Package/Module registration/unregistration } const LOCALE_SABBREVLANGNAME = $00000003; { abbreviated language name } LOAD_LIBRARY_AS_DATAFILE = 2; HKEY_CURRENT_USER = $80000001; KEY_ALL_ACCESS = $000F003F; OldLocaleOverrideKey = 'Software\Borland\Delphi\Locales'; // do not localize NewLocaleOverrideKey = 'Software\Borland\Locales'; // do not localize function FindHInstance(Address: Pointer): LongWord; var MemInfo: TMemInfo; begin VirtualQuery(Address, MemInfo, SizeOf(MemInfo)); if MemInfo.State = $1000{MEM_COMMIT} then Result := Longint(MemInfo.AllocationBase) else Result := 0; end; function FindClassHInstance(ClassType: TClass): LongWord; begin Result := FindHInstance(Pointer(ClassType)); end; function FindResourceHInstance(Instance: LongWord): LongWord; var CurModule: PLibModule; begin CurModule := LibModuleList; while CurModule <> nil do begin if (Instance = CurModule.Instance) or (Instance = CurModule.CodeInstance) or (Instance = CurModule.DataInstance) then begin Result := CurModule.ResInstance; Exit; end; CurModule := CurModule.Next; end; Result := Instance; end; function LoadResourceModule(ModuleName: PChar): LongWord; var FileName: array[0..260] of Char; Key: LongWord; LocaleName, LocaleOverride: array[0..4] of Char; Size: Integer; P: PChar; function FindBS(Current: PChar): PChar; begin Result := Current; while (Result^ <> #0) and (Result^ <> '\') do Result := CharNext(Result); end; function ToLongPath(AFileName: PChar): PChar; var CurrBS, NextBS: PChar; Handle, L: Integer; FindData: TWin32FindData; Buffer: array[0..260] of Char; GetLongPathName: function (ShortPathName: PChar; LongPathName: PChar; cchBuffer: Integer): Integer stdcall; begin Result := AFileName; Handle := GetModuleHandle(kernel); if Handle <> 0 then begin @GetLongPathName := GetProcAddress(Handle, 'GetLongPathNameA'); if Assigned(GetLongPathName) and (GetLongPathName(AFileName, Buffer, SizeOf(Buffer)) <> 0) then begin lstrcpy(AFileName, Buffer); Exit; end; end; if AFileName[0] = '\' then begin if AFileName[1] <> '\' then Exit; CurrBS := FindBS(AFileName + 2); // skip server name if CurrBS^ = #0 then Exit; CurrBS := FindBS(CurrBS + 1); // skip share name if CurrBS^ = #0 then Exit; end else CurrBS := AFileName + 2; // skip drive name L := CurrBS - AFileName; lstrcpyn(Buffer, AFileName, L + 1); while CurrBS^ <> #0 do begin NextBS := FindBS(CurrBS + 1); if L + (NextBS - CurrBS) + 1 > SizeOf(Buffer) then Exit; lstrcpyn(Buffer + L, CurrBS, (NextBS - CurrBS) + 1); Handle := FindFirstFile(Buffer, FindData); if (Handle = -1) then Exit; FindClose(Handle); if L + 1 + lstrlen(FindData.cFileName) + 1 > SizeOf(Buffer) then Exit; Buffer[L] := '\'; lstrcpy(Buffer + L + 1, FindData.cFileName); Inc(L, lstrlen(FindData.cFileName) + 1); CurrBS := NextBS; end; lstrcpy(AFileName, Buffer); end; begin GetModuleFileName(0, FileName, SizeOf(FileName)); // Get host appliation name LocaleOverride[0] := #0; if (RegOpenKeyEx(HKEY_CURRENT_USER, NewLocaleOverrideKey, 0, KEY_ALL_ACCESS, Key) = 0) or (RegOpenKeyEx(HKEY_CURRENT_USER, OldLocaleOverrideKey, 0, KEY_ALL_ACCESS, Key) = 0) then try Size := SizeOf(LocaleOverride); if RegQueryValueEx(Key, ToLongPath(FileName), nil, nil, LocaleOverride, @Size) <> 0 then RegQueryValueEx(Key, '', nil, nil, LocaleOverride, @Size); finally RegCloseKey(Key); end; lstrcpy(FileName, ModuleName); GetLocaleInfo(GetThreadLocale, LOCALE_SABBREVLANGNAME, LocaleName, SizeOf(LocaleName)); Result := 0; if (FileName[0] <> #0) and ((LocaleName[0] <> #0) or (LocaleOverride[0] <> #0)) then begin P := PChar(@FileName) + lstrlen(FileName); while (P^ <> '.') and (P <> @FileName) do Dec(P); if P <> @FileName then begin Inc(P); // First look for a locale registry override if LocaleOverride[0] <> #0 then begin lstrcpy(P, LocaleOverride); Result := LoadLibraryEx(FileName, 0, LOAD_LIBRARY_AS_DATAFILE); end; if (Result = 0) and (LocaleName[0] <> #0) then begin // Then look for a potential language/country translation lstrcpy(P, LocaleName); Result := LoadLibraryEx(FileName, 0, LOAD_LIBRARY_AS_DATAFILE); if Result = 0 then begin // Finally look for a language only translation LocaleName[2] := #0; lstrcpy(P, LocaleName); Result := LoadLibraryEx(FileName, 0, LOAD_LIBRARY_AS_DATAFILE); end; end; end; end; end; procedure EnumModules(Func: TEnumModuleFunc; Data: Pointer); assembler; begin EnumModules(TEnumModuleFuncLW(Func), Data); end; procedure EnumResourceModules(Func: TEnumModuleFunc; Data: Pointer); begin EnumResourceModules(TEnumModuleFuncLW(Func), Data); end; procedure EnumModules(Func: TEnumModuleFuncLW; Data: Pointer); var CurModule: PLibModule; begin CurModule := LibModuleList; while CurModule <> nil do begin if not Func(CurModule.Instance, Data) then Exit; CurModule := CurModule.Next; end; end; procedure EnumResourceModules(Func: TEnumModuleFuncLW; Data: Pointer); var CurModule: PLibModule; begin CurModule := LibModuleList; while CurModule <> nil do begin if not Func(CurModule.ResInstance, Data) then Exit; CurModule := CurModule.Next; end; end; procedure AddModuleUnloadProc(Proc: TModuleUnloadProc); begin AddModuleUnloadProc(TModuleUnloadProcLW(Proc)); end; procedure RemoveModuleUnloadProc(Proc: TModuleUnloadProc); begin RemoveModuleUnloadProc(TModuleUnloadProcLW(Proc)); end; procedure AddModuleUnloadProc(Proc: TModuleUnloadProcLW); var P: PModuleUnloadRec; begin New(P); P.Next := ModuleUnloadList; @P.Proc := @Proc; ModuleUnloadList := P; end; procedure RemoveModuleUnloadProc(Proc: TModuleUnloadProcLW); var P, C: PModuleUnloadRec; begin P := ModuleUnloadList; if (P <> nil) and (@P.Proc = @Proc) then begin ModuleUnloadList := ModuleUnloadList.Next; Dispose(P); end else begin C := P; while C <> nil do begin if (C.Next <> nil) and (@C.Next.Proc = @Proc) then begin P := C.Next; C.Next := C.Next.Next; Dispose(P); Break; end; C := C.Next; end; end; end; procedure NotifyModuleUnload(HInstance: LongWord); var P: PModuleUnloadRec; begin P := ModuleUnloadList; while P <> nil do begin try P.Proc(HInstance); except // Make sure it doesn't stop notifications end; P := P.Next; end; end; procedure RegisterModule(LibModule: PLibModule); begin LibModule.Next := LibModuleList; LibModuleList := LibModule; end; procedure UnregisterModule(LibModule: PLibModule); var CurModule: PLibModule; begin try NotifyModuleUnload(LibModule.Instance); finally if LibModule = LibModuleList then LibModuleList := LibModule.Next else begin CurModule := LibModuleList; while CurModule <> nil do begin if CurModule.Next = LibModule then begin CurModule.Next := LibModule.Next; Break; end; CurModule := CurModule.Next; end; end; end; end; { ResString support function } function LoadResString(ResStringRec: PResStringRec): string; var Buffer: array[0..1023] of Char; begin if ResStringRec <> nil then if ResStringRec.Identifier < 64*1024 then SetString(Result, Buffer, LoadString(FindResourceHInstance(ResStringRec.Module^), ResStringRec.Identifier, Buffer, SizeOf(Buffer))) else Result := PChar(ResStringRec.Identifier); end; procedure _IntfClear(var Dest: IUnknown); asm MOV EDX,[EAX] TEST EDX,EDX JE @@1 MOV DWORD PTR [EAX],0 PUSH EAX PUSH EDX MOV EAX,[EDX] CALL [EAX].vmtRelease.Pointer POP EAX @@1: end; procedure _IntfCopy(var Dest: IUnknown; const Source: IUnknown); asm MOV ECX,[EAX] { save dest } MOV [EAX],EDX { assign dest } TEST EDX,EDX { need to addref source before releasing dest } JE @@1 { to make self assignment (I := I) work right } PUSH ECX PUSH EDX MOV EAX,[EDX] CALL [EAX].vmtAddRef.Pointer POP ECX @@1: TEST ECX,ECX JE @@2 PUSH ECX MOV EAX,[ECX] CALL [EAX].vmtRelease.Pointer @@2: end; procedure _IntfCast(var Dest: IUnknown; const Source: IUnknown; const IID: TGUID); asm TEST EDX,EDX JE _IntfClear PUSH EAX PUSH ECX PUSH EDX MOV ECX,[EAX] TEST ECX,ECX JE @@1 PUSH ECX MOV EAX,[ECX] CALL [EAX].vmtRelease.Pointer MOV EDX,[ESP] @@1: MOV EAX,[EDX] CALL [EAX].vmtQueryInterface.Pointer TEST EAX,EAX JE @@2 MOV AL,reIntfCastError JMP Error @@2: end; procedure _IntfAddRef(const Dest: IUnknown); begin if Dest <> nil then Dest._AddRef; end; procedure TInterfacedObject.AfterConstruction; begin // Release the constructor's implicit refcount InterlockedDecrement(FRefCount); end; procedure TInterfacedObject.BeforeDestruction; begin if RefCount <> 0 then Error(reInvalidPtr); end; // Set an implicit refcount so that refcounting // during construction won't destroy the object. class function TInterfacedObject.NewInstance: TObject; begin Result := inherited NewInstance; TInterfacedObject(Result).FRefCount := 1; end; function TInterfacedObject.QueryInterface(const IID: TGUID; out Obj): HResult; const E_NOINTERFACE = HResult($80004002); begin if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE; end; function TInterfacedObject._AddRef: Integer; begin Result := InterlockedIncrement(FRefCount); end; function TInterfacedObject._Release: Integer; begin Result := InterlockedDecrement(FRefCount); if Result = 0 then Destroy; end; procedure _CheckAutoResult; asm TEST EAX,EAX JNS @@2 MOV ECX,SafeCallErrorProc TEST ECX,ECX JE @@1 MOV EDX,[ESP] CALL ECX @@1: MOV AL,reSafeCallError JMP Error @@2: end; procedure _IntfDispCall; asm JMP DispCallByIDProc end; procedure _IntfVarCall; asm end; function CompToDouble(acomp: Comp): Double; cdecl; begin Result := acomp; end; procedure DoubleToComp(adouble: Double; var result: Comp); cdecl; begin result := adouble; end; function CompToCurrency(acomp: Comp): Currency; cdecl; begin Result := acomp; end; procedure CurrencyToComp(acurrency: Currency; var result: Comp); cdecl; begin result := acurrency end; function GetMemory(Size: Integer): Pointer; cdecl; begin Result := SysGetMem(Size); end; function FreeMemory(P: Pointer): Integer; cdecl; begin if P = nil then Result := 0 else Result := SysFreeMem(P); end; function ReallocMemory(P: Pointer; Size: Integer): Pointer; cdecl; begin Result := SysReallocMem(P, Size); end; function GetCurrentThreadId: DWORD; stdcall; external kernel name 'GetCurrentThreadId'; initialization ExitCode := 0; ErrorAddr := nil; RandSeed := 0; FileMode := 2; Test8086 := 2; Test8087 := 3; TVarData(Unassigned).VType := varEmpty; TVarData(Null).VType := varNull; TVarData(EmptyParam).VType := varError; TVarData(EmptyParam).VError := $80020004; {DISP_E_PARAMNOTFOUND} ClearAnyProc := @VarInvalidOp; ChangeAnyProc := @VarCastError; RefAnyProc := @VarInvalidOp; if _isNECWindows then _FpuMaskInit; _FpuInit(); _Assign( Input, '' ); { _ResetText( Input ); } _Assign( Output, '' ); { _RewritText( Output ); } CmdLine := GetCommandLine; CmdShow := GetCmdShow; MainThreadID := GetCurrentThreadID; finalization Close(Input); Close(Output); UninitAllocator; end.
26.910978
123
0.50511
47693080daafbd0b6e82785cb51a35aeddf0a82c
3,500
pas
Pascal
2. Semester/AUD/Uebung 4/WC_ADS.pas
AndreasRoither/SE-Hagenberg
8c437bcfef203b84475224b8efecafdcede8f2b9
[ "MIT" ]
null
null
null
2. Semester/AUD/Uebung 4/WC_ADS.pas
AndreasRoither/SE-Hagenberg
8c437bcfef203b84475224b8efecafdcede8f2b9
[ "MIT" ]
null
null
null
2. Semester/AUD/Uebung 4/WC_ADS.pas
AndreasRoither/SE-Hagenberg
8c437bcfef203b84475224b8efecafdcede8f2b9
[ "MIT" ]
null
null
null
(* WC_ADS 23.04.2017 *) (* Container for strings *) UNIT WC_ADS; INTERFACE FUNCTION IsEmpty: BOOLEAN; FUNCTION Contains(s: STRING): BOOLEAN; PROCEDURE Insert(s: STRING); PROCEDURE Remove(s: STRING); PROCEDURE DisposeTree(); IMPLEMENTATION TYPE Node = ^NodeRec; NodeRec = RECORD data: STRING; left, right: Node; END; VAR Tree : Node; PROCEDURE InitTree; BEGIN Tree := NIL; END; FUNCTION NewNode (data: STRING): Node; VAR n: Node; BEGIN New(n); n^.data := data; n^.left := NIL; n^.right := NIL; NewNode := n; END; (* Check if binsearchtree is empty *) FUNCTION IsEmpty: BOOLEAN; BEGIN IsEmpty := Tree = NIL; END; (* check if binsearchtree contains string recursive *) FUNCTION ContainsRec(VAR t: Node; s: STRING): BOOLEAN; BEGIN IF t = NIL THEN BEGIN ContainsRec := FALSE; END ELSE IF t^.data = s THEN ContainsRec := TRUE ELSE IF s < t^.data THEN BEGIN ContainsRec := ContainsRec(t^.left, s); END ELSE BEGIN ContainsRec := ContainsRec(t^.right, s); END; END; (* check if binsearchtree contains string Uses a help function *) FUNCTION Contains(s: STRING): BOOLEAN; BEGIN Contains := ContainsRec(Tree, s); END; (* Insert in binsearchtree recursive *) PROCEDURE InsertRec (VAR t: Node; n: Node); BEGIN IF t = NIL THEN BEGIN t := n; END ELSE BEGIN IF (n^.data = t^.data) THEN Exit ELSE IF n^.data < t^.data THEN InsertRec(t^.left, n) ELSE InsertRec(t^.right, n) END; END; (* Insert a string in binsearchtree Uses a help function *) PROCEDURE Insert (s : String); BEGIN InsertRec(Tree, NewNode(s)); END; (* Remove a string from binsearchtree *) PROCEDURE Remove(s: STRING); VAR n, nPar: Node; st: Node; (*subtree*) succ, succPar: Node; BEGIN nPar := NIL; n := Tree; WHILE (n <> NIL) AND (n^.data <> s) DO BEGIN nPar := n; IF s < n^.data THEN n := n^.left ELSE n := n^.right; END; IF n <> NIL THEN BEGIN (* no right subtree *) IF n^.right = NIL THEN BEGIN st := n^.left; END ELSE BEGIN IF n^.right^.left = NIL THEN BEGIN (* right subtree, but no left subtree *) st := n^.right; st^.left := n^.left; END ELSE BEGIN (*common case*) succPar := NIL; succ := n^.right; WHILE succ^.left <> NIL DO BEGIN succPar := succ; succ := succ^.left; END; succPar^.left := succ^.right; st := succ; st^.left := n^.left; st^.right := n^.right; END; END; (* insert the new sub-tree *) IF nPar = NIL THEN Tree := st ELSE IF n^.data < nPar^.data THEN nPar^.left := st ELSE nPar^.right := st; Dispose(n); END; (* n <> NIL *) END; (* Removes all the elements from the binary search tree recursive *) PROCEDURE DisposeTree_rec(VAR Tree : Node); BEGIN IF Tree <> NIL THEN BEGIN (* Traverse the left subtree in postorder. *) DisposeTree_rec (Tree^.Left); (* Traverse the right subtree in postorder. *) DisposeTree_rec (Tree^.Right); (* Delete this leaf node from the tree. *) Dispose (Tree); END END; (* Removes all the elements from the binary search tree calls rec. function *) PROCEDURE DisposeTree(); BEGIN DisposeTree_rec(Tree); END; BEGIN InitTree; END.
20.467836
79
0.578
f164dbdf74bedb8e1f90150296db24235f22943b
72,850
dfm
Pascal
3.Class.MClock.VoV/1/UnitFormMain.dfm
milphaser/LClocks
8ffe6f46ad4885dcfb6390faaff8d1d68418bc4e
[ "MIT" ]
null
null
null
3.Class.MClock.VoV/1/UnitFormMain.dfm
milphaser/LClocks
8ffe6f46ad4885dcfb6390faaff8d1d68418bc4e
[ "MIT" ]
null
null
null
3.Class.MClock.VoV/1/UnitFormMain.dfm
milphaser/LClocks
8ffe6f46ad4885dcfb6390faaff8d1d68418bc4e
[ "MIT" ]
null
null
null
object Form1: TForm1 Left = 0 Top = 0 Caption = 'Matrix Clocks - test application' ClientHeight = 552 ClientWidth = 845 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -14 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False OnShow = FormShow PixelsPerInch = 120 TextHeight = 17 object imgExample: TImage Left = 424 Top = 3 Width = 410 Height = 444 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 Picture.Data = { 0A544A504547496D616765E3700000FFD8FFE000104A46494600010101006000 600000FFE110DC4578696600004D4D002A000000080004013B00020000000600 00084A8769000400000001000008509C9D00010000000C000010C8EA1C000700 00080C0000003E000000001CEA00000008000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000004E656C6C7900000590 030002000000140000109E9004000200000014000010B2929100020000000338 390000929200020000000338390000EA1C00070000080C00000892000000001C EA00000008000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000323031333A30323A32302031353A34323A31390032 3031333A30323A32302031353A34323A31390000004E0065006C006C00790000 00FFE10B18687474703A2F2F6E732E61646F62652E636F6D2F7861702F312E30 2F003C3F787061636B657420626567696E3D27EFBBBF272069643D2757354D30 4D7043656869487A7265537A4E54637A6B633964273F3E0D0A3C783A786D706D 65746120786D6C6E733A783D2261646F62653A6E733A6D6574612F223E3C7264 663A52444620786D6C6E733A7264663D22687474703A2F2F7777772E77332E6F 72672F313939392F30322F32322D7264662D73796E7461782D6E7323223E3C72 64663A4465736372697074696F6E207264663A61626F75743D22757569643A66 616635626464352D626133642D313164612D616433312D643333643735313832 6631622220786D6C6E733A64633D22687474703A2F2F7075726C2E6F72672F64 632F656C656D656E74732F312E312F222F3E3C7264663A446573637269707469 6F6E207264663A61626F75743D22757569643A66616635626464352D62613364 2D313164612D616433312D6433336437353138326631622220786D6C6E733A78 6D703D22687474703A2F2F6E732E61646F62652E636F6D2F7861702F312E302F 223E3C786D703A437265617465446174653E323031332D30322D32305431353A 34323A31392E3838353C2F786D703A437265617465446174653E3C2F7264663A 4465736372697074696F6E3E3C7264663A4465736372697074696F6E20726466 3A61626F75743D22757569643A66616635626464352D626133642D313164612D 616433312D6433336437353138326631622220786D6C6E733A64633D22687474 703A2F2F7075726C2E6F72672F64632F656C656D656E74732F312E312F223E3C 64633A63726561746F723E3C7264663A53657120786D6C6E733A7264663D2268 7474703A2F2F7777772E77332E6F72672F313939392F30322F32322D7264662D 73796E7461782D6E7323223E3C7264663A6C693E4E656C6C793C2F7264663A6C 693E3C2F7264663A5365713E0D0A0909093C2F64633A63726561746F723E3C2F 7264663A4465736372697074696F6E3E3C2F7264663A5244463E3C2F783A786D 706D6574613E0D0A202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020200A20202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 20202020202020202020202020202020200A2020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 202020202020202020202020202020202020202020200A202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020200A20202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 0A20202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 20202020200A2020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 202020202020202020200A202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020200A20202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 20202020202020202020202020202020202020200A2020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 202020202020202020202020202020202020202020202020200A202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020200A20 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020200A20202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 20202020202020200A2020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 202020202020202020202020200A202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020200A20202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 20202020202020202020202020202020202020202020200A2020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 202020202020202020202020202020202020202020202020202020200A202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 200A202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020200A20202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 20202020202020202020200A2020202020202020202020202020202020202020 20202020202020203C3F787061636B657420656E643D2777273F3EFFDB004300 07050506050407060506080707080A110B0A09090A150F100C1118151A191815 18171B1E27211B1D251D1718222E222528292B2C2B1A202F332F2A32272A2B2A FFDB0043010708080A090A140B0B142A1C181C2A2A2A2A2A2A2A2A2A2A2A2A2A 2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A 2A2A2A2A2AFFC00011080154013E03012200021101031101FFC4001F00000105 01010101010100000000000000000102030405060708090A0BFFC400B5100002 010303020403050504040000017D010203000411051221314106135161072271 14328191A1082342B1C11552D1F02433627282090A161718191A25262728292A 3435363738393A434445464748494A535455565758595A636465666768696A73 7475767778797A838485868788898A92939495969798999AA2A3A4A5A6A7A8A9 AAB2B3B4B5B6B7B8B9BAC2C3C4C5C6C7C8C9CAD2D3D4D5D6D7D8D9DAE1E2E3E4 E5E6E7E8E9EAF1F2F3F4F5F6F7F8F9FAFFC4001F010003010101010101010101 0000000000000102030405060708090A0BFFC400B51100020102040403040705 040400010277000102031104052131061241510761711322328108144291A1B1 C109233352F0156272D10A162434E125F11718191A262728292A35363738393A 434445464748494A535455565758595A636465666768696A737475767778797A 82838485868788898A92939495969798999AA2A3A4A5A6A7A8A9AAB2B3B4B5B6 B7B8B9BAC2C3C4C5C6C7C8C9CAD2D3D4D5D6D7D8D9DAE2E3E4E5E6E7E8E9EAF2 F3F4F5F6F7F8F9FAFFDA000C03010002110311003F00FA468A28A0028A28A00C AF146B63C35E13D535B6B737234FB592E0C21F6EFDAA4E33838E9E95C97C39F8 B765E3CF0FEAFA9DC69CFA4FF64E1E78DE612FEE8C7BC3E703A80DC63B56B7C5 3FF924BE29FF00B05DC7FE806BE6BD4F53B8F03E8C896424C78CBC1F670A0886 079C364473FF006CC3F3FEDD007B97C2AF8CA9F13B55BFB24D09F4CFB140B316 6BAF377EE38031B171EB5E9693C2F234692A33AF550C091F857CDDE12874DF02 78C7E22DAEA971736B63A6687696F34D6240987EE63426327A3163C1F539E2B1 6EB458B41D47C01AD687E186F0EC377AADB2437D36ABE7DD5FC6E412CF1A8DAA 0AE33FEF631CD007D116BE3BD2EF7E225EF83EDC486F6C6D45C4F2B60202C536 A2F39270F93E98EFDBA2171092009A324B6D1F30EBE9F5AF07F0E782FC3EFF00 B56789636D3815B0B68B51B61E6BFEEEE1BCA7693EF739676383C73D2AAFC0FF 0002E91E20D575FD77588E4B89B4CF10486C93CD6090C8A4317DA3824FCA39CF 02803D93C27E26BCD7B489EF35BD1DB41923BA681209EE04864501487CE06339 3C7B5740D2C68CAAEEAACFC282704FD2BE72F87DA1685AFF00ECE7E2A83C5130 B6B28356BAB8175DEDE458E3DAE3D4E78C77CE3BD47F016ED7C69E3D9755F1A5 FC979AE693A7C51E956D731EDC418C1994742D82BCFF00B64F39C800FA1B59D5 ECB40D16EF55D52610DA5A446595CF603D3D49E807726BC99FE37F8965D25BC4 5A7FC36BF9FC32A0B7DB5EED56468C13FBC11ED271D0F71D79AE83E3E5A5D5E7 C12D792CC316458A5902E725165466E9E8067F0AB7E1BF17F87AC7E08E9BAEDD 5E43269969A54493ED20E59230AD16D3D5B236EDF5A00AFABFC5ED3ACF47F096 A9A5593EA167E27BC4B589DA4F29A02CC1496183920E4119EA3AD7A0492C70AE E9A458D49C659B02BC33E29EBD63E27B2F861ACE92B2AD95DEBD0B42258FCB6D A1C0FBBDBA7E54CD3B42D3BE277C76F185A78F15AEA2D14243A7E98D3BA288C9 E6501483CFCA783FC7CF6A00F79A624B1C8CCB1C8ACC870C15B257EB5F2B5DF8 9759D03E157C40D1740D4AE6E349D375A8ECACAEFCEDED15BBB387557F4F9107 1FF3D0FAD7A6E97E01F87FE11D77C23A9E99AC4FA3DFDD28583C9BA2C3562C17 21F706041DC3818CEEE318E003AFF0378FD3C6975E218BFB3FEC2BA25FBD933B 4FBC4BB4905FEE8DA38E9CD75BE7C3E4F9BE6A797FDFDC31E9D6BE3AB9B8D645 CF8BE19A2B85F06AF8A4B6BB35A1C4AE8666013FDDC024F6C95CF6AF53F8A1E1 31A85DF8462F0643A36ADA759DAB35BF85E7BD100B98D949595177A97E0139CF 519E726803DD11D6440F1B0653D0A9C835C4FC49F889278022D23ECFA2B6AF3E AB77F648614B9109DE71B792A4724E3B5727F03AFF004AB4D63C43E1DB6F0FEA 7E1BD4A131DCDC69975746786304633112015EA0F39C823938E20FDA2A196E5F C1105BDD1B3965D6D112E5464C2C7003807AE0F3F8500753A678DFC7379AB5A5 B5F7C31B9B1B69A6449AE9B5685C4284805F6819381CE075C577C93452B308E4 472BC3056071F5AF37D03C15E27D3B5FB3BBBFF8A975AADBC520692CA4B64559 C7F7490E48AF27F8DF2C7E0AF883A80F076A7359C9E21B1FF89FDBDBC7BD6142 E079BC7DD2D93C71D4F3F3D007D40B3C4F1991254641D5830207E34473452A16 8A44751C12AC08AF13F1858782B49F87BE0DF0CE9F6FA86AD67A8CE874EB2D3A E5604D4DFE525A7908FBADBC13D3EF76C0C60F81B4E9340F8A3E35D223D263D0 603E1B79DB4A82F9AE5226F9304B1FE2C367DB771401F448B885B66D9A33E667 66187CD8F4F5A70963694C61D4BAF2541E47E15F237FC227A5FF00C32CC1E2E6 59CEB76D73B6DEEBED0F9813ED253628CE02F2C7A672735D96B1E19B1F07F8FF 00E166ADA235C45A8EB171B752BA79D9DAEF708B717C93D7CC6CFD6803E84373 000C4CF180870C4B8F94FA1AE57E2578F17E1DF8622D61B4E3A879B7696C2113 79582C18E73B4FF77D3BD791F827C11E19F1AFC4FF008976FE282F7020D4E431 5AFDA9A3550649034BB548C9180013C0CFBD7257B7D7975FB35FD96E6E65BBB6 D3FC562D6CEE256C968421207A80093F9E3B5007D6B24B1C2BBA691635271966 C0A7D7CF5E31B6B9F16FED0BAAE8FA9680DE27B2D374E88DA698DA80B444DEA8 CD2E4FDE396238E79F6AEDFE065B6AFA7786353D375492092D2DB507160B1EA0 978D04479F299D188054F6E3A9A00E8FC7FF0011344F87BA0CD7DAB5CC6D75B0 9B6B1571E6DC37600750B9EADD07E9567C05E286F1A78174DF10C96A2CDAF919 8C0AFBC261D97AE067EEFA561FC59F0EE9171E06F11EBB71A7C12EA9068B7104 37522EE68936B1C2E785392791CF38A6FC0AFF009223E1CFFAE327FE8E7A00F4 0A28A2800A28A2800A28A2800A28A2800A28A28039CF1F5AEA37FE08D46C747D 2A1D5E7BB8FC86B39AE3C859236E1FE7C8C7CA4F7AF24BDF0B78E751B7D021BC F861A4489E1D0A34E075A3FBB0BB700FCFF30F91786CD7BF51401E112685E3E9 F54D6F50B8F861A2CD3EBD0AC3A8799AC6E595140006DDF85E839183919AC0B5 F861E2BB5B7862FF0085656131B79565B7965F10333C054E4043BFE55CF381D7 BE6BE96A2803C0351F0C78FF0054F1CDB78BAE7E1C69A357B7284491EB7B55CA 7DDDCA1B07181F90CE6B4FC356DF133C230DEC5A0FC39D26DD2FAE9AEE70DACE FDD236013F339C741C0AF6CA2803E783E09F1A9F0B49E1CFF8567A6FF654B7A6 FA4B71AFB7CF2E00C93BF247038E95A573A3FC43B8F1369BE201F0D348B7D4B4 C88436D35B6B3E56231C042AAE032E091823A1C57BAD1401E5727887E30CD13C 537C3FD1648DD4AB236A6A4303D4119E4579BC9F097C432EAA6F4FC29D2950B6 F368BAEB080B7AECDFC7D0715F4E51401E1FAD69FF0011B5F5D25752F869A314 D1A74B8B148B57F296164C6DC0560303038E9C56678BBC1FE39F1ADFADFEB5F0 CF4A17CAA10DD5B6B5E548EA3F858AB7CC3EB5F41D1401E1B61A578FF4CF0849 E17B3F857E1F5D1E556596D9B530C24CF56625B25B81F31391818E82B17C35E0 0F18F8535A8F55D2FE18E96D77093F676B9D70CA2DF391F2066C0E0F5E4D7D19 450078459E85E3FB1D3F5CB183E18E8E6DB5E95E5D42393592E2567CE48CBFCB D4E318C567DF7823C6DA8685A6E9537C34D3563D294A58DC47AEB2CF0296CE04 9BF7633D8E71DABE87A2803C2FC27A4FC45F05C770342F86DA4A4D7441B9B99B 59F366988E9B9D989EE78E9478C748F889E3CB3B7B5F13FC36D2AEA2B690C910 5D68C7B588C1FBAE33C57BA51401F32E9FF09FC45A5EA76B7F67F0AB4D4B8B59 926898F8864203A90C0E0C9CF2057436DA078FADAF75CBBFF8561A34F3EBCA53 507B8D63CC32A9CE5797F9473D063A0F415EF345007CEB73E05F1ADDF856D3C3 F2FC35D3CD958CC66B36FEDF6325B31209D8E5F20123A74EFD6A7D23C1FE38D0 F5237FA77C33D323BA7B37B29656D799DA68DCE5B7E5CE493DFAF03D2BE83A28 03C07FE118F1E7FC205FF086FF00C2B3D2BFB137EFF23FB71B39F33CCCEFDFBB EF7BD5DD4B4EF891AB5E687737DF0E349797407DFA791AD63CA3F2F5C3FCDF71 7AE7A57B8D1401F2C2FC31F1DEA9AE7882FF0058F87F6B3CFA95F35C893FB584 062DCCC595195FE65391F7BD0575579E18F1CDEF83ED7C2F27C2ED1A3D22D261 3C56F16B3B30E33F3160F927E63D4D7BED1401E03E2CF0C78FBC677B15F6B1F0 DB4B5BF893CB4BCB5D6FC994273F292ADC8E4F5CD6B78693E26F843448F49F0E FC35D12CECD18B6C5D5831663D59896249381C9F4AF68A2803C8756D43E2CEB9 A35DE97A97C3ED225B4BC85A19906AC14B230C1190D91C56AFC3387C67A2A5AE 81AAF842C345D06D617114906A3F687562DB82F2C49C9279AF49A2800A28A280 0A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A280 0A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A280 0A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800ACDD52FA48AFF00 4EB0B793CB96EE6259B00911A0DCDD7D7E55FF008167B5695666A76324BA9699 7F6E9BE4B498ABAE40CC722ED6C67D0ED6FA291DE93D8DE872F3FBDD9FDF676F C6C431DF6A3FF0980B3B85863B26B49248954EE762AE83731C71F78E00FC7D93 51BABBB8D7EDF48B2BB3679B592E64996357638655551BB2319624F19E00E335 A0D60ADAC45A86F3BE381E0D98E086656CFF00E39FAD509748BE9E486EFF00B4 3C8BF84CD189522575685DF2148207202A73EA0F504E65A67442749CA3276565 6DBAEBADACEFD08D35E993C0B26B53449F688AD1E468C7DD2EA0FE848A640DAB 41A9C9A55C6A3E7C97164D3C5726145F264521586D030572EA4679E0F26ACA68 4B169F1E911C87FB2BEC525B4A8C7F78E5B680D9C75C6FCFB91C532DB49B9D39 E7D467B99355BE4B6F26105563CA8E76FA6E638CB1E381C0A5666AA7412972DB 56ECADFF0080EFB5B77AEABB97746D43FB5745B4BE286369E30CE87F81BF887E 0722AED51D134F6D2B44B4B2793CC921882C8FFDE7EAC7F139ABD56AF6D4E0AD C9ED25ECFE1BBB7A740A28A2999051451400514514005145140186975A86A8DA 9FF665CC70AC372B6B133A02136E3CD7E9CB7CCCA01E3283D4D2F872FEE2F9B5 00F73F6DB482E3CBB6BB2AAA651B46E1F2800ED6CAEE00038A825F0FDC4F06AD A7477125A5B5E5C0B959A3C124381E6464707EF2927D9C0F5ABD6FA7EA369629 0457D1B94962DB88163548830DC8000472A081E9C74ACD5EE7A751D1F66E316A EED6D354ACB5BDB7EEAFDF76CCA8F55D498C3AA7DA4359CBA93597D9046A02C7 E69843EEC6EDDB8063CE30718EF5A3ABDCDDBEADA7E9965706D0DCA4B2C93AA2 B3058F68DAA1811925C7241E01A8D7C3405F2B3DF4AF64976D7A96854712925B EF75DBB89603D7BE38A927D26F2E8C572D7DE45F5BCD3186558C32889D8E1197 8CFCA17DF2A393DCB3B1529E1DCD495ADAF4EE9F2DD5B5B3DDEBF32A41AC5EA5 9E997374C1C35E49A7DD054E19848D1AC83D3E741C74C39F415D1D60BE84D15B E95A740D23DBC1726EEE277232ECA4BF38EED2306E98C03ED5BD551BF539712E 9369D3F3FBAEEDF3FD2C14514551C814514500159BAA5F4915FE9D616F27972D DCC4B360122341B9BAFAFCABFF0002CF6AD2ACCD4EC649752D32FEDD37C96931 575C8198E45DAD8CFA1DADF4523BD27B1BD0E5E7F7BB3FBECEDF8D8CF7BFD42C 7C49656D7577E60BC9E4062F236C31C5B58A6D9081BA4F9572B93D4F00006ADE A93DE4DACDA69763746CFCD825B892658D5DB08514280C08E4BE4F1D17DF34DF EC091EF616B9D4A79ED2DEE0DCC30480160FCE017EA5549381F4C938A59B48BE B936F72751F22FEDDE65495230EAD13BE4232F19C2AA73EABDFBC6A763950738 C935A26B6D2FAD9DADD34BEFD35632DB5B9C78326D5AEA356B8B5866322AF01D E22C0E3D01299F6CD456526AB1DEC76379A8F9CD7D6124E932C28BF67914A03B 46395FDE820364FCBC939AB50E882DACA0D32390B69A2DA58AE11F05E66723E6 271DF32138C75E9E8CB3D1E6D3656BDB8BB9B529EDED4C16E85550ECE0E3DD98 AAE49C0E07039A350E7A1EFF002DB56EDA7FE02BCACF57AEDDF62DE89A836A9A 35BDDCB188E570565419C2BA92AE067B6E06AFD67E85A7C9A5E896D693B89265 05A571D0C8C4B391EDB89AD0AB5B6A70D7E4F6B2F67F0DDDBD3A0514514CC828 A28A0028A28A002B175CD565B6D5746D2ACDC25C6A372773100EC86352F21C1F 5C2A7B7999ED5B5583AF69934BAE685AC5A4465934FB878E5407930CCBB188FF 0075BCB63ECAD40185A7F89F57B93A6EB267825D2F52D565B05B3106D68630F2 22481F392C5A30482318738E993AFAD6A3A8DC78AED3C3FA45EC76123D94B7B3 5C341E69C2BA22A80481C97249EBF2E38CE6A0B4F053DB6A36E1F53F3348B3BE 9750B5B116E159257DE70D267E645691D946D07246490314F9FC3FACDDDCDAEA 89AA4363ABC1F6AB7F30DA89637B6925DC8A5370F9955232083D436430340043 E2D997E17C9E28BBB645B982C24B8920527619501CA83C9C165E3D8D436D73E2 283589B41BFD4A09EEAEB4C6BBB5BC8ED8208254654752B93B932E84679C6E04 9E08B29E151168B0F869642DA11D2E6B3B8DD8F3A476DA0386F5C79A4F18CB0C 7B32D344D4348B8B9D7753BD7D735182C0DB5BC70DB8837203BB18DCD97760B9 6E0703000A00D6F0EEB0BAFF00872C355588C26EA1591A23D636FE25FC0E47E1 5A5595E17D264D0BC2DA7E9B3CA259EDE0513480F0D21E5C8F6DC4E3DAB56800 A28A2800A28A2800A28A2800A28A280389D47C597B8D49F4E9A2453AB5BE8966 5E3DEAB2B32896520609C17601720662FF006AB5FC3BA86A126A5ABE93AACA97 32E9D2C7E5DD2C613CD8E48C30DCA0E0303B871D400715983C272CCBAE699BDE D639B528F56D3EF5143F95292AE4153D48963624775900CFA5FB4D0B53D352EA EE2BE8AE755D42FA09AEE7307971F94A515911373151E5AB0192C773649F400C 98BC47ACB496FAD79F049A55C6B2FA60B25870CB1F9CD6EB2EF273BBCC50C463 1B5B18C8CD6C6BFA86A1FDBBA5689A4DC476725F24F3C972F17985238B602154 F192D22F27A0078CE08AABE0A906A3187D50B6910EA2DA9C563E400EB3B317C1 933CA09199C2EDCE4FDE2062A6BAD0755BF9AD7513A8C569AA58DC5C8B794DBF 9B1B5B48E711BA065CFCAB19C820E547BD0053B3F12EA2BA7E897BA894225D46 6D26F9628F0A6512BC2B2AF52019220319C6253E82BB1AE424F0C4B6F69A0689 6F24F3C16F7E751BDBB7006F657694F4E01799D4E3A050DE82BAFA0028A28A00 28A28A002B175CD565B6D5746D2ACDC25C6A372773100EC86352F21C1F5C2A7B 7999ED5B5583AF69934BAE685AC5A4465934FB878E5407930CCBB188FF0075BC B63ECAD40185A7F89F57B93A6EB267825D2F52D565B05B3106D68630F222481F 392C5A30482318738E993B5AE5F6A33788B4FD0F48BC8EC64B8B69EEE6B8787C D6548CC681554F192D28249ECA7D73556D3C14F6DA8DB87D4FCCD22CEFA5D42D 6C45B856495F79C3499F9915A47651B41C919240C54D71A0EB17AF67A92EA715 96AF68F7512C86DBCD89EDE5932A8C9B94E42A44721B8653D4139004B1F144DF F0AE6E3C437F6EBF69B2B6B87B88A338569202EAFB7AE0131923AE011D6AB69D 77E211A9C3A5EA9A941249A9E9525DC37105B05FB2CA8D1AB00A49DCBFBE4233 CFCA724E78B76DE17369A3DB787965F3F477B2B982F8CB8F326790AFCD91D33B A5271C73F4A8F4FD02F7469CEADA9EA32EB37163A7B5A5AC70DB88D8A6559B23 71DF2318D067E51F2F0064D006A786B583AF786ECF51922F266950ACD10E91CA A4AC8A3D83AB0FC2B52B1FC29A4CDA2785ECEC6F1C4974AAD2DC3039065918C8 F8F6DCCD8F6AD8A0028A28A0028A28A0028A28A002B2758D5A4B2D4349D3ED42 1B9D46E760DE09091229791B8F65DA3D19D4F20115AD5CF7886C25FF008487C3 FACC10BCDF61B89209923049114E9B4B003AE1C464FA2EE3DA8032EC3C5DAA5D 4BA7EA6C968DA2EA3A9CBA7C71244DE7C615A44494B97DA4168F950A301C7270 73A7ACEAFA91F12DAE83A149670DD4B672DE4B3DE42D2AAA2B222A8557524967 EB9E029E0E6A8D9F832F2DEF6D2D9EFEDFFB16C3519351B6B78E065977399184 6CDBB1B15A4247193850718C99A6D1F5EBBBEB4D6E096C2CB56816E6D1D2681A 48E4B679818C9DAF90C1511BAE09661C678009A1F168FF00856EDE29BAB528D0 D8BDCCD6C1BF8D14EE4079E372900FD0D436BAA788E3D525D1F523A73DFCFA69 BCB496085D22491582BC6E0BB16019D30C36E413C0C511F85A68FC37178499FC ED224D2A6B6BABB71FBD3336D018658F5DD2B1E0E085E696D74CD534DBBB8F10 EBD72BA9DE5AE9ED6D041616EC9BD41DEC76EE6CBB954E070318E68036741D5E 2D7FC3F63AADBA144BB8165F2C9C942472A4FA8391F8568563F84F4A9F44F096 9BA7DEB892EA18079EC318321F99F18EDB89C7B56C5001451450014514500145 1450014514500721A978C2E621A8B69E90304D4ADF48B332AB10D70E5448ED82 328BE601818398DB9E4634FC3FAA5FDD5FEABA66AFE43DDE9D32289ADA231C73 46E8194856662A41DCA464FDDCF7C0C45F0B4F2AEB9A5266D9FF00B5A3D634FB C92132461CB2C98232324489202B9076B2FAD68D8E93ACE966F35032DB5E6A9A 9DEDBB5C844658618176232A02F9C840EC0F763F771C500528FC57AB3CB0EA66 3B33A2CFABB698B0AC6C67004A601297DDB70655FBBB3EE9EB915ABAF6ABA8C3 AD697A368C6DA2BABF59A66B8BA89A548A3882EEF915D4B12D2201F30C727DAB 3A3F075E8BD8AD64D461FEC483536D52381202B379864694465836DD8256DDD3 38017B66AC5D693ADEA17369AB24B6969AA584F7514092C65E296DA47C00F86C 862A91B641EA31819C0008AD7C5777F63D16EF50822892EAFA6D2EF153384B85 778D5D4E7EE19222B8EBFBC5E7839EB2B8D97C39756F61A068714D2DCEDD48EA 57F7862DAADB6469DBD429699D005C93B777276935D950014514500145145001 593AC6AD2596A1A4E9F6A10DCEA373B06F04848914BC8DC7B2ED1E8CEA79008A D6AE7BC43612FF00C243E1FD66085E6FB0DC4904C9182488A74DA5801D70E232 7D1771ED4019761E2ED52EA5D3F5364B46D1751D4E5D3E389226F3E30AD2224A 5CBED20B47CA85180E393839D7D6B54D446BD61A2688D6B15CDCC135D4971771 34AB1C71945C045652496957F886003D78ACDB3F065E5BDEDA5B3DFDBFF62D86 A326A36D6F1C0CB2EE732308D9B76362B4848E3270A0E3193627D2B5EBCB9B2D 6229ACACF55B43756C639612F14B6D24A0A676BE436D8E26E1BAEE1C678009AC BC525FC013788AFEDB63D9DBCF25CC119E37C05D640A4F6DD1B633DB155B4DD5 7C44D7D169DAA9D385CEA1A649796925BC2EA96F2214568DC1762E019A32186D CE1B81C53EDFC333DAE85078619FED3A5DC595D47A8DD3F123CB290495F98E37 192538C1C6073C729A768FA9E9979FDB3AF5F2EA0FA769EF6B6F1595AB2B3A12 ACEE57731691BCA41B57818E339E0035FC3BACA7883C3D67AA246623711E5E22 73E5B8255D33DF6B0619F6AD2AC5F0869775A3F852CED75120DE1DF35C852085 9647691D411C1019C81F4ADAA0028A28A0028A28A0028A28A0028AC8F12DDEBD 65A6A49E17D2ADB54BB3205686E6EFECEAA983960769C9CE0638EBED5CB7F6FF 00C51FFA12347FFC1D7FF6BA00F40270326BCFAEBE3AFC39B3D61B4D9BC4B119 55F63491C323C41BFEBA2A9523DC1C7BD733F1275BF89F2FC36D7125F0B58D84 26D4F9D7369AA19648E2C8DE42EC19F977679E064F6AF90E803F47E09E1BAB78 EE2D6549A19543C7246C195D48C8208E0823BD495F3EFC10D5FE22DB7C2FB48B 49F0E59EA9A709A5FB2CF79A8F90C13772A1769CA86DD83F51DABD0BFB7FE28F FD091A3FFE0EBFFB5D007A0515E7FF00DBFF00147FE848D1FF00F075FF00DAE8 FEDFF8A3FF0042468FFF0083AFFED7401E814579FF00F6FF00C51FFA12347FFC 1D7FF6BA3FB7FE28FF00D091A3FF00E0EBFF00B5D007A0515E7FFDBFF147FE84 8D1FFF00075FFDAE8FEDFF008A3FF42468FF00F83AFF00ED7401E814579FFF00 6FFC51FF00A12347FF00C1D7FF006BA3FB7FE28FFD091A3FFE0EBFFB5D007A05 15E7FF00DBFF00147FE848D1FF00F075FF00DAE8FEDFF8A3FF0042468FFF0083 AFFED7401E81505EDEDAE9D652DE6A17115B5B40A5E59A670A88A3A924F00570 DFDBFF00147FE848D1FF00F075FF00DAEBCC3E3F6ABF102EFE1E4516BDE1FB5D 2B4C37B1F9F259DF99CB9C36D571B4617760E4FF00105EF8A00F51D27E387C3C D6B594D32C7C451FDA25609119A0962491BD03BA81EDC9193D335DF57E6E57D9 7E11D77E2A2F82F47593C25617645945FE9175AA98E5906C1867528486231904 E73401EB14579FFF006FFC51FF00A12347FF00C1D7FF006BA3FB7FE28FFD091A 3FFE0EBFFB5D007A0515E7FF00DBFF00147FE848D1FF00F075FF00DAE8FEDFF8 A3FF0042468FFF0083AFFED7401E814579FF00F6FF00C51FFA12347FFC1D7FF6 BA3FB7FE28FF00D091A3FF00E0EBFF00B5D007A0515E7FFDBFF147FE848D1FFF 00075FFDAE8FEDFF008A3FF42468FF00F83AFF00ED7401E81589AFF8CBC39E15 6893C45AD59E9CF30CC693CA159C671903AE3DFA5735FDBFF147FE848D1FFF00 075FFDAEBE4BF8AB3EBD73F13B5993C5701B6D44CFCC1BF7AC498F9155BBA85C 60F7EB401F7669FA859EAB6115EE99750DDDACCBBA39A070E8E3D88E2AC57CB7 FB3AEA5E3AB2D0F595F0CE8906ABA69B88FF00E3EEF0DBA452ED3BB67CA7248D 99F4C2FAD7B27F6FFC51FF00A12347FF00C1D7FF006BA00F40A2BCFF00FB7FE2 8FFD091A3FFE0EBFFB5D1FDBFF00147FE848D1FF00F075FF00DAE803D028AF3F FEDFF8A3FF0042468FFF0083AFFED75C9FC40F1078C63D2209FC4BA658F87962 90B41756BE296B690B6390008F1271FC255BE9401ED945782780BC6FF18B50BD 8A31E1E8F59D20BAFF00A6DF8368DB33824485537F1DC464D779ADFC4DBCD37C 49AD695A6784750D5D7448E392EEE2DEE22508AF1F983E56209E33D33D2803BF A2B33C37E20B1F15786EC75CD259CDA5EC4248FCC5C30EC411EA0820FD2B4E80 0A28A28011955D0ABA865618208C822BCD6EFF0067DF87577ACB6A0FA2B47B9F 7B5B4370E9093ECA0F03D8607B57A5D140115A5A5BD859C369650476F6F0208E 286250AA8A0600007000A968A2800A28A2800A28A2800A28A2800A28A2800A28 A2800AADA8E9B65ABE9D3D86A96B15DDA5C2EC96199432B8F706ACD1401E17E3 4F829E10F05E88DE2CF0FE972C93691750DF4B6B3CAD34724092032A6D6CF1B3 279CFDDAF718268EE6DE39E0712452A87475E8CA4641A65DDAC37D653DA5D209 209E368A443D1958608FC8D71DF09EEA65F06B6857CE5EF7C3B752E952B37565 88FEE9BE86229401DBD1451400514514005145140051451400570DF153C0FA27 8ABC19AB5CDF6976F71A9DB69F3B59DC94FDE46E10B280C39C6E038E95DCD365 8D2685E2906E4752AC3D41EB40187E064B05F0168926936905A5ACF630CE9140 81146F40C781DF26B7AB8AF841239F857A45B4AD996C44B64F9EC6195E3FE482 BB5A0028A28A002A19AD2DAE25865B8B78A59206DD13BA06319F5527A1FA54D4 50015E5727C3AB8F10FC50F195E6A77DAE699A75DA59243F60BB304778A202B2 06C0F9B078FC4D7AA51401C3695E32F0AE81AADAF8374AB4BBB7B5B59D74D8AE 52DDBEC8971B77083CD279908FAF27939AEE6BC64F8675F8FC54DA28D1EE1A07 F198F110D4815FB38B6C64A939CEF046DDB8F7E95ECD40051451400514514005 1451400514514005145140051451400514514005145140051451400570683FE1 1DF8DF22FDDB5F15E9E1C7BDDDAF07F38987FDF15DE570FF00162DE583C29078 8ACD0BDDF86EF22D4D02F578D0E265FA1899FF002A00EE28A8EDEE22BBB58AE2 DDC490CC8248DD7A3291907F2A92800A28A2800A28A2800A28A2800A28A28038 7F86FF00E8B7BE31D2CF0D69E21B89557D12654987EAED5DC570FA1FFA0FC69F 15DA371FDA161637E9FF0001F32163FF008E27E55DC500145145001451450014 514500145145001451595ACEAD2595E6976368236BAD46E7CB5F3012123552F2 36063F85768FF6997A8E2803568AE32CBC5FA8DD4F63A83416A745D4352974F8 5630C674DA5D16566CED219A33F2803019793C8AD5D7355D4935AB1D1742168B 797504D72F35DAB3A451C6517EEA9049669147518018F3D28037A8AE7ECBC549 2F80A5F11DEDB343F65B69A5B9814E76BC3B848AA7B8DC8D83E98AA9A6EB3E22 92F574FD522D3A3BBBED364BDB27855CC70BA14568E4CB65F0658FE65DB9F9B8 1C5007574567787F588BC41A059EA90218D6E63DCD193931B8386427B956047E 15A340051451400514514005158B7FE29B2D3FFB43CC8E797EC2F0C0C22504C9 3CA46C8501232FF3C67B0C48BCF5C4FA36B90EB3F6B8C5B4F6775653793716B7 3B3CC8C950CA7E466520AB020827F30450069D15CF2F8CEC9B555B5FB25E0B67 BD6B05D4195040D70B9CC63E6DFF007815CEDDBB863357359D7E2D1E6B3B65B4 B9BFBDBD66105A5AECDEE14659B2ECAA0018C9247503A9A00D5A2B16CFC53617 B1E95246B2A47AA349144D22E364C80968586787F924F6CC6C33D33B54005457 36D15E5A4D6D72824866468E443D1948C11F91A968A00E23E14DCCB1F84A5F0F DE485EF3C39772697216EAC919CC4DF431327EB5DBD7078FF8477E3867EEDA78 AF4FFF00C9BB5FF185BFF21FE5DE500145158575E2CB5B76BA586D2EEF1E0BB4 B144B7552679CAEE28B96006D5392CC540C119C8A00DDA2B3745D6E1D6E1B968 EDE7B59AD2E1ADAE2DEE02EF8A4015B076965395652082460D50B1F19D95FEA3 0DBC769791DBDD4F2DB5ADFC8A9E45C491EEDCAA4316FE07C12A01D8704F1900 E868AC6D63C4916957F0D8C3617BA95E4B0BDC7D9EC950B2449805CEF6518CB0 0002493D01C1A92CFC45637F73611DBB168B52B4FB5D9CDC6D99463701DC101D 4E0F627D0E003568A28A00E1F54FF40F8E5E1FB9EDAA68F79647FDE8DE2957F4 2FFAD7715C3FC41FF43F107823565EB06BAB6AC7D16E21923FFD08AD77140051 451400514514005145140051451400573DE20B097FE124F0F6B30C6F2AD95C49 6F32A2EE2B1CE9B77E3D9D63CFA2963DABA1AA3A8DFB5ACF656D0AAB4F793F96 A1BA0500B3B1FF0080A903DC8A362A107376473765E0ED42DEEACAC9EEED468B A7EA32EA36EB123099CB976589B9DA155A42723390AA303926CDD699E20BABCB 1D6AD7EC36FA9DA7DAED5A09C1F2A6B7925050EE52486C451377EAC38CF162DF C457334F6D70D6F0FF0066DDDE3DA44C8E4C8A54B00EDC6305908C76C8F7ABBE 21D5A6D1745B8BDB6B37BB9238D9C22901542A962CC4F4000FA9E00A9E656B9B BC2D555234EDABF3F91936DE1AB9B6F0F43E1795C5CE9F7565769A85E11B5CCB 2B024A8C9C6E324A70738C0E7D534DD2B56D3EF86B3E23BA82E7FB374E7B5863 B185F322928CF2153FC4DE52611738E7939E3A4BEBB8F4FD3AE6F26C98EDE269 5F1D70A093FCAB26CF54D565B8169776D6B0DC5CD9B5CDB146665520A828FC0C E0BA723AE4F4A6DA444284E71725B7F5F9751DE0DD36EF4AF09595B6A58178DB E7B8518C2492BB48CBC75C17233ED5B75534BD423D574BB7BD854AACC818A1EA 87BA9F70723F0AB74F733945C24E32DD0514514121451450079BB69379359EB9 04313DD6A3A7789E3D505BA32AB5C45BA391402C40FF005795049037478CF15B 3A5DDDC58DFEABAF6A5A7DCDAC3AADEDA5B5ADBB2A79C14848848E37600DEEC4 8EA15738ED5A575AD416D717D3C1671CB3C52C362AE182B4D2B1C88CB63855F3 01CF38CBF1C73774BD4A4BD96EEDAEEDD6DEEAD240922248645219432B2B1519 041F4EA0D2BAD8DDE1EAC61CED69FF000DFE68E3A1D2757D96DE1D1A5CC915B6 BCDA836A0EC8616B7FB4BDCAE0EEDDBC92136EDE0E4F4C1AD0BFBB9EEB5CD33C 47A7E9B77776FA73DF69F3C3104F34E5D17CC405B0CBBA0C75CE1B38E081AB36 BD756B790FDAB4D1159CF79F638E4337EF5989203797B71B49079DD9C738ABF7 F777904B043A7D90B99252C59A494C71C6A075660AC72723031CF3D3145D03C3 D44D27D7CD74F3B9C64D617D0E81E1DB1BDB611EA779E2137C615901F214DC4B 72E0919076A12870719239E457A05615A6B705D8D2EFE6B348CDCBCD6825C863 1386E54363946311E78C909C7A6ED09A7B135294E93B4D5BFE03B0514514CC8E 27E2B5B4B1F8463D7EC90BDDF872EE2D56355EAC919C4ABF43133D7636B730DE D9C3756AE248278D648DC746561907F234B3C115D5B4B6F708248A5428E8DD19 48C107F0AE33E14CF2C1E15B8F0EDE397BAF0DDE4BA6316EAF1A1CC2DF431327 E46803B7AF3FB6BDD6F48F076A16BA069D25EEAD1EB7750CD845CC4B2CEF3098 AB3287FDD48840DC32580CE335E81588352669AF27D2F4B4B894DCADA09436CF 30A03B99DB692114EE5EE7208C7349BB1A4294AA7C3FE5F999DE1C92DFC3FA2D B42DA6EAD14F7DA818E57BE31B4F3CCE0B34CFB5C8DB818E3A05C0000AC8D0B4 7D5ADD3C3BA04BA65C4516857F2CF35FC8C8629620932C7B30D92CDE6292081B 70D9ED9ECF48D4DF524BA59A05866B4B86B795524F3177001B21B03230C3B0E7 22AAC3AEDCFF006BDB59DEE9EB6CB76F2AC1FBFDD26132773A6DF941038209EA 01EB47322FEAF52F28DB55BEABB5FE7A76304DEDD37886D3C5DA6E8D7F7D6B7D A59B4F2233189237597746482F8DADB9BE60481853D0E69963A65C699FF0AFF4 5B840F7B60924D72D19CAA225ABC4FF51E64D18CD755A85F5F4170B169F60971 FBA691E59E730C6B8C6177056CB1FA0181D6AB586AD6D7975A75D8B4588EA966 1A29881BF8F9FCA638F462473D9BF12EAF60587A8E1CE969EABCFF00C99B5451 45330388F8BE0C5F0DAEF50407CCD2EE6D6FD08EDE54E8E4FF00DF21ABB70430 041041E411589E35D3BFB5FC07AF69DB771BAD3A78947FB463603F5C52782351 FED7F00681A86EDC6E74E82463FED18D723F3CD006E514514005145140051451 40051451400563EAF6EEBAD68FA8AAB3A5BCAF0C814676ACABB437E0C107D093 DAB62B3B55D5974EB8D3AD92312DCEA174208A32DB780A5E463ECA88C7DCED1C 67349AB9A52A8E9CB9979AFBD59FE6665AF87EFA19ADAD1E4B71A6D9DEBDDC4C 85BCD7C96658C8C6000CE79C9C80381D6B42F2DEEF57F0CEA1693225BDC5CC57 102649DA01DCA8C7BF2BB49FAD645A78D25B9BDB490E9A8BA3DEDFCBA7DBDE8B 92CED2217019A3D9808CD1B007713F749001E34B59D6EEACB53B2D2F4AB18EF6 FEEE39660B35C18638E28F6866660AC7EF3A00029CE4F4C52E546D3C54E72537 BA77F9EFF8BDCB3AA5BCB7E8FA698FFD12EED668E6941E5090AA00FA866FCAA8 DA5A6A16B72BA96B72DB85B1B278156DB736FC95677208183FBB5C28CF7E4D49 65E27B4B9F073788A78E4B7B7860926B88D865A2316E122FB9528C3DF154F4EF 12EAB773FD92F7458ACEF2E74F6BEB18C5D991640A543248762EC60648F206E1 F3704E28B752615E5187225A7E3E7F7AD0D3F0E5A4F65E1FB68AEC6D9DB74B22 FF00719DCB95FC0B63F0AD3AA5A3EAB6FAE68B69A9D9EE10DD44245571865CF5 561D8839047A835769A565632A937526E6F76EE14514532028A28A00E4BFB2A6 95353B18B69BCB7D51352B7133155914B2B8E403C64489DF0466B42CE3D42CE5 BBD46E6D55A7BEB98105B4526EF263F95092DB79232CC7B76CD57D47C60967FD A3F67B51726D2EEDF4F8479A17CFBA976FEEF383B55449192DCFF1F1F2F37742 D6E6D4EE350B3D42D12CEFF4F99639A28A632A32B20747572AB9041C74041523 D099E53B658C94959AD1FF00C0BFDED5CA5058EB0FE256BFD4ACADAE152564B5 717640B688F1954D9CB91D493EC303ABB581AE6AB691C3636CB0C067952E55AE 0C524912B155DADB0ED0DD4F19C743CE6A04F19CCD7D1C874C51A3CBA9369897 BF68CC8650C63DDE504C6C32A94077E7A1C60D6BEAD7FA95ACF6B6FA4696B7D3 4E58B3CD3986185547259C2B1C92400029CF3C8C51CBD03EB6F9D4F915D6DBDB EEBFCFD7533AEED9CD9E87A5C56705A3ADD472791136F586284EE241C0E3845E 9D5C57495CCE9BE314BEB2D1AEE6B4F220D4EE26B36612EF114E8CC00CE06E46 31380DC73B38F9B8E9A9A5630A955D4495B6BFDED8514514CC42B8493FE29DF8 DD1BFDDB4F1558146FFAFBB6E47E7131FF00BF75DDD715F15AD661E0D1AE58A1 7BDF0EDD45AAC2ABD59623FBD5FA188C82803B5AE5162D5A3D12F34CD18A25E4 5A84BE63C92ED610C9234A1D4ED3C90E1412080437A62BA5B4BA86FACA0BBB57 12413C6B2C6E3A32B0C83F91AE76EFC62D1F9E2C6C45D336A434BB206628279C 02642CDB4ED44DAE09C31CC6DC74A4D5CE8A35BD9744F54F5EEBFE1D9774C8EE 348D32D6D62D2638435C6C648AE0C98520B34ACC5464E739CF5F5C9C557FECBD 4AE75EB2BABAB6B28A4B5959A4BF81887B88F6B058F6E320720905880578CF6B DA0EB12EAD0DDA5E5A0B3BDB1B936D730AC9E6206DAAE0AB955DCA51D1B381D7 18E2B274CF19CDA85DD84AFA62C5A4EA7752DAD95E0B9DCEEC81C8668F60DAAC 23720863FC39033C2E52FEB525294925777BEFD7E7F9DC7EAB0EB7AE5B59AFD8 224B1910B5DDA3DD344F21CFCA85B6676E3923009CE0E3041B770249F59D0AD8 411C4F6DBEEA648DB72C2BE5346141C0E09938E06761F4A9358D5355B4BB4B7D 23488EF3F70F34B3DD5D1B785002005DC11F2C724E0800004E6ABE95E2B8B533 A24A6DDA0B7D6ECBED16ACE7E612050E636E319D872083CEC7F6C9CA3FAD68A2 A29257B6FD6EBBEBF9E88E868A28AA38C0804104641ED5C47C20262F86F6BA73 9FDE697757560E3D3CA9DD40FF00BE42D76F5C3FC3FF00F43F11F8E3493D60D7 0DD01FECDC431C9FFA16EA00EE28A28A0028A28A0028A28A0028A28A002B99F1 242D6FE29F0D6B0E5BECF6D3CB6B363A279E9B518FFC0D517FEDA574D450070B A7F85B58B6974FD21A2B68B47D375597508EE9272D24D1B34AE916C2BC10D20C 9CF45E3A902EDC47AD5D6A9A7F88AC34B87ED36E979633595C5C3465E2699764 8AC578CF92AD82BF75CF52067ADA28038EB7D06F62F0A27846F17CEFED2B1BD3 7B7F1676432CAD921460641333E3241C274EB87E9D6DAB5BEA71EB7E285B2B0B 6D274B96DBF73319049B8C6F24C4951B5710AE0727939C639EBA8A00E7FC0D63 73A7F832C62BF87ECF712992E64836E3C932C8D2ECC7AAEFC7E15D0514500145 145001451450079F0D06E678F5CD2EDF636A367AEC7AD598B872A92A33ACA324 038195963CE0E0AE715AFA743AC69B71A86B37D608F75AADEDAC62CA098B8B68 46C8CB1709C919773DB0319EF5D551401C3C5E19D69648347296B1E916FACB6A 62ED66264743334EB179657EF091802DBB1B467A9C54BE225F146BFA7436FA5D 8A5B5AB5DCF15F23DE3412CD023154D8FE592A24C649032070A79DD5D9D1401C 5EA3632369BE16D0A0D36D74F952FE19BEC96EFE6A5B416CDBCB2B6D5E388D33 8EB2815DA5145001451450014C9A18EE209219D03C72294746190C08C1069F50 DDDB8BCB29ED9A49621346D19921728E9918CAB0E411D8F63401C37C35D561D1 FC332F86F58BB8E1B8D07526D1E333B85332939B6C67A968D9001DF0696D748B D7D38D9D92C6DA9681AFCF7C90CF26D1711CAD2BAFCC01C663B8600E08DE8476 38F24D4E4D6BC3FF0018F45D03C42ED3CF75A869C4DF11C5F8827C4339FF006F CB76471EB183DC57D33401CC69516AFA499AEAF6CA39EEF5AD544B34304A4ADA 45E4AC6096DBF310B0AE73B412C40278CE668DE16D62C9F45D2678AD63D2B43B C96E62B949CB4970A5655893615F94812FCC727EEF1D78EEA8A00E135EB7F13F 8A6CB4E4FEC9823D2E6899EFF4F92FDA09266DDF2C6CDE5121303246149CE0E0 020E8DE2CD75E25F0AD9ADA436F258F997D73142DB96DD3C8785501C0E0B4BC7 032236E38AEAA8A0028A28A002B87D33FD03E396BD6DFC3AA68D69783FDE8A49 623FA32FE95DC570FAF7FA0FC68F095DAF1FDA1637D60FEFB447328FFC86DF95 00771451450014514500145145001451450051D575BD2B41B55B9D7353B3D360 77F2D65BCB858559B04ED058819C0271EC6B27FE163F81FF00E872F0FF00FE0D 20FF00E2AB7AEACAD6FA1115F5B4373183B824D18719F5C1FAD53FF846F43FFA 0369FF00F80A9FE1401C8F8CFE2FF85F40F06EA5A9E8DE20D1B53D42087FD1AD 20BF8A46924242AFCAAD92013938EC0D7C8977F133C6D79AD1D566F146A82EF7 6E0D1DD322AFB0452142FF00B2063DABEDAD73C09E1CD7F41BCD2AEB49B48E2B B88C6648604474CF465207041C11F4AF9AEEBF658F1826B26DECF51D2E6B12DF 2DDC923A1DBEE9B4907D8123DE803D83E177C66D1BC45E04B6B9F176BDA4E9BA BC2ED05C25D5DC50194AE312056238208E83190D8AEC7FE163F81FFE872F0FFF 00E0D20FFE2AA9F82BE19E81E0EF09DA68CB656D7F2420B4D753DBA979A4272C DCE703B019E001D7AD6F7FC237A1FF00D01B4FFF00C054FF000A00CDFF00858F E07FFA1CBC3FFF0083483FF8AA3FE163F81FFE872F0FFF00E0D20FFE2AB4BFE1 1BD0FF00E80DA7FF00E02A7F851FF08DE87FF406D3FF00F0153FC280337FE163 F81FFE872F0FFF00E0D20FFE2A8FF858FE07FF00A1CBC3FF00F83483FF008AAD 2FF846F43FFA0369FF00F80A9FE147FC237A1FFD01B4FF00FC054FF0A00CDFF8 58FE07FF00A1CBC3FF00F83483FF008AA3FE163F81FF00E872F0FF00FE0D20FF 00E2AB4BFE11BD0FFE80DA7FFE02A7F851FF0008DE87FF00406D3FFF000153FC 280337FE163F81FF00E872F0FF00FE0D20FF00E2AB97F889F19BC3FE1AF04DE5 FF0086B5CD1F56D53E58EDADE0BD8E52198E37B2AB64AA8C9FC8719AEEBFE11B D0FF00E80DA7FF00E02A7F8560F8DFC11E12D5FC15A9DAEB36769A7D9F90D249 790C288F6FB7E6DE081DB19C77E9DE803E59D0FF00680F1F697AFC57F7FAC3EA 76DBC19ECE7440922F703006C3E8477C751C57D5D0FC4BF03CD6F1CA3C5FA126 F50DB5F528432E467046EE0D7CE3F08BE055AF8E6DE2F10EA3AA9FEC68AEDE3F B22C5B659C211C31CE1010467193E9EB5F518F0D684AA02E8BA7800600FB2A7F 8500677FC2C7F03FFD0E5E1FFF00C1A41FFC551FF0B1FC0FFF00439787FF00F0 6907FF00155A5FF08DE87FF406D3FF00F0153FC28FF846F43FFA0369FF00F80A 9FE14019BFF0B1FC0FFF00439787FF00F06907FF001547FC2C7F03FF00D0E5E1 FF00FC1A41FF00C55697FC237A1FFD01B4FF00FC054FF0A3FE11BD0FFE80DA7F FE02A7F850066FFC2C7F03FF00D0E5E1FF00FC1A41FF00C551FF000B1FC0FF00 F439787FFF0006907FF155A5FF0008DE87FF00406D3FFF000153FC28FF00846F 43FF00A0369FFF0080A9FE1401F3B7ED15F12F4CBCBFD02CBC2977617D756120 D41355B39D666B7704854565240395DC41F44E2A0F831F1E3586F15268DE3CD6 219B4DBA57D97D7AE917D99C2961B9F8054E08E7B9183D8FA8FC51F81FA478FE CEDE5D31A0D1B52B5055258A01E5CAA79DAEA31DFA11D327AD647C2EFD9EACBC 15AB36AFE22BC8358BD085218443FB98B3C16F9BEF363207000C9EBD803D13FE 163F81FF00E872F0FF00FE0D20FF00E2A8FF00858FE07FFA1CBC3FFF0083483F F8AAD2FF00846F43FF00A0369FFF0080A9FE147FC237A1FF00D01B4FFF00C054 FF000A00CDFF00858FE07FFA1CBC3FFF0083483FF8AA3FE163F81FFE872F0FFF 00E0D20FFE2AB4BFE11BD0FF00E80DA7FF00E02A7F851FF08DE87FF406D3FF00 F0153FC280337FE163F81FFE872F0FFF00E0D20FFE2A8FF858FE07FF00A1CBC3 FF00F83483FF008AAD2FF846F43FFA0369FF00F80A9FE147FC237A1FFD01B4FF 00FC054FF0A00CDFF858FE07FF00A1CBC3FF00F83483FF008AAE07E26FC49F0B C3A8F84AF746D4E0D6EEAC75759E48B49952E5D6028D13E76B60126540012327 8AF50FF846F43FFA0369FF00F80A9FE15C8FC54D16CACBE176B577A5E9F6D6F7 166915E2B410AA1FDCCA92F503FD8A00D6B5F89FE05BBB386E53C5FA246B346B 2049B508A37504670CA5B2A7D41E454DFF000B1FC0FF00F439787FFF0006907F F1557E2D0741B885268F48D3D96450EADF654E41E73D29FF00F08DE87FF406D3 FF00F0153FC280337FE163F81FFE872F0FFF00E0D20FFE2AB17C49F15F45D36D A19FC3BABF86B5921CF9F037882DEDE40B8E0A162549CF6247D6BACFF846F43F FA0369FF00F80A9FE158BE24F00DA6B96D0DB69F345A2461C9B87B2B180CB2AE 3EE87743B39EE06680313C3FF1DFC09AE5CFD926D5574ABCCED315EB28427DA5 52D191FF0002AE8358F893E0EF0FEAD2E99AD7882CECAF61DBE6432B10CBB806 1DBD08355342F84DE0CD0665B887468EF6F0107ED9A893732EE1DC17C853FEE8 15C4DCE97E25D63E2BFC43B2F0E7F61882786C61B97D52291D9435B100C6178E 99CE7DA803D92DEE20BCB68EE6D268E782550F1CB13065752320823820FAD495 E5BE0ED4B50F08F89F40F873169D28D2EDECAE07F695E0C4977247B599A350DF 2C799300B75E83A64FA950014514500145145001451450014514500145145001 451450015E5FF1BD755B8F0B4C89188F43B5B692EEF25DE337332902DEDB6F5D AD21566E3042E33CD7A8570BF1287F69DD7857C36A73FDA9ACC524E9D9A0B706 77CFE2883F1A00A3F05B42B8F0B685AD681731BA9B0D4C2A332901C1B680920F 7F9B774AF48A28A0028A28A0028A28A0028A28A0028A28A0028A28A0028A28A0 028A28A002B33C4BA77F6C785356D376EEFB6594D063D77A15FEB5A74500735F 0E751FED6F865E1CBD2DB9A4D360DE7FDA08037EA0D74B5C3FC24FF47F054FA5 1FBDA46A97B627E8B70E57FF001D65AEE2800A28A2800A8D2DE08A79678E18D2 59B1E648AA033E06064F7C0A928A00E7F50F0CB5F78F746F118BA08BA6DADCC0 60F2F264F37673BB3C6367A77AE828A2800A28A2800A28A2800A28A2800A28A2 800A28A2800A28A2800AE146359F8ECC7EFC3E1DD180FF00727BA933FF00A2E1 FF00C7ABBAAE17E1963527F13F894FCDFDAFACCC2193FBD0418823FF00D16C7F 1A00EEA8A28A0028A28A0028A28A0028A28A0028A28A0028A28A0028A28A0028 A28A0028A28A00E1FC0FFE85E37F1DE943EEA6A70DF28F69EDD09FFC7A36FD6B B8AE1ED7FD07E3CEA112F09AA787E19CFBBC13BA1FD255AEE2800A28A2800A28 A2800A28A2800A28A8E7B886DA3F32E654850B2A6E91828DCC42A8C9EE49007A 9205004945555D4EC1F527D3D2F6DDAF635DCF6C2553228E392B9C81C8FCC52D F6A363A5C027D4EF2DECE12DB449712AC6A5BD3248E783F950059A29010CA0A9 041E411DEA941AE693756D3DC5AEA9673416C489E58EE1196223A8620E07E340 17A8A28A0028A28A0028A28A00C5F18EB63C37E0AD63592406B2B39664CF770A 768FC5B03F1A87C07A29F0EFC3FD0F4A752B2DB59462607AF98572E7FEFA2D58 BF1489BFD3B42F0E28DDFDB9ACDBC1320EA608DBCE94FF00DF3163F1AEEA800A 28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A 28A280387F13FF00A1FC5AF04DE8F956E56FAC243EBBA259547E709FCEBB8AE1 FE287FA3D9787354E8BA77886CA576FEEA3B185BF496BB8A0028A28A0028A28A 0028A28A002B98F114AEFE34F0AD8C807D9649AE276CF4692388EC5F7FBECDF5 407B574F59FABDA59DC476935EDC7D98DA5DC734336F09B64CEC0B93C7CE1DA3 C770E40E71401E77A53C02CBC3D09788EBA3C4F75F681111E6EEDF3994B77DBE 5E3AF629DB15D06A777A7C9F1234CB8D46E6CDF4D3A55EA42F33A94132CB1894 64F1B820607BE03F6CD74914BA37F6FCF1C32587F6B98C79CA8C9F68D83046E1 F7B1C8EBC722A0BDB6F0FE97A508B561630589B86940BE75D9E73BB48482E7EF 162C7F3C5007236D3CDFF0A124B7B595D6F24D0A792D6266FDF18421D840EBC2 B2018E84AD5CD3468D7FE3C4874216F3E9B2787C4772B6F830B2191440AC07FB 1E7601EC4D7626CEDA5BF8B50D81AE2385E28E40C78472ACC31D3928BCFB5654 72787EE343D4A3D1B50B0B4B721D6E6E74F9635F21D872E48E030EB934011780 2E66BBF87FA34B71319DFECCA82620832AAFCAAE73DC800FE35D154367690585 8C1676712C36F6F1AC5146BD11146001F40054D4005145140051451401C2DDE7 57F8E9A7C1D60D034792E891DA6B97F2D41F7D91B9FC7DEBBAAE1BE1E03A96BF E31F1131C8BDD58D9C27B18AD544408F6DFE65773401C16BDAC6A2E9E24BAB0B C920FB25DDA68F6FB09222695A132CDB4F05B17000241C797EE73B1E1E4974DF 146AFA28BDB9BBB482DAD6EA1FB54ED3491B4866465DEC4923F72180278DC7B6 053E4F0BC771A96B915E2ACFA56B491C92C5BCAB24EAA10B0C74CAA44410410C 84F7E05F08A5B69D7B1596A57AB7D7AF119B519A62D31546185C8C60019000C0 F98939C9C807353EA1A848353F117F685DC52D96BF169F0DA79A560F23CF8E16 568FA3160EEDB8F2095C10062BA2F155C5C49ACF87B478A7B8B6B7D4AEE41732 DBB947291C2F2040E395DCCAB92083804679A9E6F0769B36B4DA897BA557B84B B92D1262209274C6C9593FBC36A9EB8254120919A27F0BADEC738BED42EDA5FB 79BDB49A294ABD99D8102A139E31BB20820EF618C50073B0EA9A859E822E8DF4 D72747D7FEC059A42C6E2DDE758B127386651283B8F398C7A9CFA0573773E148 C69BA7693A7FC9611DFADEDE3CCE5E49D964F3B927EF334A14927B023D2BA4A0 028A28A0028A28A0028A28A002B0754BB9A7F1868DA4433345198A7BFB8D8C54 C8B114454C8EC5A60C477D983C120EF5646A7A54F3F88349D5AC9D4496665827 46381241281B80F70E91B0FF00748EF401CE5B26A7A1F8F34BB4BABED4A686F8 4EB717776FBADEEE5DBBD238A30CDE4B280E790808423E63C8BBAC2DC6B5E3B8 F426BEBDB1B2834C3765ACA630B492B49B14971CE14293B7A12C320E00AB7A6F 8274BD2F51B6BA825BC74B2321B2B59672D0DA970436C5FA120649C0240C0A63 78322B8B0B15BDD4F50FB7DAC4F0B5FDBCE639658DCE59189C92BC0C77180410 79A00CCB8F136A67E0B5BEBA9201A9DCD8C199D1010B24A550C817A7058B63A7 1E94F8ECAFADF57D6FC3961AADF38FECC82F2D26B9B96965867679573B8F2549 890ED276FDE18C122B65FC2D692A3D94858E8C74D5D3D74DDCDE58504FCDD783 B70011CF1D7A620FF84624D3B48D4D749BCB9B9D56FE0107DB6FE73232800AA7 41D137B3600049272727340183E3AB997C4BF002FB548E311CD369316A6A839D 8C816703F02B5DD595D25F69F6F770FF00ABB889655FA30047F3AA326836CBE0 F7F0FDB822D4581B28C31C909E5EC19FC2B23E165FB6A3F0A7C373B925D74F8A 17CF5DD18F2DB3EF953401D65145140051451400514514005731E2295DFC69E1 5B1900FB2C935C4ED9E8D24711D8BEFF007D9BEA80F6AE9EA9EA3A643A91B569 59E392D2E52E619233865619047D1959D0FB31EFCD0079BE94F00B2F0F425E23 AE8F13DD7DA044479BBB7CE652DDF6F978EBD8A76C5741A9DDE9F27C48D32E35 1B9B37D34E957A90BCCEA504CB2C625193C6E08181EF80FDB35D6A595A477B25 E25AC2B75228479C4603B28E80B7523DAA01A2E9BF62FB1BD9432DBF9CF71E5C CBE60F319CBB37CD9E77331F6CF1401C45B4F37FC28492DED6575BC93429E4B5 899BF7C610876103AF0AC8063A12B5734D1A35FF008F121D085BCFA6C9E1F11D CADBE0C2C8645102B01FEC79D807B135D93595BBEA315F3479B98A27851F2784 72A5863A72517F2AAEFA3DAAE997767A7A2E9C2E95C349688B1B2B30C171818D DDF2680333C017335DFC3FD1A5B898CEFF0066541310419557E55739EE4007F1 AE8AA1B3B482C2C60B3B38961B7B78D628A35E888A3000FA002A6A0028A28A00 2B3BC45AB47A0786753D5E6C6CB1B596E0E7BEC52D8FD2B46B86F8B47ED9E15B 2F0F83F3788354B5D3CE3A88CC81E43F4D91B7E7401A1F0D3487D0FE1A685653 E4DC7D91669C9EA6593F78F9FF008139AEA680028000000E0014500709AE6BDA 881E23BAB0BA680595CDA6916D8E42493343E64DB4F05809D00CE40D87B31CEB E81F6AB0F13EADA34D7F717D6F05B5ADD42F72E1E44F34CA8C85B0323308619F EF1ED8A26F0B25D5FEBB6F763CCD2F5A58E6708E55E29D5550B03DB212260474 287DA9CBE146B5B3BE365AADE36A57CD0F9BA8DC3A997646C30A02A85000DDC0 03258E4F24D0073B3EADA9C8352F100D46E62FB0EBF1E9D15965561683CF8E17 0C3192CDBDD836720EDC70315BFE2ABBB96D5F40D1ADAEA7B44D4EEA413CF6E4 07D91C2F26D0C41DB960BC8E700F4A965F06D84DAC497A6E6F1609AE92F26B05 900B79674C6D908DBBB20AA9C060A4A824134B73E186D4164379A9DE2CE97E6F 6C6E20651259FC9B36A920A9520BE4329187230719A00C18757D4AD3445BB9AF 5EE5B49D7BFB3E4666E6E6DDE65886F0300BA8914E71D63FF68E7BDAE62E7C28 A9A569FA358963663505BDBE9E76DD24C524F3B24F766942E7B05C818E0574F4 00514514005145140051451400560EAB7B3CBE2ED1F47B795A2478E6BEB928C4 16488A2AA67D0BCAA4FB2107835BD58FA9E973CBE22D2757B32A5ED04B6F3A13 8DF04BB49C7B878E36FA06EE680396F0E6A3AA4ABE14D6AE7549E7FF008489E4 5B9B4908F2A30D04932796A07CBB7CA0BD79049393CD6AEAEF79ABF8E13418B5 1BBD3AD61D30DE3496842BC92349B172C41E142B1C742586738AB7A6F82F4FD2 F51B7B98AE2F258ACDA56B2B4964061B432677140003D0B01B89C0240C0A88F8 3DEE6D2C5EEB59D421D4EDA0781EFAD64559258DCE5918B2904640C36030C641 04D0067CFE29D47FE14D5B78823651A95C58C1FBD540CAB2CA510C817A6016DD 8E9C77A7476FA9C3AB6B7E1EB4D5EEE775D36DEF6CEE2E640D24331795704803 284C484A9E3961D0E2B564F0A5ACB6EFA63332E8674D5B04B0573B54027E607A 8217001CE7F2E623E1CB8D374BD4E4D36FAE6FF58BD816DD6F6FE452C8002A9C 2AAAED4DECD8032C49C924D006AE83A9FF006D786F4DD57CBF2FEDD6915CECFE EEF40D8FD6B97F855FE8FE1FD5F4AEDA56BB7D6AA3D14CC655FF00C76415D669 5A743A468D65A6DAEEF22CEDD2DE3DC7276A28519FC05727E10FF43F897E3BD3 8708F7169A822FFD7580231FFBEA13401DBD14514005145140051451400563EA F70CDAD68FA72B32A5C4AF34841C6E5897705FFBE8A1F7008EF5B154751D3DAE E7B2B9819527B39C48A5BA329055D4FD558FE20527B1BD094633BCBB3FBECEDF 8D8E66CA699A1D33586B89D6EEEF55960963799CA18CBC8BE584CED1B42A9071 9CAFB9AD5D4D0EA3E2BB5D32E1E74B41652DC110CCF1EF7DE8A325483C027BFF 0017B0ABD1681A743A91BE8E1713798D28065728AEC0867099DA18E4E4819E4F A9CC72787AD2E6DE24BC79E592292574992778DD448C599432B676F20633D00F 4151CAED63BE58AA32A9CEAEB7E9AABDED6D7ECE8BFE184F0CDCCF79E17B29A7 9BCE94C5B4CA47DFC12031FAE3355B46B59E58F5CB1D46F66BB3F6BF2CCC7E42 035BC4C7681F7402C718E9EE79AD3874E8EDEE6D9ED98C505B5BB4096E990982 570719C7017038EE6965B46860BD7D3424775724C9BDC92A64D81031EBC00ABC 0F4A76D8E675A3CD3E4D39B6D36F7AFF0097620F0F5ECDA8787ACAE6EB067788 0948E8CC3827F1209AD2AADA75845A5E996D636F9F2ADE358D49EA703A9F73D6 ACD52DB539EB38CAA49C36BBB7A0514514CC82B85D5C8D5FE36E81618CC7A269 B71A9C9DC7992910460FBE3CD35DD570BE062755F1BF8D75E23E437E9A5C19EC 96C986C7B192493F2A00EEA8A28A00E4B55BDB874D72E629DE2F26E6DF4E88AB 11E5AB988C8E3D18F9BD7FD85AD3D262FB1788351D3E19A57B648209D12595A4 31B39915802C49C1F2D4E3DCFAD4EDA34725EEA1E7AACD67A8C6BE742E7F8C0D B91F550BEE0A8F5E0FEC1B68ACE782D649A27B874696E0CCEF2B6D23F8C9CF41 81CE067A75073B3BDCF4E55E93A5ECF6BDBA7F87F2B3FBFCCE7E496778EFF566 9E74BAB7D612DE35F39B608BCD8E3D9B33B4860C4F4CE5B3D856FF008805A2D8 C736A37935BDB43207748A464331C1013E5F98F2410075200E69EFA069D26A5F 6E7858CC645948F35F633A8015CA67696000C1C6781E82A29FC3B6978CCD7EF7 1311726E622B71247E4B150BF295604703D7A938C6714598DE228CE516DB56EC 95F64ACB5E9AD9F9DED732225D434EF0E5ADEDC99A3962D415A286690BBA5BCB 30411B924E4857CF24E081E95D6D655C688B24369691CB29B58AE56E25F3A779 5DF61DCAB9724E37853D7F871DEB56AA2AC73E26AC6ADA4B7BB7F27B2FCDFCC2 8A28AA38C28A28A0028A28A002B26FA6926F1269BA7A3948FCB96EE5DA48DFB0 A2AAF1DB3267FE022B5AA8DE58C92EA7637D6EC0496E5D1D58E03C4E06E1D3AE 55187FBB8EF9A4CDA838C6779767F7D9DBF131225BAD37C57A7C4D3DEC96F742 5125D4F3EF8EE242BBD55532447801882028C291CE6AD5FA49A978AD74D92E2E 60B68AC4CE3ECF33445DD9F6E4B2919DA074E9F373DAAD59F86F4EB1BB8E7816 5FDC163044D33347016FBDB149C0CE48F60481814C6F0E5BCF696C979717525C 411B466E52774775620B2920E4A9C0E092460739E6A2CEC77BC4517352BEA95A F6D6FAEB6BF4565BFA68909A5CB71AC782ED2496EDA0B8BAB44DD73100183151 9619E3359D609752DE6B7A517BBB52228DECD2E2E0CD22FDE1E6872C782CA3E5 24FDD39EB8AD87D0EDA50D04993606D16D4598242000F5EBC1C600230463AF4C 44DA10B6B2BD1A74B21BDBB88446E6EA6691940C81C9CF0BB89006327AF5CD16 7A131AD4973A8BB733BAD345AA7F86DB7A6ECB7A45EB6A5A258DF3A046B9B78E 62A3A02CA0E3F5AE4A49134DF8EC64959628751F0E12CCC700B5BCF9249FF766 FC85767696B158D8C1696E088A08D62407B2A8C0FD057CD5F169B54F09F8C4E9 08D2CD6DAB7DB46992312C42DEC7B26873E8B32AB01E9255AD8F3EA38B9B71DA FA1F4D23AC88AF1B06561956539047AD2D43656B1D8D85BDA403115BC4B120F6 5181FCAA6A640514514005145140156FF53B0D2ADC5C6A97B6F650960824B995 6352C7B658819E0FE559DFF09AF857FE865D1FFF0003E2FF00E2AAF6ABA2E95A EDAADB6B7A659EA56EAE1D62BC816640C011B806046704F3EF591FF0AE3C0FFF 00426F87FF00F05707FF00134014BC51F13FC31E1DF0BDFEAD16B1A75FC96B09 78ED6DEF236799FA2A80093C923271C0C9AF95EEBF681F88D71ACB5FC7AE8B75 DC4ADAC56F1F92A33F77690491EE493EF5F51788FE11F8375CF0DDF69B6BE1DD 234D9EE612915E5AE9F12490BF55604283C103233C8C8EF5F305DFECF7F11ADF 5A361168A9729BB0B7715CC7E4B2FF007B248207B100FB5007D29F0F3E2E687E 2EF05DA6A7ABEA5A6E97A864C5756D2DD2478917A950C73B48C11E99C64E335D 3FFC26BE15FF00A19747FF00C0F8BFF8AAE4BC05F05FC33E18F075A69DAEE8BA 46B3A90CC9737771651CA4BB7F0A975CED1C01D3A670335D27FC2B8F03FF00D0 9BE1FF00FC15C1FF00C4D0059FF84D7C2BFF00432E8FFF0081F17FF1547FC26B E15FFA19747FFC0F8BFF008AAADFF0AE3C0FFF00426F87FF00F05707FF001347 FC2B8F03FF00D09BE1FF00FC15C1FF00C4D0059FF84D7C2BFF00432E8FFF0081 F17FF1547FC26BE15FFA19747FFC0F8BFF008AAADFF0AE3C0FFF00426F87FF00 F05707FF001347FC2B8F03FF00D09BE1FF00FC15C1FF00C4D007827C64F8FBAC C7E279F43F026A31DAD8DA6125BEB709235C39193B58E40519C71CE41E7147C0 0F8C92DAEA67C2BE2AB8B74B3BA69AE20BF98AC6526626471231C0218EE209E7 381C82307C60FD9F7577F11CBAD78034D827B0B900C9A7DBEC88DB38183B1780 54E01C0E724F18AB9F06BF67FD42CB5CFEDCF887A6DA8821465834CB8093F9AC C31BE45E57001381D7383C63900F78FF0084D7C2BFF432E8FF00F81F17FF0015 47FC26BE15FF00A19747FF00C0F8BFF8AAADFF000AE3C0FF00F426F87FFF0005 707FF1347FC2B8F03FFD09BE1FFF00C15C1FFC4D0059FF0084D7C2BFF432E8FF 00F81F17FF001547FC26BE15FF00A19747FF00C0F8BFF8AAADFF000AE3C0FF00 F426F87FFF0005707FF1347FC2B8F03FFD09BE1FFF00C15C1FFC4D0059FF0084 D7C2BFF432E8FF00F81F17FF001547FC26BE15FF00A19747FF00C0F8BFF8AAAD FF000AE3C0FF00F426F87FFF0005707FF1347FC2B8F03FFD09BE1FFF00C15C1F FC4D0059FF0084D7C2BFF432E8FF00F81F17FF001547FC26BE15FF00A19747FF 00C0F8BFF8AAADFF000AE3C0FF00F426F87FFF0005707FF1347FC2B8F03FFD09 BE1FFF00C15C1FFC4D0059FF0084D7C2BFF432E8FF00F81F17FF001547FC26BE 15FF00A19747FF00C0F8BFF8AAADFF000AE3C0FF00F426F87FFF0005707FF134 7FC2B8F03FFD09BE1FFF00C15C1FFC4D0059FF0084D7C2BFF432E8FF00F81F17 FF001547FC26BE15FF00A19747FF00C0F8BFF8AAADFF000AE3C0FF00F426F87F FF0005707FF1347FC2B8F03FFD09BE1FFF00C15C1FFC4D0059FF0084D7C2BFF4 32E8FF00F81F17FF001547FC26BE15FF00A19747FF00C0F8BFF8AAADFF000AE3 C0FF00F426F87FFF0005707FF1347FC2B8F03FFD09BE1FFF00C15C1FFC4D0059 FF0084D7C2BFF432E8FF00F81F17FF001547FC26BE15FF00A19747FF00C0F8BF F8AAADFF000AE3C0FF00F426F87FFF0005707FF1347FC2B8F03FFD09BE1FFF00 C15C1FFC4D0059FF0084D7C2BFF432E8FF00F81F17FF001547FC26BE15FF00A1 9747FF00C0F8BFF8AAADFF000AE3C0FF00F426F87FFF0005707FF1347FC2B8F0 3FFD09BE1FFF00C15C1FFC4D0059FF0084D7C2BFF432E8FF00F81F17FF001547 FC26BE15FF00A19747FF00C0F8BFF8AAADFF000AE3C0FF00F426F87FFF000570 7FF1347FC2B8F03FFD09BE1FFF00C15C1FFC4D0059FF0084D7C2BFF432E8FF00 F81F17FF00155F387C78F8BB0EA7E2EB0D33C3B059DC47E1FBC8EEE3D47224F3 26001DAB83829D33D7257DB9FA1BFE15C781FF00E84DF0FF00FE0AE0FF00E26B C57E28FECDF7BAAF88DF56F008B0B7B6B803CDD39B102C4C00198F036ED3D71C 60E7AE7800EB7E10FC72B4F19E95750F8BAE34FD2B53B22B991E658A3B946CE1 9431E08C7233DC1EF81D7788FE26693A35B4371A5CFA7EB6A5F13C76DAB5BA4B 1AE3EF2ABB80FF004C835C7FC29F809A6784F48B993C6767A66B9A95DB29D935 B2CD15B28CE026F5E49CF2703A01DB27A5F127C26D0F54B6860D034AF0EE89F3 933CE340B69E465C744DC36A9F720D004DA07C62F04788645821D6A2B1BB6207 D9751FF477C9E0005BE563FEE93506B7F136F34DF126B5A5699E11D43575D123 8E4BBB8B7B889422BC7E60F9588278CF4CF4A8BC3BF02FC07E1F985C9D21352B BCEE33DF85719F68C0118FC16B3E4F87571E21F8A1E32BCD4EFB5CD334EBB4B2 487EC176608EF14405640D81F360F1F89A00F41F0DF882C7C55E1BB1D7349673 697B10923F3170C3B1047A82083F4AD3AF1BF14E9171E1DD634FD0BC15AEEA51 EA92BDB2E95A3D9C852D6C2DA323CD92E1790EAD86259F924E39AF64A0028A28 A0028A28A0028A28A0028A28A0028A28A0028A28A0028A28A0028A28A0028A28 A0028A28A0028A28A0028A28A0028A28A0028A28A0028A28A0028A28A0028A28 A0028A28A0028A28A00E3755F855E16D67C4B71AFDEC17BFDA373B7CD962D426 8C30500018560318038E95D95145007FFFD9} end object gb2: TGroupBox Left = 3 Top = 299 Width = 417 Height = 148 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 Caption = 'Process 2' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -15 Font.Name = 'Tahoma' Font.Style = [] ParentFont = False TabOrder = 6 object labelM2: TLabel Left = 226 Top = 10 Width = 118 Height = 17 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 AutoSize = False Caption = 'Matrix Clock 2' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -15 Font.Name = 'Tahoma' Font.Style = [fsBold, fsItalic] ParentFont = False end object stxt2: TStaticText Left = 9 Top = 75 Width = 128 Height = 22 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 Alignment = taCenter Caption = 'Send message to :' TabOrder = 0 end object btnP2toP0: TButton Left = 9 Top = 105 Width = 55 Height = 32 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 Caption = 'P0' TabOrder = 1 OnClick = btnP2toP0Click end object btnP2toP1: TButton Left = 72 Top = 105 Width = 55 Height = 32 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 Caption = 'P1' TabOrder = 2 OnClick = btnP2toP1Click end object btnEventP2: TButton Left = 9 Top = 26 Width = 118 Height = 33 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 Caption = 'Internal Event' TabOrder = 3 OnClick = btnEventP0Click end end object gb1: TGroupBox Left = 3 Top = 154 Width = 417 Height = 148 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 Caption = 'Process 1' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -15 Font.Name = 'Tahoma' Font.Style = [] ParentFont = False TabOrder = 5 object labelM1: TLabel Left = 226 Top = 14 Width = 118 Height = 20 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 AutoSize = False Caption = 'Matrix Clock 1' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -15 Font.Name = 'Tahoma' Font.Style = [fsBold, fsItalic] ParentFont = False end object sTxt1: TStaticText Left = 9 Top = 77 Width = 128 Height = 22 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 Alignment = taCenter Caption = 'Send message to :' TabOrder = 0 end object btnP1toP0: TButton Left = 9 Top = 105 Width = 55 Height = 32 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 Caption = 'P0' TabOrder = 1 OnClick = btnP1toP0Click end object btnP1toP2: TButton Left = 72 Top = 105 Width = 55 Height = 32 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 Caption = 'P2' TabOrder = 2 OnClick = btnP1toP2Click end object btnEventP1: TButton Left = 9 Top = 33 Width = 118 Height = 32 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 Caption = 'Internal Event' TabOrder = 3 OnClick = btnEventP0Click end end object gb0: TGroupBox Left = 3 Top = 10 Width = 417 Height = 148 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 Caption = 'Process 0' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -15 Font.Name = 'Tahoma' Font.Style = [] ParentFont = False TabOrder = 4 object labelM0: TLabel Left = 226 Top = 14 Width = 118 Height = 17 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 AutoSize = False Caption = 'Matrix Clock 0' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -15 Font.Name = 'Tahoma' Font.Style = [fsBold, fsItalic] ParentFont = False end object sTxt0: TStaticText Left = 9 Top = 77 Width = 128 Height = 22 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 Alignment = taCenter Caption = 'Send message to :' TabOrder = 0 end object btnP0toP1: TButton Left = 9 Top = 105 Width = 55 Height = 32 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 Caption = 'P1' TabOrder = 1 OnClick = btnP0toP1Click end object btnP0toP2: TButton Left = 72 Top = 103 Width = 55 Height = 33 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 Caption = 'P2' TabOrder = 2 OnClick = btnP0toP2Click end end object btnEventP0: TButton Left = 12 Top = 46 Width = 117 Height = 32 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 Caption = 'Internal Event' TabOrder = 0 OnClick = btnEventP0Click end object sgMatrix0: TStringGrid Left = 153 Top = 50 Width = 263 Height = 106 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 ColCount = 3 FixedCols = 0 RowCount = 3 FixedRows = 0 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -15 Font.Name = 'Tahoma' Font.Style = [] GridLineWidth = 2 ParentFont = False TabOrder = 1 RowHeights = ( 24 24 24) end object sgMatrix1: TStringGrid Left = 148 Top = 187 Width = 263 Height = 106 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 ColCount = 3 FixedCols = 0 RowCount = 3 FixedRows = 0 GridLineWidth = 2 TabOrder = 2 RowHeights = ( 24 24 24) end object sgMatrix2: TStringGrid Left = 153 Top = 335 Width = 263 Height = 106 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 ColCount = 3 DoubleBuffered = False FixedCols = 0 RowCount = 3 FixedRows = 0 Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = 20 Font.Name = 'Tahoma' Font.Style = [] GridLineWidth = 2 ParentDoubleBuffered = False ParentFont = False TabOrder = 3 RowHeights = ( 24 24 24) end object sbMsgReceived: TStatusBar Left = 0 Top = 533 Width = 845 Height = 19 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 Panels = < item Width = 175 end item Width = 175 end item Width = 175 end item Width = 115 end> end object rgImageExamples: TRadioGroup Left = 424 Top = 455 Width = 410 Height = 64 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 Caption = 'Select Image Example ' Columns = 4 ItemIndex = 0 Items.Strings = ( 'Example1' 'Example2' 'Example3' 'Example4') TabOrder = 8 OnClick = rgImageExamplesClick end object btnReset: TButton Left = 97 Top = 466 Width = 200 Height = 37 Margins.Left = 4 Margins.Top = 4 Margins.Right = 4 Margins.Bottom = 4 Caption = 'Reset Matrix Clocks' TabOrder = 9 OnClick = btnResetClick end end
54.898267
70
0.860398
47883c1accc41ff6d57c6e4aa71a1cbda63e8644
1,682
pas
Pascal
uiarbitre.pas
shaya1/royalship
d04fb8d2e5d5e59e2fd4f5457973922c092e4ab9
[ "MIT" ]
null
null
null
uiarbitre.pas
shaya1/royalship
d04fb8d2e5d5e59e2fd4f5457973922c092e4ab9
[ "MIT" ]
null
null
null
uiarbitre.pas
shaya1/royalship
d04fb8d2e5d5e59e2fd4f5457973922c092e4ab9
[ "MIT" ]
null
null
null
(* Copyright (c) 2007 Cheikh Malik, * Kechai Icham, * Lipp Simon * * 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. *) // ~ master: bataillenavale.lpr unit UIarbitre; {$mode objfpc}{$H+} interface Uses SysUtils; type TCase = array[0..1] of integer; Type Iarbitre=Class Constructor Create();virtual;abstract; Destructor Destroy();virtual;abstract; Procedure Tour(); virtual;abstract; Procedure MiseEnPlace;virtual;abstract; Function JeuEnCours: boolean;virtual;abstract; end; implementation initialization end.
33.64
80
0.702735
476d52d807530b5ef39cac681afc76adc57ed2f7
186,870
pas
Pascal
Source/frmPyIDEMain.pas
sk-Prime/pyscripter
47ca411066d5acfc60115a135d08d985665aa417
[ "MIT" ]
null
null
null
Source/frmPyIDEMain.pas
sk-Prime/pyscripter
47ca411066d5acfc60115a135d08d985665aa417
[ "MIT" ]
null
null
null
Source/frmPyIDEMain.pas
sk-Prime/pyscripter
47ca411066d5acfc60115a135d08d985665aa417
[ "MIT" ]
null
null
null
{----------------------------------------------------------------------------- Unit Name: frmPyIDEMain Author: Kiriakos Vlahos Date: 11-Feb-2005 Purpose: The main form of the Pytnon IDE History: v 1.1 Improved Python Syntax highlighting HTML documentation and disassembly views (Tools, Source Views menu) TODO list view Find and Replace in Files Powerful parameter functionality (see parameters.txt) Parameterized Code Templates (Ctrl-J) Accept files dropped from Explorer File change notification sys.stdin and raw_input implemented Choice of Python version to run via command line parameters External Tools (External run and caputure output) Integration with Python tools such as PyLint Run Python Script externally (highly configurable) Persist and optionally reopen open files Bug fixes History: v 1.2 Updated the User Interface using Themes Messages History Previous/Next identifier reference (as in GExperts) Find Definition/Find references using BicycleRepairMan Find definition by clicking as in Delphi Reduced flicker on start and exit and somewhat on resizing** Converting line breaks (Windows, Unix, Mac) Detecting loading/saving UTF-8 encoded files Help file and context sensitive Help Check for updates History: v 1.3 Code completion in the editor (Press Ctrl+Space while or before typing a name) Parameter completion in the editor (Press Shift+Ctrl+Space) Find definition and find references independent of BicycleRepairMan and arguably faster and better Find definition by clicking works for imported modules and names Revamped Code Explorer Window featuring incremental search, properties, global variables, docstrings in hints etc. A new feature-rich Python code parser was developed for implementing the above Improved the Variable Windows shows interpreter globals when not debugging and Doc strings Improved code and parameter completion in the interactive interpreter Integrated regular expression tester Code and debugger hints Set the current directory to the path of the running script Added IDE option MaskFUPExceptions for resolving problems in importing Scipy Tested with FastMM4 for memory leaks etc. and fixed a couple of related bugs Note on Code and Parameter completion: The code and parameter completion should be one of the best you can find in any Python IDE. However,if you find that code and parameter completion is not very accurate for certain modules and packages such as wxPython and scipy you can achieve near perfect completion if you add these packages to the IDE option "Special Packages" (comma separated text). By default it is set to "wx, scipy". Special packages are imported to the interpreter instead of scanning their source code. History: v 1.5 New Features Unit test integration (Automatic generation of tests, and testing GUI) Added highlighting of HTML, XML and CSS files Command line parameters for scripts run internally or debugged Conditional breakpoints Persistence of breakpoints, watches, bookmarks and file positions Save and restore IDE windows layouts Generate stack information when untrapped exceptions occur and give users the option to mail the generated report Running scripts does not polute the namespace of PyScripter Names in variables window are now sorted Allow only a single Instance of Pyscripter and open command line files of additional invocations at new tabs Interpreter window is now searchable Added option to File Explorer to browse the directory of the Active script New distinctive application icon thanks to Frank Mersmann and Tobias Hartwich IDE shortcut customization File Explorer autorefreshes Improved bracket highlighting Copy to Clipboard Breakpoins, Watches and Messages User customization (PyScripter.ini) is now stored in the user's Application Data direcrory to support network installations(breaking change) To restore old settings copy the ini file to the new location. Bug fixes Resolved problems with dropping files from File Explorer Restore open files options not taken into account Resolved problems with long Environment variables in Tools Configure Resolved problems with help files Reduced problems with running wxPython scripts Changing the Python Open dialog filter did not affect syntax highlighting CodeExplorer slow when InitiallyExpanded is set Help related issues Other fixes. History: v 1.7.1 New Features Unicode based editor and interactive interpreter Full support for Python source file encodings Support for Python v2.5 and Current User installations Check syntax as you type and syntax hints (IDE option) Tab indents and Shift-Tab unindents (Editor Options - Tab Indents) Editor Zoom in/out with keyboard Alt+- and Ctrl+mouse wheel Improved Debugger hints and completion in the interpreter work with expressions e.g. sys.path[1]. for debugger expression hints place the cursor on ')' or ']' Improved activation of code/debugger hints IDE options to Clean up Interpreter namespace and sys.modules after run File Open can open multiple files Syntax highlighting scheme selection from the menu File filters for HTML, XML and CSS files can be customized Option to disable gutter Gradient (Editor Options - Gutter Gradient) Option to disable theming of text selection (Editor Options - theme selection) Option to hide the executable line marks. Active Line Color Editor option added. Set to None to use default background Files submenu in Tabs popup for easy open file selection Add Watch at Cursor added to the Run menu and the Waches Window popup menu Pop up menu added to the External Process indicator to allow easy termination of such processes If the PyScripter.ini file exists in PyScripter directory it is used in preference to the User Directory in order to allow USB storage installations Editor options for each open file are persisted Improved speed of painting the Interpreter window Auto close brackets Interactive Interpreter Pop up menu with separately persisted Editor Options Toggle comment (Ctrl+^) in addition to comment/uncomment File Explorer improvements (Favorites, Create New Folder) File Templates Windows Explorer file association (installation and IDE option) Command line history Color coding of new and changed variables in the Variables Window Repeat scrolling of editor tabs Massively improved start up time Faster Python source file scanning Bug fixes Gutter glyphs painted when gutter is invisible Bracket highlighting related bugs Selecting whole lines by dragging mouse in the gutter sets breakpoint Speed improvements and bugfixes related to layouts Error in Variable Windows when showing dictionaries with non string keys File notification error for Novell network disks Wrong line number in External Run traceback message No horizontal scroll in output window Code completion Error with packages containing module with the same name Problems with sys.stdin.readline() and partial line output (stdout) statements Infinite loop when root of package is the top directory of a drive Infinite loop with cyclical Python imports History: v 1.7.2 New Features Store toolbar positions Improved bracket completion now also works with strings (Issue #4) Bug fixes Bracket highlighting with non default background Opening wrongly encoded UTF8 files results in empty module File Format (Line End) choice not respected Initial Empty module was not syntax highlighted Save As dialog had no default extension set Unit Testing broken (regression) Gap in the default tool bar (Issue #3) History: v 1.9.9.6 New Features Remote interpreter and debugger Python 2.6, 3.0 and 3.1 support Project Explorer supporting multiple run configurations with advanced options New debugger command: Pause Execute selection command added (Ctrl-F7) Interpreter command history improvements: - Delete duplicates - Filter history by typing the first few command characters - Up|Down keys at the prompt recall commands from history Code Explorer shows imported names for (from ... import) syntax (Issue 12) Improved sort order in code completion Save modified files dialog on exit Finer control on whether the UTF-8 BOM is written - Three file encodings supported (ANSI, UTF-8, UTF-8 without BOM) IDE option to detect UTF-8 encoding (useful for non-Python files) IDE options for default line breaks and encoding for new files Warning when file encoding results in information loss IDE option to position the editor tabs at the top IDE window navigation shortcuts Pretty print interpreter output option (on by default) Pyscripter is now Vista ready Docking window improvements PYTHONDLLPATH command line option so that Pyscripter can work with unregistered Python Watches Window: DblClick on empty space adds a watch, pressing Delete deletes (Issue 45) Wrapping in Search & Replace (Issue 38) New IDE Option "Save Environment Before Run" (Issue 50) New IDE command Restore Editor pair to Maximize Editor (both work by double clicking the TabControl) New IDE Option "Smart Next Previous Tab" (z-Order) on by default (Issue 20) Word Wrap option exposed in Editor Options New File Reload command Import/Export Settings (Shortcuts, Highlighter schemes) New IDE option "Auto-reload changed files" on by default (Issue 25) New menu command to show/hide the menu bar. The shortcut is Shift-F10 (Issue 63) New command line option --DPIAWARE (-D) to avoid scaling in VISTA high DPI displays (Issue 77) New command line option --NEWINSTANCE (-N) to start a new instance of PyScripter You can disable a breakpoint by Ctrl+Clicking in the gutter Syntax Errors are indicated by icon in the TabControl (Issue 93) Command to jump to the first syntax error (Shift+Ctrl+E) New Firefox-like search/replace interface Incremental Search (Issue 100) New command "Highlight search text" (Shift+Ctrl+H) New command line option --DEBUG (-B) to use debug version of Python dll (Issue 108) New command "Word wrap" visible in the Editor toolbar (Issue 112) New command "Go to Debugger Position" (Issue 118) The size of the auto completion list is now persisted Split Editor View (Issue 31) New parameter $[CmdLineArgs] that returns the active command line arguments and can be used with external tools New IDE options "Editor code completion" and "Interpreter code completion" which can be used to disable code completion New IDE option "Show Tab Close Button" New debugger command "Post mortem" (Issue 26) New IDE option "Post mortem on exception" Auto-resizing the fields of list views by double clicking on column separators Advanced search and replace external tool added (uses re.sub) Enhanced Execute Selection command (Issue 73) Two new IDE options added (Dock Animation Interval and Dock Animation Move Width - Issue 134) Toolbar customization Two new IDE options added ("Interpreter History Size" and "Save Command History") (Issue 131) Cut and copy without selection now cut and copy the current line (as in Visual Studio, Issue 64) Removed the Interpeter options "Clean up Namespace" and "Clean up sys.modules" Improved HTML, XML highlighting with code completion and Web preview C/C++ highlighting added Two new interpreter commands added: Copy without prompts, and Paste with prompts (Issue 183) Localization using gettext YAML highlighter added Ability to run initialization scripts (see help file) Bug fixes Shell Integration - Error when opening multiple files Configure External Run - ParseTraceback not saved properly Order of tabs not preserved in minimised docked forms sys.argv contained unicode strings instead of ansi strings Bug fixes and improvements in Editor Options Keystrokes tab (Issue 6) Better error handling of File Open and File Save Page Setup Header and Footer not saved (Issue 7) Hidden Tabbed windows reappearing when restarting Duplicate two-key editor command not detected "Clean up namespace" and "Clean up sys modules" settings become effective after restarting PyScripter Exception when setting the Active Line Color in Editor Options dialog Raw_input does not accept unicode strings Error in docstring extraction (Issue 11) Fixed some problems with the toggle comment command Fixed rare bug in restoring layout Code tips wrong if comments are present among parameters (Issue 15) Notification of file changes can miss files (Issue 17) Certain syntax coloring options were not saved ToDo List did not support encoded files and unicode ToDo List did not support multiline comments (Issue 14) Fixed bug in IDE Shortcuts dialog Swapped the positions of the indent/dedent buttons (Issue 23) Syntax highlighter changes to the interpreter are not persisted Multiple target assignments are now parsed correctly Gutter gradient setting not saved Handling of string exceptions Disabling a breakpoint had no effect Tab order not preserved when restarting PyScripter Disassembly and Documentation views not working with remote engines PyScripter "freezes" when displaying modal dialogs when running GUI scripts with remote engines More robust "Reinitialize" of remote Python engines (Issues 143, 145) Shift-Tab does not work well with the Trim Trailing Spaces editor option Issues 28, 32, 39, 40, 41, 46, 47, 48, 49, 52, 55, 56, 57, 65, 66, 67, 70, 71, 72, 74, 75, 76, 81, 82, 83, 86, 88, (89), 90, 91, 92, 94, 96, 98, 99 100, 102, 105, 106, 107, 109, 113, 117, 119, 120, 122, 123, 125, 132, 134, 135, 136, 137, 138, 139, 140, 141, 146, 147, 150, 153, 155, 160, 164, 165, 166, 167, 168, 169, 171, 174, 178, (182), 186, 193, 195, 196, 197, 198, 201, 202, 204, 206, 208, 212, 219, 226, 228, 229, 234, 235, 237, 253, 261 fixed History: v 1.9.9.7 New Features Updated theme engine with customizable themes Python 3.1 support Bug fixes Issues 269, 273, 287, 291, 292 History: v 2.0 New Features Support for Python 2.7 Moved to Rpyc v3.07, now bundled with PyScripter IDE Option "Reinitialize before run" was added defaulting to True The default Python engine is now the remote engine Spanish translation by Javier Pim�s (incomplete) was added Bug fixes Issues 236, 304, 322, 333, 334 History: v 2.1.1 New Features Support for Python 3.2 New IDE Option added "Jump to error on Exception" (Issue 130) New IDE Option added "File template for new Python scirpts" (Issue 385) New IDE Option added "Auto completion font" (Issue 365) French translation by Groupe AmiensPython added Bug fixes Issues 297, 307, 346, 354, 358, 371, 375, 376, 382, 384, 387, 389 History: v 2.3.3 New Features Native unicode strings throught (speed improvements on XP) Revamped Code Explorer (Issues 192, 163, 213, 225) Improvements to Code completion - Auto-completion for the import statement in Python 2.5 and later (Issue 230) - Processing of function return statements - Background module parsing and caching of parsed modules Start-up Python scripts pyscripter_init.py and python_init.py. See help file for details. Imporved "Match Brace" (Issue 426) and New Editor Command "Select to brace" Italian translation by Vincenzo Demasi added Russian translation by Aleksander Dragunkin added New IDE option "Highlight selected word" (Issue 404) New IDE option "Use Python colors in IDE" New Edit command "Copy File Name" available at the contex menu of the tab bar New commands "Previous Frame", "Next Frame" to change frame using the keyboard (Issue 399) JavaScript and PHP Syntax Highlighters added Issues addressed 103, 239, 267, 270, 271, 294, 317, 324, 343, 378, 395, 403, 405, 407, 411, 412, 413, 419, 421, 422, 425, 432 History: v 2.3.4 New Features Compatibility with Python 3.1.3rc, 3.2a4 Add watches by dragging and dropping text Ctrl + Mouse scroll scrolls whole pages in print preview Search for custom skins first in the Skins subdirectory of the Exe file if it exists Issues addressed 430, 434, 435, 439, 440, 441, 443, 446 History: v 2.4.1 New Features Side-by-side file editing (Issue 214) Enhanced regular expression window (findall - Issue 161) Open file at a specific line:column (Issue 447) Issues addressed Reduced flicker when resizing form and panels 415, 437, 449 History: v 2.4.3 New Features 100% portable by placing PyScripter.ini in the PyScripter exe directory Ctrl+Mousewheel for zooming the interpreter (Issue 475) Show docstrings during completion list (Issue 274) New IDE Option "File Change Notification" introduced with possible values Full, NoMappedDrives(default), Disabled (Issue 470) Background color for Matching and Unbalanced braces (Issue 472) New IDE option "Case Sensitive Code Completion" (default True) New IDE option "Complete Python keywords" (default True) New IDE option "Complete as you type" (default True, Issue 473) New IDE option "Complete with word-break chars" (default True) New IDE option "Auto-complete with one entry" (default True, Issue 452) Issues addressed Command line history not saved Editing a watch to an empty string crashes PyScripter Replace in Find-in-Files now supports subexpression substitution (Issue 332) Import statement completion does not include builtin module names 461, 463, 468, 471, 474, 478, 488, 496, 504, 508, 509, 511, 512, 515, 525, 526, 527, 528, 532, 559, 560 History: v 2.5.1 New Features This is the first joint 32-bit and 64-bit version release Python 3.3 support added Recent Projects menu item added Expandable lists and tuples in the Variables window (Issue 583) Expandable watches as in the Variables window (Issue 523) Basic support for Cython files added (Issue 542) New interpreter action Paste & Execute (Issue 500) Replaces Paste with Prompt New PyIDE option "Display package names in editor tabs" default True (Issue 115) New search option "Auto Case Sensitive" (case insensitive when search text is lower case) The Abort command raises a KeyboardInterrupt at the Remote Engine (Issue 618) Incremental search in the Project Explorer matches any part of a filename (Issue 623) New IDE option "File line limit for syntax check as you type" default 1000 Issues addressed 516, 348, 549, 563, 564, 568, 576, 587, 591, 592, 594, 597, 598, 599, 612, 613, 615 History: v 2.5.1 New Features Issues addressed 639, 657, 673 History: v 2.6 New Features Compatibility with Python 3.4 History: v 3.0 New Features Python 3.5, 3.6 and 3.7 support New Style Engine (VCL Styles) with high quality choices Visual Style Preview and selection (View, Select Style) Visual Source highligther theme selection (Editor Options, Select theme) German Translation added History: v 3.1 New Features Code folding Indentation lines New IDE option "Compact line numbers" pip tool added Internal Interpreter is hidden by default Kabyle language added Issues addressed 16, 571, 685, 690, 718, 721, 765, 814, 836 History: v 3.2 New Features Dpi awareness (Issue 769) Issues addressed #705 #711 #717, #748 History: v 3.3 New Features Thread debugging (#455) Much faster Python output redirection Form Layout and placement stored in PyScripter.local.ini Issues addressed #659, #827, #848, #849 History: v 3.4 New Features Switch Python Engines without exiting PyScripter Faster loading times Initial support for running Jupyter notebooks inside PyScripter Syntax highlighting for JSON files New IDE option "Style Main Window Border" Find in Files and ToDo folders can include parameters (#828) Issues addressed #627, #852, #858, #862, #868, #872 History: v 3.4.2 New Features New Edit Command Read Only (#883) Files opened by PyScripter from the Python directory during debugging are read only by default to prevent accidental changes. Close All to the Right Editor command added (#866) New editor parameter [$-CurLineNumber] (#864) New IDE Option "File Explorer background processing'. Set to false if you get File Explorer errors Console output including multiprocessing is now shown in interpreter #891 Issues addressed #645, #672, #722, #762, #793, #800, #869, #879, #889, #890, #893, #896, #898, #899, #906 History: v 3.5 New Features Open and work with remote files from Windows and Linux machines as if they were local Run and Debug scripts on remote Windows and Linux machines using SSH Python 3 type hints used in code completion Connection to Python server with Windows named pipes. Avoids firewall issues. Requires the installation of pywin32 (pip install pywin32). IDE option to force the use of sockets for connection to the Python server. (default True) New Editor commands Copy Line Up/Down (Shift+Alt+Up/Down) and Move Line Up/Down (Alt + Up/Down) as in Visual Studio PyScripter icons given a facelift by Salim Saddaquzzaman Upgraded rpyc to 4.x. As a result Python 2.5 is no longer supported. Issues addressed #501, #682, #907 History: v 3.6 New Features Much faster Remote Engine using asynchronous Windows named pipes if pywin32 is available. IDE option to force the use of sockets for connection to the Python server now defaults to False Enhancements to the SSH Engine - now compatible with PuTTY Execute system commands in the interpreter with !. Supports parameter substitution. Clickable status panels with Python version and engine type Text drag & drop between PyScripter and other applications (#554) Triple-click selects line and Quadraple-click selects all Double-click drag selects whole words - triple-click drag selects whole lines Consistent syntax color themes accross supported languages (#855) New IDE option "Trim trailing spaces when saving files" (#667) New IDE Option 'Step into open files only'. Defaults to False. (#510) Localization of the installer Issues addressed #624, #743, #857, #904, #922, #927, 928, #929, #936 History: v 3.6.1 New Features Python 3.8 support. Dropped support for Python 3.0 and 3.1. Compatibility with conda distributions JSON and YAML file templates added Three new styles added (Windows10BlackPearl, Windows10BlueWhale, Windows10ClearDay) Translation improvements "Always Use Sockets" IDE option is True by default (#938) Issues addressed #311, #941, #955 History: v 3.6.2 New Features Improved compatibility with venv virtual environments Restore code folding state when you start PyScripter (#973) Syntax for adding and removing parameters (#971) $[proc=?Question] adds parameter proc and $[proc=] removes it Highlighters and styles are now installed under ProgramData Improved DPI scaling Two new styles added (Calypso and Stellar) Issues addressed #948, #962, #966, #967, #968, #972 History: v 3.6.3 New Features The status panel with text position info can now be clicked to show the "Go to line" dialog. Issues addressed #983, #985 History: v 3.6.4 New Features Added support for Python 3.9 (and removed support for Python 2.6) Added support for virtualenv v20+. Dropped support for earlier versions. Issues addressed #998, #1001, #1003, #1008, #1009 } { TODO : Review Search and Replace } { TODO : Auto PEP8 tool } { TODO: LiveTemplates features for Code Templates } {------------------------------------------------------------------------------} // Bugs and minor features // TODO: Internal Tool as in pywin // TODO: Find module expert // TODO: Code helpers, automatically fill the self parameter in methods // TODO: UML Editor View // TODO: Refactorings using rope // TODO: Plugin architecture // TODO Package as an Application Scripter Component unit frmPyIDEMain; interface uses WinAPI.Windows, WinAPI.Messages, WinApi.ActiveX, System.Types, System.UITypes, System.SysUtils, System.Classes, System.Actions, System.Variants, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ImgList, Vcl.ActnList, Vcl.Menus, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, VCL.Styles, AMHLEDVecStd, JvAppInst, JvComponentBase, JvExControls, JvDockTree, JvDockControlForm, JvDockVIDStyle, JvDockVSNetStyle, JvDockVSNetStyleSpTBX, JvAppStorage, JvAppIniStorage, JvFormPlacement, JvDSADialogs, TB2Dock, TB2Toolbar, TB2Item, TB2ExtItems, SpTBXCustomizer, SpTbxSkins, SpTBXItem, SpTBXEditors, SpTBXMDIMRU, SpTBXTabs, SpTBXDkPanels, SynEditTypes, SynEditMiscClasses, SynEdit, dmCommands, dlgCustomShortcuts, uEditAppIntfs, uHighlighterProcs, cFileTemplates, cPySupportTypes, cPyBaseDebugger, cPyDebugger, cRefactoring, cPyScripterSettings, cPyControl, System.ImageList, Vcl.VirtualImageList; const WM_FINDDEFINITION = WM_USER + 100; WM_CHECKFORUPDATES = WM_USER + 110; WM_SEARCHREPLACEACTION = WM_USER + 130; type { Trick to add functionality to TTSpTBXTabControl} TSpTBXTabControl = class(SpTBXTabs.TSPTBXTabControl) private zOrderPos : integer; zOrderProcessing : Boolean; public zOrder : TList; procedure WMDropFiles(var Msg: TMessage); message WM_DROPFILES; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; TPyIDEMainForm = class(TForm, IIDELayouts, IPyIDEServices) DockServer: TJvDockServer; AppStorage: TJvAppIniFileStorage; BGPanel: TPanel; CloseTimer: TTimer; TBXDockTop: TSpTBXDock; MainMenu: TSpTBXToolbar; FileMenu: TSpTBXSubmenuItem; mnNewModule: TSpTBXItem; mnFileOpen: TSpTBXItem; N14: TSpTBXSeparatorItem; mnFileClose: TSpTBXItem; mnFileCloseAll: TSpTBXItem; N1: TSpTBXSeparatorItem; mnFileSave: TSpTBXItem; mnFileSaveAs: TSpTBXItem; mnFileSaveAll: TSpTBXItem; N2: TSpTBXSeparatorItem; PageSetup1: TSpTBXItem; PrinterSetup1: TSpTBXItem; PrintPreview1: TSpTBXItem; Print1: TSpTBXItem; N4: TSpTBXSeparatorItem; N3: TSpTBXItem; EditMenu: TSpTBXSubmenuItem; mnEditUndo: TSpTBXItem; mnEditRedo: TSpTBXItem; N5: TSpTBXSeparatorItem; mnEditCut: TSpTBXItem; mnEditCopy: TSpTBXItem; mnEditPaste: TSpTBXItem; mnEditDelete: TSpTBXItem; mnEditSelectAll: TSpTBXItem; N6: TSpTBXSeparatorItem; Parameters1: TSpTBXSubmenuItem; mnInsertParameter: TSpTBXItem; mnInsertModifier: TSpTBXItem; N16: TSpTBXSeparatorItem; mnReplaceParameter: TSpTBXItem; mnIsertCodeTemplate: TSpTBXItem; mnSourceCode: TSpTBXSubmenuItem; mnIndentBlock: TSpTBXItem; mnDedentBlock: TSpTBXItem; mnToggleComment: TSpTBXItem; mnTabify: TSpTBXItem; mnUnTabify: TSpTBXItem; SearchMenu: TSpTBXSubmenuItem; mnSearchFind: TSpTBXItem; mnSearchFindNext: TSpTBXItem; mnSearchFindPrevious: TSpTBXItem; mnSearchReplace: TSpTBXItem; N15: TSpTBXSeparatorItem; mnFindinFiles: TSpTBXItem; N7: TSpTBXSeparatorItem; mnGoToLine: TSpTBXItem; mnFindFunction: TSpTBXItem; N23: TSpTBXSeparatorItem; mnMatchingBrace: TSpTBXItem; RunMenu: TSpTBXSubmenuItem; mnSyntaxCheck: TSpTBXItem; mnImportModule: TSpTBXItem; N21: TSpTBXSeparatorItem; mnRun: TSpTBXItem; N22: TSpTBXSeparatorItem; mnExternalRun: TSpTBXItem; mnConfigureExternalRun: TSpTBXItem; N8: TSpTBXSeparatorItem; mnDebug: TSpTBXItem; mnRunToCursor: TSpTBXItem; mnStepInto: TSpTBXItem; mnStepOver: TSpTBXItem; mnStepOut: TSpTBXItem; mnAbortDebugging: TSpTBXItem; N9: TSpTBXSeparatorItem; mnTogglebreakpoint: TSpTBXItem; mnClearAllBreakpoints: TSpTBXItem; ToolsMenu: TSpTBXSubmenuItem; mnPythonPath: TSpTBXItem; N13: TSpTBXSeparatorItem; mnConfigureTools: TSpTBXItem; N20: TSpTBXSeparatorItem; OptionsMenu: TSpTBXSubmenuItem; mnIDEOptions: TSpTBXItem; mnEditorOptions: TSpTBXItem; mnCustomizeParameters: TSpTBXItem; mnCodeTemplates: TSpTBXItem; ViewMenu: TSpTBXSubmenuItem; mnNextEditor: TSpTBXItem; mnPreviousEditor: TSpTBXItem; N10: TSpTBXSeparatorItem; mnuToolbars: TSpTBXSubmenuItem; mnViewStatusBar: TSpTBXItem; mnViewII: TSpTBXItem; mnViewFileExplorer: TSpTBXItem; mnViewCodeExplorer: TSpTBXItem; mnViewToDoList: TSpTBXItem; mnViewFindResults: TSpTBXItem; mnViewOutput: TSpTBXItem; DebugWindows1: TSpTBXSubmenuItem; mnViewCallStack: TSpTBXItem; mnViewVariables: TSpTBXItem; mnViewBreakpoints: TSpTBXItem; mnViewWatches: TSpTBXItem; mnViewMessages: TSpTBXItem; HelpMenu: TSpTBXSubmenuItem; mnHelpPythonManuals: TSpTBXItem; N18: TSpTBXSeparatorItem; PyScripter1: TSpTBXSubmenuItem; mnHelpParameters: TSpTBXItem; mnHelpExternalTools: TSpTBXItem; N17: TSpTBXSeparatorItem; mnHelpAbout: TSpTBXItem; MainToolBar: TSpTBXToolbar; tbiFileNewModule: TSpTBXItem; tbiFileOpen: TSpTBXItem; tbiFileSave: TSpTBXItem; tbiFileSaveAll: TSpTBXItem; TBXSeparatorItem1: TSpTBXSeparatorItem; tbiFilePrint: TSpTBXItem; TBXSeparatorItem2: TSpTBXSeparatorItem; tbiEditCut: TSpTBXItem; tbiEditCopy: TSpTBXItem; tbiEditPaste: TSpTBXItem; TBXSeparatorItem3: TSpTBXSeparatorItem; tbiEditUndo: TSpTBXItem; tbiEditRedo: TSpTBXItem; TBXSeparatorItem4: TSpTBXSeparatorItem; tbiSearchFind: TSpTBXItem; tbiSearchFindNext: TSpTBXItem; tbiSearchReplace: TSpTBXItem; tbiFindInFiles: TSpTBXItem; TBXSeparatorItem5: TSpTBXSeparatorItem; tbiAbout: TSpTBXItem; DebugToolbar: TSpTBXToolbar; tbiRunRun: TSpTBXItem; TBXSeparatorItem6: TSpTBXSeparatorItem; tbiRunDebug: TSpTBXItem; tbiRunRunToCursor: TSpTBXItem; tbiRunStepInto: TSpTBXItem; tbiRunStepOver: TSpTBXItem; tbiRunStepOut: TSpTBXItem; tbiRunAbort: TSpTBXItem; TBXSeparatorItem7: TSpTBXSeparatorItem; tbiRunToggleBreakpoint: TSpTBXItem; tbiRunClearAllBreakpoints: TSpTBXItem; ViewToolbar: TSpTBXToolbar; TBXDockLeft: TSpTBXDock; TBXDockRight: TSpTBXDock; TBXDockBottom: TSpTBXDock; mnTools: TSpTBXSubmenuItem; TabControlPopupMenu: TSpTBXPopupMenu; mnNewModule2: TSpTBXItem; mnFileClose2: TSpTBXItem; mnFileCloseAll2: TSpTBXItem; N12: TSpTBXSeparatorItem; mnEditorOptions2: TSpTBXItem; RecentSubmenu: TSpTBXSubmenuItem; EditorViewsMenu: TSpTBXSubmenuItem; TBXSeparatorItem8: TSpTBXSeparatorItem; EditorToolbar: TSpTBXToolbar; tbiEditDedent: TSpTBXItem; tbiEditIndent: TSpTBXItem; TBXSeparatorItem10: TSpTBXSeparatorItem; tbiEditToggleComment: TSpTBXItem; TBXSeparatorItem11: TSpTBXSeparatorItem; tbiEditSpecialCharacters: TSpTBXItem; tbiEditLineNumbers: TSpTBXItem; mnFindPreviousReference: TSpTBXItem; mnFindNextReference: TSpTBXItem; mnFindDefinition: TSpTBXItem; TBXSeparatorItem9: TSpTBXSeparatorItem; TBXSubmenuItem3: TSpTBXSubmenuItem; mnEditLBMac: TSpTBXItem; mnEditLBUnix: TSpTBXItem; mnEditLBDos: TSpTBXItem; TBXSeparatorItem12: TSpTBXSeparatorItem; mnEditUtf8: TSpTBXItem; TBXSeparatorItem13: TSpTBXSeparatorItem; mnFindReferences: TSpTBXItem; tbiBrowseNext: TSpTBXSubmenuItem; tbiBrowsePrevious: TSpTBXSubmenuItem; TBXSeparatorItem14: TSpTBXSeparatorItem; mnHelpContents: TSpTBXItem; mnHelpEditorShortcuts: TSpTBXItem; TBXSeparatorItem15: TSpTBXSeparatorItem; mnCheckForUpdates: TSpTBXItem; mnViewRegExpTester: TSpTBXItem; mnCommandLineParams: TSpTBXItem; mnIDEShortCuts: TSpTBXItem; mnUnitTestWizard: TSpTBXItem; mnViewUnitTests: TSpTBXItem; TBXSeparatorItem16: TSpTBXSeparatorItem; mnLayouts: TSpTBXSubmenuItem; mnLayOutSeparator: TSpTBXSeparatorItem; tbiViewLayouts: TSpTBXSubmenuItem; TBXItem47: TSpTBXItem; TBXItem48: TSpTBXItem; TBXItem49: TSpTBXItem; mnMaximizeEditor: TSpTBXItem; TBXSeparatorItem17: TSpTBXSeparatorItem; TBXSeparatorItem18: TSpTBXSeparatorItem; TBXSubmenuItem4: TSpTBXSubmenuItem; TBXSeparatorItem19: TSpTBXSeparatorItem; mnNoSyntax: TSpTBXItem; TBXSeparatorItem20: TSpTBXSeparatorItem; TBXSeparatorItem21: TSpTBXSeparatorItem; mnSyntax: TSpTBXSubmenuItem; mnZoomOut: TSpTBXItem; mnZoomIn: TSpTBXItem; TBXSeparatorItem22: TSpTBXSeparatorItem; mnFiles: TSpTBXSubmenuItem; mnAddWatchAtCursor: TSpTBXItem; RunningProcessesPopUpMenu: TSpTBXPopupMenu; mnFileTemplates: TSpTBXItem; TBXSubmenuItem5: TSpTBXSubmenuItem; TBXSeparatorItem23: TSpTBXSeparatorItem; mnNewFile: TSpTBXItem; JvAppInstances: TJvAppInstances; mnEditAnsi: TSpTBXItem; mnEditUtf8NoBom: TSpTBXItem; mnuFindInFilesResults: TSpTBXItem; TBXSubmenuItem6: TSpTBXSubmenuItem; mnNavEditor: TSpTBXItem; TBXSeparatorItem24: TSpTBXSeparatorItem; mnNavCodeExplorer: TSpTBXItem; mnNavFileExplorer: TSpTBXItem; mnNavUnitTests: TSpTBXItem; mnNavOutput: TSpTBXItem; mnNavTodo: TSpTBXItem; TBXSeparatorItem25: TSpTBXSeparatorItem; mnNavMessages: TSpTBXItem; mnNavBreakpoints: TSpTBXItem; mnNavWatches: TSpTBXItem; mnNavVariables: TSpTBXItem; mnNavCallStack: TSpTBXItem; mnNavInterpreter: TSpTBXItem; tbiRunPause: TSpTBXItem; mnPause: TSpTBXItem; mnPythonEngines: TSpTBXSubmenuItem; mnEngineRemoteWx: TSpTBXItem; mnEngineRemoteTk: TSpTBXItem; mnEngineRemote: TSpTBXItem; mnEngineInternal: TSpTBXItem; mnReinitEngine: TSpTBXItem; TBXSeparatorItem26: TSpTBXSeparatorItem; TBXSeparatorItem27: TSpTBXSeparatorItem; mnExecSelection: TSpTBXItem; TBXItem77: TSpTBXItem; TBXSeparatorItem28: TSpTBXSeparatorItem; mnRestoreEditor2: TSpTBXItem; mnMaximizeEditor2: TSpTBXItem; mnFileReload: TSpTBXItem; TBXSeparatorItem29: TSpTBXSeparatorItem; TBXSubmenuItem7: TSpTBXSubmenuItem; mnImportShortcuts: TSpTBXItem; mnExportShortcuts: TSpTBXItem; TBXSeparatorItem30: TSpTBXSeparatorItem; mnImportHighlighters: TSpTBXItem; mnExportHighlighters: TSpTBXItem; mnViewMainMenu: TSpTBXItem; FindToolbar: TSpTBXToolbar; tbiFindLabel: TSpTBXLabelItem; tbiFindNext: TSpTBXItem; tbiFindPrevious: TSpTBXItem; tbiReplaceSeparator: TSpTBXSeparatorItem; tbiReplaceLabel: TSpTBXLabelItem; TBXSeparatorItem32: TSpTBXSeparatorItem; tbiSearchOptions: TSpTBXSubmenuItem; tbiWholeWords: TSpTBXItem; tbiSearchInSelection: TSpTBXItem; tbiRegExp: TSpTBXItem; tbiCaseSensitive: TSpTBXItem; tbiIncrementalSearch: TSpTBXItem; SpTBXSeparatorItem1: TSpTBXSeparatorItem; tbiHighlight: TSpTBXItem; tbiReplaceExecute: TSpTBXItem; SpTBXSeparatorItem2: TSpTBXSeparatorItem; tbiSearchFromCaret: TSpTBXItem; TBXSeparatorItem31: TSpTBXSeparatorItem; mnGotoSyntaxError: TSpTBXItem; mnSearchHighlight: TSpTBXItem; tbiEditWordWrap: TSpTBXItem; mnGoToDebugLine: TSpTBXItem; mnSplitEditors: TSpTBXSubmenuItem; mnSplitEditorVer: TSpTBXItem; mnSplitEditorHor: TSpTBXItem; mnHideSecondEditor: TSpTBXItem; TBXSeparatorItem33: TSpTBXSeparatorItem; mnPostMortem: TSpTBXItem; SpTBXCustomizer: TSpTBXCustomizer; ToolbarPopupMenu: TSpTBXPopupMenu; SpTBXSeparatorItem3: TSpTBXSeparatorItem; mnViewCustomizeToolbars: TSpTBXItem; UserToolbar: TSpTBXToolbar; JvFormStorage: TJvFormStorage; mnNavProjectExplorer: TSpTBXItem; mnViewProjectExplorer: TSpTBXItem; ProjectMenu: TSpTBXSubmenuItem; mnProjectSaveAs: TSpTBXItem; mnProjectSave: TSpTBXItem; mnProjectOpen: TSpTBXItem; mnProjectNew: TSpTBXItem; SpTBXSeparatorItem4: TSpTBXSeparatorItem; mnNavProjectExplorer2: TSpTBXItem; SpTBXSubmenuItem2: TSpTBXSubmenuItem; mnHelpProjectHome: TSpTBXItem; mnHelpWebSupport: TSpTBXItem; mnFileCloseAllOther: TSpTBXItem; mnEditUtf16BE: TSpTBXItem; mnEditUtf16LE: TSpTBXItem; StatusBar: TSpTBXStatusBar; SpTBXSeparatorItem5: TSpTBXSeparatorItem; lbStatusMessage: TSpTBXLabelItem; SpTBXRightAlignSpacerItem1: TSpTBXRightAlignSpacerItem; lbStatusCaret: TSpTBXLabelItem; SpTBXSeparatorItem6: TSpTBXSeparatorItem; lbStatusModified: TSpTBXLabelItem; SpTBXSeparatorItem7: TSpTBXSeparatorItem; lbStatusOverwrite: TSpTBXLabelItem; SpTBXSeparatorItem8: TSpTBXSeparatorItem; lbStatusCaps: TSpTBXLabelItem; SpTBXSeparatorItem9: TSpTBXSeparatorItem; StatusLED: TAMHLEDVecStd; tbciStatusLed: TTBControlItem; ExternalToolsLED: TAMHLEDVecStd; tbciStatusExternal: TTBControlItem; SpTBXSeparatorItem10: TSpTBXSeparatorItem; mnMainToolbarVisibilityToggle: TSpTBXItem; mnDebugtoolbarVisibilityToggle: TSpTBXItem; mnEditorToolbarVisibilityToggle: TSpTBXItem; mnViewToolbarVisibilityToggle: TSpTBXItem; mnuUserToolbarVisibilityToggle: TSpTBXItem; mnLanguage: TSpTBXSubmenuItem; actlImmutable: TActionList; actViewPreviousEditor: TAction; actViewNextEditor: TAction; actlStandard: TActionList; actNavProjectExplorer: TAction; actViewProjectExplorer: TAction; actViewCustomizeToolbars: TAction; actPostMortem: TAction; actViewHideSecondEditor: TAction; actViewSplitEditorHor: TAction; actExecSelection: TAction; actNavEditor: TAction; actNavOutput: TAction; actNavUnitTests: TAction; actNavTodo: TAction; actNavCodeExplorer: TAction; actNavFileExplorer: TAction; actNavMessages: TAction; actNavCallStack: TAction; actNavVariables: TAction; actNavInterpreter: TAction; actNavBreakpoints: TAction; actNavWatches: TAction; actNewFile: TAction; actPythonRemoteWx: TAction; actPythonRemoteTk: TAction; actPythonRemote: TAction; actPythonInternal: TAction; actPythonReinitialize: TAction; actAddWatchAtCursor: TAction; actViewSplitEditorVer: TAction; actEditorZoomOut: TAction; actEditorZoomIn: TAction; actMaximizeEditor: TAction; actLayoutDebug: TAction; actLayoutsDelete: TAction; actLayoutSave: TAction; actViewRegExpTester: TAction; actBrowseForward: TAction; actBrowseBack: TAction; actFindReferences: TAction; actFindDefinition: TAction; actViewUnitTests: TAction; actViewOutput: TAction; actViewFindResults: TAction; actViewToDoList: TAction; actViewFileExplorer: TAction; actViewCodeExplorer: TAction; actViewII: TAction; actMessagesWin: TAction; actWatchesWin: TAction; actBreakPointsWin: TAction; actClearAllBreakpoints: TAction; actToggleBreakPoint: TAction; actRunLastScript: TAction; actRunLastScriptExternal: TAction; actDebugAbort: TAction; actDebugPause: TAction; actStepOut: TAction; actStepOver: TAction; actStepInto: TAction; actRunToCursor: TAction; actRestoreEditor: TAction; actDebug: TAction; actRunDebugLastScript: TAction; actExternalRunConfigure: TAction; actExternalRun: TAction; actViewStatusBar: TAction; actFileExit: TAction; actFileCloseAll: TAction; actFileOpen: TAction; actFileNewModule: TAction; actImportModule: TAction; actCommandLine: TAction; actRun: TAction; actSyntaxCheck: TAction; actVariablesWin: TAction; actCallStackWin: TAction; actViewMainMenu: TAction; tbiRecentFileList: TSpTBXMRUListItem; mnPreviousList: TSpTBXMRUListItem; mnNextList: TSpTBXMRUListItem; tbiSearchText: TSpTBXComboBox; TBControlItem2: TTBControlItem; tbiReplaceText: TSpTBXComboBox; TBControlItem4: TTBControlItem; TabControl1: TSpTBXTabControl; tbiRightAlign: TSpTBXRightAlignSpacerItem; tbiScrollLeft: TSpTBXItem; tbiTabClose: TSpTBXItem; tbiScrollRight: TSpTBXItem; tbiTabFiles: TSpTBXSubmenuItem; tbiTabSep: TSpTBXSeparatorItem; SpTBXSeparatorItem11: TSpTBXSeparatorItem; SpTBXItem1: TSpTBXItem; SpTBXSeparatorItem12: TSpTBXSeparatorItem; SpTBXItem2: TSpTBXItem; SpTBXItem3: TSpTBXItem; TabControl2: TSpTBXTabControl; SpTBXRightAlignSpacerItem2: TSpTBXRightAlignSpacerItem; SpTBXSeparatorItem13: TSpTBXSeparatorItem; tbiTabFiles2: TSpTBXSubmenuItem; tbiScrollLeft2: TSpTBXItem; tbiScrollRight2: TSpTBXItem; tbiTabClose2: TSpTBXItem; TabSplitter: TSpTBXSplitter; actViewSplitWorkspaceVer: TAction; actViewSplitWorkspaceHor: TAction; actViewHideSecondaryWorkspace: TAction; mnSplitWorkspace: TSpTBXSubmenuItem; SpTBXItem7: TSpTBXItem; SpTBXItem8: TSpTBXItem; SpTBXItem9: TSpTBXItem; SpTBXSeparatorItem14: TSpTBXSeparatorItem; SpTBXSeparatorItem15: TSpTBXSeparatorItem; SpTBXSeparatorItem16: TSpTBXSeparatorItem; SpTBXSubmenuItem1: TSpTBXSubmenuItem; tbiRecentProjects: TSpTBXMRUListItem; tbiAutoCaseSensitive: TSpTBXItem; actSelectStyle: TAction; tbiSelectStyle: TSpTBXItem; SpTBXItem5: TSpTBXItem; LocalAppStorage: TJvAppIniFileStorage; SpTBXSeparatorItem17: TSpTBXSeparatorItem; mnPythonVersions: TSpTBXSubmenuItem; tbiSelectPythonVersion: TSpTBXSubmenuItem; actPythonSetup: TAction; SpTBXSeparatorItem18: TSpTBXSeparatorItem; SpTBXItem4: TSpTBXItem; SpTBXItem6: TSpTBXItem; SpTBXSeparatorItem19: TSpTBXSeparatorItem; SpTBXItem10: TSpTBXItem; SpTBXSeparatorItem20: TSpTBXSeparatorItem; SpTBXItem11: TSpTBXItem; actRemoteFileOpen: TAction; SpTBXSeparatorItem21: TSpTBXSeparatorItem; SpTBXItem12: TSpTBXItem; SpTBXItem13: TSpTBXItem; actPythonSSH: TAction; mnPythonEngineSSH: TSpTBXItem; SpTBXItem14: TSpTBXItem; SpTBXSeparatorItem22: TSpTBXSeparatorItem; lbPythonVersion: TSpTBXLabelItem; SpTBXSeparatorItem23: TSpTBXSeparatorItem; lbPythonEngine: TSpTBXLabelItem; vilImages: TVirtualImageList; procedure mnFilesClick(Sender: TObject); procedure actEditorZoomInExecute(Sender: TObject); procedure actEditorZoomOutExecute(Sender: TObject); procedure mnNoSyntaxClick(Sender: TObject); procedure mnSyntaxPopup(Sender: TTBCustomItem; FromLink: Boolean); procedure actMaximizeEditorExecute(Sender: TObject); procedure actLayoutDebugExecute(Sender: TObject); procedure actLayoutsDeleteExecute(Sender: TObject); procedure actLayoutSaveExecute(Sender: TObject); procedure actViewUnitTestsExecute(Sender: TObject); procedure actCommandLineExecute(Sender: TObject); procedure JvAppInstancesCmdLineReceived(Sender: TObject; CmdLine: TStrings); procedure actViewRegExpTesterExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure TabContolContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean); procedure actSyntaxCheckExecute(Sender: TObject); procedure actRunExecute(Sender: TObject); procedure actToggleBreakPointExecute(Sender: TObject); procedure actClearAllBreakpointsExecute(Sender: TObject); procedure actDebugExecute(Sender: TObject); procedure actStepIntoExecute(Sender: TObject); procedure actStepOverExecute(Sender: TObject); procedure actStepOutExecute(Sender: TObject); procedure actRunToCursorExecute(Sender: TObject); procedure actDebugAbortExecute(Sender: TObject); procedure actViewIIExecute(Sender: TObject); procedure actMessagesWinExecute(Sender: TObject); procedure actNextEditorExecute(Sender: TObject); procedure actPreviousEditorExecute(Sender: TObject); procedure actCallStackWinExecute(Sender: TObject); procedure actVariablesWinExecute(Sender: TObject); procedure actBreakPointsWinExecute(Sender: TObject); procedure actWatchesWinExecute(Sender: TObject); procedure actViewCodeExplorerExecute(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure actViewStatusBarExecute(Sender: TObject); procedure actFileExitExecute(Sender: TObject); procedure actFileNewModuleExecute(Sender: TObject); procedure actFileOpenExecute(Sender: TObject); procedure actFileCloseAllExecute(Sender: TObject); procedure actViewFileExplorerExecute(Sender: TObject); procedure TabControlTabClosing(Sender: TObject; var Allow, CloseAndFree: Boolean); procedure FormShortCut(var Msg: TWMKey; var Handled: Boolean); procedure CloseTimerTimer(Sender: TObject); procedure actImportModuleExecute(Sender: TObject); procedure actViewToDoListExecute(Sender: TObject); procedure actViewFindResultsExecute(Sender: TObject); procedure actViewOutputExecute(Sender: TObject); procedure actExternalRunExecute(Sender: TObject); procedure actExternalRunConfigureExecute(Sender: TObject); procedure actFindDefinitionExecute(Sender: TObject); procedure actFindReferencesExecute(Sender: TObject); procedure PreviousListClick(Sender: TObject; S : string); procedure tbiBrowsePreviousClick(Sender: TObject); procedure NextListClick(Sender: TObject; S : string); procedure tbiBrowseNextClick(Sender: TObject); function ApplicationHelp(Command: Word; Data: NativeInt; var CallHelp: Boolean): Boolean; procedure FormShow(Sender: TObject); procedure actAddWatchAtCursorExecute(Sender: TObject); procedure actNewFileExecute(Sender: TObject); procedure actNavWatchesExecute(Sender: TObject); procedure actNavBreakpointsExecute(Sender: TObject); procedure actNavInterpreterExecute(Sender: TObject); procedure actNavVariablesExecute(Sender: TObject); procedure actNavCallStackExecute(Sender: TObject); procedure actNavMessagesExecute(Sender: TObject); procedure actNavFileExplorerExecute(Sender: TObject); procedure actNavCodeExplorerExecute(Sender: TObject); procedure actNavTodoExecute(Sender: TObject); procedure actNavUnitTestsExecute(Sender: TObject); procedure actNavOutputExecute(Sender: TObject); procedure actNavRETesterExecute(Sender: TObject); procedure actNavEditorExecute(Sender: TObject); procedure actDebugPauseExecute(Sender: TObject); procedure actPythonReinitializeExecute(Sender: TObject); procedure actPythonEngineExecute(Sender: TObject); procedure actExecSelectionExecute(Sender: TObject); procedure actRestoreEditorExecute(Sender: TObject); procedure actViewMainMenuExecute(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure TabControlMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure SearchOptionsChanged(Sender: TObject); procedure tbiSearchOptionsPopup(Sender: TTBCustomItem; FromLink: Boolean); procedure tbiSearchTextChange(Sender: TObject); procedure tbiSearchTextKeyPress(Sender: TObject; var Key: Char); procedure tbiReplaceTextChange(Sender: TObject); procedure actViewSplitEditorVerExecute(Sender: TObject); procedure actViewSplitEditorHorExecute(Sender: TObject); procedure actViewHideSecondEditorExecute(Sender: TObject); procedure actPostMortemExecute(Sender: TObject); procedure FindToolbarVisibleChanged(Sender: TObject); procedure actViewCustomizeToolbarsExecute(Sender: TObject); procedure SpTBXCustomizerGetCustomizeForm(Sender: TObject; var CustomizeFormClass: TSpTBXCustomizeFormClass); procedure actViewProjectExplorerExecute(Sender: TObject); procedure actNavProjectExplorerExecute(Sender: TObject); procedure actRunLastScriptExternalExecute(Sender: TObject); procedure actRunLastScriptExecute(Sender: TObject); procedure actRunDebugLastScriptExecute(Sender: TObject); procedure EditorViewsMenuClick(Sender: TObject); procedure tbiRecentFileListClick(Sender: TObject; const Filename: string); procedure tbiSearchTextExit(Sender: TObject); procedure tbiReplaceTextKeyPress(Sender: TObject; var Key: Char); procedure TabControlActiveTabChange(Sender: TObject; TabIndex: Integer); procedure tbiScrollLeftClick(Sender: TObject); procedure tbiScrollRightClick(Sender: TObject); procedure actViewSplitWorkspaceVerExecute(Sender: TObject); procedure actViewSplitWorkspaceHorExecute(Sender: TObject); procedure actViewHideSecondaryWorkspaceExecute(Sender: TObject); procedure tbiRecentProjectsClick(Sender: TObject; const Filename: string); procedure actSelectStyleExecute(Sender: TObject); procedure mnPythonVersionsPopup(Sender: TTBCustomItem; FromLink: Boolean); procedure PythonVersionsClick(Sender: TObject); procedure actPythonSetupExecute(Sender: TObject); procedure actRemoteFileOpenExecute(Sender: TObject); procedure lbPythonVersionClick(Sender: TObject); procedure lbPythonEngineClick(Sender: TObject); procedure lbStatusCaretClick(Sender: TObject); private DSAAppStorage: TDSAAppStorage; ShellExtensionFiles : TStringList; // function FindAction(var Key: Word; Shift: TShiftState) : TCustomAction; procedure DebugActiveScript(ActiveEditor: IEditor; InitStepIn : Boolean = False; RunToCursorLine : integer = -1); procedure SetupRunConfiguration(var RunConfig: TRunConfiguration; ActiveEditor: IEditor); procedure tbiSearchTextAcceptText(const NewText: string); procedure tbiReplaceTextAcceptText(const NewText: string); procedure DrawCloseButton(Sender: TObject; ACanvas: TCanvas; State: TSpTBXSkinStatesType; const PaintStage: TSpTBXPaintStage; var AImageList: TCustomImageList; var AImageIndex: Integer; var ARect: TRect; var PaintDefault: Boolean); function GetActiveTabControl: TSpTBXCustomTabControl; procedure SetActiveTabControl(const Value: TSpTBXCustomTabControl); procedure ApplyIDEOptionsToEditor(Editor: IEditor); procedure OpenInitialFiles; protected fCurrentBrowseInfo : string; function DoCreateEditor(TabControl : TSpTBXTabControl): IEditor; function CmdLineOpenFiles(): boolean; function OpenCmdLineFile(FileName : string) : Boolean; procedure DebuggerBreakpointChange(Sender: TObject; Editor : IEditor; ALine: integer); procedure DebuggerCurrentPosChange(Sender: TObject; const OldPos, NewPos: TEditorPos); procedure DebuggerErrorPosChange(Sender: TObject; const OldPos, NewPos: TEditorPos); procedure UpdateStandardActions; procedure UpdateStatusBarPanels; procedure ApplicationOnHint(Sender: TObject); procedure ApplcationOnShowHint(var HintStr: string; var CanShow: Boolean; var HintInfo: Vcl.Controls.THintInfo); procedure ApplicationActionUpdate(Action: TBasicAction; var Handled: Boolean); procedure ApplicationActionExecute(Action: TBasicAction; var Handled: Boolean); procedure TabToolBarDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure TabToolbarlDragDrop(Sender, Source: TObject; X, Y: Integer); procedure WMFindDefinition(var Msg: TMessage); message WM_FINDDEFINITION; procedure WMSearchReplaceAction(var Msg: TMessage); message WM_SEARCHREPLACEACTION; procedure WMCheckForUpdates(var Msg: TMessage); message WM_CHECKFORUPDATES; procedure WMSpSkinChange(var Message: TMessage); message WM_SPSKINCHANGE; procedure CMStyleChanged(var Message: TMessage); message CM_STYLECHANGED; procedure SyntaxClick(Sender : TObject); procedure SelectEditor(Sender : TObject); procedure mnLanguageClick(Sender: TObject); // Browse MRU stuff procedure PrevClickHandler(Sender: TObject); procedure NextClickHandler(Sender: TObject); procedure PrevMRUAdd(S : string); procedure NextMRUAdd(S : string); private OldMonitorProfile : string; // IIDELayouts implementation function LayoutExists(const Layout: string): Boolean; procedure LoadLayout(const Layout : string); procedure SaveLayout(const Layout : string); // IPyIDEServices implementation function GetActiveEditor : IEditor; procedure WriteStatusMsg(const S : string); function ShowFilePosition(FileName : string; Line, Offset : integer; SelLen : integer = 0; ForceToMiddle : boolean = True; FocusEditor : boolean = True) : boolean; procedure ClearPythonWindows; procedure SaveEnvironment; procedure SaveFileModules; procedure SetRunLastScriptHints(const ScriptName : string); function GetStoredScript(const Name: string): TStrings; function GetMessageServices: IMessageServices; function GetUnitTestServices: IUnitTestServices; function GetIDELayouts: IIDELayouts; function GetAppStorage: TJvCustomAppStorage; function GetLocalAppStorage: TJvCustomAppStorage; public JvDockVSNetStyleSpTBX: TJvDockVSNetStyleSpTBX; ActiveTabControlIndex : integer; PythonKeywordHelpRequested : Boolean; MenuHelpRequested : Boolean; Layouts : TStringList; fLanguageList : TStringList; procedure ScaleForPPI(NewPPI: Integer); override; procedure StoreApplicationData; procedure RestoreApplicationData; procedure StoreLocalApplicationData; procedure RestoreLocalApplicationData; function DoOpenFile(AFileName: string; HighlighterName : string = ''; TabControlIndex : integer = 1) : IEditor; function NewFileFromTemplate(FileTemplate : TFileTemplate; TabControlIndex : integer = 1) : IEditor; procedure UpdateDebugCommands(DebuggerState : TDebuggerState); procedure DebuggerStateChange(Sender: TObject; OldState, NewState: TDebuggerState); procedure ApplicationOnIdle(Sender: TObject; var Done: Boolean); procedure DebuggerYield(Sender: TObject; DoIdle : Boolean); procedure PyIDEOptionsChanged(Sender: TObject); procedure SetupCustomizer; procedure SetupLanguageMenu; procedure SetupToolsMenu; procedure SetupLayoutsMenu; procedure SetupSyntaxMenu; procedure SetupPythonVersionsMenu; procedure LayoutClick(Sender : TObject); procedure LoadToolbarLayout(const Layout: string); procedure LoadToolbarItems(const Path : string); procedure SaveToolbarLayout(const Layout: string); procedure SaveToolbarItems(const Path : string); function JumpToFilePosInfo(FilePosInfo : string) : boolean; procedure FindDefinition(Editor : IEditor; TextCoord : TBufferCoord; ShowMessages, Silent, JumpToFirstMatch : Boolean; var FilePosInfo : string); procedure AdjustBrowserLists(FileName: string; Line: Integer; Col: Integer; FilePosInfo: string); procedure ThemeEditorGutter(Gutter : TSynGutter); procedure UpdateCaption; procedure ChangeLanguage(LangCode : string); function EditorFromTab(Tab : TSpTBXTabItem) : IEditor; procedure SplitWorkspace(SecondTabsVisible : Boolean; Alignment : TAlign = alRight; Size : integer = -1); procedure MoveTab(Tab : TSpTBXTabItem; TabControl : TSpTBXTabControl; Index : integer = -1); function TabControl(TabControlIndex : integer = 1) : TSpTBXTabControl; function TabControlIndex(TabControl : TSpTBXCustomTabControl) : integer; procedure ConfigureFileExplorer(FCN : TFileChangeNotificationType; BackgroundProcessing : Boolean); procedure ShowIDEDockForm(Form: TForm); property ActiveTabControl : TSpTBXCustomTabControl read GetActiveTabControl write SetActiveTabControl; end; Const ctkRemember : TDSACheckTextKind = 100; FactoryToolbarItems = 'Factory Toolbar Items v1.0'; var PyIDEMainForm: TPyIDEMainForm; implementation uses Winapi.ShellAPI, System.Contnrs, System.Math, System.IniFiles, System.DateUtils, System.RegularExpressions, Vcl.Clipbrd, Vcl.StdActns, Vcl.Themes, JvCreateProcess, JclSysInfo, JclFileUtils, JclStrings, JclSysUtils, JvJVCLUtils, SpTBXControls, VirtualTrees, VirtualExplorerTree, MPDataObject, SynHighlighterPython, SynEditHighlighter, SynEditKeyCmds, SynCompletionProposal, PythonEngine, PythonVersions, VarPyth, JvGnugettext, StringResources, uCmdLine, uCommonFunctions, uSearchHighlighter, uParams, dlgNewFile, dlgCommandLine, dlgToolProperties, dlgStyleSelector, dlgPickList, frmEditor, frmIDEDockWin, frmCommandOutput, frmPythonII, frmProjectExplorer, frmMessages, frmCallStack, frmBreakPoints, frmVariables, frmWatches, frmCodeExplorer, frmFileExplorer, frmRegExpTester, frmUnitTests, frmToDo, frmFindResults, frmWebPreview, frmModSpTBXCustomize, cTools, cParameters, cPythonSourceScanner, cFilePersist, cCodeHint, cPyRemoteDebugger, cProjectClasses, dlgPythonVersions, dlgRemoteFile, cSSHSupport; {$R *.DFM} { TWorkbookMainForm } function TPyIDEMainForm.DoCreateEditor(TabControl : TSpTBXTabControl): IEditor; begin if GI_EditorFactory <> nil then begin Result := GI_EditorFactory.CreateTabSheet(TabControl); Result.SynEdit.Assign(EditorOptions); Result.SynEdit2.Assign(EditorOptions); TEditorForm(Result.Form).ParentTabItem.OnTabClosing := TabControlTabClosing; TEditorForm(Result.Form).ParentTabItem.OnDrawTabCloseButton := DrawCloseButton; ApplyIDEOptionsToEditor(Result); end else Result := nil; end; function TPyIDEMainForm.DoOpenFile(AFileName: string; HighlighterName : string = ''; TabControlIndex : integer = 1) : IEditor; Var IsRemote : Boolean; Server, FName : string; TabCtrl : TSpTBXTabControl; begin Result := nil; IsRemote := TSSHFileName.Parse(AFileName, Server, FName); // activate the editor if already open if IsRemote then begin Result := GI_EditorFactory.GetEditorByNameOrTitle(AFileName); if Assigned(Result) then begin Result.Activate; Exit; end; end else if AFileName <> '' then begin AFileName := GetLongFileName(ExpandFileName(AFileName)); Result := GI_EditorFactory.GetEditorByName(AFileName); if Assigned(Result) then begin Result.Activate; Exit; end; end; // create a new editor, add it to the editor list, open the file TabCtrl := TabControl(TabControlIndex); TabCtrl.Toolbar.BeginUpdate; try Result := DoCreateEditor(TabCtrl); if Result <> nil then begin try if IsRemote then Result.OpenRemoteFile(FName, Server) else Result.OpenFile(AFileName, HighlighterName); tbiRecentFileList.MRURemove(AFileName); Result.Activate; except Result.Close; raise end; if (AFileName <> '') and (GI_EditorFactory.Count = 2) and (GI_EditorFactory.Editor[0].FileName = '') and (GI_EditorFactory.Editor[0].RemoteFileName = '') and not GI_EditorFactory.Editor[0].Modified then GI_EditorFactory.Editor[0].Close; if (AFileName = '') and (HighlighterName = 'Python') then TEditorForm(Result.Form).DefaultExtension := 'py'; end; finally TabCtrl.Toolbar.EndUpdate; if Assigned(TabCtrl.ActiveTab) then TabCtrl.MakeVisible(TabCtrl.ActiveTab); UpdateCaption; end; end; procedure TPyIDEMainForm.EditorViewsMenuClick(Sender: TObject); begin GI_EditorFactory.UpdateEditorViewMenu; end; type TTBCustomItemAccess = class(TTBCustomItem); procedure TPyIDEMainForm.FormCreate(Sender: TObject); Var TabHost : TJvDockTabHostForm; LocalOptionsFileName: string; begin // Create JvDockVSNetStyleSpTBX JvDockVSNetStyleSpTBX := TJvDockVSNetStyleSpTBX.Create(Self); JvDockVSNetStyleSpTBX.Name := 'JvDockVSNetStyleSpTBX'; JvDockVSNetStyleSpTBX.AlwaysShowGrabber := False; DockServer.DockStyle := JvDockVSNetStyleSpTBX; // App Instances ShellExtensionFiles := TStringList.Create; if not CmdLineReader.readFlag('NEWINSTANCE') then begin JvAppInstances.Active := True; JvAppInstances.Check; end; // Notifications SkinManager.AddSkinNotification(Self); PyIDEOptions.OnChange.AddHandler(PyIDEOptionsChanged); // JvDocking Fonts with JvDockVSNetStyleSpTBX.TabServerOption as TJvDockVIDTabServerOption do begin ActiveFont.Assign(ToolbarFont); InactiveFont.Assign(ToolbarFont); end; // Layout stuff Layouts := TStringList.Create; Layouts.Sorted := True; Layouts.Duplicates := dupError; // GI_PyIDEServices GI_PyIDEServices := Self; // Application Storage AppStorage.Encoding := TEncoding.UTF8; AppStorage.FileName := TPyScripterSettings.OptionsFileName; // LocalAppStorage LocalOptionsFileName := ChangeFileExt(ExtractFileName(Application.ExeName), '.local.ini'); LocalAppStorage.FileName := TPyScripterSettings.UserDataPath + LocalOptionsFileName; //OutputDebugString(PWideChar(Format('%s ElapsedTime %d ms', ['Before All Forms', StopWatch.ElapsedMilliseconds]))); // Create and layout IDE windows PythonIIForm := TPythonIIForm.Create(self); PythonIIForm.PopupParent := Self; CallStackWindow := TCallStackWindow.Create(Self); CallStackWindow.PopupParent := Self; VariablesWindow := TVariablesWindow.Create(Self); VariablesWindow.PopupParent := Self; WatchesWindow := TWatchesWindow.Create(Self); WatchesWindow.PopupParent := Self; BreakPointsWindow := TBreakPointsWindow.Create(Self); BreakPointsWindow.PopupParent := Self; OutputWindow := TOutputWindow.Create(Self); OutputWindow.PopupParent := Self; MessagesWindow := TMessagesWindow.Create(Self); MessagesWindow.PopupParent := Self; CodeExplorerWindow := TCodeExplorerWindow.Create(Self); CodeExplorerWindow.PopupParent := Self; FileExplorerWindow := TFileExplorerWindow.Create(Self); FileExplorerWindow.PopupParent := Self; ToDoWindow := TToDoWindow.Create(Self); ToDoWindow.PopupParent := Self; RegExpTesterWindow := TRegExpTesterWindow.Create(Self); RegExpTesterWindow.PopupParent := Self; UnitTestWindow := TUnitTestWindow.Create(Self); UnitTestWindow.PopupParent := Self; FindResultsWindow := TFindResultsWindow.Create(Self); FindResultsWindow.PopupParent := Self; ProjectExplorerWindow := TProjectExplorerWindow.Create(Self); ProjectExplorerWindow.PopupParent := Self; // And now translate after all the docking forms have been created // They will be translated as well TP_GlobalIgnoreClass(TJvFormStorage); TP_GlobalIgnoreClass(TJvAppIniFileStorage); TranslateComponent(Self); //OutputDebugString(PWideChar(Format('%s ElapsedTime %d ms', ['After Translate', StopWatch.ElapsedMilliseconds]))); // Setup Languages fLanguageList := TStringList.Create; SetUpLanguageMenu; // ActionLists TActionProxyCollection.ActionLists := [actlStandard, CommandsDataModule.actlMain, PythonIIForm.InterpreterActionList, ProjectExplorerWindow.ProjectActionList, CallStackWindow.actlCallStack]; // Read Settings from PyScripter.ini if FileExists(AppStorage.IniFile.FileName) then RestoreApplicationData else PyIDEOptions.Changed; // Read Settings from PyScripter.local.ini if FileExists(LocalAppStorage.IniFile.FileName) then begin RestoreLocalApplicationData; if OldMonitorProfile = MonitorProfile then JvFormStorage.RestoreFormPlacement else WindowState := wsMaximized; end else WindowState := wsMaximized; // DSA stuff DSAAppStorage := TDSAAppStorage.Create(AppStorage, 'DSA'); RegisterDSACheckMarkText(ctkRemember, _(SDSActkRememberText)); RegisterDSA(dsaSearchFromStart, 'SearchFromStart', 'Search from start question', DSAAppStorage, ctkRemember); RegisterDSA(dsaReplaceFromStart, 'ReplaceFromStart', 'Replace from start question', DSAAppStorage, ctkRemember); RegisterDSA(dsaReplaceNumber, 'ReplaceNumber', 'Information about number of replacements', DSAAppStorage, ctkShow); RegisterDSA(dsaSearchStartReached, 'SearchStartReached', 'Information: search start reached', DSAAppStorage, ctkShow); RegisterDSA(dsaPostMortemInfo, 'PostMortemInfo', 'Instructions: Post Mortem', DSAAppStorage, ctkShow); // Store Factory Settings if not AppStorage.PathExists(FactoryToolbarItems) then SaveToolbarItems(FactoryToolbarItems); if (OldMonitorProfile = MonitorProfile) and LocalAppStorage.PathExists('Layouts\Default\Forms') and LocalAppStorage.PathExists('Layouts\Current\Forms') then begin try //OutputDebugString(PWideChar(Format('%s ElapsedTime %d ms', ['Before LoadLayout', StopWatch.ElapsedMilliseconds]))); LoadLayout('Current'); //OutputDebugString(PWideChar(Format('%s ElapsedTime %d ms', ['After LoadLayout', StopWatch.ElapsedMilliseconds]))); except LocalAppStorage.DeleteSubTree('Layouts\Default'); if Layouts.IndexOf('Default') >= 0 then Layouts.Delete(Layouts.IndexOf('Default')); Vcl.Dialogs.MessageDlg(Format(_(SErrorLoadLayout), [LocalAppStorage.IniFile.FileName]), mtError, [mbOK], 0); end; LocalAppStorage.DeleteSubTree('Layouts\Current'); end else begin TabHost := ManualTabDock(DockServer.LeftDockPanel, FileExplorerWindow, ProjectExplorerWindow); DockServer.LeftDockPanel.Width := PPIScale(200); ManualTabDockAddPage(TabHost, CodeExplorerWindow); ShowDockForm(FileExplorerWindow); TabHost := ManualTabDock(DockServer.BottomDockPanel, CallStackWindow, VariablesWindow); DockServer.BottomDockPanel.Height := PPIScale(150); ManualTabDockAddPage(TabHost, WatchesWindow); ManualTabDockAddPage(TabHost, BreakPointsWindow); ManualTabDockAddPage(TabHost, OutputWindow); ManualTabDockAddPage(TabHost, MessagesWindow); ManualTabDockAddPage(TabHost, PythonIIForm); ShowDockForm(PythonIIForm); Application.ProcessMessages; end; Application.OnIdle := ApplicationOnIdle; Application.OnHint := ApplicationOnHint; Application.OnShowHint := ApplcationOnShowHint; Application.OnActionUpdate := ApplicationActionUpdate; Application.OnActionExecute := ApplicationActionExecute; // Editor Views Menu GI_EditorFactory.SetupEditorViewMenu; //Update; // Tab Conrol Drag Drop and other TabControl events TabControl1.Toolbar.OnDragOver := TabToolbarDragOver; TabControl1.Toolbar.OnDragDrop := TabToolbarlDragDrop; TabControl2.Toolbar.OnDragOver := TabToolbarDragOver; TabControl2.Toolbar.OnDragDrop := TabToolbarlDragDrop; TabControl1.Toolbar.OnMouseDown := TabControlMouseDown; TabControl2.Toolbar.OnMouseDown := TabControlMouseDown; //Set the HelpFile Application.HelpFile := ExtractFilePath(Application.ExeName) + 'PyScripter.chm'; Application.OnHelp := Self.ApplicationHelp; //Flicker MainMenu.DoubleBuffered := True; MainToolBar.DoubleBuffered := True; DebugToolbar.DoubleBuffered := True; ViewToolbar.DoubleBuffered := True; EditorToolbar.DoubleBuffered := True; UserToolbar.DoubleBuffered := True; SkinManager.AddSkinNotification(Self); SkinManager.BroadcastSkinNotification; end; procedure TPyIDEMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if JvGlobalDockIsLoading then begin CanClose := False; CloseTimer.Enabled := True; Exit; end else if PyControl.DebuggerState <> dsInactive then begin if Vcl.Dialogs.MessageDlg(_(SAbortDebugging), mtWarning, [mbYes, mbNo], 0) = mrYes then begin if (PyControl.DebuggerState in [dsPaused, dsPostMortem]) or (PyControl.ActiveDebugger is TPyInternalDebugger) then begin CanClose := False; PyControl.ActiveDebugger.Abort; CloseTimer.Enabled := True; Exit; end else begin CanClose := False; PyControl.ActiveInterpreter.ReInitialize; CloseTimer.Enabled := True; Exit; end; end else begin // mrNo CanClose := False; Exit; end; end; if OutputWindow.JvCreateProcess.State <> psReady then if Vcl.Dialogs.MessageDlg(_(SKillExternalTool), mtConfirmation, [mbYes, mbCancel], 0) = mrYes then begin OutputWindow.actToolTerminateExecute(Self); CanClose := True; end else CanClose := False; // Ask about saving unsaved editor buffers if CanClose and (GI_EditorFactory <> nil) then CanClose := GI_EditorFactory.CanCloseAll; // Ask about saving unsaved project CanClose := CanClose and ProjectExplorerWindow.CanClose; if CanClose then begin // Shut down CodeExplorerWindow Worker thread CodeExplorerWindow.ShutDownWorkerThread; // Disconnect ChangeNotify FileExplorerWindow.FileExplorerTree.Active := False; ConfigureFileExplorer(fcnDisabled, False); // Disable CodeHint timer CodeHint.CancelHint; // Shut down help Application.OnHelp := nil; // QC25183 try Application.HelpCommand(HELP_QUIT, 0); except end; // Stop accepting files DragAcceptFiles(TabControl1.Handle, False); DragAcceptFiles(TabControl2.Handle, False); ClearPythonWindows; // Give the time to the treads to terminate Sleep(200); // We need to do this here so that MRU and docking information are persisted try SaveEnvironment; except on E: EFileStreamError do Vcl.Dialogs.MessageDlg(Format(_(SFileSaveError), [AppStorage.FullFileName, E.Message]), mtError, [mbOK], 0); end; TabControl1.Toolbar.BeginUpdate; TabControl2.Toolbar.BeginUpdate; try if GI_EditorFactory <> nil then GI_EditorFactory.CloseAll; finally TabControl1.Toolbar.EndUpdate; TabControl2.Toolbar.EndUpdate; end; SkinManager.RemoveSkinNotification(Self); end; end; procedure TPyIDEMainForm.TabContolContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean); Var IV: TTBItemViewer; TabCtrl : TSpTBXTabControl; begin TabCtrl := Sender as TSpTBXTabControl; ActiveTabControl := TabCtrl; IV := TabCtrl.View.ViewerFromPoint( TabCtrl.Toolbar.ScreenToClient(TabCtrl.ClientToScreen(MousePos))); if Assigned(IV) and (IV.Item is TSpTBXTabItem) then IV.Item.Checked := True; //To update File Close CommandsDataModule.UpdateMainActions; Handled := False; end; procedure TPyIDEMainForm.actNavBreakpointsExecute(Sender: TObject); begin ShowDockForm(BreakPointsWindow); BreakPointsWindow.FormActivate(Sender); end; procedure TPyIDEMainForm.actNavCallStackExecute(Sender: TObject); begin ShowDockForm(CallStackWindow); CallStackWindow.FormActivate(Sender); end; procedure TPyIDEMainForm.actNavCodeExplorerExecute(Sender: TObject); begin ShowDockForm(CodeExplorerWindow); CodeExplorerWindow.FormActivate(Sender); // only when activated by the menu or the keyboard - Will be reset by frmIDEDockWin PyIDEMainForm.JvDockVSNetStyleSpTBX.ChannelOption.MouseleaveHide := False; end; procedure TPyIDEMainForm.actNavEditorExecute(Sender: TObject); Var Editor : IEditor; begin Editor := GetActiveEditor; if Assigned(Editor) then Editor.Activate; end; procedure TPyIDEMainForm.ShowIDEDockForm(Form: TForm); begin ShowDockForm(Form as TIDEDockWindow); if Assigned(Form.OnActivate) then Form.OnActivate(Self); // only when activated by the menu or the keyboard - Will be reset by frmIDEDockWin PyIDEMainForm.JvDockVSNetStyleSpTBX.ChannelOption.MouseleaveHide := False; end; procedure TPyIDEMainForm.ClearPythonWindows; begin VariablesWindow.ClearAll; UnitTestWindow.ClearAll; CallStackWindow.ClearAll; end; procedure TPyIDEMainForm.actNavFileExplorerExecute(Sender: TObject); begin ShowIDEDockForm(FileExplorerWindow); end; procedure TPyIDEMainForm.actNavInterpreterExecute(Sender: TObject); begin ShowIDEDockForm(PythonIIForm); end; procedure TPyIDEMainForm.actNavMessagesExecute(Sender: TObject); begin ShowIDEDockForm(MessagesWindow); end; procedure TPyIDEMainForm.actNavOutputExecute(Sender: TObject); begin ShowIDEDockForm(OutputWindow); end; procedure TPyIDEMainForm.actNavProjectExplorerExecute(Sender: TObject); begin ShowIDEDockForm(ProjectExplorerWindow); end; procedure TPyIDEMainForm.actNavRETesterExecute(Sender: TObject); begin ShowIDEDockForm(RegExpTesterWindow); end; procedure TPyIDEMainForm.actNavTodoExecute(Sender: TObject); begin ShowIDEDockForm(ToDoWindow); end; procedure TPyIDEMainForm.actNavUnitTestsExecute(Sender: TObject); begin ShowIDEDockForm(UnitTestWindow); end; procedure TPyIDEMainForm.actNavVariablesExecute(Sender: TObject); begin ShowIDEDockForm(VariablesWindow); end; procedure TPyIDEMainForm.actNavWatchesExecute(Sender: TObject); begin ShowIDEDockForm(WatchesWindow); end; procedure TPyIDEMainForm.actNewFileExecute(Sender: TObject); begin with TNewFileDialog.Create(Self) do begin if ShowModal = mrOK then begin NewFileFromTemplate(SelectedTemplate); end; Free; end; end; procedure TPyIDEMainForm.actNextEditorExecute(Sender: TObject); Var TabItem : TSpTBXTabItem; TabCtrl : TSpTBXTabControl; begin TabCtrl := ActiveTabControl as TSpTBXTabControl; if TabCtrl.PagesCount <= 1 then Exit; TabItem := nil; if PyIDEOptions.SmartNextPrevPage then with TabCtrl do begin Repeat Inc(zOrderPos); if zOrderPos >= zOrder.Count then ZOrderPos := 0; while zOrderPos < zOrder.Count do begin TabItem := zOrder[zOrderPos]; if Items.IndexOf(TabItem) < 0 then begin zOrder.Delete(zOrderPos); TabItem := nil; end else break; end; Until Assigned(TabItem) or (ZOrder.Count = 0); KeyPreview := True; zOrderProcessing := True; end else begin if Assigned(TabCtrl.ActivePage) then TabItem := TabCtrl.ActivePage.Item.GetNextTab(True, sivtNormal) else TabItem := TabCtrl.Pages[0].Item; end; if not Assigned(TabItem) and (TabCtrl.PagesCount > 0) then TabItem := TabCtrl.Pages[0].Item; if Assigned(TabItem) then TabItem.Checked := True; end; procedure TPyIDEMainForm.actPostMortemExecute(Sender: TObject); begin PyControl.ActiveDebugger.EnterPostMortem; end; procedure TPyIDEMainForm.actPreviousEditorExecute(Sender: TObject); Var TabItem : TSpTBXTabItem; TabCtrl : TSpTBXTabControl; begin TabCtrl := ActiveTabControl as TSpTBXTabControl; if TabCtrl.PagesCount <= 1 then Exit; TabItem := nil; if PyIDEOptions.SmartNextPrevPage then with TabCtrl do begin Repeat Dec(zOrderPos); if zOrderPos < 0 then zOrderPos := zOrder.Count - 1; while zOrderPos < zOrder.Count do begin TabItem := zOrder[zOrderPos]; if Items.IndexOf(TabItem) < 0 then begin zOrder.Delete(zOrderPos); TabItem := nil; end else break; end; Until Assigned(TabItem) or (ZOrder.Count = 0); KeyPreview := True; zOrderProcessing := True; end else begin if Assigned(TabCtrl.ActivePage) then TabItem := TabCtrl.ActivePage.Item.GetNextTab(False, sivtNormal) else TabItem := TabCtrl.Pages[TabCtrl.PagesCount-1].Item; end; if not Assigned(TabItem) then TabItem := TabCtrl.Pages[TabCtrl.PagesCount-1].Item; if Assigned(TabItem) then TabItem.Checked := True; end; procedure TPyIDEMainForm.actPythonEngineExecute(Sender: TObject); Var EngineType : TPythonEngineType; SSHServer: string; begin EngineType := TPythonEngineType((Sender as TAction).Tag); if EngineType = peSSH then begin SSHServer := SelectSSHServer; if SSHServer <> '' then PyControl.ActiveSSHServerName := SSHServer else Exit; end; PyControl.PythonEngineType := EngineType; end; procedure TPyIDEMainForm.actPythonReinitializeExecute(Sender: TObject); begin if not GI_PyControl.Inactive then begin if Vcl.Dialogs.MessageDlg(_(STerminateInterpreter), mtWarning, [mbYes, mbNo], 0) = idNo then Exit; end; PyControl.ActiveInterpreter.ReInitialize; end; procedure TPyIDEMainForm.actPythonSetupExecute(Sender: TObject); begin TThread.ForceQueue(nil, procedure begin with TPythonVersionsDialog.Create(Self) do begin ShowModal; Release; SetupPythonVersionsMenu; end; end); end; procedure TPyIDEMainForm.actSyntaxCheckExecute(Sender: TObject); var ActiveEditor : IEditor; begin ActiveEditor := GetActiveEditor; if not Assigned(ActiveEditor) then Exit; if TPyInternalInterpreter(PyControl.InternalInterpreter).SyntaxCheck(ActiveEditor) then begin GI_PyIDEServices.Messages.AddMessage(Format(_(SSyntaxIsOK), [ActiveEditor.FileTitle])); ShowDockForm(MessagesWindow); end; end; procedure TPyIDEMainForm.actImportModuleExecute(Sender: TObject); var ActiveEditor : IEditor; begin ActiveEditor := GetActiveEditor; if not Assigned(ActiveEditor) then Exit; PyControl.ActiveInterpreter.ImportModule(ActiveEditor, True); GI_PyIDEServices.Messages.AddMessage(Format(_(SModuleImportedOK), [ActiveEditor.FileTitle])); ShowDockForm(MessagesWindow); end; procedure TPyIDEMainForm.actToggleBreakPointExecute(Sender: TObject); var ActiveEditor : IEditor; begin ActiveEditor := GetActiveEditor; if Assigned(ActiveEditor) and ActiveEditor.HasPythonFile then PyControl.ToggleBreakpoint(ActiveEditor, ActiveEditor.SynEdit.CaretY); end; procedure TPyIDEMainForm.actClearAllBreakpointsExecute(Sender: TObject); begin PyControl.ClearAllBreakpoints; end; procedure TPyIDEMainForm.actCommandLineExecute(Sender: TObject); begin with TCommandLineDlg.Create(Self) do begin SynParameters.Text := PyIDEOptions.CommandLine; cbUseCommandLine.Checked := PyIDEOptions.UseCommandLine; if ShowModal = mrOk then begin PyIDEOptions.CommandLine := SynParameters.Text; PyIDEOptions.UseCommandLine := cbUseCommandLine.Checked; end; Release; end; end; procedure TPyIDEMainForm.actRunDebugLastScriptExecute(Sender: TObject); begin if GI_PyControl.Inactive then PyControl.Debug(PyControl.RunConfig); end; procedure TPyIDEMainForm.actRunExecute(Sender: TObject); var ActiveEditor : IEditor; RunConfig : TRunConfiguration; begin Application.ProcessMessages; ActiveEditor := GetActiveEditor; if not Assigned(ActiveEditor) then Exit; RunConfig := TRunConfiguration.Create; try SetupRunConfiguration(RunConfig, ActiveEditor); PyControl.Run(RunConfig); finally RunConfig.Free; end; WriteStatusMsg(_(StrScriptRunOK)); //MessageBeep(MB_ICONASTERISK); end; procedure TPyIDEMainForm.actRunLastScriptExecute(Sender: TObject); begin if GI_PyControl.Inactive then PyControl.Run(PyControl.RunConfig); end; procedure TPyIDEMainForm.actRunLastScriptExternalExecute(Sender: TObject); begin PyControl.ExternalRun(PyControl.RunConfig); end; procedure TPyIDEMainForm.actDebugExecute(Sender: TObject); var ActiveEditor : IEditor; begin Assert(GI_PyControl.PythonLoaded and not GI_PyControl.Running); ActiveEditor := GetActiveEditor; if Assigned(ActiveEditor) then begin if GI_PyControl.Inactive then DebugActiveScript(ActiveEditor) else if PyControl.DebuggerState = dsPaused then PyControl.ActiveDebugger.Resume; end; end; procedure TPyIDEMainForm.actDebugPauseExecute(Sender: TObject); begin PyControl.ActiveDebugger.Pause; end; procedure TPyIDEMainForm.actSelectStyleExecute(Sender: TObject); begin TStyleSelectorForm.Execute; end; procedure TPyIDEMainForm.actStepIntoExecute(Sender: TObject); var ActiveEditor : IEditor; begin Assert(GI_PyControl.PythonLoaded and not GI_PyControl.Running); ActiveEditor := GetActiveEditor; if Assigned(ActiveEditor) then begin if GI_PyControl.Inactive then DebugActiveScript(ActiveEditor, True) else if PyControl.DebuggerState = dsPaused then PyControl.ActiveDebugger.StepInto; end; end; procedure TPyIDEMainForm.actStepOverExecute(Sender: TObject); begin PyControl.ActiveDebugger.StepOver; end; procedure TPyIDEMainForm.actStepOutExecute(Sender: TObject); begin PyControl.ActiveDebugger.StepOut; end; procedure TPyIDEMainForm.actDebugAbortExecute(Sender: TObject); begin PyControl.ActiveDebugger.Abort; end; procedure TPyIDEMainForm.actRunToCursorExecute(Sender: TObject); var ActiveEditor : IEditor; begin Application.ProcessMessages; ActiveEditor := GetActiveEditor; if Assigned(ActiveEditor) then begin if GI_PyControl.Inactive then DebugActiveScript(ActiveEditor, False, ActiveEditor.SynEdit.CaretY) else if PyControl.DebuggerState = dsPaused then PyControl.ActiveDebugger.RunToCursor(ActiveEditor, ActiveEditor.SynEdit.CaretY); end; end; procedure TPyIDEMainForm.DebuggerBreakpointChange(Sender: TObject; Editor : IEditor; ALine: integer); begin if not Assigned(Editor) then Exit; if (ALine >= 1) and (ALine <= Editor.SynEdit.Lines.Count) then begin Editor.SynEdit.InvalidateGutterLine(ALine); Editor.SynEdit.InvalidateLine(ALine); Editor.SynEdit2.InvalidateGutterLine(ALine); Editor.SynEdit2.InvalidateLine(ALine); end else Editor.SynEdit.Invalidate; TThread.ForceQueue(nil, procedure begin BreakPointsWindow.UpdateWindow; end); end; procedure TPyIDEMainForm.UpdateCaption; Var Editor : IEditor; begin if TabControl1.Toolbar.IsUpdating or TabControl2.Toolbar.IsUpdating then Exit; Editor := GetActiveEditor; if Assigned(Editor) then Caption := Format('PyScripter - %s%s', [Editor.GetFileNameOrTitle, iff(Editor.Modified, '*', '')]) else Caption := 'PyScripter'; end; procedure TPyIDEMainForm.SetupRunConfiguration(var RunConfig: TRunConfiguration; ActiveEditor: IEditor); begin RunConfig.ScriptName := ActiveEditor.GetFileNameOrTitle; RunConfig.EngineType := PyControl.PythonEngineType; RunConfig.Parameters := iff(PyIDEOptions.UseCommandLine, PyIDEOptions.CommandLine, ''); RunConfig.ExternalRun.Assign(ExternalPython); RunConfig.ExternalRun.Parameters := Parameters.ReplaceInText(RunConfig.ExternalRun.Parameters); RunConfig.ReinitializeBeforeRun := PyIDEOptions.ReinitializeBeforeRun; RunConfig.WorkingDir := ''; end; procedure TPyIDEMainForm.DebugActiveScript(ActiveEditor: IEditor; InitStepIn : Boolean = False; RunToCursorLine : integer = -1); var RunConfig: TRunConfiguration; begin Assert(GI_PyControl.Inactive); RunConfig := TRunConfiguration.Create; try SetupRunConfiguration(RunConfig, ActiveEditor); PyControl.Debug(RunConfig, InitStepIn, RunToCursorLine); finally RunConfig.Free; end; end; procedure TPyIDEMainForm.UpdateDebugCommands(DebuggerState : TDebuggerState); var Editor : IEditor; PyFileActive : boolean; begin Editor := GetActiveEditor; PyFileActive := Assigned(Editor) and (Editor.SynEdit.Highlighter = CommandsDataModule.SynPythonSyn); actSyntaxCheck.Enabled := PyFileActive and GI_PyControl.Inactive; actRun.Enabled := PyFileActive and GI_PyControl.Inactive; actExternalRun.Enabled := PyFileActive and GI_PyControl.Inactive; actImportModule.Enabled := PyFileActive and GI_PyControl.Inactive; actDebug.Enabled := PyFileActive and (GI_PyControl.Inactive or (DebuggerState = dsPaused)); actStepInto.Enabled := PyFileActive and (GI_PyControl.Inactive or (DebuggerState = dsPaused)); actStepOut.Enabled := DebuggerState = dsPaused; actStepOver.Enabled := DebuggerState = dsPaused; actDebugAbort.Enabled := DebuggerState in [dsPaused, dsDebugging, dsRunning, dsPostMortem]; actDebugPause.Enabled := DebuggerState = dsDebugging; actRunToCursor.Enabled := PyFileActive and (GI_PyControl.Inactive or (DebuggerState = dsPaused)) and PyControl.IsExecutableLine(Editor, Editor.SynEdit.CaretY); actToggleBreakPoint.Enabled := PyFileActive; actClearAllBreakPoints.Enabled := PyFileActive; actAddWatchAtCursor.Enabled := PyFileActive; actExecSelection.Enabled := GI_PyControl.PythonLoaded and not GI_PyControl.Running and PyFileActive; actPythonReinitialize.Enabled := Assigned(PyControl.ActiveInterpreter) and (icReInitialize in PyControl.ActiveInterpreter.InterpreterCapabilities) and not (PyControl.DebuggerState in [dsPaused, dsPostMortem]); actPostMortem.Enabled := GI_PyControl.Inactive and Assigned(PyControl.ActiveDebugger) and PyControl.ActiveDebugger.PostMortemEnabled; if DebuggerState = dsPaused then begin actDebug.Caption := _(SResumeCaption); actDebug.Hint := _(SResumeHint); end else begin actDebug.Caption := _('Debug'); actDebug.Hint := _(SDebugHint); end; actRunLastScript.Enabled := GI_PyControl.Inactive and (PyControl.RunConfig.ScriptName <> ''); actRunDebugLastScript.Enabled := actRunLastScript.Enabled; actRunLastScriptExternal.Enabled := actRunLastScript.Enabled; CallStackWindow.actPreviousFrame.Enabled := (DebuggerState = dsPaused); CallStackWindow.actNextFrame.Enabled := (DebuggerState = dsPaused); //Refresh; end; procedure TPyIDEMainForm.SetActiveTabControl(const Value: TSpTBXCustomTabControl); begin ActiveTabControlIndex := TabControlIndex(Value); end; procedure TPyIDEMainForm.SetRunLastScriptHints(const ScriptName: string); Var S : string; begin S := XtractFileName(ScriptName); if S <> '' then S := Format(' - %s ', [S]); actRunLastScript.Hint := _(sHintRun) + S; actRunDebugLastScript.Hint := _(sHintDebug) + S; actRunLastScriptExternal.Hint := _(sHintExternalRun) + S; end; procedure TPyIDEMainForm.DebuggerErrorPosChange(Sender: TObject; const OldPos, NewPos: TEditorPos); { Invalidates old and/or new error line but does not Activate the Editor } begin if csDestroying in ComponentState then Exit; if Assigned(OldPos.Editor) and (OldPos.Line > 0) then begin // Remove possible error line OldPos.Editor.SynEdit.InvalidateLine(OldPos.Line); OldPos.Editor.SynEdit2.InvalidateLine(OldPos.Line); end; if Assigned(NewPos.Editor) and (NewPos.Line > 0) then begin NewPos.Editor.SynEdit.InvalidateLine(NewPos.Line); NewPos.Editor.SynEdit2.InvalidateLine(NewPos.Line); end; end; procedure TPyIDEMainForm.DebuggerCurrentPosChange(Sender: TObject; const OldPos, NewPos: TEditorPos); begin if csDestroying in ComponentState then Exit; if Assigned(OldPos.Editor) and (OldPos.Line > 0) then // Remove possible current lines with OldPos.Editor do begin SynEdit.InvalidateGutterLine(OldPos.Line); SynEdit.InvalidateLine(OldPos.Line); SynEdit2.InvalidateGutterLine(OldPos.Line); SynEdit2.InvalidateLine(OldPos.Line); end; if not Assigned(NewPos.Editor) then Exit; if GetActiveEditor <> NewPos.Editor then NewPos.Editor.Activate; with NewPos.Editor.SynEdit do begin if (NewPos.Line > 0) and (CaretY <> NewPos.Line) then begin CaretXY := BufferCoord(1, NewPos.Line); EnsureCursorPosVisible; end; InvalidateGutterLine(NewPos.Line); InvalidateLine(NewPos.Line); end; NewPos.Editor.SynEdit2.InvalidateGutterLine(NewPos.Line); NewPos.Editor.SynEdit2.InvalidateLine(NewPos.Line); end; procedure TPyIDEMainForm.DebuggerStateChange(Sender: TObject; OldState, NewState: TDebuggerState); var s: string; begin if csDestroying in ComponentState then Exit; if GI_PyControl.PythonLoaded then case NewState of dsDebugging, dsRunning: begin s := _('Running'); if PyIDEOptions.PythonEngineType = peInternal then Screen.Cursor := crHourGlass; StatusLED.LEDColorOn := clRed; end; dsPaused: begin s := _('Paused'); Screen.Cursor := crDefault; StatusLED.LEDColorOn := clYellow; end; dsInactive: begin s := _('Ready'); Screen.Cursor := crDefault; StatusLED.LEDColorOn := clGreen; end; dsPostMortem : begin s := _('Post mortem'); Screen.Cursor := crDefault; StatusLED.LEDColorOn := clPurple; end; end else begin s := _('Python not available'); Screen.Cursor := crDefault; StatusLED.LEDColorOn := clGray; end; StatusLED.Hint := _('Debugger state: ') +s; lbStatusMessage.Caption := ' ' + s; StatusBar.Refresh; CallStackWindow.UpdateWindow(NewState, OldState); // also updates Variables and Watches UpdateDebugCommands(NewState); end; procedure TPyIDEMainForm.DebuggerYield(Sender: TObject; DoIdle : Boolean); begin Application.ProcessMessages; if DoIdle then // Application.Idle yields control to other applications // and calls CheckSynchronize which runs synchronized methods initiated in threads Application.DoApplicationIdle else CheckSynchronize; end; procedure TPyIDEMainForm.SaveFileModules; var i : integer; FileCommands : IFileCommands; begin for i := 0 to GI_EditorFactory.Count -1 do if ((GI_EditorFactory[i].FileName <> '') or (GI_EditorFactory[i].RemoteFileName <> '')) and GI_EditorFactory[i].Modified then begin FileCommands := GI_EditorFactory[i] as IFileCommands; if Assigned(FileCommands) then FileCommands.ExecSave; end; end; procedure TPyIDEMainForm.ApplicationOnIdle(Sender: TObject; var Done: Boolean); Var i : integer; begin UpdateStandardActions; CommandsDataModule.UpdateMainActions; PythonIIForm.UpdateInterpreterActions; UpdateStatusBarPanels; UpdateDebugCommands(PyControl.DebuggerState); if Assigned(GI_ActiveEditor) then TEditorForm(GI_ActiveEditor.Form).DoOnIdle; PythonIIForm.DoOnIdle; // If a Tk or Wx remote engine is active pump up event handling // This is for processing input output coming from event handlers if (PyControl.ActiveInterpreter is TPyRemoteInterpreter) and (GI_PyControl.Inactive) then with(TPyRemoteInterpreter(PyControl.ActiveInterpreter)) do begin if Connected and (EngineType in [peRemoteTk, peRemoteWx]) then // Ignore exceptions here ServeConnection; end; if ShellExtensionFiles.Count > 0 then begin for i := 0 to ShellExtensionFiles.Count - 1 do OpenCmdLineFile(ShellExtensionFiles[i]); ShellExtensionFiles.Clear; end; Done := True; end; procedure TPyIDEMainForm.ApplicationOnHint(Sender: TObject); Var S : string; begin S := StringReplace(GetLongHint(Application.Hint), #13#10, ' ', [rfReplaceAll]); WriteStatusMsg(S); end; procedure TPyIDEMainForm.ApplcationOnShowHint(var HintStr: string; var CanShow: Boolean; var HintInfo: Vcl.Controls.THintInfo); begin if HintInfo.HintControl is TBaseVirtualTree then HintInfo.HideTimeout := 5000; end; function TPyIDEMainForm.ShowFilePosition(FileName: string; Line, Offset: integer; SelLen : integer = 0; ForceToMiddle : boolean = True; FocusEditor : boolean = True): boolean; Var Editor : IEditor; begin Result := False; if FileName <> '' then begin if (FileName[1] ='<') and (FileName[Length(FileName)] = '>') then FileName := Copy(FileName, 2, Length(FileName)-2); Editor := GI_EditorFactory.GetEditorByNameOrTitle(FileName); if not Assigned(Editor) and (FileName.StartsWith('ssh') or FileExists(FileName)) then begin try DoOpenFile(FileName, '', TabControlIndex(ActiveTabControl)); except Exit; end; Editor := GI_EditorFactory.GetEditorByNameOrTitle(FileName); if GI_PyControl.PythonLoaded and Editor.FileName.StartsWith(PyControl.PythonVersion.InstallPath, True) then Editor.ReadOnly := True; end; if Assigned(Editor) then begin Result := True; Sleep(200); Application.ProcessMessages; // to deal with focus problems // sets the focus to the editor if (Editor <> GetActiveEditor) or FocusEditor then Editor.Activate; if (Line > 0) then with Editor.SynEdit do begin CaretXY := BufferCoord(Offset,Line); EnsureCursorPosVisibleEx(ForceToMiddle); if SelLen > 0 then SelLength := SelLen; end; end; end; end; procedure TPyIDEMainForm.SpTBXCustomizerGetCustomizeForm(Sender: TObject; var CustomizeFormClass: TSpTBXCustomizeFormClass); begin CustomizeFormClass := TSpTBXCustomizeFormMod; end; procedure TPyIDEMainForm.actViewSplitEditorHorExecute(Sender: TObject); Var Editor : IEditor; begin Editor := GetActiveEditor; if Assigned(Editor) then Editor.SplitEditorHorizontally end; procedure TPyIDEMainForm.actViewSplitEditorVerExecute(Sender: TObject); Var Editor : IEditor; begin Editor := GetActiveEditor; if Assigned(Editor) then Editor.SplitEditorVertrically; end; procedure TPyIDEMainForm.actViewSplitWorkspaceHorExecute(Sender: TObject); begin SplitWorkspace(True, alBottom); end; procedure TPyIDEMainForm.actViewSplitWorkspaceVerExecute(Sender: TObject); begin SplitWorkspace(True, alRight); end; procedure TPyIDEMainForm.actViewStatusBarExecute(Sender: TObject); begin StatusBar.Visible := not StatusBar.Visible; //This is to avoid the Status bar appearing above Bottom Dock Tab if StatusBar.Visible then StatusBar.Top := Height - StatusBar.Height; end; procedure TPyIDEMainForm.actViewIIExecute(Sender: TObject); begin if not PythonIIForm.Visible then ShowDockForm(PythonIIForm) else HideDockForm(PythonIIForm); end; procedure TPyIDEMainForm.actViewMainMenuExecute(Sender: TObject); begin MainMenu.Visible := not MainMenu.Visible; end; procedure TPyIDEMainForm.actViewCodeExplorerExecute(Sender: TObject); begin if not CodeExplorerWindow.Visible then ShowDockForm(CodeExplorerWindow) else HideDockForm(CodeExplorerWindow); end; procedure TPyIDEMainForm.actViewCustomizeToolbarsExecute(Sender: TObject); begin SpTBXCustomizer.Show; end; procedure TPyIDEMainForm.actViewFileExplorerExecute(Sender: TObject); begin if not FileExplorerWindow.Visible then ShowDockForm(FileExplorerWindow) else HideDockForm(FileExplorerWindow); end; procedure TPyIDEMainForm.actViewToDoListExecute(Sender: TObject); begin if not ToDoWindow.Visible then begin ShowDockForm(ToDoWindow); ToDoWindow.ToDoView.SetFocus; end else HideDockForm(ToDoWindow); end; procedure TPyIDEMainForm.actViewRegExpTesterExecute(Sender: TObject); begin if not RegExpTesterWindow.Visible then ShowDockForm(RegExpTesterWindow) else HideDockForm(RegExpTesterWindow); end; procedure TPyIDEMainForm.actViewUnitTestsExecute(Sender: TObject); begin if not UnitTestWindow.Visible then ShowDockForm(UnitTestWindow) else HideDockForm(UnitTestWindow); end; procedure TPyIDEMainForm.actViewOutputExecute(Sender: TObject); begin if not OutputWindow.Visible then ShowDockForm(OutputWindow) else HideDockForm(OutputWindow); end; procedure TPyIDEMainForm.actViewProjectExplorerExecute(Sender: TObject); begin if not ProjectExplorerWindow.Visible then ShowDockForm(ProjectExplorerWindow) else HideDockForm(ProjectExplorerWindow); end; procedure TPyIDEMainForm.actViewFindResultsExecute(Sender: TObject); begin if not FindResultsWindow.Visible then begin ShowDockForm(FindResultsWindow); end else HideDockForm(FindResultsWindow); end; procedure TPyIDEMainForm.actViewHideSecondaryWorkspaceExecute(Sender: TObject); var I: Integer; IV: TTBItemViewer; List : TObjectList; begin // Move all tabs to TabControl1 // Note that the Pages property may have a different order than the // physical order of the tabs TabControl1.Toolbar.BeginUpdate; TabControl2.Toolbar.BeginUpdate; List := TObjectList.Create(False); try for I := 0 to TabControl2.View.ViewerCount - 1 do begin IV := TabControl2.View.Viewers[I]; if IV.Item is TSpTBXTabItem then List.Add(IV.Item) end; for i := 0 to List.Count - 1 do MoveTab(TSpTBXTabItem(List[I]), TabControl1); finally TabControl1.Toolbar.EndUpdate; TabControl2.Toolbar.EndUpdate; List.Free; end; SplitWorkspace(False); end; procedure TPyIDEMainForm.actViewHideSecondEditorExecute(Sender: TObject); Var Editor : IEditor; begin Editor := GetActiveEditor; if Assigned(Editor) then with TEditorForm(Editor.Form) do begin EditorSplitter.Visible:= False; SynEdit2.Visible := False; end; end; procedure TPyIDEMainForm.actMessagesWinExecute(Sender: TObject); begin if not MessagesWindow.Visible then ShowDockForm(MessagesWindow) else HideDockForm(MessagesWindow); end; procedure TPyIDEMainForm.actCallStackWinExecute(Sender: TObject); begin if not CallStackWindow.Visible then ShowDockForm(CallStackWindow) else HideDockForm(CallStackWindow); end; procedure TPyIDEMainForm.actVariablesWinExecute(Sender: TObject); begin if not VariablesWindow.Visible then ShowDockForm(VariablesWindow) else HideDockForm(VariablesWindow); end; procedure TPyIDEMainForm.actAddWatchAtCursorExecute(Sender: TObject); var Editor : IEditor; begin Editor := GetActiveEditor; if Assigned(Editor) then TEditorForm(Editor.Form).AddWatchAtCursor; end; procedure TPyIDEMainForm.actBreakPointsWinExecute(Sender: TObject); begin if not BreakPointsWindow.Visible then ShowDockForm(BreakPointsWindow) else HideDockForm(BreakPointsWindow); end; procedure TPyIDEMainForm.actWatchesWinExecute(Sender: TObject); begin if not WatchesWindow.Visible then ShowDockForm(WatchesWindow) else HideDockForm(WatchesWindow); end; function TPyIDEMainForm.GetActiveEditor : IEditor; { Returns the active editor irrespective of whether it is has the focus If want the active editor with focus then use GI_ActiveEditor } Var ActivePage : TSpTBXTabSheet; begin // Find Active Page ActivePage := ActiveTabControl.ActivePage; if not Assigned(ActivePage) then begin ActivePage := TabControl1.ActivePage; if not Assigned(ActivePage) then ActivePage := TabControl2.ActivePage; end; if Assigned(ActivePage) and (ActivePage.ComponentCount > 0) and (ActivePage.Components[0] is TEditorForm) then Result := TEditorForm(ActivePage.Components[0]).GetEditor else Result := nil; end; function TPyIDEMainForm.GetActiveTabControl: TSpTBXCustomTabControl; begin if ActiveTabControlIndex = 2 then Result := TabControl2 else Result := TabControl1; end; function TPyIDEMainForm.GetAppStorage: TJvCustomAppStorage; begin Result := AppStorage; end; function TPyIDEMainForm.GetIDELayouts: IIDELayouts; begin Result := Self; end; function TPyIDEMainForm.GetLocalAppStorage: TJvCustomAppStorage; begin Result := LocalAppStorage; end; function TPyIDEMainForm.GetMessageServices: IMessageServices; begin Result := MessagesWindow; end; function TPyIDEMainForm.GetStoredScript(const Name: string): TStrings; begin Result := CommandsDataModule.JvMultiStringHolder.StringsByName[Name]; end; function TPyIDEMainForm.GetUnitTestServices: IUnitTestServices; begin Result := UnitTestWindow; end; function TPyIDEMainForm.TabControl(TabControlIndex: integer): TSpTBXTabControl; begin if TabControlIndex = 2 then Result := TabControl2 else Result := TabControl1; end; function TPyIDEMainForm.TabControlIndex( TabControl: TSpTBXCustomTabControl): integer; begin if TabControl = TabControl2 then Result := 2 else Result := 1; end; procedure TPyIDEMainForm.UpdateStatusBarPanels; var ptCaret: TPoint; Editor : IEditor; begin Editor := GI_ActiveEditor; if Editor <> nil then begin ptCaret := Editor.GetCaretPos; if (ptCaret.X > 0) and (ptCaret.Y > 0) then lbStatusCaret.Caption := Format('%d:%d', [ptCaret.Y, ptCaret.X]) else lbStatusCaret.Caption := ''; if GI_ActiveEditor.GetModified then lbStatusModified.Caption := _(SModified) else lbStatusModified.Caption := ' '; lbStatusOverwrite.Caption := Editor.GetEditorState; end else begin lbStatusCaret.Caption := ''; lbStatusModified.Caption := ''; lbStatusOverwrite.Caption := ''; end; if GetCapsLockKeyState then lbStatusCAPS.Caption := 'CAPS' else lbStatusCAPS.Caption := ' '; if GI_PyControl.PythonLoaded then begin lbPythonVersion.Caption := PyControl.PythonVersion.DisplayName; lbPythonEngine.Caption := _(EngineTypeName[PyControl.PythonEngineType]); end else begin lbPythonVersion.Caption := _('Python Not Available'); lbPythonEngine.Caption := ' '; end; ExternalToolsLED.Visible := OutputWindow.JvCreateProcess.State <> psReady; end; function TPyIDEMainForm.CmdLineOpenFiles(): boolean; var i : integer; begin Result := False; for i := Low(CmdLineReader.readNamelessString) to High(CmdLineReader.readNamelessString) do Result := OpenCmdLineFile(CmdLineReader.readNamelessString[i]) or Result; // Project Filename if CmdLineReader.readString('PROJECT') <> '' then ProjectExplorerWindow.DoOpenProjectFile(CmdLineReader.readString('PROJECT')); end; procedure TPyIDEMainForm.ConfigureFileExplorer(FCN: TFileChangeNotificationType; BackgroundProcessing : Boolean); begin case FCN of fcnFull: with FileExplorerWindow.FileExplorerTree do begin TreeOptions.VETMiscOptions := TreeOptions.VETMiscOptions + [toChangeNotifierThread, toTrackChangesInMappedDrives]; // Connect ChangeNotify OnAfterShellNotify := CommandsDataModule.ProcessShellNotify; end; fcnNoMappedDrives: with FileExplorerWindow.FileExplorerTree do begin TreeOptions.VETMiscOptions := TreeOptions.VETMiscOptions + [toChangeNotifierThread] - [toTrackChangesInMappedDrives]; // Connect ChangeNotify OnAfterShellNotify := CommandsDataModule.ProcessShellNotify; end; fcnDisabled: with FileExplorerWindow.FileExplorerTree do begin TreeOptions.VETMiscOptions := TreeOptions.VETMiscOptions - [toChangeNotifierThread, toTrackChangesInMappedDrives]; // Connect ChangeNotify OnAfterShellNotify := nil; end; end; with FileExplorerWindow.FileExplorerTree do begin if BackgroundProcessing then begin TreeOptions.VETImageOptions := TreeOptions.VETImageOptions + [toThreadedImages]; TreeOptions.VETFolderOptions := TreeOptions.VETFolderOptions + [toThreadedExpandMark]; end else begin TreeOptions.VETImageOptions := TreeOptions.VETImageOptions - [toThreadedImages]; TreeOptions.VETFolderOptions := TreeOptions.VETFolderOptions - [toThreadedExpandMark]; end; end; if FileExplorerWindow.FileExplorerTree.Active then FileExplorerWindow.FileExplorerTree.RefreshTree; end; procedure TPyIDEMainForm.OpenInitialFiles; begin TabControl1.Toolbar.BeginUpdate; TabControl2.Toolbar.BeginUpdate; try // Open Files on the command line // if there was no file on the command line try restoring open files if not CmdLineOpenFiles and PyIDEOptions.RestoreOpenFiles then TPersistFileInfo.ReadFromAppStorage(AppStorage, 'Open Files'); // If we still have no open file then open an empty file if GI_EditorFactory.GetEditorCount = 0 then actFileNewModuleExecute(Self); finally TabControl1.Toolbar.EndUpdate; TabControl2.Toolbar.EndUpdate; if Assigned(TabControl1.ActiveTab) then TabControl1.MakeVisible(TabControl1.ActiveTab); if Assigned(TabControl2.ActiveTab) then TabControl2.MakeVisible(TabControl2.ActiveTab); if Assigned(GetActiveEditor()) then GetActiveEditor.Activate; UpdateCaption; // Start the Python Code scanning thread CodeExplorerWindow.WorkerThread.Start; end; end; procedure TPyIDEMainForm.ApplyIDEOptionsToEditor(Editor: IEditor); begin with TEditorForm(Editor.Form) do begin SynCodeCompletion.Options := PythonIIForm.SynCodeCompletion.Options; SynCodeCompletion.TriggerChars := PythonIIForm.SynCodeCompletion.TriggerChars; SynCodeCompletion.TimerInterval := PythonIIForm.SynCodeCompletion.TimerInterval; Synedit.CodeFolding.Assign(PyIDEOptions.CodeFolding); Synedit2.CodeFolding.Assign(PyIDEOptions.CodeFolding); if PyIDEOptions.CompactLineNumbers then begin SynEdit.OnGutterGetText := TEditorForm(Editor.Form).SynEditGutterGetText; SynEdit2.OnGutterGetText := TEditorForm(Editor.Form).SynEditGutterGetText; end else begin SynEdit.OnGutterGetText := nil; SynEdit2.OnGutterGetText := nil; end; SynEdit.InvalidateGutter; SynEdit2.InvalidateGutter; end; end; procedure TPyIDEMainForm.FormDestroy(Sender: TObject); begin GI_PyIDEServices := nil; SkinManager.RemoveSkinNotification(Self); PyIDEOptions.OnChange.RemoveHandler(PyIDEOptionsChanged); FreeAndNil(Layouts); FreeAndNil(fLanguageList); FreeAndNil(DSAAppStorage); FreeAndNil(ShellExtensionFiles); end; procedure TPyIDEMainForm.actFileExitExecute(Sender: TObject); begin Close; end; procedure TPyIDEMainForm.actFileNewModuleExecute(Sender: TObject); Var TemplateName : string; FileTemplate : TFileTemplate; begin FileTemplate := nil; TemplateName := PyIDEOptions.FileTemplateForNewScripts; if TemplateName <> '' then FileTemplate := FileTemplates.TemplateByName(TemplateName); if Assigned(FileTemplate) then NewFileFromTemplate(FileTemplate, TabControlIndex(ActiveTabControl)) else DoOpenFile('', 'Python', TabControlIndex(ActiveTabControl)); end; procedure TPyIDEMainForm.actFileOpenExecute(Sender: TObject); Var i : integer; Editor : IEditor; begin with CommandsDataModule.dlgFileOpen do begin Title := _(SOpenFile); FileName := ''; Filter := GetHighlightersFilter(CommandsDataModule.Highlighters) + _(SFilterAllFiles); Editor := GetActiveEditor; if Assigned(Editor) and (Editor.FileName <> '') and (ExtractFileDir(Editor.FileName) <> '') then InitialDir := ExtractFileDir(Editor.FileName); Options := Options + [ofAllowMultiSelect]; if Execute then begin for i := 0 to Files.Count - 1 do DoOpenFile(Files[i], '', TabControlIndex(ActiveTabControl)); end; Options := Options - [ofAllowMultiSelect]; end; end; procedure TPyIDEMainForm.actFileCloseAllExecute(Sender: TObject); begin if GI_EditorFactory <> nil then begin if GI_EditorFactory.CanCloseAll then begin TabControl1.Toolbar.BeginUpdate; TabControl2.Toolbar.BeginUpdate; try GI_EditorFactory.CloseAll; finally TabControl1.Toolbar.EndUpdate; TabControl2.Toolbar.EndUpdate; UpdateCaption; end; end; end; end; procedure TPyIDEMainForm.PyIDEOptionsChanged(Sender: TObject); var Editor : IEditor; i : integer; CaseSensitive, CompleteAsYouType, CompleteWithWordBreakChars : Boolean; begin if PyIDEOptions.StyleMainWindowBorder then Self.StyleElements := Self.StyleElements + [seBorder] else Self.StyleElements := Self.StyleElements - [seBorder]; EditorSearchOptions.SearchTextAtCaret := PyIDEOptions.SearchTextAtCaret; MaskFPUExceptions(PyIDEOptions.MaskFPUExceptions); CommandsDataModule.SynPythonSyn.DefaultFilter := PyIDEOptions.PythonFileFilter; CommandsDataModule.SynCythonSyn.DefaultFilter := PyIDEOptions.CythonFileFilter; CommandsDataModule.SynWebHTMLSyn.DefaultFilter := PyIDEOptions.HTMLFileFilter; CommandsDataModule.SynWebXMLSyn.DefaultFilter := PyIDEOptions.XMLFileFilter; CommandsDataModule.SynWebCssSyn.DefaultFilter := PyIDEOptions.CSSFileFilter; CommandsDataModule.SynCppSyn.DefaultFilter := PyIDEOptions.CPPFileFilter; CommandsDataModule.SynYAMLSyn.DefaultFilter := PyIDEOptions.YAMLFileFilter; CommandsDataModule.SynJSONSyn.DefaultFilter := PyIDEOptions.JSONFileFilter; CommandsDataModule.SynGeneralSyn.DefaultFilter := PyIDEOptions.GeneralFileFilter; // Dock animation parameters JvDockVSNetStyleSpTBX.SetAnimationInterval(PyIDEOptions.DockAnimationInterval); JvDockVSNetStyleSpTBX.SetAnimationMoveWidth(PyIDEOptions.DockAnimationMoveWidth); // Set Python engine actPythonInternal.Visible := not PyIDEOptions.InternalInterpreterHidden; if not actPythonInternal.Visible and (PyIDEOptions.PythonEngineType = peInternal) then PyIDEOptions.PythonEngineType := peRemote; PyControl.PythonEngineType := PyIDEOptions.PythonEngineType; TThread.ForceQueue(nil, procedure begin ConfigureFileExplorer(PyIDEOptions.FileChangeNotification, PyIDEOptions.FileExplorerBackgroundProcessing); end); // Command History Size PythonIIForm.CommandHistorySize := PyIDEOptions.InterpreterHistorySize; if PyIDEOptions.ShowTabCloseButton then begin TabControl1.TabCloseButton := tcbAll; TabControl2.TabCloseButton := tcbAll; end else begin TabControl1.TabCloseButton := tcbNone; TabControl2.TabCloseButton := tcbNone; end; if TabControl1.TabPosition <> PyIDEOptions.EditorsTabPosition then case PyIDEOptions.EditorsTabPosition of ttpTop: begin TabControl1.TabPosition := ttpTop; TabControl2.TabPosition := ttpTop; for i := 0 to GI_EditorFactory.Count - 1 do TEditorForm(GI_EditorFactory.Editor[i].Form).ViewsTabControl.TabPosition := ttpBottom; end; ttpBottom: begin TabControl1.TabPosition := ttpBottom; TabControl2.TabPosition := ttpBottom; for i := 0 to GI_EditorFactory.Count - 1 do TEditorForm(GI_EditorFactory.Editor[i].Form).ViewsTabControl.TabPosition := ttpTop; end; end; // Code completion CaseSensitive := PyIDEOptions.CodeCompletionCaseSensitive; CompleteAsYouType := PyIDEOptions.CompleteAsYouType; CompleteWithWordBreakChars := PyIDEOptions.CompleteWithWordBreakChars; with PythonIIForm do begin with SynCodeCompletion do begin if CaseSensitive then Options := Options + [scoCaseSensitive] else Options := Options - [scoCaseSensitive]; if CompleteWithWordBreakChars then Options := Options + [scoEndCharCompletion] else Options := Options - [scoEndCharCompletion]; TriggerChars := '.'; TimerInterval := 200; if CompleteAsYouType then begin for i := ord('a') to ord('z') do TriggerChars := TriggerChars + Chr(i); for i := ord('A') to ord('Z') do TriggerChars := TriggerChars + Chr(i); if CompleteWithWordBreakChars or PyIDEOptions.CompleteWithOneEntry then TimerInterval := 600; end; end; end; for i := 0 to GI_EditorFactory.Count - 1 do begin Editor := GI_EditorFactory.Editor[i]; ApplyIDEOptionsToEditor(Editor); end; tbiRecentFileList.MaxItems := PyIDEOptions.NoOfRecentFiles; Editor := GetActiveEditor; if Assigned(Editor) then Editor.SynEdit.InvalidateGutter; end; procedure TPyIDEMainForm.StoreApplicationData; Var TempStringList : TStringList; ActionProxyCollection : TActionProxyCollection; i : integer; TempCursor : IInterface; begin TempCursor := WaitCursor; TempStringList := TStringList.Create; AppStorage.BeginUpdate; try AppStorage.WriteString('PyScripter Version', ApplicationVersion); AppStorage.WriteString('Language', GetCurrentLanguage); // UnScale and Scale back PyIDEOptions.CodeFolding.GutterShapeSize := PPIUnScale(PyIDEOptions.CodeFolding.GutterShapeSize); AppStorage.WritePersistent('IDE Options', PyIDEOptions); PyIDEOptions.CodeFolding.GutterShapeSize := PPIScale(PyIDEOptions.CodeFolding.GutterShapeSize); with CommandsDataModule do begin AppStorage.DeleteSubTree('Editor Options'); AppStorage.WritePersistent('Editor Options', EditorOptions); AppStorage.DeleteSubTree('Highlighters'); for i := 0 to Highlighters.Count - 1 do if CommandsDataModule.IsHighlighterStored(Highlighters.Objects[i]) then AppStorage.WritePersistent('Highlighters\'+Highlighters[i], TPersistent(Highlighters.Objects[i])); AppStorage.WritePersistent('Highlighters\Intepreter', PythonIIForm.SynEdit.Highlighter); AppStorage.DeleteSubTree('Interpreter Editor Options'); TempStringList.Add('KeyStrokes'); AppStorage.WritePersistent('Interpreter Editor Options', InterpreterEditorOptions, True, TempStringList); AppStorage.WritePersistent('Editor Search Options', EditorSearchOptions); TempStringList.Clear; TempStringList.Add('Lines'); TempStringList.Add('Highlighter'); AppStorage.DeleteSubTree('Print Options'); AppStorage.WritePersistent('Print Options', SynEditPrint, True, TempStringList); AppStorage.WriteString('Print Options\HeaderItems', SynEditPrint.Header.AsString); AppStorage.WriteString('Print Options\FooterItems', SynEditPrint.Footer.AsString); AppStorage.StorageOptions.PreserveLeadingTrailingBlanks := True; AppStorage.DeleteSubTree('File Templates'); AppStorage.WriteObjectList('File Templates', FileTemplates); AppStorage.DeleteSubTree('Code Templates'); AppStorage.WriteStringList('Code Templates', CodeTemplatesCompletion.AutoCompleteList); AppStorage.StorageOptions.PreserveLeadingTrailingBlanks := False; end; AppStorage.WritePersistent('Secondary Tabs', TabsPersistsInfo); AppStorage.WritePersistent('ToDo Options', ToDoExpert); AppStorage.DeleteSubTree('Find in Files Options'); AppStorage.WritePersistent('Find in Files Options', FindResultsWindow.FindInFilesExpert); AppStorage.WritePersistent('Find in Files Results Options', FindResultsWindow); AppStorage.WritePersistent('Variables Window Options', VariablesWindow); AppStorage.WritePersistent('Call Stack Window Options', CallStackWindow); AppStorage.WritePersistent('Breakpoints Window Options', BreakPointsWindow); AppStorage.WritePersistent('Messages Window Options', MessagesWindow); AppStorage.WritePersistent('RegExp Tester Options', RegExpTesterWindow); AppStorage.WriteBoolean('File Explorer Filter', FileExplorerWindow.actEnableFilter.Checked); AppStorage.WriteString('File Explorer Path', FileExplorerWindow.ExplorerPath); AppStorage.WriteStringList('File Explorer Favorites', FileExplorerWindow.Favorites); AppStorage.WritePersistent('Code Explorer Options', CodeExplorerWindow); AppStorage.WriteStringList('Custom Params', CustomParams); AppStorage.DeleteSubTree('Tools'); AppStorage.WriteCollection('Tools', ToolsCollection, 'Tool'); AppStorage.DeleteSubTree('SSH'); AppStorage.StorageOptions.StoreDefaultValues := True; AppStorage.WriteCollection('SSH', SSHServers, 'Server'); AppStorage.StorageOptions.StoreDefaultValues := False; AppStorage.WritePersistent('Tools\External Run', ExternalPython); AppStorage.WriteString('Output Window\Font Name', OutputWindow.lsbConsole.Font.Name); AppStorage.WriteInteger('Output Window\Font Size', OutputWindow.lsbConsole.Font.Size); AppStorage.WritePersistent('Watches', WatchesWindow); AppStorage.WriteBoolean('Status Bar', StatusBar.Visible); // Save Style Name AppStorage.WriteString('Style Name', TStyleSelectorForm.CurrentSkinName); // Save Toolbar Items SaveToolbarItems('Toolbar Items'); // Needed since save toolbar Items below does not save secondary shortcuts! Issue 307 // Save IDE Shortcuts AppStorage.DeleteSubTree('IDE Shortcuts'); ActionProxyCollection := TActionProxyCollection.Create(apcctChanged); try AppStorage.WriteCollection('IDE Shortcuts', ActionProxyCollection, 'Action'); finally ActionProxyCollection.Free; end; // Save Interpreter History TempStringList.Clear; for I := 0 to PythonIIForm.CommandHistory.Count - 1 do TempStringList.Add(StrStringToEscaped(PythonIIForm.CommandHistory[i])); AppStorage.StorageOptions.PreserveLeadingTrailingBlanks := True; AppStorage.WriteStringList('Command History', TempStringList); AppStorage.StorageOptions.PreserveLeadingTrailingBlanks := False; // Project Filename AppStorage.WriteString('Active Project', ActiveProject.FileName); finally AppStorage.EndUpdate; TempStringList.Free; end; // Save MRU Lists tbiRecentFileList.SaveToIni(AppStorage.IniFile, 'MRU File List'); tbiRecentProjects.SaveToIni(AppStorage.IniFile, 'MRU Project List'); AppStorage.Flush; end; procedure TPyIDEMainForm.StoreLocalApplicationData; begin LocalAppStorage.BeginUpdate; try LocalAppStorage.WriteString('PyScripter Version', ApplicationVersion); LocalAppStorage.WriteString('Monitor profile', MonitorProfile); LocalAppStorage.WriteStringList('Layouts', Layouts); // Form Placement JvFormStorage.SaveFormPlacement; // Store Python Versions PyControl.WriteToAppStorage(LocalAppStorage); finally LocalAppStorage.EndUpdate; end; LocalAppStorage.Flush; end; procedure TPyIDEMainForm.RestoreApplicationData; Const DefaultHeader='$TITLE$\.1\.0\.-13\.Arial\.0\.96\.10\.0\.1\.2'; DefaultFooter='$PAGENUM$\\.$PAGECOUNT$\.1\.0\.-13\.Arial\.0\.96\.10\.0\.1\.2'; Var ActionProxyCollection : TActionProxyCollection; TempStringList : TStringList; FName : string; i : Integer; PyScripterVersion : string; begin PyScripterVersion := AppStorage.ReadString('PyScripter Version', '1.0'); // Change language ChangeLanguage(AppStorage.ReadString('Language', GetCurrentLanguage)); // Remove since it is now stored in PyScripter.local.ini if AppStorage.PathExists('Layouts') then AppStorage.DeleteSubTree('Layouts'); if AppStorage.PathExists('IDE Options') then begin AppStorage.ReadPersistent('IDE Options', PyIDEOptions); PyIDEOptions.CodeFolding.GutterShapeSize := PPIScale(PyIDEOptions.CodeFolding.GutterShapeSize); PyIDEOptions.Changed; AppStorage.DeleteSubTree('IDE Options'); end; if AppStorage.PathExists('Editor Options') then with CommandsDataModule do begin EditorOptions.Gutter.Gradient := False; //default value AppStorage.ReadPersistent('Editor Options', EditorOptions); if (CompareVersions(PyScripterVersion, '3.1') > 0) then begin if (EditorOptions.Keystrokes.FindCommand(ecFoldAll) < 0) then with EditorOptions.Keystrokes do begin AddKey(ecFoldAll, VK_OEM_MINUS, [ssCtrl, ssShift]); {- _} AddKey(ecUnfoldAll, VK_OEM_PLUS, [ssCtrl, ssShift]); {= +} AddKey(ecFoldNearest, VK_OEM_2, [ssCtrl]); // Divide {'/'} AddKey(ecUnfoldNearest, VK_OEM_2, [ssCtrl, ssShift]); AddKey(ecFoldLevel1, ord('K'), [ssCtrl], Ord('1'), [ssCtrl]); AddKey(ecFoldLevel2, ord('K'), [ssCtrl], Ord('2'), [ssCtrl]); AddKey(ecFoldLevel3, ord('K'), [ssCtrl], Ord('3'), [ssCtrl]); AddKey(ecUnfoldLevel1, ord('K'), [ssCtrl, ssShift], Ord('1'), [ssCtrl, ssShift]); AddKey(ecUnfoldLevel2, ord('K'), [ssCtrl, ssShift], Ord('2'), [ssCtrl, ssShift]); AddKey(ecUnfoldLevel3, ord('K'), [ssCtrl, ssShift], Ord('3'), [ssCtrl, ssShift]); end; EditorOptions.Gutter.DigitCount := 2; end; for i := 0 to Highlighters.Count - 1 do begin TSynCustomHighlighter(Highlighters.Objects[i]).BeginUpdate; try AppStorage.ReadPersistent('Highlighters\'+Highlighters[i], TPersistent(Highlighters.Objects[i])); finally TSynCustomHighlighter(Highlighters.Objects[i]).EndUpdate; end; end; CommandsDataModule.ApplyEditorOptions; if AppStorage.PathExists('Highlighters\Intepreter') then begin PythonIIForm.SynEdit.Highlighter.BeginUpdate; try AppStorage.ReadPersistent('Highlighters\Intepreter', PythonIIForm.SynEdit.Highlighter); finally PythonIIForm.SynEdit.Highlighter.EndUpdate; end; end; AppStorage.DeleteSubTree('Highlighters'); if AppStorage.PathExists('Interpreter Editor Options') then begin InterpreterEditorOptions.Gutter.Gradient := False; //default value AppStorage.ReadPersistent('Interpreter Editor Options', InterpreterEditorOptions); InterpreterEditorOptions.Options := (InterpreterEditorOptions.Options - [eoTrimTrailingSpaces, eoScrollPastEol]) + [eoTabsToSpaces]; PythonIIForm.SynEdit.Assign(InterpreterEditorOptions); PythonIIForm.RegisterHistoryCommands; end; if AppStorage.PathExists('Editor Search Options') then begin AppStorage.ReadPersistent('Editor Search Options', EditorSearchOptions); tbiSearchText.Items.CommaText := EditorSearchOptions.SearchTextHistory; tbiReplaceText.Items.CommaText := EditorSearchOptions.ReplaceTextHistory; end; AppStorage.ReadPersistent('Print Options', SynEditPrint); SynEditPrint.Header.AsString := AppStorage.ReadString('Print Options\HeaderItems', DefaultHeader); SynEditPrint.Footer.AsString := AppStorage.ReadString('Print Options\FooterItems', DefaultFooter); AppStorage.StorageOptions.PreserveLeadingTrailingBlanks := True; if AppStorage.PathExists('File Templates') then begin AppStorage.ReadObjectList('File Templates', FileTemplates, FileTemplates.CreateListItem); FileTemplates.AddDefaultTemplates; end; if AppStorage.PathExists('Code Templates') then AppStorage.ReadStringList('Code Templates', CodeTemplatesCompletion.AutoCompleteList); AppStorage.StorageOptions.PreserveLeadingTrailingBlanks := False; end; AppStorage.ReadPersistent('Secondary Tabs', TabsPersistsInfo); if AppStorage.PathExists('ToDo Options') then AppStorage.ReadPersistent('ToDo Options', ToDoExpert); AppStorage.ReadPersistent('Find in Files Options', FindResultsWindow.FindInFilesExpert); AppStorage.ReadPersistent('Find in Files Results Options', FindResultsWindow); AppStorage.ReadPersistent('Variables Window Options', VariablesWindow); AppStorage.ReadPersistent('Call Stack Window Options', CallStackWindow); AppStorage.ReadPersistent('Breakpoints Window Options', BreakPointsWindow); AppStorage.ReadPersistent('Messages Window Options', MessagesWindow); AppStorage.ReadPersistent('RegExp Tester Options', RegExpTesterWindow); FileExplorerWindow.actEnableFilter.Checked := AppStorage.ReadBoolean('File Explorer Filter', True); FileExplorerWindow.ExplorerPath := AppStorage.ReadString('File Explorer Path'); AppStorage.ReadStringList('File Explorer Favorites', FileExplorerWindow.Favorites); AppStorage.ReadPersistent('Code Explorer Options', CodeExplorerWindow); AppStorage.ReadStringList('Custom Params', CustomParams); RegisterCustomParams; AppStorage.ReadCollection('Tools', ToolsCollection, True, 'Tool'); AppStorage.ReadCollection('SSH', SSHServers, True, 'Server'); AppStorage.ReadPersistent('Tools\External Run', ExternalPython); OutputWindow.lsbConsole.Font.Name := AppStorage.ReadString('Output Window\Font Name', DefaultCodeFontName); OutputWindow.lsbConsole.Font.Size := AppStorage.ReadInteger('Output Window\Font Size', 9); OutputWindow.FontOrColorUpdated; AppStorage.ReadPersistent('Watches', WatchesWindow); StatusBar.Visible := AppStorage.ReadBoolean('Status Bar'); // Load Style Name TStyleSelectorForm.SetStyle(AppStorage.ReadString('Style Name', 'Windows10')); // Load IDE Shortcuts ActionProxyCollection := TActionProxyCollection.Create(apcctEmpty); try AppStorage.ReadCollection('IDE Shortcuts', ActionProxyCollection, True, 'Action'); ActionProxyCollection.ApplyShortCuts; finally ActionProxyCollection.Free; end; // Restore Interpreter History TempStringList := TStringList.Create; try AppStorage.StorageOptions.PreserveLeadingTrailingBlanks := True; AppStorage.ReadStringList('Command History', TempStringList); AppStorage.StorageOptions.PreserveLeadingTrailingBlanks := False; PythonIIForm.CommandHistory.Clear; for I := 0 to TempStringList.Count - 1 do PythonIIForm.CommandHistory.Add(StrEscapedToString(TempStringList[i])); PythonIIForm.CommandHistoryPointer := TempStringList.Count; // one after the last one finally TempStringList.Free; end; // Project Filename if CmdLineReader.readString('PROJECT') = '' then begin FName := AppStorage.ReadString('Active Project'); if FName <> '' then ProjectExplorerWindow.DoOpenProjectFile(FName); end; // Load MRU Lists tbiRecentFileList.LoadFromIni(AppStorage.IniFile, 'MRU File List'); tbiRecentProjects.LoadFromIni(AppStorage.IniFile, 'MRU Project List'); end; procedure TPyIDEMainForm.RestoreLocalApplicationData; begin OldMonitorProfile := LocalAppStorage.ReadString('Monitor profile'); LocalAppStorage.ReadStringList('Layouts', Layouts, True); if OldMonitorProfile <> MonitorProfile then begin LocalAppStorage.DeleteSubTree('Layouts\Default'); if Layouts.IndexOf('Default') >= 0 then Layouts.Delete(Layouts.IndexOf('Default')); LocalAppStorage.DeleteSubTree('Layouts\Current'); end; end; function TPyIDEMainForm.EditorFromTab(Tab : TSpTBXTabItem) : IEditor; Var Sheet : TSpTBXTabSheet; begin Result := nil; if Assigned(Tab) then begin Sheet := (Tab.Owner as TSpTBXTabControl).GetPage(Tab); if Assigned(Sheet) and (Sheet.ControlCount > 0) then Result := (Sheet.Controls[0] as TEditorForm).GetEditor; end; end; procedure TPyIDEMainForm.TabControlActiveTabChange(Sender: TObject; TabIndex: Integer); Var Index : integer; TabCtrl : TSpTBXTabControl; begin EditorSearchOptions.InitSearch; UpdateCaption; TabCtrl := Sender as TSpTBXTabControl; if Assigned(TabCtrl.ActivePage) and not (csDestroying in ComponentState) then // zOrder with TabCtrl do if not zOrderProcessing then begin Index := zOrder.IndexOf(TabCtrl.ActivePage.Item); if Index < 0 then zOrder.Insert(0, TabCtrl.ActivePage.Item) else zOrder.Move(Index, 0); zOrderPos := 0; end; end; procedure TPyIDEMainForm.TabControlMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); Var Editor : IEditor; IV: TTBItemViewer; TabItem : TSpTBXTabItem; begin TabItem := nil; IV := (Sender as TSpTBXTabToolbar).View.ViewerFromPoint(Point(X,Y)); if Assigned(IV) and (IV.Item is TSpTBXTabItem) then TabItem := TSpTBXTabItem(IV.Item); if Assigned(TabItem) and (Button = mbMiddle) then begin Editor := EditorFromTab(TabItem); if Assigned(Editor) then (Editor as IFileCommands).ExecClose; end else if (not Assigned(IV) or (IV.Item is TSpTBXRightAlignSpacerItem)) and (Shift = [ssLeft, ssDouble]) then begin if LocalAppStorage.PathExists('Layouts\BeforeZoom\Forms') then actRestoreEditorExecute(Sender) else actMaximizeEditorExecute(Sender); end; end; procedure TPyIDEMainForm.TabControlTabClosing(Sender: TObject; var Allow, CloseAndFree: Boolean); Var Editor : IEditor; begin Editor := EditorFromTab(Sender as TSpTBXTabItem); if Assigned(Editor) then begin Allow := False; TThread.ForceQueue(nil, procedure begin (Editor as IFileCommands).ExecClose; end); end; end; procedure TPyIDEMainForm.TabToolbarlDragDrop(Sender, Source: TObject; X, Y: Integer); Var Tab : TSpTBXTabItem; TargetTabControl : TSpTBXTabControl; IV : TTBItemViewer; Index : integer; begin if (Source is TSpTBXTabItemDragObject) and (TSpTBXTabItemDragObject(Source).SouceItem is TSpTBXTabItem) and (Sender is TSpTBXTabToolbar) and (TSpTBXTabItemDragObject(Source).SourceControl <> Sender) then begin Tab := TSpTBXTabItemDragObject(Source).SouceItem as TSpTBXTabItem; TargetTabControl := TSpTBXTabToolbar(Sender).Owner as TSpTBXTabControl; IV := TSpTBXTabToolbar(Sender).View.ViewerFromPoint(Point(X,Y)); if Assigned(IV) and (IV is TSpTBXTabItemViewer) then Index := TargetTabControl.Toolbar.Items.IndexOf(TSpTBXTabItemViewer(IV).Item) else Index := -1; MoveTab(Tab, TargetTabControl, Index); end; end; procedure TPyIDEMainForm.TabToolBarDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin if (Source is TSpTBXTabItemDragObject) then begin if TSpTBXTabItemDragObject(Source).DragCursorAccept <> crDrag then begin TSpTBXTabItemDragObject(Source).DragCursorAccept := crDrag; TSpTBXTabItemDragObject(Source).DragCursorCancel := crNo; end; Accept := True; end; end; procedure TPyIDEMainForm.UpdateStandardActions; Var L, R : Boolean; begin actBreakPointsWin.Checked := BreakPointsWindow.Visible; actCallStackWin.Checked := CallStackWindow.Visible; actMessagesWin.Checked := MessagesWindow.Visible; actVariablesWin.Checked := VariablesWindow.Visible; actViewCodeExplorer.Checked := CodeExplorerWindow.Visible; actViewFileExplorer.Checked := FileExplorerWindow.Visible; actViewToDoList.Checked := ToDoWindow.Visible; actViewRegExpTester.Checked := RegExpTesterWindow.Visible; actViewUnitTests.Checked := UnitTestWindow.Visible; actViewOutput.Checked := OutputWindow.Visible; actViewFindResults.Checked := FindResultsWindow.Visible; actVIewII.Checked := PythonIIForm.Visible; actViewProjectExplorer.Checked := ProjectExplorerWindow.Visible; actViewSplitEditorHor.Enabled := Assigned(GI_ActiveEditor); actViewSplitEditorVer.Enabled := Assigned(GI_ActiveEditor); actViewHideSecondEditor.Enabled := Assigned(GI_ActiveEditor) and GI_ActiveEditor.SynEdit2.Visible; actViewHideSecondaryWorkspace.Enabled := TabControl2.Visible; actWatchesWin.Checked := WatchesWindow.Visible; actViewStatusbar.Checked := StatusBar.Visible; actViewMainMenu .Checked := MainMenu.Visible; actFileNewModule.Enabled := GI_EditorFactory <> nil; actFileOpen.Enabled := GI_EditorFactory <> nil; actFileCloseAll.Enabled := (GI_EditorFactory <> nil) and (GI_EditorFactory.GetEditorCount > 0); actCommandLine.Checked := PyIDEOptions.UseCommandLine and (PyIDEOptions.CommandLine <> ''); // Refactoring actFindDefinition.Enabled := Assigned(GI_ActiveEditor) and GI_ActiveEditor.HasPythonFile; actFindReferences.Enabled := actFindDefinition.Enabled; actBrowseBack.Enabled := mnPreviousList.Count > 0; actBrowseForward.Enabled := mnNextList.Count > 0; // Python Engines case PyIDEOptions.PythonEngineType of peInternal : actPythonInternal.Checked := True; peRemote : actPythonRemote.Checked := True; peRemoteTk : actPythonRemoteTk.Checked := True; peRemoteWx : actPythonRemoteWx.Checked := True; peSSH : actPythonSSH.Checked := True; end; // Scroll Buttons TabControl1.ScrollState(L, R); tbiScrollLeft.Enabled := L; tbiScrollRight.Enabled := R; TabControl2.ScrollState(L, R); tbiScrollLeft2.Enabled := L; tbiScrollRight2.Enabled := R; end; procedure TPyIDEMainForm.FormShortCut(var Msg: TWMKey; var Handled: Boolean); begin Handled := CommandsDataModule.actlMain.IsShortCut(Msg); end; procedure TPyIDEMainForm.ChangeLanguage(LangCode: string); Var i : integer; begin if CompareText(GetCurrentLanguage, LangCode) <> 0 then begin UseLanguage(LangCode); RetranslateComponent(Self); RetranslateComponent(CommandsDataModule); SetupLanguageMenu; GI_EditorFactory.SetupEditorViewMenu; for i := 0 to GI_EditorFactory.Count - 1 do GI_EditorFactory.Editor[i].Retranslate; RegisterCustomParams; // To get tranlations of descriptions end; end; procedure TPyIDEMainForm.ScaleForPPI(NewPPI: Integer); begin // FCurrentPPI is changed to the NewPPI in the inherited method // Status bar StatusBar.Toolbar.Items.ViewBeginUpdate; try lbPythonVersion.MinWidth := MulDiv(lbPythonVersion.MinWidth, NewPPI, FCurrentPPI); lbPythonEngine.MinWidth := MulDiv(lbPythonEngine.MinWidth, NewPPI, FCurrentPPI); lbStatusCaret.CustomWidth := MulDiv(lbStatusCaret.CustomWidth, NewPPI, FCurrentPPI); lbStatusModified.CustomWidth := MulDiv(lbStatusModified.CustomWidth, NewPPI, FCurrentPPI); lbStatusOverwrite.CustomWidth := MulDiv(lbStatusOverwrite.CustomWidth, NewPPI, FCurrentPPI); lbStatusCaps.CustomWidth := MulDiv(lbStatusCaps.CustomWidth, NewPPI, FCurrentPPI); finally StatusBar.ToolBar.Items.ViewEndUpdate; end; inherited; end; procedure TPyIDEMainForm.LoadToolbarItems(const Path : string); var MemIni: TMemIniFile; SL: TStringList; begin if AppStorage.PathExists(Path) then begin MemIni := TMemIniFile.Create(''); SL := TStringList.Create; try AppStorage.ReadStringList(Path, SL); MemIni.SetStrings(SL); SpLoadItems(Self, MemIni); finally MemIni.Free; SL.Free; end; end; end; procedure TPyIDEMainForm.SaveToolbarItems(const Path : string); var MemIni: TMemIniFile; SL : TStringList; begin AppStorage.DeleteSubTree(Path); MemIni := TMemIniFile.Create(''); SL := TStringList.Create; try SpSaveItems(Self, MemIni); SL.Clear; MemIni.GetStrings(SL); AppStorage.WriteStringList(Path, SL); finally MemIni.Free; SL.Free; end; end; procedure TPyIDEMainForm.SaveToolbarLayout(const Layout: string); var ToolbarLayout: TStringList; begin ToolbarLayout := TStringList.Create; try SpTBXCustomizer.SaveLayout(ToolbarLayout, Layout); LocalAppStorage.WriteStringList('Layouts\' + Layout + '\Toolbars', ToolbarLayout); finally ToolbarLayout.Free; end; end; procedure TPyIDEMainForm.LoadToolbarLayout(const Layout: string); var ToolbarLayout: TStringList; Path: string; begin Path := 'Layouts\'+ Layout; if LocalAppStorage.PathExists(Path + '\Toolbars') then begin ToolbarLayout := TStringList.Create; try LocalAppStorage.ReadStringList(Path + '\Toolbars', ToolbarLayout); SpTBXCustomizer.LoadLayout(ToolbarLayout, Layout); finally ToolbarLayout.Free; end; end; end; procedure TPyIDEMainForm.CloseTimerTimer(Sender: TObject); begin PostMessage(Application.Handle, WM_CLOSE, 0, 0); CloseTimer.Enabled := False; end; procedure TPyIDEMainForm.SetupToolsMenu; Var i : integer; MenuItem : TSpTBXItem; Action : TAction; Tool : TExternalTool; begin // delete actions and menus added in previous calls mnTools.Clear; for i := actlStandard.ActionCount - 1 downto 0 do if actlStandard.Actions[i].Category = 'External Tools' then actlStandard.Actions[i].Free; for i := 0 to ToolsCollection.Count - 1 do begin Tool := (ToolsCollection.Items[i] as TToolItem).ExternalTool; if Tool.Caption <> '' then begin MenuItem := TSpTBXItem.Create(Self); Action := TExternalToolAction.CreateExtToolAction(Self, Tool); Action.ActionList := actlStandard; mnTools.Add(MenuItem); MenuItem.Action := Action; MenuItem.Images := TPyScripterSettings.ShellImages; end; end; end; procedure TPyIDEMainForm.SetupLanguageMenu; Var MenuItem : TSpTBXItem; i : integer; CurrentLanguage : string; HaveLang : boolean; begin mnLanguage.Clear; CurrentLanguage := GetCurrentLanguage; DefaultInstance.BindtextdomainToFile ('languagecodes',ExtractFilePath(Application.ExeName)+'locale\languagecodes.mo'); DefaultInstance.GetListOfLanguages ('default',fLanguageList); fLanguageList.Insert(0, 'en'); HaveLang := False; for i := 0 to fLanguageList.Count - 1 do begin MenuItem := TSpTBXItem.Create(Self); // Translate the language code to English language name and then to a localized language name MenuItem.Caption := dgettext('languages', dgettext('languagecodes', fLanguageList[i])); MenuItem.Tag := i; if fLanguageList[i] = CurrentLanguage then begin MenuItem.Checked := True; HaveLang := True; end; MenuItem.OnClick := mnLanguageClick; MenuItem.HelpContext := 360; mnLanguage.Add(MenuItem); end; if not HaveLang then mnLanguage.Items[0].Checked := True; end; procedure TPyIDEMainForm.SetupLayoutsMenu; Var i : integer; MenuItem : TSpTBXItem; begin // delete previous Layouts while mnLayouts.Items[0] <> mnLayOutSeparator do mnLayouts.Items[0].Free; for i := Layouts.Count - 1 downto 0 do begin MenuItem := TSpTBXItem.Create(Self); mnLayouts.Insert(0, MenuItem); MenuItem.Caption := Layouts[i]; MenuItem.GroupIndex := 2; MenuItem.OnClick := LayoutClick; MenuItem.Hint := Format(_(SApplyLayout), [Layouts[i]]); end; end; procedure TPyIDEMainForm.mnSyntaxPopup(Sender: TTBCustomItem; FromLink: Boolean); Var i : integer; Editor : IEditor; begin Editor := GetActiveEditor; for i := 0 to mnSyntax.Count - 3 do begin mnSyntax.Items[i].Enabled := Assigned(Editor); mnSyntax.Items[i].Checked := Assigned(Editor) and Assigned(Editor.Synedit.Highlighter) and (Editor.Synedit.Highlighter.FriendlyLanguageName = mnSyntax.Items[i].Caption); end; mnNoSyntax.Enabled := Assigned(Editor); mnNoSyntax.Checked := Assigned(Editor) and not Assigned(Editor.SynEdit.Highlighter); end; procedure TPyIDEMainForm.MoveTab(Tab: TSpTBXTabItem; TabControl: TSpTBXTabControl; Index: integer); Var NewTab : TSpTBXTabItem; Sheet, NewSheet : TSpTBXTabSheet; EditorForm : TEditorForm; begin if (Tab.Owner = TabControl) or not Assigned(Tab) then Exit; if Index >= 0 then NewTab := TabControl.Insert(Index, Tab.Caption) else NewTab := TabControl.Add(Tab.Caption); EditorForm := nil; Sheet := (Tab.Owner as TSpTBXTabControl).GetPage(Tab); if Assigned(Sheet) and (Sheet.ControlCount > 0) then EditorForm := Sheet.Controls[0] as TEditorForm; if Assigned(EditorForm) then begin EditorForm.Visible := False; NewSheet := (NewTab.Owner as TSpTBXTabControl).GetPage(NewTab); EditorForm.ParentTabItem := NewTab; EditorForm.ParentTabControl := TabControl; EditorForm.Parent := NewSheet; EditorForm.Align := alClient; NewSheet.InsertComponent(EditorForm); // changes ownership NewTab.OnTabClosing := TabControlTabClosing; NewTab.OnDrawTabCloseButton := DrawCloseButton; EditorForm.Visible := True; end; Tab.Free; NewTab.Click; end; procedure TPyIDEMainForm.SyntaxClick(Sender: TObject); Var Editor : IEditor; begin // Change Syntax sheme Editor := GetActiveEditor; if Assigned(Editor) then begin Editor.SynEdit.Highlighter := TSynCustomHighlighter((Sender as TTBCustomItem).Tag); Editor.SynEdit2.Highlighter := Editor.SynEdit.Highlighter; TEditorForm(Editor.Form).DefaultExtension := ''; end; end; procedure TPyIDEMainForm.mnNoSyntaxClick(Sender: TObject); Var Editor : IEditor; begin Editor := GetActiveEditor; if Assigned(Editor) then begin Editor.SynEdit.Highlighter := nil; Editor.SynEdit2.Highlighter := nil; end; end; procedure TPyIDEMainForm.PythonVersionsClick(Sender: TObject); begin PyControl.PythonVersionIndex := (Sender as TTBCustomItem).Tag; end; procedure TPyIDEMainForm.mnPythonVersionsPopup(Sender: TTBCustomItem; FromLink: Boolean); Var i : integer; PythonLoaded: Boolean; begin PythonLoaded := GI_PyControl.PythonLoaded; for i := 0 to mnPythonVersions.Count - 3 do begin mnPythonVersions.Items[i].Enabled := PyControl.DebuggerState = dsInactive; mnPythonVersions.Items[i].Checked := PythonLoaded and (PyControl.PythonVersionIndex = mnPythonVersions.Items[i].Tag); end; case Sender.Tag of 0: mnPythonVersions.Items[mnPythonVersions.Count-1].ImageIndex := 154; 1: mnPythonVersions.Items[mnPythonVersions.Count-1].ImageIndex := 6; // from Interpreter end; end; procedure TPyIDEMainForm.SetupSyntaxMenu; Var i : integer; MenuItem : TSpTBXItem; begin while mnSyntax.Count > 2 do mnSyntax.Delete(0); for i := CommandsDataModule.Highlighters.Count - 1 downto 0 do begin MenuItem := TSpTBXItem.Create(Self); mnSyntax.Insert(0, MenuItem); MenuItem.Caption := _(CommandsDataModule.Highlighters[i]); MenuItem.Tag := Integer(CommandsDataModule.Highlighters.Objects[i]); MenuItem.GroupIndex := 3; MenuItem.OnClick := SyntaxClick; MenuItem.Hint := Format(_(SUseSyntax), [MenuItem.Caption]); end; end; procedure TPyIDEMainForm.SetupPythonVersionsMenu; Var i : Integer; MenuItem : TTBCustomItem; begin // remove previous versions while mnPythonVersions.Count > 2 do mnPythonVersions.Items[0].Free; // Add versions in reverse order for i := Length(PyControl.CustomPythonVersions) - 1 downto 0 do begin MenuItem := TSpTBXItem.Create(Self); mnPythonVersions.Insert(0, MenuItem); MenuItem.Caption := PyControl.CustomPythonVersions[i].DisplayName; MenuItem.GroupIndex := 3; MenuItem.Tag := -(i + 1); MenuItem.OnClick := PythonVersionsClick; MenuItem.Hint := Format(_(SSwitchtoVersion), [MenuItem.Caption]); end; if Length(PyControl.CustomPythonVersions) > 0 then begin MenuItem := TSpTBXSeparatorItem.Create(Self); MenuItem.Tag := MenuItem.Tag.MaxValue; mnPythonVersions.Insert(0, MenuItem); end; for i := Length(PyControl.RegPythonVersions) - 1 downto 0 do begin MenuItem := TSpTBXItem.Create(Self); mnPythonVersions.Insert(0, MenuItem); MenuItem.Caption := PyControl.RegPythonVersions[i].DisplayName; MenuItem.GroupIndex := 3; MenuItem.Tag := i; MenuItem.OnClick := PythonVersionsClick; MenuItem.Hint := Format(_(SSwitchtoVersion), [MenuItem.Caption]); end; end; procedure TPyIDEMainForm.SplitWorkspace(SecondTabsVisible : Boolean; Alignment : TAlign; Size : integer); begin TabSplitter.Visible := False; TabControl2.Visible := False; ActiveTabControlIndex := 1; if SecondTabsVisible then begin TabControl2.Align := Alignment; if Alignment = alRight then TabControl2.Width := IfThen(Size >= 0, Size, (BGPanel.ClientWidth - 5) div 2) else TabControl2.Height := IfThen(Size >= 0, Size, (BGPanel.ClientHeight - 5) div 2); TabSplitter.Align := Alignment; TabControl2.Visible := True; TabSplitter.Visible := True; end; end; procedure TPyIDEMainForm.SetupCustomizer; var K: Integer; ItemStyle: TTBItemStyle; ActionList: TActionList; Action: TContainedAction; ItemsList: TList; I: Integer; ParentItem: TTBCustomItem; C: TComponent; J: Integer; Item: TTBCustomItem; begin SpTBXCustomizer.Items.Clear; ItemsList := TList.Create; try for I := 0 to ComponentCount - 1 do begin ParentItem := nil; C := Components[I]; if C is TSpTBXToolbar and TSpTBXToolbar(C).Customizable then ParentItem := TSpTBXToolbar(C).Items; if Assigned(ParentItem) then begin for J := 0 to ParentItem.Count - 1 do begin Item := ParentItem[j]; ItemStyle := TTBCustomItemAccess(Item).ItemStyle; // Exclude the submenus, separators, labels, groups and edit items if (ItemStyle * [tbisSubMenu, tbisSeparator, tbisEmbeddedGroup, tbisClicksTransparent] = []) and not (Item is TTBEditItem) then ItemsList.Add(Item); end; end; end; for I := Low(TActionProxyCollection.ActionLists) to High(TActionProxyCollection.ActionLists) do begin ActionList := TActionProxyCollection.ActionLists[I]; for J := 0 to ActionList.ActionCount - 1 do begin Action := ActionList.Actions[J]; for K := 0 to ItemsList.Count - 1 do if TTBCustomItem(ItemsList[K]).Action = Action then begin Action := nil; break; end; if Assigned(Action) then begin // Find items of External actions on UserToolbars Item := FindComponent('tb' + Action.Name) as TTBCustomItem; if not Assigned(Item) then begin Item := TSpTBXItem.Create(Self); Item.Name := 'tb' + Action.Name; if Action is TExternalToolAction then Item.Images := TPyScripterSettings.ShellImages; SpTBXCustomizer.Items.Add(Item); end; Item.Action := Action; end; end; end; finally ItemsList.Free; end; end; procedure TPyIDEMainForm.LoadLayout(const Layout: string); Var Path : string; i : integer; SaveActiveControl : TWinControl; TempCursor : IInterface; begin Path := 'Layouts\'+ Layout; if LocalAppStorage.PathExists(Path + '\Forms') then begin TempCursor := WaitCursor; SaveActiveControl := ActiveControl; try // Now Load the DockTree LoadDockTreeFromAppStorage(LocalAppStorage, Path); finally for i := 0 to Screen.FormCount - 1 do begin if Screen.Forms[i] is TIDEDockWindow then TIDEDockWindow(Screen.Forms[i]).FormDeactivate(Self); end; end; if CanActuallyFocus(SaveActiveControl) then try SaveActiveControl.SetFocus; except end; end; // Now Restore the toolbars LoadToolbarLayout(Layout); end; procedure TPyIDEMainForm.SaveLayout(const Layout: string); begin LocalAppstorage.DeleteSubTree('Layouts\'+Layout); SaveDockTreeToAppStorage(LocalAppStorage, 'Layouts\'+ Layout); SaveToolbarLayout(Layout); end; procedure TPyIDEMainForm.LayoutClick(Sender: TObject); begin LoadLayout(TSpTBXItem(Sender).Caption); TSpTBXItem(Sender).Checked := True; end; function TPyIDEMainForm.LayoutExists(const Layout: string): Boolean; begin Result := Layouts.IndexOf(Name) >= 0; end; procedure TPyIDEMainForm.lbPythonEngineClick(Sender: TObject); var MousePos : TPoint; begin GetCursorPos(MousePos); MousePos := ScreenToClient(MousePos); mnPythonEngines.Popup(MousePos.X, MousePos.Y, True); end; procedure TPyIDEMainForm.lbPythonVersionClick(Sender: TObject); begin actPythonSetup.Execute; end; procedure TPyIDEMainForm.lbStatusCaretClick(Sender: TObject); begin CommandsDataModule.actSearchGoToLineExecute(Self); end; procedure TPyIDEMainForm.actLayoutSaveExecute(Sender: TObject); Var LayoutName : string; TempCursor : IInterface; begin if InputQuery(_(SSaveCurrentLayout), _(SLayoutName), LayoutName) then begin TempCursor := WaitCursor; if Layouts.IndexOf(LayoutName) < 0 then begin Layouts.Add(LayoutName); SetupLayoutsMenu; end; SaveLayout(LayoutName); end; end; procedure TPyIDEMainForm.actLayoutsDeleteExecute(Sender: TObject); Var LayoutName : string; i : integer; begin with TPickListDialog.Create(Self) do begin Caption := _(SDeleteLayouts); lbMessage.Caption := _(SSelectLayouts); CheckListBox.Items.Assign(Layouts); if ShowModal = IdOK then begin for i := CheckListBox.Count - 1 downto 0 do begin if CheckListBox.Checked[i] then begin LayoutName := Layouts[i]; LocalAppstorage.DeleteSubTree('Layouts\'+LayoutName); Layouts.Delete(i); SetupLayoutsMenu; end; end; end; Free; end; end; procedure TPyIDEMainForm.actLayoutDebugExecute(Sender: TObject); begin if Layouts.IndexOf('Debug') < 0 then Layouts.Add('Debug'); SaveLayout('Debug'); SetupLayoutsMenu; end; procedure TPyIDEMainForm.actExternalRunExecute(Sender: TObject); Var ActiveEditor : IEditor; RunConfig : TRunConfiguration; begin ActiveEditor := GetActiveEditor; if Assigned(ActiveEditor) then begin ActiveEditor.Activate; RunConfig := TRunConfiguration.Create; try SetupRunConfiguration(RunConfig, ActiveEditor); PyControl.ExternalRun(RunConfig); finally RunConfig.Free; end; end; end; procedure TPyIDEMainForm.actExecSelectionExecute(Sender: TObject); begin if Assigned(GI_ActiveEditor) and GI_ActiveEditor.HasPythonFile and GI_ActiveEditor.SynEdit.SelAvail then GI_ActiveEditor.ExecuteSelection; end; procedure TPyIDEMainForm.actExternalRunConfigureExecute(Sender: TObject); begin EditTool(ExternalPython, True); end; procedure TPyIDEMainForm.WriteStatusMsg(const S: string); begin lbStatusMessage.Caption := S; end; procedure TPyIDEMainForm.ThemeEditorGutter(Gutter : TSynGutter); Var GradColor: TColor; begin Assert(SkinManager.GetSkinType <> sknSkin); if SkinManager.GetSkinType in [sknNone, sknWindows] then begin Gutter.GradientStartColor := clWindow; Gutter.GradientEndColor := clBtnFace; Gutter.Font.Color := clSilver; Exit; end; // Delphi Styles if not StyleServices.GetElementColor(StyleServices.GetElementDetails(ttTabItemNormal), ecFillColor, GradColor) or (GradColor = clNone) then GradColor := StyleServices.GetSystemColor(clBtnFace); Gutter.Font.Color := StyleServices.GetSystemColor(clGrayText);; with Gutter do begin BorderStyle := gbsNone; GradientStartColor := LightenColor(GradColor, 40); GradientEndColor := DarkenColor(GradColor, 20); end; end; procedure TPyIDEMainForm.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; with ActiveTabControl as TSpTBXTabControl do if (Key = VK_Control) and zOrderProcessing then begin zOrderProcessing := False; KeyPreview := False; if (zOrderPos > 0) and (zOrderPos < zOrder.Count) then begin zOrder.Move(zOrderPos, 0); zOrderPos := 0; end; end; end; procedure TPyIDEMainForm.AdjustBrowserLists(FileName: string; Line: Integer; Col: Integer; FilePosInfo: string); begin if FilePosInfo <> '' then begin // Adjust previous/next menus PrevMRUAdd(Format(FilePosInfoFormat, [FileName, Line, Col])); mnNextList.Clear; fCurrentBrowseInfo := FilePosInfo; end; end; procedure TPyIDEMainForm.actFindDefinitionExecute(Sender: TObject); Var FilePosInfo : string; FileName : string; CaretXY : TBufferCoord; begin Application.ProcessMessages; if Assigned(GI_ActiveEditor) then begin FileName := GI_ActiveEditor.GetFileNameOrTitle; CaretXY := GI_ActiveEditor.ActiveSynEdit.CaretXY; FindDefinition(GI_ActiveEditor, CaretXY, True, False, True, FilePosInfo); AdjustBrowserLists(FileName, CaretXY.Line, CaretXY.Char, FilePosInfo); end; end; procedure TPyIDEMainForm.FindDefinition(Editor : IEditor; TextCoord: TBufferCoord; ShowMessages, Silent, JumpToFirstMatch: Boolean; var FilePosInfo : string); var Defs : Variant; Token : string; FName, FileName, ErrMsg: string; TokenType, Start, Line, Col: Integer; Attri: TSynHighlighterAttributes; TempCursor : IInterface; CE: TBaseCodeElement; ParsedModule : TParsedModule; begin FilePosInfo := ''; VarClear(Defs); if Assigned(Editor) and Editor.HasPythonFile then with Editor.SynEdit do begin if GetHighlighterAttriAtRowColEx(TextCoord, Token, TokenType, Start, Attri) then begin case TokenType of Ord(tkFunctionName), Ord(tkClassName): begin if not Silent then Vcl.Dialogs.MessageDlg(Format(_(SFindDefinitionWarning), [Token]), mtInformation, [mbOK], 0); Exit; end; Ord(tkIdentifier) : begin TempCursor := WaitCursor; FName := Editor.GetFileNameOrTitle; if ShowMessages then begin GI_PyIDEServices.Messages.ClearMessages; GI_PyIDEServices.Messages.AddMessage(_(SDefinitionsOf) + Token + '"'); end; FileName := ''; Line := 0; Col := 1; CE := PyScripterRefactor.FindDefinitionByCoordinates(FName, CaretY, CaretX, ErrMsg); if Assigned(CE) and not CE.IsProxy then begin ParsedModule := CE.GetModule; FileName := ParsedModule.FileName; Line := CE.CodePos.LineNo; Col := CE.CodePos.CharOffset; if ShowMessages then GI_PyIDEServices.Messages.AddMessage(_(SDefinitionFound), FileName, Line, Col); end; if ShowMessages then ShowDockForm(MessagesWindow); if FileName <> '' then begin FilePosInfo := Format(FilePosInfoFormat, [Filename, Line, Col]); if JumpToFirstMatch then ShowFilePosition(Filename, Line, Col); end else begin if ShowMessages then GI_PyIDEServices.Messages.AddMessage(_(SDefinitionNotFound)); MessageBeep(MB_ICONASTERISK); end; end; else if not Silent then Vcl.Dialogs.MessageDlg(_(SPlaceCursorOnName), mtError, [mbOK], 0); end; end; end; end; procedure TPyIDEMainForm.FindToolbarVisibleChanged(Sender: TObject); Var SearchCommands : ISearchCommands; begin if not FindToolbar.Visible then begin ClearAllHighlightedTerms; SearchCommands := CommandsDataModule.FindSearchTarget; if Assigned(SearchCommands) and CanActuallyFocus(SearchCommands.SearchTarget) then SearchCommands.SearchTarget.SetFocus; end; end; procedure TPyIDEMainForm.actFindReferencesExecute(Sender: TObject); var Token : string; FName, FileName, ErrMsg : string; TokenType, Start, Line, Col, i : Integer; Attri: TSynHighlighterAttributes; TempCursor : IInterface; FoundReferences : Boolean; ResultsList : TStringList; RegEx : TRegEx; begin Application.ProcessMessages; TempCursor := WaitCursor; if Assigned(GI_ActiveEditor) and GI_ActiveEditor.HasPythonFile then with GI_ActiveEditor.ActiveSynEdit do begin if GetHighlighterAttriAtRowColEx(CaretXY, Token, TokenType, Start, Attri) then begin case TokenType of Ord(tkFunctionName), Ord(tkClassName), Ord(tkIdentifier) : begin FName := GI_ActiveEditor.FileName; if FName = '' then FName := GI_ActiveEditor.FileTitle; GI_PyIDEServices.Messages.ClearMessages; GI_PyIDEServices.Messages.AddMessage(_(SReferencesOf) + Token + '"'); ResultsList := TStringList.Create; try PyScripterRefactor.FindReferencesByCoordinates(FName, CaretY, CaretX, ErrMsg, ResultsList); FoundReferences := ResultsList.Count > 0; RegEx.Create(FilePosInfoRegExpr); i := 0; while i < ResultsList.Count -1 do begin with RegEx.Match(ResultsList[i]) do if Success then begin FileName := GroupValue(1); Line := StrToInt(GroupValue(2)); Col := StrToInt(GroupValue(3)); GI_PyIDEServices.Messages.AddMessage(ResultsList[i+1], Filename, Line, Col, Token.Length); end; Inc(i, 2); end; finally ResultsList.Free; end; ShowDockForm(MessagesWindow); if not FoundReferences then begin GI_PyIDEServices.Messages.AddMessage(_(SReferencesNotFound)); MessageBeep(MB_ICONASTERISK); end; end; else Vcl.Dialogs.MessageDlg(_(SPlaceCursorOnName), mtError, [mbOK], 0); end; end; end; end; procedure TPyIDEMainForm.WMSpSkinChange(var Message: TMessage); begin // Update EditorOptions ThemeEditorGutter(EditorOptions.Gutter); PyIDEOptions.CodeFolding.FolderBarLinesColor := EditorOptions.Gutter.Font.Color; // BGPanel.Color := CurrentTheme.GetItemColor(GetItemInfo('inactive')); // Application.HintColor := CurrentTheme.GetViewColor(VT_DOCKPANEL); end; procedure TPyIDEMainForm.CMStyleChanged(var Message: TMessage); begin SkinManager.BroadcastSkinNotification; end; procedure TPyIDEMainForm.WMFindDefinition(var Msg: TMessage); Var FilePosInfo : string; FileName : string; Line, Col : integer; begin if Assigned(GI_ActiveEditor) then begin FileName := GI_ActiveEditor.GetFileNameOrTitle; Line := Msg.LParam; Col := Msg.WParam; FindDefinition(GI_ActiveEditor, BufferCoord(Col, Line), False, True, True, FilePosInfo); AdjustBrowserLists(FileName, Line, Col, FilePosInfo); end; end; procedure TPyIDEMainForm.WMSearchReplaceAction(var Msg: TMessage); Var Action : TCustomAction; begin if Msg.LParam <> 0 then begin Action := TCustomAction(Msg.LParam); Action.Execute; end else begin if Msg.WParam = 2 then begin // incremental search CommandsDataModule.IncrementalSearch; end; end; end; function TPyIDEMainForm.JumpToFilePosInfo(FilePosInfo: string): boolean; Var FileName : string; Line, Col : integer; begin Result := False; with TRegEx.Match(FilePosInfo, FilePosInfoRegExpr) do if Success then begin FileName := GroupValue(1); Line := StrToInt(GroupValue(2)); Col := StrToInt(GroupValue(3)); Exit(ShowFilePosition(FileName, Line, Col)); end; end; procedure TPyIDEMainForm.DrawCloseButton(Sender: TObject; ACanvas: TCanvas; State: TSpTBXSkinStatesType; const PaintStage: TSpTBXPaintStage; var AImageList: TCustomImageList; var AImageIndex: Integer; var ARect: TRect; var PaintDefault: Boolean); Var Editor : IEditor; PatternColor: TColor; R : TRect; begin Editor := EditorFromTab(TSpTBXTabItem(Sender)); if not Assigned(Editor) then Exit; PaintDefault := False; AImageIndex := -1; if State = sknsHotTrack then begin R := ARect; InflateRect(R, -1, -1); SpDrawXPButton(ACanvas, R, True, False, True, False, False, False); end; PatternColor := CurrentSkin.GetTextColor(skncToolbarItem, State); if Editor.Modified then begin R := SpCenterRect(ARect, PPIScale(2), PPIScale(2)); ExcludeClipRect(ACanvas.Handle,R.Left, R.Top, R.Right, R.Bottom); end; SpDrawGlyphPattern(ACanvas, ARect, gptClose, PatternColor); if Editor.Modified then SelectClipRgn(ACanvas.Handle, 0); end; procedure TPyIDEMainForm.PrevClickHandler(Sender: TObject); var A: TSpTBXMRUItem; begin if Sender is TSpTBXMRUItem then begin A := TSpTBXMRUItem(Sender); if Assigned(mnPreviousList.OnClick) then mnPreviousList.OnClick(mnPreviousList, A.MRUString); end; end; procedure TPyIDEMainForm.PreviousListClick(Sender: TObject; S : string); Var i, Index : integer; begin Index := mnPreviousList.IndexOfMRU(S); if (Index >= 0) and (Index < mnPreviousList.Count) then begin JumpToFilePosInfo(S); NextMRUAdd(fCurrentBrowseInfo); fCurrentBrowseInfo := S; for i := 0 to Index - 1 do NextMRUAdd(TSpTBXMRUItem(mnPreviousList.Items[i]).MRUString); for i := 0 to Index do mnPreviousList.MRURemove(TSpTBXMRUItem(mnPreviousList.Items[0]).MRUString); end; end; procedure TPyIDEMainForm.PrevMRUAdd(S : string); begin mnPreviousList.MRUAdd(S); mnPreviousList.Items[0].OnClick := PrevClickHandler; end; procedure TPyIDEMainForm.tbiBrowsePreviousClick(Sender: TObject); begin if mnPreviousList.Count > 0 then PreviousListClick(Sender, TSpTBXMRUItem(mnPreviousList.Items[0]).MRUString); end; function TPyIDEMainForm.NewFileFromTemplate( FileTemplate: TFileTemplate; TabControlIndex : integer): IEditor; Var i, j : integer; TabCtrl : TSpTBXTabControl; Editor : IEditor; EditorView: IEditorView; begin // create a new editor, add it to the editor list TabCtrl := TabControl(TabControlIndex); TabCtrl.Toolbar.BeginUpdate; try Result := DoCreateEditor(TabCtrl); if Result <> nil then begin try Result.OpenFile('', FileTemplate.Highlighter); Result.Activate; except Result.Close; raise end; Result.SynEdit.SelText := Parameters.ReplaceInText(FileTemplate.Template); // Locate the caret symbol | for i := 0 to Result.SynEdit.Lines.Count - 1 do begin j := CharPos(Result.SynEdit.Lines[i], '|'); if j > 0 then begin Result.SynEdit.CaretXY := BufferCoord(j + 1, i + 1); Result.SynEdit.ExecuteCommand(ecDeleteLastChar, ' ', nil); break; end; end; Result.SynEdit.ClearUndo; Result.SynEdit.Modified := False; TEditorForm(Result.Form).DefaultExtension := FileTemplate.Extension; // Jupyter support if (LowerCase(FileTemplate.Extension) = 'ipynb') and (OutputWindow.JvCreateProcess.State = psReady) then begin Editor := Result; (Editor as IFileCommands).ExecSave; TThread.ForceQueue(nil, procedure begin EditorView := Editor.ActivateView(GI_EditorFactory.ViewFactory[WebPreviewFactoryIndex]); if Assigned(EditorView) then EditorView.UpdateView(Editor); end); end; end; finally TabCtrl.Toolbar.EndUpdate; if Assigned(TabCtrl.ActiveTab) then TabCtrl.MakeVisible(TabCtrl.ActiveTab); UpdateCaption; end; end; procedure TPyIDEMainForm.NextClickHandler(Sender: TObject); var A: TSpTBXMRUItem; begin if Sender is TSpTBXMRUItem then begin A := TSpTBXMRUItem(Sender); if Assigned(mnNextList.OnClick) then mnNextList.OnClick(mnNextList, A.MRUString); end; end; procedure TPyIDEMainForm.NextListClick(Sender: TObject; S : string); Var i, Index : integer; begin Index := mnNextList.IndexOfMRU(S); if (Index >= 0) and (Index < mnNextList.Count) then begin JumpToFilePosInfo(S); PrevMRUAdd(fCurrentBrowseInfo); fCurrentBrowseInfo := S; for i := 0 to Index - 1 do PrevMRUAdd(TSpTBXMRUItem(mnNextList.Items[i]).MRUString); for i := 0 to Index do mnNextList.MRURemove(TSpTBXMRUItem(mnNextList.Items[0]).MRUString); end; end; procedure TPyIDEMainForm.NextMRUAdd(S : string); begin mnNextList.MRUAdd(S); mnNextList.Items[0].OnClick := NextClickHandler; end; function TPyIDEMainForm.OpenCmdLineFile(FileName : string): Boolean; begin // Try to see whether it contains line/char info Result := JumpToFilePosInfo(FileName); if not Result and FileExists(FileName) then Result := Assigned(DoOpenFile(FileName, '', TabControlIndex(ActiveTabControl))); end; procedure TPyIDEMainForm.tbiBrowseNextClick(Sender: TObject); begin if mnNextList.Count > 0 then begin NextListClick(Sender, TSpTBXMRUItem(mnNextList.Items[0]).MRUString); end; end; procedure TPyIDEMainForm.ApplicationActionExecute(Action: TBasicAction; var Handled: Boolean); Var Msg : Cardinal; begin if (Action is TEditAction) and Assigned(Screen.ActiveControl) and (Screen.ActiveControl is TCombobox) and not TComboBox(Screen.ActiveControl).DroppedDown then begin Msg := 0; if Action is TEditCopy then Msg := WM_COPY else if Action is TEditCut then Msg := WM_CUT else if Action is TEditPaste then Msg := WM_PASTE; if Msg <> 0 then begin PostMessage(Screen.ActiveControl.Handle, Msg, 0, 0); Handled := True; end; end; end; procedure TPyIDEMainForm.ApplicationActionUpdate(Action: TBasicAction; var Handled: Boolean); begin if (Action is TEditAction) then begin if Assigned(Screen.ActiveControl) and (Screen.ActiveControl is TCombobox) and not TComboBox(Screen.ActiveControl).DroppedDown then begin TEditAction(Action).Enabled := (Action is TEditCut) and (TComboBox(Screen.ActiveControl).SelLength > 0) or (Action is TEditCopy) and (TComboBox(Screen.ActiveControl).SelLength > 0) or (Action is TEditPaste) and Clipboard.HasFormat(CF_UNICODETEXT); Handled := (Action is TEditCut) or (Action is TEditCopy) or (Action is TEditPaste); end else if ((Action is TEditCopy) or (Action is TEditCut)) and Assigned(GI_ActiveEditor) then begin TEditAction(Action).Enabled := True; Handled := True; end; end; end; function TPyIDEMainForm.ApplicationHelp(Command: Word; Data: NativeInt; var CallHelp: Boolean): Boolean; Var KeyWord : string; begin CallHelp := True; Result := False; // We are not going to show popup help //if Command = HELP_SETPOPUP_POS then exit; if not PythonKeywordHelpRequested and not MenuHelpRequested and Active and (ActiveControl is TSynEdit) and (TSynEdit(ActiveControl).Highlighter = CommandsDataModule.SynPythonSyn) then begin Keyword := TSynEdit(ActiveControl).WordAtCursor; if Keyword <> '' then begin CallHelp := not CommandsDataModule.ShowPythonKeywordHelp(KeyWord); Result := True; end; end; end; procedure TPyIDEMainForm.WMCheckForUpdates(var Msg: TMessage); begin try CommandsDataModule.actCheckForUpdatesExecute(nil); // nil so that we get no confirmation except // fail silently end; end; procedure TPyIDEMainForm.FormShow(Sender: TObject); begin //OutputDebugString(PWideChar(Format('%s ElapsedTime %d ms', ['FormShow start', StopWatch.ElapsedMilliseconds]))); // Do not execute again OnShow := nil; // Repeat here to make sure it is set right MaskFPUExceptions(PyIDEOptions.MaskFPUExceptions); // fix for staturbar appearing above interpreter if StatusBar.Visible then StatusBar.Top := MaxInt; // Update Syntax and Layouts menu SetupLayoutsMenu; SetupSyntaxMenu; // Start accepting files DragAcceptFiles(TabControl1.Handle, True); DragAcceptFiles(TabControl2.Handle, True); TThread.ForceQueue(nil, procedure begin // Activate File Explorer FileExplorerWindow.FileExplorerTree.Active := True; //Application.ProcessMessages; // Load Python Engine and Assign Debugger Events PyControl.LoadPythonEngine; SetupPythonVersionsMenu; // Update External Tools SetupToolsMenu; // After creating internal interpreter SetupCustomizer; // After setting up the Tools menu // Load Toolbar Items after setting up the Tools menu if FileExists(AppStorage.IniFile.FileName) then LoadToolbarItems('Toolbar Items'); with PyControl do begin OnBreakpointChange := DebuggerBreakpointChange; OnCurrentPosChange := DebuggerCurrentPosChange; OnErrorPosChange := DebuggerErrorPosChange; OnStateChange := DebuggerStateChange; OnYield := DebuggerYield; end; // This is needed to update the variables window PyControl.DoStateChange(dsInactive); // Open initial files after loading Python (#879) OpenInitialFiles; if Layouts.IndexOf('Default') < 0 then begin SaveLayout('Default'); Layouts.Add('Default'); end; if PyIDEOptions.AutoCheckForUpdates and (DaysBetween(Now, PyIDEOptions.DateLastCheckedForUpdates) >= PyIDEOptions.DaysBetweenChecks) and ConnectedToInternet then PostMessage(Handle, WM_CHECKFORUPDATES, 0, 0); if not GI_PyControl.PythonLoaded then actPythonSetupExecute(Self); end); //OutputDebugString(PWideChar(Format('%s ElapsedTime %d ms', ['FormShow end', StopWatch.ElapsedMilliseconds]))); end; procedure TPyIDEMainForm.JvAppInstancesCmdLineReceived(Sender: TObject; CmdLine: TStrings); var i : integer; begin if JvAppInstances.AppInstances.InstanceIndex[GetCurrentProcessID] <> 0 then Exit; for i := 0 to CmdLine.Count - 1 do if (CmdLine[i][1] <> '-') then //DoOpenFile(CmdLine[i]); ShellExtensionFiles.Add(CmdLine[i]) end; //function TPyIDEMainForm.FindAction(var Key: Word; Shift: TShiftState) : TCustomAction; //var // ShortCut : TShortCut; // i, j : Integer; // Action : TContainedAction; // ActionList : TActionList; //begin // Result := nil; // ShortCut := Menus.ShortCut(Key, Shift); // if ShortCut <> scNone then // for j := 0 to Length(TActionProxyCollection.ActionLists) do begin // if j = Length(TActionProxyCollection.ActionLists) then // ActionList := actlImmutable // else // ActionList := TActionProxyCollection.ActionLists[j]; // for i := 0 to ActionList.ActionCount - 1 do // begin // Action := ActionList[I]; // if (TCustomAction(Action).ShortCut = ShortCut) or // (TCustomAction(Action).SecondaryShortCuts.IndexOfShortCut(ShortCut) <> -1) then // begin // Result := TCustomAction(Action); // Exit; // end; // end; // end; //end; procedure TPyIDEMainForm.SaveEnvironment; begin // Save the list of open files AppStorage.DeleteSubTree('Open Files'); TPersistFileInfo.WriteToAppStorage(AppStorage, 'Open Files'); // Delete BeforeZoom layout if it exists if LocalAppStorage.PathExists('Layouts\BeforeZoom\Forms') then LocalAppstorage.DeleteSubTree('Layouts\BeforeZoom'); // Save Layout SaveLayout('Current'); // Store other application data and flush AppStorage StoreApplicationData; StoreLocalApplicationData; end; procedure TPyIDEMainForm.actMaximizeEditorExecute(Sender: TObject); var i : TJvDockPosition; Panel : TJvDockPanel; begin SaveLayout('BeforeZoom'); for i := Low(TJvDockPosition) to High(TJvDockPosition) do begin Panel := DockServer.DockPanel[i]; if not (Panel is TJvDockVSNETPanel) then continue; while Panel.DockClientCount >0 do TJvDockVSNETPanel(Panel).DoAutoHideControl( Panel.DockClients[Panel.DockClientCount-1] as TWinControl); end; end; procedure TPyIDEMainForm.actRemoteFileOpenExecute(Sender: TObject); Var FileName, Server : string; begin if ExecuteRemoteFileDialog(FileName, Server, rfdOpen) then begin DoOpenFile(TSSHFileName.Format(Server, FileName), '', TabControlIndex(ActiveTabControl)); end; end; procedure TPyIDEMainForm.actRestoreEditorExecute(Sender: TObject); begin if LocalAppStorage.PathExists('Layouts\BeforeZoom\Forms') then begin LoadLayout('BeforeZoom'); LocalAppstorage.DeleteSubTree('Layouts\BeforeZoom'); end; end; procedure TPyIDEMainForm.actEditorZoomOutExecute(Sender: TObject); begin if ActiveControl is TSynEdit then begin TSynEdit(ActiveControl).Font.Size := Max(TSynEdit(ActiveControl).Font.Size - 1, 2); TSynEdit(ActiveControl).Gutter.Font.Size := Max(TSynEdit(ActiveControl).Font.Size - 2, 2); end; end; procedure TPyIDEMainForm.actEditorZoomInExecute(Sender: TObject); begin if ActiveControl is TSynEdit then begin TSynEdit(ActiveControl).Font.Size := TSynEdit(ActiveControl).Font.Size + 1; TSynEdit(ActiveControl).Gutter.Font.Size := TSynEdit(ActiveControl).Font.Size - 2; end; end; procedure TPyIDEMainForm.mnFilesClick(Sender: TObject); //Fill in the Files submenu of the Tabs popup menu Var Editor, ActiveEditor : IEditor; i : integer; List : TStringList; MenuItem : TSpTBXItem; begin mnFiles.Clear; ActiveEditor := GetActiveEditor; List := TStringList.Create; List.Duplicates := dupAccept; List.Sorted := True; try for i := 0 to GI_EditorFactory.Count - 1 do List.AddObject(GI_EditorFactory.Editor[i].GetFileNameOrTitle, TObject(GI_EditorFactory.Editor[i].Form)); for i:= 0 to List.Count - 1 do begin Editor := TEditorForm(List.Objects[i]).GetEditor; MenuItem := TSpTBXItem.Create(Self); mnFiles.Add(MenuItem); MenuItem.Caption := List[i]; MenuItem.GroupIndex := 3; MenuItem.Hint := Editor.GetFileNameOrTitle; MenuItem.Checked := Editor = ActiveEditor; if Editor.Modified then MenuItem.ImageIndex := 23; MenuItem.OnClick := SelectEditor; end; finally List.Free; end; end; procedure TPyIDEMainForm.mnLanguageClick(Sender: TObject); begin ChangeLanguage(fLanguageList[(Sender as TSpTBXItem).Tag]); SetupSyntaxMenu; SetupToolsMenu; end; procedure TPyIDEMainForm.tbiScrollLeftClick(Sender: TObject); begin TabControl((Sender as TSPTBXItem).Tag).ScrollLeft; end; procedure TPyIDEMainForm.tbiScrollRightClick(Sender: TObject); begin TabControl((Sender as TSPTBXItem).Tag).ScrollRight; end; procedure TPyIDEMainForm.tbiSearchOptionsPopup(Sender: TTBCustomItem; FromLink: Boolean); begin with EditorSearchOptions do begin tbiSearchFromCaret.Checked := SearchFromCaret; tbiSearchInSelection.Checked := SearchSelectionOnly; tbiWholeWords.Checked := SearchWholeWords; tbiRegExp.Checked := UseRegExp; tbiAutoCaseSensitive.Checked := SearchCaseSensitiveType = scsAuto; tbiCaseSensitive.Checked := SearchCaseSensitiveType = scsCaseSensitive; tbiCaseSensitive.Enabled := not tbiAutoCaseSensitive.Checked; tbiIncrementalSearch.Checked := IncrementalSearch; end; end; procedure TPyIDEMainForm.tbiSearchTextAcceptText(const NewText: string); Var S : string; i: integer; begin if NewText <> '' then begin // update Items i := tbiSearchText.Items.IndexOf(NewText); if i > -1 then tbiSearchText.Items.Delete(i); tbiSearchText.Items.Insert(0, NewText); tbiSearchText.Text := NewText; tbiSearchText.Perform(WM_KEYDOWN, VK_END, 0); // Update History S := ''; for i := 0 to tbiSearchText.Items.Count - 1 do begin if i >= 10 then break; if i > 0 then S := S + ','; S := S + AnsiQuotedStr(tbiSearchText.Items[i], '"'); end; EditorSearchOptions.SearchTextHistory := S; end; end; procedure TPyIDEMainForm.tbiSearchTextKeyPress(Sender: TObject; var Key: Char); begin if (Key = Char(VK_ESCAPE)) and not tbiSearchText.DroppedDown then begin Key := #0; FindToolbar.Visible := False; end else if (Key = Char(VK_RETURN)) and not tbiSearchText.DroppedDown then begin Key := #0; tbiSearchTextAcceptText(tbiSearchText.Text); CommandsDataModule.actSearchFindNext.Execute; end; end; procedure TPyIDEMainForm.tbiSearchTextChange(Sender: TObject); begin if EditorSearchOptions.SearchText <> tbiSearchText.Text then begin EditorSearchOptions.SearchText := tbiSearchText.Text; EditorSearchOptions.InitSearch; CommandsDataModule.UpdateMainActions; ClearAllHighlightedTerms; if CommandsDataModule.actSearchHighlight.Enabled and CommandsDataModule.actSearchHighlight.Checked then CommandsDataModule.actSearchHighlightExecute(Sender); if EditorSearchOptions.IncrementalSearch then PostMessage(Handle, WM_SEARCHREPLACEACTION, 2, 0); end; end; procedure TPyIDEMainForm.tbiSearchTextExit(Sender: TObject); begin tbiSearchTextAcceptText(tbiSearchText.Text); end; procedure TPyIDEMainForm.tbiRecentFileListClick(Sender: TObject; const Filename: string); Var S : string; begin S := FileName; DoOpenFile(S, '', TabControlIndex(ActiveTabControl)); // A bit problematic since it Frees the MRU Item which calls this click handler tbiRecentFileList.MRURemove(S); end; procedure TPyIDEMainForm.tbiRecentProjectsClick(Sender: TObject; const Filename: string); begin ProjectExplorerWindow.DoOpenProjectFile(FileName); tbiRecentProjects.MRURemove(Filename); end; procedure TPyIDEMainForm.tbiReplaceTextAcceptText(const NewText: string); Var S : string; i: integer; begin if NewText <> '' then begin // update Items i := tbiReplaceText.Items.IndexOf(NewText); if i > -1 then tbiReplaceText.Items.Delete(i); tbiReplaceText.Items.Insert(0, NewText); tbiReplaceText.Text := NewText; tbiReplaceText.Perform(WM_KEYDOWN, VK_END, 0); // Update History S := ''; for i := 0 to tbiReplaceText.Items.Count - 1 do begin if i >= 10 then break; if i > 0 then S := S + ','; S := S + tbiReplaceText.Items[i].QuotedString('"'); end; EditorSearchOptions.ReplaceTextHistory := S; end; end; procedure TPyIDEMainForm.tbiReplaceTextChange(Sender: TObject); begin EditorSearchOptions.ReplaceText := tbiReplaceText.Text; EditorSearchOptions.InitSearch; CommandsDataModule.UpdateMainActions; end; procedure TPyIDEMainForm.tbiReplaceTextKeyPress(Sender: TObject; var Key: Char); begin if (Key = Char(VK_ESCAPE)) and not tbiReplaceText.DroppedDown then begin Key := #0; FindToolbar.Visible := False; end else if (Key = Char(VK_RETURN)) and not tbiReplaceText.DroppedDown then begin Key := #0; tbiReplaceTextAcceptText(tbiReplaceText.Text); CommandsDataModule.actSearchReplaceNow.Execute; // PostMessage(Handle, WM_SEARCHREPLACEACTION, 0, LPARAM(Action)); end; end; procedure TPyIDEMainForm.SearchOptionsChanged(Sender: TObject); begin with EditorSearchOptions do begin SearchFromCaret := tbiSearchFromCaret.Checked; SearchSelectionOnly := tbiSearchInSelection.Checked; SearchWholeWords := tbiWholeWords.Checked; UseRegExp := tbiRegExp.Checked; if tbiAutoCaseSensitive.Checked then SearchCaseSensitiveType := scsAuto else if tbiCaseSensitive.Checked then SearchCaseSensitiveType := scsCaseSensitive else SearchCaseSensitiveType := scsNotCaseSenitive; IncrementalSearch := tbiIncrementalSearch.Checked and not SearchWholeWords; InitSearch; end; ClearAllHighlightedTerms; if CommandsDataModule.actSearchHighlight.Enabled and CommandsDataModule.actSearchHighlight.Checked then CommandsDataModule.actSearchHighlightExecute(Sender); end; procedure TPyIDEMainForm.SelectEditor(Sender: TObject); begin ShowFilePosition((Sender as TTBCustomItem).Hint, -1, -1); end; { TTSpTBXTabControl } procedure TSpTBXTabControl.WMDropFiles(var Msg: TMessage); var i, iNumberDropped: Integer; FileName: array[0..MAX_PATH - 1] of Char; begin try iNumberDropped := DragQueryFile(THandle(Msg.wParam), Cardinal(-1), nil, 0); for i := 0 to iNumberDropped - 1 do begin DragQueryFile(THandle(Msg.wParam), i, FileName, MAX_PATH); PyIDEMainForm.DoOpenFile(FileName, '', PyIDEMainForm.TabControlIndex(Self)); end; finally Msg.Result := 0; DragFinish(THandle(Msg.wParam)); end; end; constructor TSpTBXTabControl.Create(AOwner: TComponent); begin inherited; zOrder := TList.Create; end; destructor TSpTBXTabControl.Destroy; begin FreeAndNil(zOrder); inherited; end; end.
36.138078
138
0.706058
f1d51bedbff3ca701f639267b9b9bfe2b270324d
9,562
pas
Pascal
src/Server/Game/GameServerPlayer.pas
eantoniobr/pangya-server
60d7e1206f032020216dcbfc1e194287068017fb
[ "Apache-2.0" ]
1
2020-08-25T00:05:31.000Z
2020-08-25T00:05:31.000Z
src/Server/Game/GameServerPlayer.pas
eantoniobr/pangya-server
60d7e1206f032020216dcbfc1e194287068017fb
[ "Apache-2.0" ]
null
null
null
src/Server/Game/GameServerPlayer.pas
eantoniobr/pangya-server
60d7e1206f032020216dcbfc1e194287068017fb
[ "Apache-2.0" ]
2
2019-08-22T14:11:59.000Z
2020-08-25T00:05:33.000Z
{*******************************************************} { } { Pangya Server } { } { Copyright (C) 2015 Shad'o Soft tm } { } {*******************************************************} unit GameServerPlayer; interface uses PlayerData, PlayerCharacters, Client, PlayerAction, PlayerItems, PlayerCaddies, PlayerQuest, PlayerMascots, IffManager.IffEntryBase, PacketWriter; type TGameServerPlayer = class; TGameInfo = packed record var GameSlot: UInt8; var LoadComplete: Boolean; var ShotReady: Boolean; var ShotSync: Boolean; var Holedistance: Single; var HoleComplete: Boolean; var ReadyForgame: Boolean; var Role: UInt8; end; TGameServerPlayer = class private var m_lobby: UInt8; var m_data: TPlayerData; var m_characters: TPlayerCharacters; var m_caddies: TPlayerCaddies; var m_mascots: TPlayerMascots; var m_items: TPlayerItems; var m_quest: TPlayerQuest; function FGetPlayerData: PPlayerData; function FReadIsAdmin: Boolean; procedure FWriteIsAdmin(isAdmin: Boolean); public var Cookies: Int64; var Action: TPlayerAction; function GameInformation: RawByteString; overload; function GameInformation(level: UInt8): RawByteString; overload; function LobbyInformations: RawByteString; function SubStractIffEntryPrice(iffEntry: TIffEntrybase; quandtity: UInt32): Boolean; function AddPangs(amount: UInt32): Boolean; function RemovePangs(amount: Uint32): Boolean; function AddCookies(amount: UInt32): Boolean; function RemoveCookies(amount: UInt32): Boolean; property Lobby: Uint8 read m_lobby write m_lobby; property Data: PPlayerData read FGetPlayerData; property Characters: TPlayerCharacters read m_characters; property Items: TPlayerItems read m_items; property Caddies: TPlayerCaddies read m_caddies; property Mascots: TPlayerMascots read m_mascots; property Quests: TPlayerQuest read m_quest; property IsAdmin: Boolean read FReadIsAdmin write FWriteIsAdmin; var InGameList: Boolean; var GameInfo: TGameInfo; procedure EquipCharacterById(Id: UInt32); procedure EquipMascotById(Id: UInt32); procedure EquipCaddieById(Id: UInt32); procedure EquipClubById(Id: UInt32); procedure EquipAztecByIffId(IffId: UInt32); constructor Create; destructor Destroy; override; end; TGameClient = TClient<TGameServerPlayer>; implementation uses PlayerCharacter, utils, PlayerEquipment, defs; constructor TGameServerPlayer.Create; begin inherited; m_characters := TPlayerCharacters.Create; m_items := TPlayerItems.Create; m_caddies := TPlayerCaddies.Create; m_mascots := TPlayerMascots.Create; m_lobby := $FF; InGameList := false; m_quest := TPlayerQuest.Create; end; destructor TGameServerPlayer.Destroy; begin m_characters.Free; m_items.Free; m_caddies.Free; m_mascots.Free; m_quest.Free; inherited; end; function TGameServerPlayer.FGetPlayerData; begin Exit(@m_data); end; function TGameServerPlayer.GameInformation: RawByteString; begin Exit(GameInformation(2)); end; function TGameServerPlayer.GameInformation(level: UInt8): RawByteString; var packet: TPacketWriter; begin packet := TPacketWriter.Create; packet.WriteUInt32(Data.playerInfo1.ConnectionId); if level >= 1 then begin packet.Write(Data.playerInfo1.nickname[0], 22); packet.WriteStr( #$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00 + #$00 ); packet.WriteUInt8(gameInfo.GameSlot); packet.WriteStr( #$00#$00#$00#$00 ); packet.WriteUInt32(data.witems.decorations.title); packet.WriteUInt32(Data.equipedCharacter.Data.IffId); // Not sure 100% packet.Write(data.witems.decorations, SizeOf(TDecorations)); packet.WriteUInt8(self.GameInfo.Role); packet.WriteUInt8( TGeneric.Iff<UInt8>(gameInfo.ReadyForgame, 2, 0) ); packet.Write(self.Data.playerInfo2.rank, 1); packet.WriteStr( #$00#$0A + #$00#$00#$00#$00 + // emblem #$00#$00#$00#$00 + // emblem #$34#$61#$65#$62 + #$00#$00#$00#$00 ); packet.WriteUInt32(Data.playerInfo1.PlayerID); packet.WriteStr( #$00#$00#$00#$00 + // shop flag #$00#$00 ); packet.WriteStr( Action.toRawByteString ); packet.WriteStr( #$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00 + #$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00 + #$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00 + #$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00 + #$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00 + #$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00 + #$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00 + #$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00 + #$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00 + #$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00 + #$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00 + #$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00 + #$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00 + #$00#$00#$00 + #$00#$00#$00#$00#$00#$00#$00#$00 ); if level >= 2 then begin packet.Write(Data.equipedCharacter.Data.IffId, SizeOf(TPlayerCharacterData)); end; end; Result := packet.ToStr; packet.free; end; function TGameServerPlayer.LobbyInformations: RawByteString; var packet: TPacketWriter; tmpGameId: UInt16; begin // Tmp fix because I'm using the game 0 as lobby null game tmpGameId := m_data.playerInfo1.game; if tmpGameId = 0 then begin tmpGameId := $ffff; end; packet := TPacketWriter.Create; packet.WriteUInt32(Data.playerInfo1.PlayerID); packet.WriteUInt32(Data.playerInfo1.ConnectionId); packet.WriteUInt16(tmpGameId); packet.Write(Data.playerInfo1.nickname[0], 22); packet.Write(self.Data.playerInfo2.rank, 1); packet.WriteStr( #$00#$00#$00#$00#$00#$00#$00 + #$00#$E8#$03#$00 + #$00 + #$02 + // gender #$00#$00#$00#$00 + // guild ID #$67#$75#$69#$6C#$64#$6D#$61#$72#$6B#$00 + #$00#$00#$00#$00#$00#$00#$00#$00#$73#$65#$72#$76#$65#$72#$74#$65 + #$73#$74#$40#$4E#$54#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00 + #$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00 + #$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00 + #$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00 + #$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00 + #$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00 + #$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00 + #$00#$00#$00#$00#$00#$00#$00#$00 ); Result := packet.ToStr; packet.free; end; procedure TGameServerPlayer.EquipCharacterById(Id: Cardinal); begin with self.m_characters.getById(Id) do begin Data.witems.CharacterId := GetId; Data.equipedCharacter := GetData; end; end; procedure TGameServerPlayer.EquipMascotById(Id: Cardinal); begin with self.m_mascots.getById(Id) do begin Data.witems.mascotId := GetIffId; Data.equipedMascot := GetData; end; end; procedure TGameServerPlayer.EquipCaddieById(Id: Cardinal); begin with self.m_caddies.getById(Id) do begin Data.witems.CaddieId := Id; Data.equipedCaddie := GetData; end; end; procedure TGameServerPlayer.EquipClubById(Id: Cardinal); begin // TODO: Should check if the item is really a club with self.m_items.getById(Id) do begin Data.witems.ClubSetId := Id; Data.equipedClub.Id := Id; Data.equipedClub.IffId := GetIffId; end; end; procedure TGameServerPlayer.EquipAztecByIffId(IffId: Cardinal); begin // TODO: Should check if the item is really a club with self.m_items.getByIffId(IffId) do begin Data.witems.AztecIffID := IffId; end; end; function TGameServerPlayer.SubStractIffEntryPrice(iffEntry: TIffEntrybase; quandtity: UInt32): Boolean; var price: UInt32; priceType: TPRICE_TYPE; begin price := iffEntry.getPrice * quandtity; case iffEntry.GetPriceType of PRICE_TYPE_PANG: begin Result := RemovePangs(price); end; PRICE_TYPE_COOKIE: begin Result := RemoveCookies(price); end; end; end; function TGameServerPlayer.AddPangs(amount: Cardinal): Boolean; begin inc(data.playerInfo2.pangs, amount); Exit(true); end; function TGameServerPlayer.RemovePangs(amount: Cardinal): Boolean; begin if data.playerInfo2.pangs - amount >= 0 then begin dec(data.playerInfo2.pangs, amount); Exit(true); end; Exit(False); end; function TGameServerPlayer.AddCookies(amount: Cardinal): Boolean; begin inc(Cookies, amount); end; function TGameServerPlayer.RemoveCookies(amount: Cardinal): Boolean; begin if Cookies - amount >= 0 then begin dec(Cookies, amount); Exit(true); end; Exit(false); end; procedure TGameServerPlayer.FWriteIsAdmin(isAdmin: Boolean); begin m_data.playerInfo1.gmflag := TGeneric.Iff(isAdmin, $f, $0); end; function TGameServerPlayer.FReadIsAdmin: Boolean; begin end; end.
26.341598
103
0.634282
bc3cfb76fdc2a3bddff15d86875846d4169f6851
12,550
pas
Pascal
Components/JVCL/run/JvBitmapButton.pas
sabatex/Delphi
0efbe6eb38bf8aa2bf269d1866741266e90b9cbf
[ "MIT" ]
null
null
null
Components/JVCL/run/JvBitmapButton.pas
sabatex/Delphi
0efbe6eb38bf8aa2bf269d1866741266e90b9cbf
[ "MIT" ]
null
null
null
Components/JVCL/run/JvBitmapButton.pas
sabatex/Delphi
0efbe6eb38bf8aa2bf269d1866741266e90b9cbf
[ "MIT" ]
1
2019-12-24T08:39:18.000Z
2019-12-24T08:39:18.000Z
{----------------------------------------------------------------------------- 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/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: JvBitmapButton.PAS, released on 2002-06-15. The Initial Developer of the Original Code is Jan Verhoeven [jan1 dott verhoeven att wxs dott nl] Portions created by Jan Verhoeven are Copyright (C) 2002 Jan Verhoeven. All Rights Reserved. Contributor(s): Robert Love [rlove att slcdug dott org]. You may retrieve the latest version of this file at the Project JEDI's JVCL home page, located at http://jvcl.sourceforge.net Known Issues: -----------------------------------------------------------------------------} // $Id: JvBitmapButton.pas,v 1.28 2005/10/26 15:51:25 ahuser Exp $ unit JvBitmapButton; {$I jvcl.inc} interface uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} Windows, Messages, {$IFDEF CLR} System.Runtime.InteropServices, {$ENDIF CLR} {$IFDEF HAS_UNIT_TYPES} Types, {$ENDIF HAS_UNIT_TYPES} Classes, Graphics, Controls, JvComponent, JvTypes; type {$IFNDEF CLR} PJvRGBTriple = ^TJvRGBTriple; {$ENDIF !CLR} {$IFDEF CLR} TPixelTransform = procedure(var Dest: TJvRGBTriple; const Source: TJvRGBTriple); {$ELSE} TPixelTransform = procedure(Dest, Source: PJvRGBTriple); {$ENDIF CLR} TJvBitmapButton = class(TJvGraphicControl) private FBitmap: TBitmap; FLighter: TBitmap; FDarker: TBitmap; FNormal: TBitmap; FPushDown: Boolean; FMouseOver: Boolean; FLatching: Boolean; FDown: Boolean; FHotTrack: Boolean; FCaption: string; FFont: TFont; FCaptionLeft: Integer; FCaptionTop: Integer; FLighterFontColor: TColor; FDarkerFontColor: TColor; procedure SetBitmap(const Value: TBitmap); procedure MakeNormal; procedure MakeDarker; procedure MakeLighter; procedure MakeHelperBitmap(Target: TBitmap; Transform: TPixelTransform); procedure MakeCaption(Target: TBitmap; FontColor: TColor); procedure SetLatching(const Value: Boolean); procedure SetDown(const Value: Boolean); procedure SetHotTrack(const Value: Boolean); procedure SetCaption(const Value: string); procedure SetFont(const Value: TFont); procedure SetCaptionLeft(const Value: Integer); procedure SetCaptionTop(const Value: Integer); procedure UpdateBitmaps; procedure SetDarkerFontColor(const Value: TColor); procedure SetLighterFontColor(const Value: TColor); protected procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseLeave(AControl: TControl); override; procedure Click; override; procedure Loaded; override; procedure Resize; override; procedure Paint; override; procedure DoBitmapChange(Sender: TObject); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Bitmap: TBitmap read FBitmap write SetBitmap; property Caption: string read FCaption write SetCaption; property CaptionLeft: Integer read FCaptionLeft write SetCaptionLeft; property CaptionTop: Integer read FCaptionTop write SetCaptionTop; property DarkerFontColor: TColor read FDarkerFontColor write SetDarkerFontColor; property Down: Boolean read FDown write SetDown default False; property Font: TFont read FFont write SetFont; property HotTrack: Boolean read FHotTrack write SetHotTrack default True; property Height default 24; property Hint; property Latching: Boolean read FLatching write SetLatching default False; property LighterFontColor: TColor read FLighterFontColor write SetLighterFontColor; property ShowHint; property Width default 24; property OnClick; property OnMouseDown; property OnMouseUp; property Visible; end; {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$RCSfile: JvBitmapButton.pas,v $'; Revision: '$Revision: 1.28 $'; Date: '$Date: 2005/10/26 15:51:25 $'; LogPath: 'JVCL\run' ); {$ENDIF UNITVERSIONING} implementation constructor TJvBitmapButton.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := 24; Height := 24; FPushDown := False; FMouseOver := False; FLatching := False; FHotTrack := True; FDown := False; FBitmap := TBitmap.Create; FBitmap.Width := 24; FBitmap.Height := 24; FBitmap.PixelFormat := pf24bit; FBitmap.Canvas.Brush.Color := clGray; FBitmap.Canvas.FillRect(Rect(1, 1, 23, 23)); FBitmap.OnChange := DoBitmapChange; FLighter := TBitmap.Create; FDarker := TBitmap.Create; FNormal := TBitmap.Create; FFont := TFont.Create; end; destructor TJvBitmapButton.Destroy; begin FBitmap.Free; FLighter.Free; FDarker.Free; FNormal.Free; FFont.Free; inherited Destroy; end; procedure TJvBitmapButton.Click; begin if FPushDown then if Assigned(OnClick) then inherited Click; end; procedure TJvBitmapButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FPushDown := not FBitmap.Transparent and (FBitmap.Canvas.Pixels[X, Y] <> FBitmap.Canvas.Pixels[0, FBitmap.Height - 1]); Repaint; inherited MouseDown(Button, Shift, X, Y); end; procedure TJvBitmapButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FPushDown := False; if Latching then FDown := not FDown else FDown := False; Repaint; inherited MouseUp(Button, Shift, X, Y); end; procedure TJvBitmapButton.Paint; begin inherited Paint; if Assigned(FBitmap) then begin if FPushDown then Canvas.Draw(1, 1, FDarker) else begin if Down then Canvas.Draw(1, 1, FDarker) else if FMouseOver and FHotTrack then Canvas.Draw(0, 0, FLighter) else Canvas.Draw(0, 0, FNormal); end; end; end; procedure TJvBitmapButton.SetBitmap(const Value: TBitmap); begin FBitmap.Assign(Value); FBitmap.Transparent := True; end; procedure TJvBitmapButton.UpdateBitmaps; begin MakeLighter; MakeDarker; MakeNormal; Repaint; end; {$IFDEF CLR} procedure LighterTransform(var Dest: TJvRGBTriple; const Source: TJvRGBTriple); {$ELSE} procedure LighterTransform(Dest, Source: PJvRGBTriple); {$ENDIF CLR} begin Dest.rgbBlue := $FF - Round(0.8 * Abs($FF - Source.rgbBlue)); Dest.rgbGreen := $FF - Round(0.8 * Abs($FF - Source.rgbGreen)); Dest.rgbRed := $FF - Round(0.8 * Abs($FF - Source.rgbRed)); end; {$IFDEF CLR} procedure DarkerTransform(var Dest: TJvRGBTriple; const Source: TJvRGBTriple); {$ELSE} procedure DarkerTransform(Dest, Source: PJvRGBTriple); {$ENDIF CLR} begin Dest.rgbBlue := Round(0.7 * Source.rgbBlue); Dest.rgbGreen := Round(0.7 * Source.rgbGreen); Dest.rgbRed := Round(0.7 * Source.rgbRed); end; procedure TJvBitmapButton.MakeLighter; begin MakeHelperBitmap(FLighter, LighterTransform); MakeCaption(FLighter, FLighterFontColor); end; procedure TJvBitmapButton.MakeDarker; begin MakeHelperBitmap(FDarker, DarkerTransform); MakeCaption(FDarker, FDarkerFontColor); end; procedure TJvBitmapButton.MouseLeave(AControl: TControl); begin FMouseOver := False; MakeDarker; MakeNormal; Repaint; end; procedure TJvBitmapButton.Loaded; begin inherited Loaded; if not FBitmap.Empty then begin MakeDarker; MakeLighter; MakeNormal; end; Resize; end; procedure TJvBitmapButton.SetLatching(const Value: Boolean); begin FLatching := Value; if not FLatching then begin FDown := False; Invalidate; end; end; procedure TJvBitmapButton.SetDown(const Value: Boolean); begin if FLatching then FDown := Value else FDown := False; Invalidate; end; procedure TJvBitmapButton.Resize; begin inherited Resize; if Assigned(FBitmap) then begin Width := FBitmap.Width; Height := FBitmap.Height; end else begin Width := 24; Height := 24; end; end; procedure TJvBitmapButton.SetHotTrack(const Value: Boolean); begin FHotTrack := Value; end; procedure TJvBitmapButton.MouseMove(Shift: TShiftState; X, Y: Integer); var Value: Boolean; begin inherited MouseMove(Shift, X, Y); Value := FBitmap.Canvas.Pixels[X, Y] <> FBitmap.Canvas.Pixels[0, FBitmap.Height - 1]; if Value <> FMouseOver then begin FMouseOver := Value; Repaint; end; end; procedure TJvBitmapButton.SetCaption(const Value: string); begin if Value <> FCaption then begin FCaption := Value; UpdateBitmaps; end; end; procedure TJvBitmapButton.SetFont(const Value: TFont); begin if Value <> FFont then begin FFont := Value; Canvas.Font.Assign(FFont); UpdateBitmaps; end; end; procedure TJvBitmapButton.SetCaptionLeft(const Value: Integer); begin if Value <> FCaptionLeft then begin FCaptionLeft := Value; UpdateBitmaps; end; end; procedure TJvBitmapButton.SetCaptionTop(const Value: Integer); begin if Value <> FCaptionTop then begin FCaptionTop := Value; UpdateBitmaps; end; end; procedure TJvBitmapButton.MakeNormal; begin FNormal.Assign(FBitmap); MakeCaption(FNormal, Font.Color); end; procedure TJvBitmapButton.SetDarkerFontColor(const Value: TColor); begin if Value <> FDarkerFontColor then begin FDarkerFontColor := Value; UpdateBitmaps; end; end; procedure TJvBitmapButton.SetLighterFontColor(const Value: TColor); begin if Value <> FLighterFontColor then begin FLighterFontColor := Value; UpdateBitmaps; end; end; procedure TJvBitmapButton.DoBitmapChange(Sender: TObject); begin if FBitmap.PixelFormat <> pf24bit then begin FBitmap.OnChange := nil; try FBitmap.PixelFormat := pf24bit; finally FBitmap.OnChange := DoBitmapChange; end; end; Width := FBitmap.Width; Height := FBitmap.Height; UpdateBitmaps; end; procedure TJvBitmapButton.MakeCaption(Target: TBitmap; FontColor: TColor); var R: TRect; begin if FCaption <> '' then with Target.Canvas do begin Brush.Style := bsClear; Font.Assign(FFont); Font.Color := FontColor; R := Rect(0, 0, Width, Height); TextRect(R, FCaptionLeft, FCaptionTop, FCaption); end; end; procedure TJvBitmapButton.MakeHelperBitmap(Target: TBitmap; Transform: TPixelTransform); var {$IFDEF CLR} P1, P2: TJvRGBTriple; PP1, PP2: IntPtr; {$ELSE} P1, P2: PJvRGBTriple; {$ENDIF CLR} X, Y: Integer; RT, GT, BT: Byte; LColor: TColor; begin Target.Width := FBitmap.Width; Target.Height := FBitmap.Height; Target.Transparent := FBitmap.Transparent; if FBitmap.Transparent then begin LColor := FBitmap.TransparentColor; Target.TransparentColor := LColor; end else LColor := clNone; RT := GetRValue(LColor); GT := GetGValue(LColor); BT := GetBValue(LColor); Target.PixelFormat := pf24bit; Assert(FBitmap.PixelFormat = pf24bit); for Y := 0 to FBitmap.Height - 1 do begin {$IFDEF CLR} PP1 := FBitmap.ScanLine[Y]; PP2 := Target.ScanLine[Y]; for X := 1 to FBitmap.Width do begin Marshal.PtrToStructure(PP1, P1); Marshal.PtrToStructure(PP2, P2); if (LColor <> clNone) and (P1.rgbBlue = BT) and (P1.rgbGreen = GT) and (P1.rgbRed = RT) then Marshal.StructureToPtr(P1, PP2, False) else begin Transform(P2, P1); Marshal.StructureToPtr(P2, PP2, False); end; PP1 := IntPtr(Longint(PP1) + 3); PP2 := IntPtr(Longint(PP2) + 3); end; {$ELSE} P1 := FBitmap.ScanLine[Y]; P2 := Target.ScanLine[Y]; for X := 1 to FBitmap.Width do begin if (LColor <> clNone) and (P1.rgbBlue = BT) and (P1.rgbGreen = GT) and (P1.rgbRed = RT) then P2^ := P1^ else Transform(P2, P1); Inc(P1); Inc(P2); end; {$ENDIF CLR} end; end; {$IFDEF UNITVERSIONING} initialization RegisterUnitVersion(HInstance, UnitVersioning); finalization UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
24.851485
97
0.701116
f1085c7143718caff1ee2867fa48806043bbe486
9,154
pas
Pascal
Source/TextEditor.CompletionProposal.Snippets.pas
ImperiumDelphi/TTextEditor
823b171ceb6c3d5e914622479a2ad607634eb645
[ "MIT" ]
null
null
null
Source/TextEditor.CompletionProposal.Snippets.pas
ImperiumDelphi/TTextEditor
823b171ceb6c3d5e914622479a2ad607634eb645
[ "MIT" ]
null
null
null
Source/TextEditor.CompletionProposal.Snippets.pas
ImperiumDelphi/TTextEditor
823b171ceb6c3d5e914622479a2ad607634eb645
[ "MIT" ]
1
2021-11-16T17:04:56.000Z
2021-11-16T17:04:56.000Z
unit TextEditor.CompletionProposal.Snippets; interface uses System.Classes, System.SysUtils, TextEditor.Types; type TTextEditorCompletionProposalSnippetItemPosition = class(TPersistent) strict private FActive: Boolean; FColumn: Integer; FRow: Integer; public constructor Create; procedure Assign(ASource: TPersistent); override; published property Active: Boolean read FActive write FActive default False; property Column: Integer read FColumn write FColumn default 0; property Row: Integer read FRow write FRow default 0; end; TTextEditorCompletionProposalSnippetItemSelection = class(TPersistent) strict private FActive: Boolean; FFromColumn: Integer; FFromRow: Integer; FToColumn: Integer; FToRow: Integer; public constructor Create; procedure Assign(ASource: TPersistent); override; published property Active: Boolean read FActive write FActive default False; property FromColumn: Integer read FFromColumn write FFromColumn default 0; property FromRow: Integer read FFromRow write FFromRow default 0; property ToColumn: Integer read FToColumn write FToColumn default 0; property ToRow: Integer read FToRow write FToRow default 0; end; TTextEditorCompletionProposalSnippetItem = class(TCollectionItem) strict private FDescription: string; FExecuteWith: TTextEditorSnippetExecuteWith; FGroupName: string; FKeyword: string; FPosition: TTextEditorCompletionProposalSnippetItemPosition; FSelection: TTextEditorCompletionProposalSnippetItemSelection; FSnippet: TStrings; procedure SetSnippet(const AValue: TStrings); protected function GetDisplayName: string; override; public constructor Create(ACollection: TCollection); override; destructor Destroy; override; procedure Assign(ASource: TPersistent); override; published property Description: string read FDescription write FDescription; property ExecuteWith: TTextEditorSnippetExecuteWith read FExecuteWith write FExecuteWith default seListOnly; property Keyword: string read FKeyword write FKeyword; property Position: TTextEditorCompletionProposalSnippetItemPosition read FPosition write FPosition; property Selection: TTextEditorCompletionProposalSnippetItemSelection read FSelection write FSelection; property Snippet: TStrings read FSnippet write SetSnippet; end; TTextEditorCompletionProposalSnippetItems = class(TOwnedCollection) protected function GetItem(const AIndex: Integer): TTextEditorCompletionProposalSnippetItem; procedure SetItem(const AIndex: Integer; const AValue: TTextEditorCompletionProposalSnippetItem); public function Add: TTextEditorCompletionProposalSnippetItem; function DoesKeywordExist(const AKeyword: string): Boolean; function Insert(const AIndex: Integer): TTextEditorCompletionProposalSnippetItem; property Items[const AIndex: Integer]: TTextEditorCompletionProposalSnippetItem read GetItem write SetItem; end; TTextEditorCompletionProposalSnippets = class(TPersistent) strict private FActive: Boolean; FItems: TTextEditorCompletionProposalSnippetItems; FOwner: TPersistent; function GetItem(const AIndex: Integer): TTextEditorCompletionProposalSnippetItem; procedure SetItems(const AValue: TTextEditorCompletionProposalSnippetItems); protected function GetOwner: TPersistent; override; public constructor Create(const AOwner: TPersistent); destructor Destroy; override; procedure Assign(ASource: TPersistent); override; property Item[const AIndex: Integer]: TTextEditorCompletionProposalSnippetItem read GetItem; published property Active: Boolean read FActive write FActive default True; property Items: TTextEditorCompletionProposalSnippetItems read FItems write SetItems; end; ETextEditorCompletionProposalSnippetException = class(Exception); implementation uses System.RTLConsts, TextEditor.Utils; { TTextEditorCompletionProposalSnippetItemPosition } constructor TTextEditorCompletionProposalSnippetItemPosition.Create; begin inherited; FActive := False; FColumn := 0; FRow := 0; end; procedure TTextEditorCompletionProposalSnippetItemPosition.Assign(ASource: TPersistent); begin if Assigned(ASource) and (ASource is TTextEditorCompletionProposalSnippetItemPosition) then with ASource as TTextEditorCompletionProposalSnippetItemPosition do begin Self.FActive := FActive; Self.FColumn := FColumn; Self.FRow := FRow; end else inherited Assign(ASource); end; { TTextEditorCompletionProposalSnippetItemSelection } constructor TTextEditorCompletionProposalSnippetItemSelection.Create; begin inherited; FActive := False; FFromColumn := 0; FFromRow := 0; FToColumn := 0; FToRow := 0; end; procedure TTextEditorCompletionProposalSnippetItemSelection.Assign(ASource: TPersistent); begin if Assigned(ASource) and (ASource is TTextEditorCompletionProposalSnippetItemPosition) then with ASource as TTextEditorCompletionProposalSnippetItemPosition do begin Self.FActive := FActive; Self.FFromColumn := FFromColumn; Self.FFromRow := FFromRow; Self.FToColumn := FToColumn; Self.FToRow := FToRow; end else inherited Assign(ASource); end; { TTextEditorCompletionProposalSnippetItem } constructor TTextEditorCompletionProposalSnippetItem.Create(ACollection: TCollection); begin inherited Create(ACollection); FExecuteWith := seListOnly; FSnippet := TStringList.Create; FSnippet.TrailingLineBreak := False; FPosition := TTextEditorCompletionProposalSnippetItemPosition.Create; FSelection := TTextEditorCompletionProposalSnippetItemSelection.Create; end; destructor TTextEditorCompletionProposalSnippetItem.Destroy; begin FSnippet.Free; FPosition.Free; FSelection.Free; inherited Destroy; end; procedure TTextEditorCompletionProposalSnippetItem.Assign(ASource: TPersistent); begin if Assigned(ASource) and (ASource is TTextEditorCompletionProposalSnippetItem) then with ASource as TTextEditorCompletionProposalSnippetItem do begin Self.FDescription := FDescription; Self.FExecuteWith := FExecuteWith; Self.FGroupName := FGroupName; Self.FKeyword := FKeyword; Self.FPosition.Assign(FPosition); Self.FSelection.Assign(FSelection); Self.FSnippet.Assign(FSnippet); end else inherited Assign(ASource); end; procedure TTextEditorCompletionProposalSnippetItem.SetSnippet(const AValue: TStrings); begin if AValue <> FSnippet then FSnippet.Assign(AValue); end; function TTextEditorCompletionProposalSnippetItem.GetDisplayName: string; begin if FKeyword <> '' then Result := FKeyword else Result := '(unnamed)'; end; { TTextEditorCompletionProposalSnippetItems } function TTextEditorCompletionProposalSnippetItems.GetItem(const AIndex: Integer): TTextEditorCompletionProposalSnippetItem; begin Result := TTextEditorCompletionProposalSnippetItem(inherited GetItem(AIndex)); end; procedure TTextEditorCompletionProposalSnippetItems.SetItem(const AIndex: Integer; const AValue: TTextEditorCompletionProposalSnippetItem); begin inherited SetItem(AIndex, AValue); end; function TTextEditorCompletionProposalSnippetItems.DoesKeywordExist(const AKeyword: string): Boolean; var LIndex: Integer; begin Result := True; for LIndex := 0 to Count - 1 do if CompareText(Items[LIndex].Keyword, AKeyword) = 0 then Exit; Result := False; end; function TTextEditorCompletionProposalSnippetItems.Add: TTextEditorCompletionProposalSnippetItem; begin Result := TTextEditorCompletionProposalSnippetItem(inherited Add); end; function TTextEditorCompletionProposalSnippetItems.Insert(const AIndex: Integer): TTextEditorCompletionProposalSnippetItem; begin Result := Add; Result.Index := AIndex; end; { TTextEditorCompletionProposalSnippets } constructor TTextEditorCompletionProposalSnippets.Create(const AOwner: TPersistent); begin inherited Create; FOwner := AOwner; FActive := True; FItems := TTextEditorCompletionProposalSnippetItems.Create(Self, TTextEditorCompletionProposalSnippetItem); end; destructor TTextEditorCompletionProposalSnippets.Destroy; begin FItems.Free; inherited Destroy; end; procedure TTextEditorCompletionProposalSnippets.Assign(ASource: TPersistent); begin if Assigned(ASource) and (ASource is TTextEditorCompletionProposalSnippets) then with ASource as TTextEditorCompletionProposalSnippets do begin Self.FActive := FActive; Self.FItems.Assign(FItems); end else inherited Assign(ASource); end; function TTextEditorCompletionProposalSnippets.GetItem(const AIndex: Integer): TTextEditorCompletionProposalSnippetItem; begin {$IFDEF TEXT_EDITOR_RANGE_CHECKS} if (AIndex < 0) or (AIndex > FItems.Count) then ListIndexOutOfBounds(AIndex); {$ENDIF} Result := FItems.Items[AIndex]; end; procedure TTextEditorCompletionProposalSnippets.SetItems(const AValue: TTextEditorCompletionProposalSnippetItems); begin FItems.Assign(AValue); end; function TTextEditorCompletionProposalSnippets.GetOwner: TPersistent; begin Result := FOwner; end; end.
31.136054
139
0.800087
6165ef5b0088bf91f15a8b15b0d90a9d7ca49c58
55
pas
Pascal
test/pascal_ISO7185/test/no/ExprErr4.pas
tanhleno/pegparser
1d4b7bffd5860a4b54d021bfcf7e93ab82aa6582
[ "MIT" ]
8
2019-05-13T16:11:24.000Z
2022-02-23T12:35:36.000Z
test/pascal_ISO7185/test/no/ExprErr4.pas
tanhleno/pegparser
1d4b7bffd5860a4b54d021bfcf7e93ab82aa6582
[ "MIT" ]
null
null
null
test/pascal_ISO7185/test/no/ExprErr4.pas
tanhleno/pegparser
1d4b7bffd5860a4b54d021bfcf7e93ab82aa6582
[ "MIT" ]
1
2021-01-27T00:51:52.000Z
2021-01-27T00:51:52.000Z
program ExprErr4; begin write(a:1:.4+3); a := 2 end.
9.166667
17
0.618182
475c222e3d03d7f2733340e8279ab276eaed7cb8
42,879
dfm
Pascal
HWSserver/source/uadm_php.dfm
RonaldoSurdi/Sistema-gerenciamento-websites-delphi
8cc7eec2d05312dc41f514bbd5f828f9be9c579e
[ "MIT" ]
1
2022-02-28T11:28:18.000Z
2022-02-28T11:28:18.000Z
HWSserver/source/uadm_php.dfm
RonaldoSurdi/Sistema-gerenciamento-websites-delphi
8cc7eec2d05312dc41f514bbd5f828f9be9c579e
[ "MIT" ]
null
null
null
HWSserver/source/uadm_php.dfm
RonaldoSurdi/Sistema-gerenciamento-websites-delphi
8cc7eec2d05312dc41f514bbd5f828f9be9c579e
[ "MIT" ]
null
null
null
object adm_php: Tadm_php Left = 187 Top = 194 BorderStyle = bsNone ClientHeight = 393 ClientWidth = 739 Color = 16119285 Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False Position = poScreenCenter OnClose = FormClose OnCreate = FormCreate OnMouseDown = FormMouseDown OnMouseMove = FormMouseMove OnMouseUp = FormMouseUp PixelsPerInch = 96 TextHeight = 13 object SpeedButton2: TSpeedButton Left = 730 Top = -1 Width = 14 Height = 14 Hint = 'Fechar janela' Caption = 'X' Flat = True Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'Verdana' Font.Style = [fsBold] ParentFont = False ParentShowHint = False ShowHint = True OnClick = SpeedButton1Click end object Panel1: TPanel Left = 0 Top = 20 Width = 739 Height = 356 Align = alClient BevelInner = bvRaised BevelOuter = bvLowered BorderStyle = bsSingle Color = 16119285 Font.Charset = DEFAULT_CHARSET Font.Color = clWhite Font.Height = -11 Font.Name = 'Arial' Font.Style = [] ParentFont = False TabOrder = 0 object GroupBox1: TGroupBox Left = 283 Top = 2 Width = 450 Height = 348 Align = alClient Caption = 'PHP encoder:' Color = 16119285 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'Arial' Font.Style = [] ParentColor = False ParentFont = False TabOrder = 0 object lbtitlephp: TLabel Left = 80 Top = 0 Width = 77 Height = 14 Caption = '<Arquivo novo>' end object editor_php: TRichEdit Left = 2 Top = 45 Width = 446 Height = 301 Align = alClient Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Courier New' Font.Style = [] ParentFont = False ScrollBars = ssBoth TabOrder = 0 WordWrap = False end object ToolBar1: TToolBar Left = 2 Top = 16 Width = 446 Height = 29 Caption = 'ToolBar1' TabOrder = 1 object bt_novo: TSpeedButton Left = 0 Top = 2 Width = 23 Height = 22 Hint = 'Novo arquivo' Flat = True Glyph.Data = { 9E020000424D9E02000000000000360100002800000012000000120000000100 08000000000068010000120B0000120B00004000000000000000835C36005A85 AD0000FF0000F2D4B100E1C9AB004E7BA60000CCFF009966660082FEFE009999 9900EDF1F100CCFFFF008A633D00AE885E008DA6BD003253760033CCFF00FDF1 DD00E1C7A300FBE9C400FEFCF100C6A584009E794D00B0B6B500FEF8EF00FDF0 D700E4D1BC00956E4700FEF6E600A5835F00FFFFFF00B8956A00FCEED00042D5 FE00E9D8C300E2D3B900FFF7DE00FEFAF600E4D3B900816039008B664000B18A 63008CAAC500537CA50095744D008F6B4300FEFCF700F4D3B200E9D8BD00FFFF FF00000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000313131313131 3131313131313131313131310000313131313131090909090909090909093131 00003131313131161B1B2D282828272700093131000031313131311D11111120 2013131300093131000031313131311D1C111111202020130009313100003131 3131310D1C1C1C111120202000093131000031313131312918181C1C11111120 0009313100003131313131291818181C1C111111000931310000313131313107 252518181C222204000931310000310605311E072E0E0B182315152C00093131 0000310A062B0807010B2E2E2614141200093131000031310B06100F081E1E2E 1A252F00093131310000312B2B101E100101012A1A0300093131313100001E1E 101E1E1E10080B1E1F1F173131313131000031312B101E100605313131313131 313131310000312B0831212B08062B3131313131313131310000310A31311E2B 310A063131313131313131310000313131311E31313131313131313131313131 0000} ParentShowHint = False ShowHint = True OnClick = bt_novoClick end object bt_abrir: TSpeedButton Left = 23 Top = 2 Width = 23 Height = 22 Hint = 'Abrir arquivo' Flat = True Glyph.Data = { 96010000424D9601000000000000B600000028000000100000000E0000000100 080000000000E0000000120B0000120B00002000000000000000FFFFFF00F7FF FF0099FFFF0094F7FF0083ECFF00DDDFDF007CDFFF006CD6FF0066CCFF00CCCC CC0066CCCC00BFC3C200BDBDBD0043B3DE0021B0CE00199CC4002D92C5001B81 B300848484001074A4007272720066666600FFFFFF0000000000000000000000 0000000000000000000000000000000000000000000000000000161605090909 09090909090909051616160B1214141414141414141414120B16051313131313 131313131313131512050F0F02070707070707070707101314090F0F06020606 0606060606060D13150C0F0E0D0204040404040404040D0F15120F0D0F020303 0303030303030D0A13140F070F040202020202020202080313140F060F0A0000 010000000000040013120F040D0F0F0F0F0F0F0F0F0F0F0F110B0F0303030303 0300000000000F130B160F0002020202000F0F0F0F0F0F051616160E00000000 0F0B161616161616161616160E0E0E0E05161616161616161616} ParentShowHint = False ShowHint = True OnClick = bt_abrirClick end object bt_salvar: TSpeedButton Left = 46 Top = 2 Width = 23 Height = 22 Hint = 'Salvar arquivo' Flat = True Glyph.Data = { 1E020000424D1E02000000000000B60000002800000014000000120000000100 08000000000068010000120B0000120B00002000000000000000FFFFFF00FFF9 EC00EDEDED00F7ECD800F2E7D300F0E4D000EBD8B600D9C8AB00C7B49200C2AF 8D00BFAC8A00BAA78500B7A48200B4A17F0099999900AF9C7A00A18E6C008673 5100A06C4800806D4B006D5A38006E502F005C4927004E392100140D0000FFFF FF00000000000000000000000000000000000000000000000000191919191919 1919191919191919191919191919191919191919190E0E0E0E0E0E0E0E0E0E0E 0E191919191919191217171515151515151717170E19191919191919120B0F00 0202020202160C170E19191919191919120B0F00130A000202160C170E191919 190E0E0E120A0D001413000202160C170E1919191217171512090D0000000000 00160C170E191919120B0F001208080C0C0C0C0C0C0C0C170E191919120B0F00 120801030303030405110C170E191919120A0D00120801030303030405110717 0E19191912090D001208010303030304051810170E1919191208080C12060101 0101010101140B170E1919191208010312121212121212121212121219191919 1208010303030304051107170E19191919191919120801030303030405181017 0E19191919191919120601010101010101140B170E1919191919191912121212 1212121212121212191919191919191919191919191919191919191919191919 1919} ParentShowHint = False ShowHint = True OnClick = bt_salvarClick end object Bevel1: TBevel Left = 69 Top = 2 Width = 12 Height = 22 Shape = bsLeftLine end object ComboBox_predefinidos: TComboBox Left = 81 Top = 2 Width = 336 Height = 22 Style = csDropDownList ItemHeight = 14 TabOrder = 0 Items.Strings = ( 'Conex'#227'o para bases' 'Usu'#225'rios on-line+contador (flash)' 'Usu'#225'rios on-line+contador (php)' 'Select na tabela selecionada' 'Insert na tabela selecionada' 'Update na tabela selecionada' 'Delete na tabela selecionada') end object bt_selecionar: TSpeedButton Left = 417 Top = 2 Width = 23 Height = 22 Hint = 'Executar rotina selecionada' Flat = True Glyph.Data = { 4E010000424D4E01000000000000760000002800000012000000120000000100 040000000000D8000000120B0000120B00001000000000000000FFFFFF0033FF FF0033CCFF009B9B9B000099CC00006699005050500000000700FFFFFF000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000007600000000000000000000004760000000000000000000004 1760000000000000000000004176000000000000000000004117600000000000 0000000004017600000000000000005555201760000000000000000520110070 0000000000000000521176000000000000000000050117600000000000000055 5550117600000000000000050111001500000000000000005011760000000000 0000000005011760000000000000000000501176000000000000000000044444 000000000000000000000000000000000000} ParentShowHint = False ShowHint = True OnClick = bt_selecionarClick end end end object Panel2: TPanel Left = 2 Top = 2 Width = 281 Height = 348 Align = alLeft Color = 16119285 Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -9 Font.Name = 'Verdana' Font.Style = [] ParentFont = False TabOrder = 1 object PageControl1: TPageControl Left = 1 Top = 1 Width = 279 Height = 346 ActivePage = TabSheet1 Align = alClient Style = tsFlatButtons TabOrder = 0 OnChange = PageControl1Change object TabSheet1: TTabSheet Caption = 'Usu'#225'rios' object DBGrid1: TDBGrid Left = 0 Top = 44 Width = 271 Height = 272 Align = alClient Color = clWhite DataSource = dm.source_sql FixedColor = 15066597 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -9 Font.Name = 'Verdana' Font.Style = [] Options = [dgTitles, dgIndicator, dgColumnResize, dgColLines, dgRowLines, dgTabs, dgRowSelect, dgConfirmDelete, dgCancelOnExit] ParentFont = False TabOrder = 0 TitleFont.Charset = DEFAULT_CHARSET TitleFont.Color = clBlack TitleFont.Height = -9 TitleFont.Name = 'Verdana' TitleFont.Style = [] OnCellClick = DBGrid1CellClick OnKeyDown = DBGrid1KeyDown OnKeyUp = DBGrid1KeyUp end object ToolBar2: TToolBar Left = 0 Top = 0 Width = 271 Height = 29 ButtonHeight = 21 Caption = 'ToolBar2' TabOrder = 1 object Label9: TLabel Left = 0 Top = 2 Width = 53 Height = 21 Alignment = taRightJustify AutoSize = False Caption = 'Localizar:' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -9 Font.Name = 'Verdana' Font.Style = [] ParentFont = False Layout = tlCenter end object ed_entidade: TEdit Left = 53 Top = 2 Width = 216 Height = 21 Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Verdana' Font.Style = [] ParentFont = False TabOrder = 0 end end object Panel3: TPanel Left = 0 Top = 29 Width = 271 Height = 15 Align = alTop BevelOuter = bvNone Color = 16119285 TabOrder = 2 object count_grade: TLabel Left = 209 Top = -1 Width = 6 Height = 14 Alignment = taRightJustify Caption = '0' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'Arial' Font.Style = [] ParentFont = False end object Label11: TLabel Left = 217 Top = -1 Width = 50 Height = 14 Alignment = taCenter AutoSize = False Caption = 'registros' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'Arial' Font.Style = [] ParentFont = False end object Label12: TLabel Left = 0 Top = 0 Width = 86 Height = 12 Caption = 'Lista de usu'#225'rios' end end end object TabSheet6: TTabSheet Caption = 'Tabelas' ImageIndex = 2 object ToolBar6: TToolBar Left = 0 Top = 0 Width = 271 Height = 29 ButtonHeight = 21 Caption = 'ToolBar2' TabOrder = 0 object Label1: TLabel Left = 0 Top = 2 Width = 53 Height = 21 Alignment = taRightJustify AutoSize = False Caption = 'Localizar:' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -9 Font.Name = 'Verdana' Font.Style = [] ParentFont = False Layout = tlCenter end object ed_tabelas: TEdit Left = 53 Top = 2 Width = 216 Height = 21 Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Verdana' Font.Style = [] ParentFont = False TabOrder = 0 end end object DBGrid2: TDBGrid Left = 0 Top = 44 Width = 271 Height = 272 Align = alClient Color = clWhite DataSource = dm.source_sql FixedColor = 15066597 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -9 Font.Name = 'Verdana' Font.Style = [] Options = [dgTitles, dgIndicator, dgColumnResize, dgColLines, dgRowLines, dgTabs, dgRowSelect, dgConfirmDelete, dgCancelOnExit] ParentFont = False TabOrder = 1 TitleFont.Charset = DEFAULT_CHARSET TitleFont.Color = clBlack TitleFont.Height = -9 TitleFont.Name = 'Verdana' TitleFont.Style = [] OnCellClick = DBGrid2CellClick OnKeyDown = DBGrid2KeyDown OnKeyUp = DBGrid2KeyUp end object Panel4: TPanel Left = 0 Top = 29 Width = 271 Height = 15 Align = alTop BevelOuter = bvNone Color = 16119285 TabOrder = 2 object count_tab: TLabel Left = 209 Top = -1 Width = 6 Height = 14 Alignment = taRightJustify Caption = '0' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'Arial' Font.Style = [] ParentFont = False end object Label14: TLabel Left = 217 Top = -1 Width = 50 Height = 14 Alignment = taCenter AutoSize = False Caption = 'registros' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'Arial' Font.Style = [] ParentFont = False end object Label15: TLabel Left = 0 Top = 0 Width = 84 Height = 12 Caption = 'Lista de tabelas:' end end end object TabSheet7: TTabSheet Caption = 'Campos' ImageIndex = 4 object ToolBar7: TToolBar Left = 0 Top = 0 Width = 271 Height = 29 ButtonHeight = 21 Caption = 'ToolBar2' TabOrder = 0 object Label2: TLabel Left = 0 Top = 2 Width = 53 Height = 21 Alignment = taRightJustify AutoSize = False Caption = 'Localizar:' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -9 Font.Name = 'Verdana' Font.Style = [] ParentFont = False Layout = tlCenter end object ed_campos: TEdit Left = 53 Top = 2 Width = 216 Height = 21 Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Verdana' Font.Style = [] ParentFont = False TabOrder = 0 end end object DBGrid3: TDBGrid Left = 0 Top = 44 Width = 271 Height = 272 Align = alClient Color = clWhite DataSource = dm.source_sql FixedColor = 15066597 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -9 Font.Name = 'Verdana' Font.Style = [] Options = [dgTitles, dgIndicator, dgColumnResize, dgColLines, dgRowLines, dgTabs, dgRowSelect, dgConfirmDelete, dgCancelOnExit] ParentFont = False TabOrder = 1 TitleFont.Charset = DEFAULT_CHARSET TitleFont.Color = clBlack TitleFont.Height = -9 TitleFont.Name = 'Verdana' TitleFont.Style = [] end object Panel5: TPanel Left = 0 Top = 29 Width = 271 Height = 15 Align = alTop BevelOuter = bvNone Color = 16119285 TabOrder = 2 object count_campos: TLabel Left = 209 Top = -1 Width = 6 Height = 14 Alignment = taRightJustify Caption = '0' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'Arial' Font.Style = [] ParentFont = False end object Label16: TLabel Left = 217 Top = -1 Width = 50 Height = 14 Alignment = taCenter AutoSize = False Caption = 'registros' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'Arial' Font.Style = [] ParentFont = False end object lb_tab: TLabel Left = 0 Top = 0 Width = 86 Height = 12 Caption = 'Lista de campos:' end end end object TabSheet2: TTabSheet Caption = 'Conex'#227'o' ImageIndex = 1 object group_servera: TGroupBox Left = 0 Top = 0 Width = 271 Height = 316 Align = alClient Caption = 'Conex'#227'o:' Color = 16119285 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -9 Font.Name = 'Verdana' Font.Style = [] ParentColor = False ParentFont = False TabOrder = 0 object Label10: TLabel Left = 8 Top = 24 Width = 44 Height = 12 Alignment = taRightJustify Caption = 'Conex'#227'o' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -9 Font.Name = 'Verdana' Font.Style = [] ParentFont = False end object Label4: TLabel Left = 8 Top = 51 Width = 42 Height = 12 Alignment = taRightJustify Caption = 'Servidor' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -9 Font.Name = 'Verdana' Font.Style = [] ParentFont = False end object Label5: TLabel Left = 2 Top = 75 Width = 48 Height = 12 Alignment = taRightJustify Caption = 'Database' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -9 Font.Name = 'Verdana' Font.Style = [] ParentFont = False end object Label6: TLabel Left = 11 Top = 99 Width = 39 Height = 12 Alignment = taRightJustify Caption = 'Usu'#225'rio' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -9 Font.Name = 'Verdana' Font.Style = [] ParentFont = False end object Label7: TLabel Left = 19 Top = 123 Width = 31 Height = 12 Alignment = taRightJustify Caption = 'Senha' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -9 Font.Name = 'Verdana' Font.Style = [] ParentFont = False end object Label8: TLabel Left = 17 Top = 147 Width = 33 Height = 12 Alignment = taRightJustify Caption = 'Dir Lib' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -9 Font.Name = 'Verdana' Font.Style = [] ParentFont = False end object YuSoftLabel3: TYuSoftLabel Left = 220 Top = 174 Width = 38 Height = 12 Hint = 'Restartar configura'#231#227'o default' Alignment = taRightJustify Caption = 'Default' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -9 Font.Name = 'Verdana' Font.Style = [fsBold] ParentFont = False ParentShowHint = False ShowHint = True OnClick = YuSoftLabel3Click OnMouseEnterState.Active = True OnMouseEnterState.BorderColor = 8454143 OnMouseEnterState.BorderWidth = 1 OnMouseEnterState.TextStyle = tsRecessed1 OnMouseEnterState.ShadowColor = clWhite OnMouseEnterState.ShadowWidth = 0 OnClickState.Active = True OnClickState.BorderColor = clBtnHighlight OnClickState.BorderWidth = 0 OnClickState.TextStyle = tsRecessed2 OnClickState.ShadowColor = 16769183 OnClickState.ShadowWidth = 0 OnExtendedState.Active = True OnExtendedState.BorderColor = clBtnHighlight OnExtendedState.BorderWidth = 1 OnExtendedState.TextStyle = tsRecessed1 OnExtendedState.ShadowColor = clWhite OnExtendedState.ShadowWidth = 0 Transparent = True end object ed_host: TEdit Left = 56 Top = 47 Width = 204 Height = 22 Color = clWhite Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'Arial' Font.Style = [] ParentFont = False TabOrder = 0 end object ComboBox_cbx: TComboBox Left = 56 Top = 23 Width = 204 Height = 20 Style = csDropDownList ItemHeight = 0 TabOrder = 1 end object ed_db: TEdit Left = 56 Top = 71 Width = 204 Height = 22 Color = clWhite Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'Arial' Font.Style = [] ParentFont = False TabOrder = 2 end object ed_user: TEdit Left = 56 Top = 95 Width = 204 Height = 22 Color = clWhite Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'Arial' Font.Style = [] ParentFont = False TabOrder = 3 end object ed_pass: TEdit Left = 56 Top = 119 Width = 204 Height = 22 Color = clWhite Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'Arial' Font.Style = [] ParentFont = False PasswordChar = '#' TabOrder = 4 end object ed_lib: TEdit Left = 56 Top = 143 Width = 204 Height = 22 Color = clWhite Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'Arial' Font.Style = [] ParentFont = False TabOrder = 5 end end end object TabSheet3: TTabSheet Caption = 'Contador' ImageIndex = 2 object PageControl2: TPageControl Left = 0 Top = 0 Width = 271 Height = 316 ActivePage = TabSheet4 Align = alClient Style = tsFlatButtons TabOrder = 0 object TabSheet4: TTabSheet Caption = 'Contador' object ToolBar4: TToolBar Left = 0 Top = 0 Width = 263 Height = 24 AutoSize = True ButtonHeight = 20 Caption = 'ToolBar3' TabOrder = 0 object ed_contador: TEdit Left = 0 Top = 2 Width = 217 Height = 20 TabOrder = 0 end object br_localizarbase2: TSpeedButton Left = 217 Top = 2 Width = 23 Height = 20 Hint = 'Localizar tabela' Flat = True Glyph.Data = { B6010000424DB601000000000000B60000002800000010000000100000000100 08000000000000010000120B0000120B00002000000000000000FFFFFF00CCFF FF00F0FBFF0099FFFF0066FFFF0033CCCC009999990033999900009999000080 8000666666005555550000333300161616000808080000000000FFFFFF000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000101010101010 10101010101010101010101010100A0D0F0F0D0A1010101010101010100A0C04 0507090C0D0F0F0D0A101010100D0500050709070F0507090C0A100A0D0D0500 050709070F050709070F0A09040D0500050709070F050709070F0B07040D0500 050709070F050709070F0B07040D0500070709070F050709070F0B07040D0504 040405070F050809070F0B07040D0400000000040F040405080F0B0705070905 0404050909000000040F0B050404050C0D0D0C0905040405090A0A0501020307 0E1010060B0B0B0B0610100A0B0B0B0A10101010101010101010101010101010 1010101010101010101010101010101010101010101010101010} ParentShowHint = False ShowHint = True OnClick = br_localizarbase2Click end object SpeedButton6: TSpeedButton Left = 240 Top = 2 Width = 23 Height = 20 Hint = 'Criar tabela para contador de visitas' Flat = True Glyph.Data = { 9E020000424D9E02000000000000360100002800000012000000120000000100 08000000000068010000120B0000120B00004000000000000000835C36005A85 AD0000FF0000F2D4B100E1C9AB004E7BA60000CCFF009966660082FEFE009999 9900EDF1F100CCFFFF008A633D00AE885E008DA6BD003253760033CCFF00FDF1 DD00E1C7A300FBE9C400FEFCF100C6A584009E794D00B0B6B500FEF8EF00FDF0 D700E4D1BC00956E4700FEF6E600A5835F00FFFFFF00B8956A00FCEED00042D5 FE00E9D8C300E2D3B900FFF7DE00FEFAF600E4D3B900816039008B664000B18A 63008CAAC500537CA50095744D008F6B4300FEFCF700F4D3B200E9D8BD00FFFF FF00000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000313131313131 3131313131313131313131310000313131313131090909090909090909093131 00003131313131161B1B2D282828272700093131000031313131311D11111120 2013131300093131000031313131311D1C111111202020130009313100003131 3131310D1C1C1C111120202000093131000031313131312918181C1C11111120 0009313100003131313131291818181C1C111111000931310000313131313107 252518181C222204000931310000310605311E072E0E0B182315152C00093131 0000310A062B0807010B2E2E2614141200093131000031310B06100F081E1E2E 1A252F00093131310000312B2B101E100101012A1A0300093131313100001E1E 101E1E1E10080B1E1F1F173131313131000031312B101E100605313131313131 313131310000312B0831212B08062B3131313131313131310000310A31311E2B 310A063131313131313131310000313131311E31313131313131313131313131 0000} ParentShowHint = False ShowHint = True OnClick = SpeedButton6Click end end object ToolBar5: TToolBar Left = 0 Top = 24 Width = 263 Height = 24 AutoSize = True ButtonHeight = 20 Caption = 'ToolBar5' TabOrder = 1 object Label3: TLabel Left = 0 Top = 2 Width = 132 Height = 12 Alignment = taCenter Caption = 'Incrementar n'#186' de visitas:' Layout = tlCenter end object ed_inccount: TEdit Left = 132 Top = 2 Width = 108 Height = 20 TabOrder = 0 Text = '0' OnKeyPress = ed_inccountKeyPress end object bt_executarvisitas: TSpeedButton Left = 240 Top = 2 Width = 23 Height = 20 Hint = 'Executar incrementa'#231#227'o autom'#225'tica' Flat = True Glyph.Data = { 4E010000424D4E01000000000000760000002800000012000000120000000100 040000000000D8000000120B0000120B00001000000000000000FFFFFF0033FF FF0033CCFF009B9B9B000099CC00006699005050500000000700FFFFFF000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000007600000000000000000000004760000000000000000000004 1760000000000000000000004176000000000000000000004117600000000000 0000000004017600000000000000005555201760000000000000000520110070 0000000000000000521176000000000000000000050117600000000000000055 5550117600000000000000050111001500000000000000005011760000000000 0000000005011760000000000000000000501176000000000000000000044444 000000000000000000000000000000000000} ParentShowHint = False ShowHint = True OnClick = bt_executarvisitasClick end end end object TabSheet5: TTabSheet Caption = 'Usu'#225'rios on-line' ImageIndex = 1 object ToolBar3: TToolBar Left = 0 Top = 0 Width = 263 Height = 24 AutoSize = True ButtonHeight = 20 Caption = 'ToolBar3' TabOrder = 0 object ed_online: TEdit Left = 0 Top = 2 Width = 217 Height = 20 TabOrder = 0 end object br_localizarbase1: TSpeedButton Left = 217 Top = 2 Width = 23 Height = 20 Hint = 'Localizar tabela' Flat = True Glyph.Data = { B6010000424DB601000000000000B60000002800000010000000100000000100 08000000000000010000120B0000120B00002000000000000000FFFFFF00CCFF FF00F0FBFF0099FFFF0066FFFF0033CCCC009999990033999900009999000080 8000666666005555550000333300161616000808080000000000FFFFFF000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000101010101010 10101010101010101010101010100A0D0F0F0D0A1010101010101010100A0C04 0507090C0D0F0F0D0A101010100D0500050709070F0507090C0A100A0D0D0500 050709070F050709070F0A09040D0500050709070F050709070F0B07040D0500 050709070F050709070F0B07040D0500070709070F050709070F0B07040D0504 040405070F050809070F0B07040D0400000000040F040405080F0B0705070905 0404050909000000040F0B050404050C0D0D0C0905040405090A0A0501020307 0E1010060B0B0B0B0610100A0B0B0B0A10101010101010101010101010101010 1010101010101010101010101010101010101010101010101010} ParentShowHint = False ShowHint = True OnClick = br_localizarbase1Click end object SpeedButton3: TSpeedButton Left = 240 Top = 2 Width = 23 Height = 20 Hint = 'Criar tabela para usu'#225'rios online' Flat = True Glyph.Data = { 9E020000424D9E02000000000000360100002800000012000000120000000100 08000000000068010000120B0000120B00004000000000000000835C36005A85 AD0000FF0000F2D4B100E1C9AB004E7BA60000CCFF009966660082FEFE009999 9900EDF1F100CCFFFF008A633D00AE885E008DA6BD003253760033CCFF00FDF1 DD00E1C7A300FBE9C400FEFCF100C6A584009E794D00B0B6B500FEF8EF00FDF0 D700E4D1BC00956E4700FEF6E600A5835F00FFFFFF00B8956A00FCEED00042D5 FE00E9D8C300E2D3B900FFF7DE00FEFAF600E4D3B900816039008B664000B18A 63008CAAC500537CA50095744D008F6B4300FEFCF700F4D3B200E9D8BD00FFFF FF00000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000313131313131 3131313131313131313131310000313131313131090909090909090909093131 00003131313131161B1B2D282828272700093131000031313131311D11111120 2013131300093131000031313131311D1C111111202020130009313100003131 3131310D1C1C1C111120202000093131000031313131312918181C1C11111120 0009313100003131313131291818181C1C111111000931310000313131313107 252518181C222204000931310000310605311E072E0E0B182315152C00093131 0000310A062B0807010B2E2E2614141200093131000031310B06100F081E1E2E 1A252F00093131310000312B2B101E100101012A1A0300093131313100001E1E 101E1E1E10080B1E1F1F173131313131000031312B101E100605313131313131 313131310000312B0831212B08062B3131313131313131310000310A31311E2B 310A063131313131313131310000313131311E31313131313131313131313131 0000} ParentShowHint = False ShowHint = True OnClick = SpeedButton3Click end end end end end end end end object pn_tit: TPanel Left = 0 Top = 0 Width = 739 Height = 20 Align = alTop Color = 14540253 TabOrder = 1 object Image3: TImage Left = 1 Top = 1 Width = 737 Height = 18 Align = alClient Stretch = True OnMouseDown = Image3MouseDown end object SpeedButton1: TSpeedButton Left = 718 Top = 3 Width = 14 Height = 14 Hint = 'Fechar janela' Caption = 'X' Flat = True Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'Verdana' Font.Style = [fsBold] ParentFont = False ParentShowHint = False ShowHint = True OnClick = SpeedButton1Click end object SpeedButton4: TSpeedButton Left = 688 Top = 3 Width = 14 Height = 14 Hint = 'Sobre' Caption = '?' Flat = True Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Verdana' Font.Style = [fsBold] ParentFont = False ParentShowHint = False ShowHint = True OnClick = SpeedButton4Click end object YuSoftLabel5: TYuSoftLabel Left = 28 Top = 3 Width = 149 Height = 13 Cursor = crHandPoint Hint = 'Acessar website' Alignment = taCenter Caption = 'WebServer - PHP encoder' DragCursor = crHandPoint Font.Charset = DEFAULT_CHARSET Font.Color = 5979648 Font.Height = -11 Font.Name = 'Verdana' Font.Style = [] ParentFont = False ParentShowHint = False ShowHint = True OnClick = YuSoftLabel5Click OnMouseEnterState.Active = True OnMouseEnterState.BorderColor = clBtnHighlight OnMouseEnterState.BorderWidth = 1 OnMouseEnterState.TextStyle = tsNone OnMouseEnterState.ShadowColor = clBtnShadow OnMouseEnterState.ShadowWidth = 0 OnClickState.Active = False OnClickState.BorderColor = clBtnHighlight OnClickState.BorderWidth = 0 OnClickState.TextStyle = tsNone OnClickState.ShadowColor = clBtnShadow OnClickState.ShadowWidth = 0 OnExtendedState.Active = True OnExtendedState.BorderColor = clBtnHighlight OnExtendedState.BorderWidth = 0 OnExtendedState.TextStyle = tsNone OnExtendedState.ShadowColor = clBtnShadow OnExtendedState.ShadowWidth = 0 Transparent = True end object biSystemMenu: TImage Left = 4 Top = 3 Width = 15 Height = 14 Proportional = True Stretch = True Transparent = True end object bt_minimize: TSpeedButton Left = 703 Top = 3 Width = 14 Height = 14 Hint = 'Minimizar janela' Caption = '-' Flat = True Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Verdana' Font.Style = [fsBold] ParentFont = False ParentShowHint = False ShowHint = True OnClick = bt_minimizeClick end object lb_nomeentidade: TLabel Left = 233 Top = 4 Width = 6 Height = 13 Caption = '0' Transparent = True end object lb_codusr: TLabel Left = 222 Top = 4 Width = 6 Height = 13 Alignment = taRightJustify Caption = '0' Transparent = True end end object pn_status: TPanel Left = 0 Top = 376 Width = 739 Height = 17 Align = alBottom BorderStyle = bsSingle Color = 14540253 TabOrder = 2 object Image4: TImage Left = 1 Top = 1 Width = 733 Height = 11 Align = alClient Stretch = True end end object SaveDialog_php: TSaveDialog DefaultExt = 'php' Filter = 'PHP (*.php)|*.php|Todos os arquivos (*.*)|*.*' Title = 'Salvar arquivo como' Left = 414 Top = 276 end object OpenDialog_php: TOpenDialog Filter = 'PHP (*.php)|*.php|Todos os arquivos (*.*)|*.*' Title = 'Abrir arquivo' Left = 374 Top = 276 end object XPManifest1: TXPManifest Left = 533 Top = 71 end end
34.94621
139
0.547354
478571bdeba23d52d4054e8706323d414d7e440d
571
pas
Pascal
Test/SimpleScripts/new_class3.pas
skolkman/dwscript
b9f99d4b8187defac3f3713e2ae0f7b83b63d516
[ "Condor-1.1" ]
79
2015-03-18T10:46:13.000Z
2022-03-17T18:05:11.000Z
Test/SimpleScripts/new_class3.pas
skolkman/dwscript
b9f99d4b8187defac3f3713e2ae0f7b83b63d516
[ "Condor-1.1" ]
6
2016-03-29T14:39:00.000Z
2020-09-14T10:04:14.000Z
Test/SimpleScripts/new_class3.pas
skolkman/dwscript
b9f99d4b8187defac3f3713e2ae0f7b83b63d516
[ "Condor-1.1" ]
25
2016-05-04T13:11:38.000Z
2021-09-29T13:34:31.000Z
type TMyClass = class constructor Build(i : Integer = -1); default; end; type TSubClass = class(TMyClass) end; type TClassRef = class of TMyClass; constructor TMyClass.Build(i : Integer = -1); begin Print(ClassName); PrintLn(i); end; function GetAClass(r : TClassRef) : TClassRef; begin Result:=r; end; var o1 := new TMyClass; var o2 := new (TMyClass)(1); var r := TSubClass; new r; new r(1); new (r)(2); o1:=new (GetAClass(TMyClass)); o1:=new (GetAClass(r))(); o1:=new (GetAClass(TSubClass))(3);
15.861111
52
0.602452
4773584472a1a37da2226060cfef2aec76cf67d7
1,222
pas
Pascal
Features/SpeechRecognition/DW.SpeechRecognition.Default.pas
AndersondaCampo/Kastri
4352181b56ab9569b086eae3e79e5dc8d6082c30
[ "MIT" ]
null
null
null
Features/SpeechRecognition/DW.SpeechRecognition.Default.pas
AndersondaCampo/Kastri
4352181b56ab9569b086eae3e79e5dc8d6082c30
[ "MIT" ]
null
null
null
Features/SpeechRecognition/DW.SpeechRecognition.Default.pas
AndersondaCampo/Kastri
4352181b56ab9569b086eae3e79e5dc8d6082c30
[ "MIT" ]
1
2021-04-05T02:15:08.000Z
2021-04-05T02:15:08.000Z
unit DW.SpeechRecognition.Default; {*******************************************************} { } { Kastri } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses DW.SpeechRecognition; type TPlatformSpeechRecognition = class(TCustomPlatformSpeechRecognition) protected class function IsSupported: Boolean; override; protected function IsRecording: Boolean; override; procedure StartRecording; override; procedure StopRecording; override; end; implementation { TPlatformSpeechRecognition } function TPlatformSpeechRecognition.IsRecording: Boolean; begin Result := False; end; class function TPlatformSpeechRecognition.IsSupported: Boolean; begin Result := False; end; procedure TPlatformSpeechRecognition.StartRecording; begin // end; procedure TPlatformSpeechRecognition.StopRecording; begin // end; end.
23.056604
71
0.527005
478f652db8ad6c58938e65b0e13e4324a5a22952
8,903
pas
Pascal
samples/1.1.4/SpringDemos/Demo.DependencyInjection/uIniFileService.pas
GitDataOrg/Spring4D
e61e8a36e140e14dbdba1d71d0edc5ac253362cd
[ "Apache-2.0" ]
2
2016-10-09T19:04:44.000Z
2017-01-19T21:45:00.000Z
samples/1.1.4/SpringDemos/Demo.DependencyInjection/uIniFileService.pas
GitDataOrg/Spring4D
e61e8a36e140e14dbdba1d71d0edc5ac253362cd
[ "Apache-2.0" ]
null
null
null
samples/1.1.4/SpringDemos/Demo.DependencyInjection/uIniFileService.pas
GitDataOrg/Spring4D
e61e8a36e140e14dbdba1d71d0edc5ac253362cd
[ "Apache-2.0" ]
null
null
null
unit uIniFileService; interface uses Classes ; type IIniFileService = interface ['{457DB193-8B7D-43B6-85EB-7CAF57949FEF}'] function GetFilename: string; function SectionExists(const Section: string): Boolean; function ReadString(const Section, Ident, Default: string): string; procedure WriteString(const Section, Ident, Value: String); function ReadInteger(const Section, Ident: string; Default: Longint): Longint; procedure WriteInteger(const Section, Ident: string; Value: Longint); function ReadBool(const Section, Ident: string; Default: Boolean): Boolean; procedure WriteBool(const Section, Ident: string; Value: Boolean); function ReadBinaryStream(const Section, Name: string; Value: TStream): Integer; function ReadDate(const Section, Name: string; Default: TDateTime): TDateTime; function ReadDateTime(const Section, Name: string; Default: TDateTime): TDateTime; function ReadFloat(const Section, Name: string; Default: Double): Double; function ReadTime(const Section, Name: string; Default: TDateTime): TDateTime; procedure WriteBinaryStream(const Section, Name: string; Value: TStream); procedure WriteDate(const Section, Name: string; Value: TDateTime); procedure WriteDateTime(const Section, Name: string; Value: TDateTime); procedure WriteFloat(const Section, Name: string; Value: Double); procedure WriteTime(const Section, Name: string; Value: TDateTime); procedure ReadSection(const Section: string; Strings: TStrings); procedure ReadSections(Strings: TStrings); overload; procedure ReadSections(const Section: string; Strings: TStrings); overload; procedure ReadSubSections(const Section: string; Strings: TStrings; Recurse: Boolean = False); procedure ReadSectionValues(const Section: string; Strings: TStrings); procedure EraseSection(const Section: string); procedure DeleteKey(const Section, Ident: String); procedure UpdateFile; function ValueExists(const Section, Ident: string): Boolean; property FileName: string read GetFilename; end; type TIniFileType = (iftFileBased, iftMemoryBased); procedure RegisterIniFileService(aServiceName: string; aFilename: string; aIniFileType: TIniFileType = iftFileBased); implementation uses IniFiles , Spring.Container ; type TIniFileImpl = class(TInterfacedObject, IIniFileService) private FIniFile: TCustomIniFile; public constructor Create(const aFilename: string; aIniFileType: TIniFileType); function GetFilename: string; function SectionExists(const Section: string): Boolean; function ReadString(const Section, Ident, Default: string): string; procedure WriteString(const Section, Ident, Value: String); function ReadInteger(const Section, Ident: string; Default: Longint): Longint; procedure WriteInteger(const Section, Ident: string; Value: Longint); function ReadBool(const Section, Ident: string; Default: Boolean): Boolean; procedure WriteBool(const Section, Ident: string; Value: Boolean); function ReadBinaryStream(const Section, Name: string; Value: TStream): Integer; function ReadDate(const Section, Name: string; Default: TDateTime): TDateTime; function ReadDateTime(const Section, Name: string; Default: TDateTime): TDateTime; function ReadFloat(const Section, Name: string; Default: Double): Double; function ReadTime(const Section, Name: string; Default: TDateTime): TDateTime; procedure WriteBinaryStream(const Section, Name: string; Value: TStream); procedure WriteDate(const Section, Name: string; Value: TDateTime); procedure WriteDateTime(const Section, Name: string; Value: TDateTime); procedure WriteFloat(const Section, Name: string; Value: Double); procedure WriteTime(const Section, Name: string; Value: TDateTime); procedure ReadSection(const Section: string; Strings: TStrings); procedure ReadSections(Strings: TStrings); overload; procedure ReadSections(const Section: string; Strings: TStrings); overload; procedure ReadSubSections(const Section: string; Strings: TStrings; Recurse: Boolean = False); procedure ReadSectionValues(const Section: string; Strings: TStrings); procedure EraseSection(const Section: string); procedure DeleteKey(const Section, Ident: String); procedure UpdateFile; function ValueExists(const Section, Ident: string): Boolean; property FileName: string read GetFilename; end; { TIniFileImpl } constructor TIniFileImpl.Create(const aFilename: string; aIniFileType: TIniFileType); begin inherited Create; case aIniFiletype of iftFileBased: FIniFile := TIniFile.Create(aFilename); iftMemoryBased: FIniFile := TMemIniFile.Create(aFilename); end; end; procedure TIniFileImpl.DeleteKey(const Section, Ident: String); begin FIniFile.DeleteKey(Section, Ident); end; procedure TIniFileImpl.EraseSection(const Section: string); begin fIniFile.EraseSection(Section); end; function TIniFileImpl.GetFilename: string; begin Result := FIniFile.FileName; end; function TIniFileImpl.ReadBinaryStream(const Section, Name: string; Value: TStream): Integer; begin Result := FIniFile.ReadBinaryStream(Section, Name, Value); end; function TIniFileImpl.ReadBool(const Section, Ident: string; Default: Boolean): Boolean; begin Result := FIniFile.ReadBool(Section, Ident, Default); end; function TIniFileImpl.ReadDate(const Section, Name: string; Default: TDateTime): TDateTime; begin Result := FIniFile.ReadDate(Section, Name, Default); end; function TIniFileImpl.ReadDateTime(const Section, Name: string; Default: TDateTime): TDateTime; begin Result := FIniFile.ReadDateTime(Section, Name, Default); end; function TIniFileImpl.ReadFloat(const Section, Name: string; Default: Double): Double; begin Result := FIniFile.ReadFloat(Section, Name, Default); end; function TIniFileImpl.ReadInteger(const Section, Ident: string; Default: Integer): Longint; begin Result := FIniFile.ReadInteger(Section, Ident, Default); end; procedure TIniFileImpl.ReadSection(const Section: string; Strings: TStrings); begin FIniFile.ReadSection(Section, Strings); end; procedure TIniFileImpl.ReadSections(const Section: string; Strings: TStrings); begin FIniFile.ReadSections(Section, Strings); end; procedure TIniFileImpl.ReadSections(Strings: TStrings); begin FIniFile.ReadSections(Strings); end; procedure TIniFileImpl.ReadSectionValues(const Section: string; Strings: TStrings); begin FIniFile.ReadSectionValues(Section, Strings); end; function TIniFileImpl.ReadString(const Section, Ident, Default: string): string; begin Result := FIniFile.ReadString(Section, Ident, Default); end; procedure TIniFileImpl.ReadSubSections(const Section: string; Strings: TStrings; Recurse: Boolean); begin FIniFile.ReadSubSections(Section, Strings, Recurse); end; function TIniFileImpl.ReadTime(const Section, Name: string; Default: TDateTime): TDateTime; begin Result := FIniFile.ReadTime(Section, Name, Default); end; function TIniFileImpl.SectionExists(const Section: string): Boolean; begin Result := FIniFile.SectionExists(Section); end; procedure TIniFileImpl.UpdateFile; begin FIniFile.UpdateFile; end; function TIniFileImpl.ValueExists(const Section, Ident: string): Boolean; begin Result := FIniFile.ValueExists(Section, Ident) end; procedure TIniFileImpl.WriteBinaryStream(const Section, Name: string; Value: TStream); begin FIniFile.WriteBinaryStream(Section, Name, Value); end; procedure TIniFileImpl.WriteBool(const Section, Ident: string; Value: Boolean); begin FIniFile.WriteBool(Section, Ident, Value); end; procedure TIniFileImpl.WriteDate(const Section, Name: string; Value: TDateTime); begin FIniFile.WriteDate(Section, Name, Value); end; procedure TIniFileImpl.WriteDateTime(const Section, Name: string; Value: TDateTime); begin FIniFile.WriteDateTime(Section, Name, Value); end; procedure TIniFileImpl.WriteFloat(const Section, Name: string; Value: Double); begin FIniFile.WriteFloat(Section, Name, Value); end; procedure TIniFileImpl.WriteInteger(const Section, Ident: string; Value: Integer); begin FIniFile.WriteInteger(Section, Ident, Value); end; procedure TIniFileImpl.WriteString(const Section, Ident, Value: String); begin FIniFile.WriteString(Section, Ident, Value); end; procedure TIniFileImpl.WriteTime(const Section, Name: string; Value: TDateTime); begin FIniFile.WriteTime(Section, Name, Value); end; procedure RegisterIniFileService(aServiceName: string; aFilename: string; aIniFileType: TIniFileType = iftFileBased); begin GlobalContainer.RegisterType<TIniFileImpl>.Implements<IIniFileService>(aServicename).AsSingleton.DelegateTo( function: TIniFileImpl begin Result := TIniFileImpl.Create(aFilename, aIniFileType); end ); GlobalContainer.Build; end; initialization end.
34.777344
119
0.770078
473bb9d2c18afa7c31b37ae984a9c288225a5b57
12,962
pas
Pascal
Libraries/SimpleServer/dwsBackgroundWorkersLibModule.pas
synapsea/DW-Script
b36c2e57f0285c217f8f0cae8e4e158d21127163
[ "Condor-1.1" ]
1
2022-02-18T22:14:44.000Z
2022-02-18T22:14:44.000Z
Libraries/SimpleServer/dwsBackgroundWorkersLibModule.pas
synapsea/DW-Script
b36c2e57f0285c217f8f0cae8e4e158d21127163
[ "Condor-1.1" ]
null
null
null
Libraries/SimpleServer/dwsBackgroundWorkersLibModule.pas
synapsea/DW-Script
b36c2e57f0285c217f8f0cae8e4e158d21127163
[ "Condor-1.1" ]
null
null
null
unit dwsBackgroundWorkersLibModule; interface uses SysUtils, Classes, dwsExprs, dwsComp, dwsUtils, dwsXPlatform, dwsIOCPWorkerThreadPool, dwsWebEnvironment, dwsJSON; const cDefaultMaxWorkersPerQueue = 32; type TBackgroundWorkEvent = procedure (const request : TWebRequest) of object; TBackgroundWorkLogEvent = procedure (const message : String) of object; TWorkQueues = TSimpleNameObjectHash<TIOCPWorkerThreadPool>; TdwsBackgroundWorkersLib = class; TWorkWebRequest = class (TWebRequest) private FHeaders : TStrings; FOwner : TdwsBackgroundWorkersLib; FPrev, FNext : TWorkWebRequest; protected function GetHeaders : TStrings; override; public Task : String; Data : RawByteString; constructor Create(aModule : TdwsBackgroundWorkersLib); destructor Destroy; override; function RemoteIP : String; override; function RawURL : String; override; function URL : String; override; function FullURL : String; override; function Method : String; override; function MethodVerb : TWebRequestMethodVerb; override; function Security : String; override; function Secure : Boolean; override; function ContentLength : Integer; override; function ContentData : RawByteString; override; function ContentType : RawByteString; override; procedure Execute(Sender : TObject); end; TdwsBackgroundWorkersLib = class(TDataModule) dwsBackgroundWorkers: TdwsUnit; procedure dwsBackgroundWorkersClassesBackgroundWorkersMethodsCreateWorkQueueEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsBackgroundWorkersClassesBackgroundWorkersMethodsDestroyWorkQueueEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsBackgroundWorkersClassesBackgroundWorkersMethodsQueueWorkEval( Info: TProgramInfo; ExtObject: TObject); procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); procedure dwsBackgroundWorkersClassesBackgroundWorkersMethodsQueueSizeEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsBackgroundWorkersClassesBackgroundWorkersMethodsQueueDelayedWorkEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsBackgroundWorkersClassesBackgroundWorkersMethodsGetWorkerCountEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsBackgroundWorkersClassesBackgroundWorkersMethodsSetWorkerCountEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsBackgroundWorkersClassesBackgroundWorkersMethodsQueueStatusAsJSONEval( Info: TProgramInfo; ExtObject: TObject); private { Private declarations } FOnBackgroundWork : TBackgroundWorkEvent; FOnBackgroundLogEvent : TBackgroundWorkLogEvent; FPools : TWorkQueues; FPoolsCS : TMultiReadSingleWrite; FWorkUnitHead : TWorkWebRequest; FWorkUnitLock : TMultiReadSingleWrite; FMaxWorkersPerQueue : Integer; public { Public declarations } property OnBackgroundWork : TBackgroundWorkEvent read FOnBackgroundWork write FOnBackgroundWork; property OnBackgroundLogEvent : TBackgroundWorkLogEvent read FOnBackgroundLogEvent write FOnBackgroundLogEvent; property MaxWorkersPerQueue : Integer read FMaxWorkersPerQueue write FMaxWorkersPerQueue; end; implementation {$R *.dfm} // Create // constructor TWorkWebRequest.Create(aModule : TdwsBackgroundWorkersLib); begin inherited Create; aModule.FWorkUnitLock.BeginWrite; try FOwner := aModule; FNext := aModule.FWorkUnitHead; if FNext <> nil then FNext.FPrev := Self; aModule.FWorkUnitHead := Self; finally aModule.FWorkUnitLock.EndWrite; end; end; // Destroy // destructor TWorkWebRequest.Destroy; begin if FOwner <> nil then begin FOwner.FWorkUnitLock.BeginWrite; try if FPrev = nil then FOwner.FWorkUnitHead := FNext else FPrev.FNext := FNext; if FNext <> nil then FNext.FPrev := FPrev; finally FOwner.FWorkUnitLock.EndWrite; end; end; FHeaders.Free; inherited; end; // GetHeaders // function TWorkWebRequest.GetHeaders : TStrings; begin if FHeaders=nil then FHeaders := TStringList.Create; Result := FHeaders; end; // RemoteIP // function TWorkWebRequest.RemoteIP : String; begin Result := '127.0.0.1'; end; // RawURL // function TWorkWebRequest.RawURL : String; begin Result := Task; end; // URL // function TWorkWebRequest.URL : String; begin Result := Task; end; // FullURL // function TWorkWebRequest.FullURL : String; begin Result := 'worker:' + Task; end; // Method // function TWorkWebRequest.Method : String; begin Result := 'POST'; end; // MethodVerb // function TWorkWebRequest.MethodVerb : TWebRequestMethodVerb; begin Result := wrmvPOST end; // Security // function TWorkWebRequest.Security : String; begin Result := ''; end; // Secure // function TWorkWebRequest.Secure : Boolean; begin Result := False; end; // ContentLength // function TWorkWebRequest.ContentLength : Integer; begin Result := Length(Data); end; // ContentData // function TWorkWebRequest.ContentData : RawByteString; begin Result := Data; end; // ContentType // function TWorkWebRequest.ContentType : RawByteString; begin Result := 'application/octet-stream'; end; // Execute // procedure TWorkWebRequest.Execute(Sender : TObject); procedure DoLog(lib : TdwsBackgroundWorkersLib; E : Exception); begin if Assigned(lib.FOnBackgroundLogEvent) then lib.FOnBackgroundLogEvent(E.ClassName + ': ' + E.Message); end; var lib : TdwsBackgroundWorkersLib; begin lib := (Sender as TdwsBackgroundWorkersLib); try try if Assigned(lib.FOnBackgroundWork) then lib.FOnBackgroundWork(Self); except on E : Exception do DoLog(lib, E); end; finally Free; end; end; procedure TdwsBackgroundWorkersLib.DataModuleCreate(Sender: TObject); begin FPoolsCS := TMultiReadSingleWrite.Create; FPools := TWorkQueues.Create; FMaxWorkersPerQueue := cDefaultMaxWorkersPerQueue; FWorkUnitLock := TMultiReadSingleWrite.Create; end; procedure TdwsBackgroundWorkersLib.DataModuleDestroy(Sender: TObject); var i : Integer; begin FOnBackgroundWork := nil; // remove all workers gracefully for i := 0 to FPools.HighIndex do if FPools.BucketObject[i] <> nil then FPools.BucketObject[i].WorkerCount := 0; // wait for completion for i := 0 to FPools.HighIndex do if FPools.BucketObject[i] <> nil then FPools.BucketObject[i].Shutdown; FPools.Clean; FreeAndNil(FPools); FreeAndNil(FPoolsCS); while FWorkUnitHead <> nil do FWorkUnitHead.Destroy; FreeAndNil(FWorkUnitLock); end; procedure TdwsBackgroundWorkersLib.dwsBackgroundWorkersClassesBackgroundWorkersMethodsCreateWorkQueueEval( Info: TProgramInfo; ExtObject: TObject); var name : String; pool : TIOCPWorkerThreadPool; begin if not Assigned(FOnBackgroundWork) then raise Exception.Create('Cannot create workers during shutdown'); name:=Info.ParamAsString[0]; FPoolsCS.BeginWrite; try pool:=FPools[name]; Info.ResultAsBoolean:=(pool=nil); if pool=nil then begin pool:=TIOCPWorkerThreadPool.Create(1); FPools[name]:=pool; end; finally FPoolsCS.EndWrite; end; end; procedure TdwsBackgroundWorkersLib.dwsBackgroundWorkersClassesBackgroundWorkersMethodsDestroyWorkQueueEval( Info: TProgramInfo; ExtObject: TObject); var name : String; pool : TIOCPWorkerThreadPool; begin if not Assigned(FOnBackgroundWork) then Exit; name:=Info.ParamAsString[0]; FPoolsCS.BeginWrite; try pool:=FPools[name]; if pool<>nil then FPools[name]:=nil; finally FPoolsCS.EndWrite; end; Info.ResultAsBoolean:=(pool<>nil); if pool<>nil then begin pool.Shutdown; pool.Free; end; end; procedure TdwsBackgroundWorkersLib.dwsBackgroundWorkersClassesBackgroundWorkersMethodsQueueSizeEval( Info: TProgramInfo; ExtObject: TObject); var name : String; pool : TIOCPWorkerThreadPool; n : Integer; begin name := Info.ParamAsString[0]; FPoolsCS.BeginRead; try pool:=FPools[name]; if pool<>nil then n := pool.QueueSize else n := 0; finally FPoolsCS.EndRead; end; Info.ResultAsInteger:=n; end; procedure TdwsBackgroundWorkersLib.dwsBackgroundWorkersClassesBackgroundWorkersMethodsQueueWorkEval( Info: TProgramInfo; ExtObject: TObject); var name : String; workUnit : TWorkWebRequest; pool : TIOCPWorkerThreadPool; begin if not Assigned(FOnBackgroundWork) then Exit; name:=Info.ParamAsString[0]; workUnit:=TWorkWebRequest.Create(Self); workUnit.Task:=Info.ParamAsString[1]; workUnit.Data:=Info.ParamAsDataString[2]; FPoolsCS.BeginRead; try pool:=FPools[name]; if pool<>nil then pool.QueueWork(workUnit.Execute, Self); finally FPoolsCS.EndRead; end; if pool=nil then begin workUnit.Free; raise Exception.CreateFmt('Unknown Work Queue "%s"', [name]); end; end; procedure TdwsBackgroundWorkersLib.dwsBackgroundWorkersClassesBackgroundWorkersMethodsQueueDelayedWorkEval( Info: TProgramInfo; ExtObject: TObject); var name : String; workUnit : TWorkWebRequest; pool : TIOCPWorkerThreadPool; delayMilliseconds : Integer; begin if not Assigned(FOnBackgroundWork) then Exit; name := Info.ParamAsString[0]; delayMilliseconds := Round(Info.ParamAsFloat[1] * 1000); workUnit := TWorkWebRequest.Create(Self); workUnit.Task := Info.ParamAsString[2]; workUnit.Data := Info.ParamAsDataString[3]; FPoolsCS.BeginRead; try pool := FPools[name]; if pool <> nil then pool.QueueDelayedWork(delayMilliseconds, workUnit.Execute, Self); finally FPoolsCS.EndRead; end; if pool = nil then begin workUnit.Free; raise Exception.CreateFmt('Unknown Work Queue "%s"', [name]); end; end; procedure TdwsBackgroundWorkersLib.dwsBackgroundWorkersClassesBackgroundWorkersMethodsGetWorkerCountEval( Info: TProgramInfo; ExtObject: TObject); var name : String; pool : TIOCPWorkerThreadPool; n : Integer; begin name := Info.ParamAsString[0]; FPoolsCS.BeginRead; try pool := FPools[name]; if pool <> nil then n := pool.WorkerCount else n := 0; finally FPoolsCS.EndRead; end; Info.ResultAsInteger := n; end; procedure TdwsBackgroundWorkersLib.dwsBackgroundWorkersClassesBackgroundWorkersMethodsSetWorkerCountEval( Info: TProgramInfo; ExtObject: TObject); var name : String; pool : TIOCPWorkerThreadPool; n : Integer; begin name := Info.ParamAsString[0]; n := Info.ParamAsInteger[1]; if n <= 0 then raise Exception.CreateFmt('WorkerCount value must be strictly positive (got %d)', [n]); if n > MaxWorkersPerQueue then raise Exception.CreateFmt('WorkerCount value too high (got %d, must be <= %d)', [n, MaxWorkersPerQueue]); if (n <> 0) and not Assigned(FOnBackgroundWork) then raise Exception.Create('Cannot create workers during shutdown'); FPoolsCS.BeginRead; try pool := FPools[name]; if pool <> nil then pool.WorkerCount := n; finally FPoolsCS.EndRead; end; if pool=nil then raise Exception.CreateFmt('Unknown Work Queue "%s"', [name]); end; procedure TdwsBackgroundWorkersLib.dwsBackgroundWorkersClassesBackgroundWorkersMethodsQueueStatusAsJSONEval( Info: TProgramInfo; ExtObject: TObject); var name : String; pool : TIOCPWorkerThreadPool; wr : TdwsJSONWriter; sizeInfo : TWorkerThreadQueueSizeInfo; begin name := Info.ParamAsString[0]; FPoolsCS.BeginRead; try pool := FPools[name]; finally FPoolsCS.EndRead; end; wr := TdwsJSONWriter.Create; try wr.BeginObject; wr.WriteString('name', name); if pool <> nil then begin wr.BeginObject('workers'); wr.WriteInteger('count', pool.WorkerCount); wr.WriteInteger('live', pool.LiveWorkerCount); wr.WriteInteger('active', pool.ActiveWorkerCount); wr.WriteInteger('peak', pool.PeakActiveWorkerCount); wr.EndObject; wr.BeginObject('queue'); sizeInfo := pool.QueueSizeInfo; wr.WriteInteger('total', sizeInfo.Total); wr.WriteInteger('delayed', sizeInfo.Delayed); wr.WriteInteger('peak', sizeInfo.Peak); wr.EndObject; end; wr.EndObject; Info.ResultAsString := wr.ToString; finally wr.Free; end; if (pool <> nil) and Info.ParamAsBoolean[1] then pool.ResetPeakStats; end; end.
26.028112
115
0.703827
f1b3c3382d7e28019c6fa15fcfa3e273402f5c95
6,236
pas
Pascal
Units/MicroCoin/UConst.pas
BigJoe01/MicroCoin
5176e9e009211a6c0bf2c9879bbd1b08f8bb003d
[ "MIT" ]
1
2021-07-14T20:20:18.000Z
2021-07-14T20:20:18.000Z
Units/MicroCoin/UConst.pas
BigJoe01/MicroCoin
5176e9e009211a6c0bf2c9879bbd1b08f8bb003d
[ "MIT" ]
null
null
null
Units/MicroCoin/UConst.pas
BigJoe01/MicroCoin
5176e9e009211a6c0bf2c9879bbd1b08f8bb003d
[ "MIT" ]
null
null
null
unit UConst; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} { Copyright (c) 2016 by Albert Molina Copyright (c) 2017 by Peter Nemeth Distributed under the MIT software license, see the accompanying file LICENSE or visit http://www.opensource.org/licenses/mit-license.php. This unit is a part of Micro Coin, a P2P crypto currency without need of historical operations. } interface {$I config.inc} {$IFNDEF FPC} type PtrInt = integer; PtrUInt = cardinal; {$ENDIF} Const CT_Genesis_Magic_String_For_Old_Block_Hash : AnsiString = '(c) Peter Nemeth - Okes rendben okes'; CT_Zero_Block_Proof_of_work_in_Hexa = {$IFDEF PRODUCTION}'0000007A35BA642D75EBDA692D25DA09AB8EABE802BC970C01DE08F60DC3F93F'{$ELSE}{$IFDEF TESTNET}''{$ELSE}{$ENDIF}{$ENDIF}; CT_NetServer_Port = {$IFDEF PRODUCTION}4004{$ELSE}{$IFDEF TESTNET}4104{$ELSE}{$ENDIF}{$ENDIF}; CT_JSONRPCMinerServer_Port = {$IFDEF PRODUCTION}4009{$ELSE}{$IFDEF TESTNET}4109{$ELSE}{$ENDIF}{$ENDIF}; CT_JSONRPC_Port = {$IFDEF PRODUCTION}4003{$ELSE}{$IFDEF TESTNET}4103{$ELSE}{$ENDIF}{$ENDIF}; CT_AccountsPerBlock = 5; CT_NewLineSecondsAvg: Cardinal = {$IFDEF PRODUCTION}300{$ELSE}{$IFDEF TESTNET}30{$ELSE}{$ENDIF}{$ENDIF}; // 60*5=300 seconds -> 5 minutes avg // -> 1 day = 86400 seconds -> 1 year = 31536000 seconds (aprox) // Each year = 105120 new blocks (aprox) // -> *5 accounts per block = 525600 new accounts each year (aprox) CT_FirstReward: UInt64 = 1000000; // 4 decimals... First reward = 100,0000 CT_MinReward: UInt64 = 10000; // 4 decimals... Min reward = 1,0000 CT_NewLineRewardDecrease: Cardinal = 420480; // Avg 4 year CT_WaitNewBlocksBeforeTransaction = 10; CT_RecoverFoundsWaitInactiveCount = 420480; // After 4 years... if an account has no operations, money will be a reward for a miner! CT_MaxFutureBlocksLockedAccount = 105120; // Maximum future blocks an account can be locked CT_MaxTransactionAmount = 1000000000000; CT_MaxTransactionFee = 100000000; CT_MaxWalletAmount = 10000000000000; // CT_MinCompactTarget: Cardinal = {$IFDEF PRODUCTION}$19000000{$ELSE}{$IFDEF TESTNET}$19000000{$ELSE}{$ENDIF}{$ENDIF}; // First compact target of block 0 CT_CalcNewTargetBlocksAverage: Cardinal = 100; CT_CalcNewTargetLimitChange_SPLIT = 10; CT_MaxAccount : Cardinal = $FFFFFFFF; CT_MaxBlock : Cardinal = $FFFFFFFF; CT_MaxPayloadSize = 255; // Max payload size in bytes CT_MaxFutureBlockTimestampOffset = 15; CT_MinNodesToCalcNAT = 4; CT_MinServersConnected = 3; CT_MaxServersConnected = 5; CT_MaxClientsConnected = 100; CT_BankToDiskEveryNBlocks = {$IFDEF PRODUCTION}100{$ELSE}10{$ENDIF}; CT_NID_secp256k1 = 714; CT_NID_secp384r1 = 715; CT_NID_sect283k1 = 729; CT_NID_secp521r1 = 716; CT_Default_EC_OpenSSL_NID = CT_NID_secp256k1; CT_AccountInfo_ForSale = 1000; CT_PROTOCOL_1 = 1; CT_PROTOCOL_2 = 2; CT_BlockChain_Protocol_Available: Word = $0002; // Protocol 2 flag CT_Protocol_Upgrade_v2_MinBlock = {$IFDEF PRODUCTION}100{$ELSE}600{$ENDIF}; CT_MagicNetIdentification = {$IFDEF PRODUCTION}$0A043580{$ELSE}$0A04FFFF{$ENDIF}; CT_NetProtocol_Version: Word = $0006; // IMPORTANT NOTE!!! // NetProtocol_Available MUST BE always >= NetProtocol_version CT_NetProtocol_Available: Word = $0006; // Remember, >= NetProtocol_version !!! CT_MaxAccountOperationsPerBlockWithoutFee = 1; CT_SafeBoxBankVersion : Word = 3; // Protocol 2 upgraded safebox version from 2 to 3 CT_MagicIdentificator: AnsiString = {$IFDEF PRODUCTION}'MicroCoin'{$ELSE}'MicroCoinTESTNET'{$ENDIF}; // // Value of Operations type in Protocol 1 CT_Op_Transaction = $01; CT_Op_Changekey = $02; CT_Op_Recover = $03; // Protocol 2 new operations CT_Op_ListAccountForSale = $04; CT_Op_DelistAccount = $05; CT_Op_BuyAccount = $06; CT_Op_ChangeKeySigned = $07; CT_Op_ChangeAccountInfo = $08; CT_OpSubtype_TransactionSender = 11; CT_OpSubtype_TransactionReceiver = 12; CT_OpSubtype_BuyTransactionBuyer = 13; CT_OpSubtype_BuyTransactionTarget = 14; CT_OpSubtype_BuyTransactionSeller = 15; CT_OpSubtype_ChangeKey = 21; CT_OpSubtype_Recover = 31; CT_OpSubtype_ListAccountForPublicSale = 41; CT_OpSubtype_ListAccountForPrivateSale = 42; CT_OpSubtype_DelistAccount = 51; CT_OpSubtype_BuyAccountBuyer = 61; CT_OpSubtype_BuyAccountTarget = 62; CT_OpSubtype_BuyAccountSeller = 63; CT_OpSubtype_ChangeKeySigned = 71; CT_OpSubtype_ChangeAccountInfo = 81; CT_ClientAppVersion : AnsiString = {$IFDEF PRODUCTION}'1.0.1'{$ELSE}{$IFDEF TESTNET}'TESTNET 1.0.0'{$ELSE}{$ENDIF}{$ENDIF}; CT_Discover_IPs = '185.28.101.93;80.211.211.48;94.177.237.196'; CT_TRUE_FALSE : Array[Boolean] Of AnsiString = ('FALSE','TRUE'); CT_MAX_0_fee_operations_per_block_by_miner = {$IFDEF PRODUCTION}2000{$ELSE}{$IFDEF TESTNET}2{$ELSE}{$ENDIF}{$ENDIF}; CT_MAX_Operations_per_block_by_miner = {$IFDEF PRODUCTION}10000{$ELSE}{$IFDEF TESTNET}50{$ELSE}{$ENDIF}{$ENDIF}; // App Params CT_PARAM_GridAccountsStream = 'GridAccountsStreamV2'; CT_PARAM_GridAccountsPos = 'GridAccountsPos'; CT_PARAM_DefaultFee = 'DefaultFee'; CT_PARAM_InternetServerPort = 'InternetServerPort'; {$IFDEF TESTNET}CT_PARAM_AutomaticMineWhenConnectedToNodes = 'AutomaticMineWhenConnectedToNodes';{$ENDIF} CT_PARAM_MinerPrivateKeyType = 'MinerPrivateKeyType'; CT_PARAM_MinerPrivateKeySelectedPublicKey = 'MinerPrivateKeySelectedPublicKey'; CT_PARAM_SaveLogFiles = 'SaveLogFiles'; CT_PARAM_SaveDebugLogs = 'SaveDebugLogs'; CT_PARAM_ShowLogs = 'ShowLogs'; CT_PARAM_MinerName = 'MinerName'; CT_PARAM_FirstTime = 'FirstTime'; CT_PARAM_ShowModalMessages = 'ShowModalMessages'; {$IFDEF TESTNET}CT_PARAM_MaxCPUs = 'MaxCPUs'; {$ENDIF} CT_PARAM_PeerCache = 'PeerCache'; CT_PARAM_TryToConnectOnlyWithThisFixedServers = 'TryToConnectOnlyWithFixedServers'; CT_PARAM_JSONRPCMinerServerPort = 'JSONRPCMinerServerPort'; CT_PARAM_JSONRPCMinerServerActive = 'JSONRPCMinerServerActive'; CT_PARAM_JSONRPCEnabled = 'JSONRPCEnabled'; CT_PARAM_JSONRPCAllowedIPs = 'JSONRPCAllowedIPs'; implementation end.
37.119048
153
0.740378
4740567105e09a80b8b228efbfd5b01d25c0b86e
4,695
pas
Pascal
properities.pas
embedix/stag-pcapp
3fed400fb80cce0f5d766d4edd7931b6f7191621
[ "MIT" ]
null
null
null
properities.pas
embedix/stag-pcapp
3fed400fb80cce0f5d766d4edd7931b6f7191621
[ "MIT" ]
null
null
null
properities.pas
embedix/stag-pcapp
3fed400fb80cce0f5d766d4edd7931b6f7191621
[ "MIT" ]
null
null
null
unit properities; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, inifiles, ExtCtrls, Spin, bsPolyglotUn; type TfrmProperities = class(TForm) btnOK: TButton; lbTyp: TListBox; Label1: TLabel; ColorBox: TColorBox; Label2: TLabel; cbTucne: TCheckBox; btnSave: TButton; cbZDoTucne: TCheckBox; seCasVz: TSpinEdit; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; bsPolyglotTranslator: TbsPolyglotTranslator; Bevel1: TBevel; Label10: TLabel; cbCreateBackups: TCheckBox; cbSaveToGVD: TCheckBox; Bevel2: TBevel; Label11: TLabel; cbNiceMenu: TCheckBox; cbBuzerace: TCheckBox; procedure FormCreate(Sender: TObject); procedure lbTypDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure lbTypClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure cbZDoTucneClick(Sender: TObject); procedure seCasVzChange(Sender: TObject); procedure cbCreateBackupsClick(Sender: TObject); procedure cbSaveToGVDClick(Sender: TObject); procedure cbNiceMenuClick(Sender: TObject); procedure cbBuzeraceClick(Sender: TObject); private { Private declarations } public { Public declarations } ini:TMemIniFile; constructor CreateWINI(owner:TComponent;StagINI:TMemIniFile); end; var frmProperities: TfrmProperities; implementation uses main; {$R *.dfm} constructor TfrmProperities.CreateWINI; begin ini:=StagINI; inherited Create(owner); end; procedure TfrmProperities.FormCreate(Sender: TObject); begin bsPolyglotTranslator.Translate; lbTyp.Clear; ini.readsection('Typ_vlaku',lbTyp.Items); cbZDoTucne.Checked:=ini.ReadBool('STAG','Z_Do_tucne',false); seCasVz.Value:=ini.ReadInteger('STAG','AutoCasVz',20); cbCreateBackups.Checked:=ini.ReadBool('STAG','CreateBackups',false); cbNiceMenu.Checked:=ini.ReadBool('STAG','NiceMenu',true); cbSaveToGVD.Checked:=ini.ReadBool('STAG','WriteOldFormatGVD',false); cbBuzerace.Checked:= ini.ReadBool('STAG','BuzeracniDialog',true); end; procedure TfrmProperities.lbTypDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); begin with control as TListBox do begin canvas.font.size:=8; Canvas.font.Color:=INI.ReadInteger('Barvy_vlaku',Items[index],0); Canvas.Pen.Style:=pssolid; Canvas.Pen.color:=clWhite; if odSelected in state then begin Canvas.font.Color:=clWhite; Canvas.Brush.Color:=clActiveCaption; end else begin Canvas.Brush.Color:=clWhite; end; Canvas.Rectangle(rect); if ini.ReadBool('Tucne_vlaky',Items[index],false) then Canvas.font.Style:=[fsBold] else Canvas.font.Style:=[]; Canvas.Textout(rect.Left+5,rect.Top+1,Items[index]); Canvas.font.Style:=[]; Canvas.font.color:=clGray; canvas.font.size:=7; Canvas.TextOut(rect.Left+45,rect.Top+2, INI.ReadString('Typ_vlaku',Items[index],'')); end; end; procedure TfrmProperities.lbTypClick(Sender: TObject); var typ:string; begin if lbTyp.ItemIndex<0 then exit; typ:=trim(lbTyp.Items[lbTyp.ItemIndex]); ColorBox.Selected:=clBlack; {nutny workaround jinak se neupdatuje} ColorBox.Selected:=ini.ReadInteger('Barvy_vlaku',typ,clBlack); cbTucne.Checked:=ini.ReadBool('Tucne_vlaky',typ,false); end; procedure TfrmProperities.btnSaveClick(Sender: TObject); var typ:string; begin if lbTyp.ItemIndex<0 then exit; typ:=trim(lbTyp.Items[lbTyp.ItemIndex]); ini.WriteBool('Tucne_vlaky',typ,cbTucne.Checked); ini.WriteInteger('Barvy_vlaku',typ,ColorBox.Selected); lbTyp.Repaint; end; procedure TfrmProperities.cbZDoTucneClick(Sender: TObject); begin ini.WriteBool('STAG','Z_Do_tucne',cbZDoTucne.Checked); end; procedure TfrmProperities.seCasVzChange(Sender: TObject); begin ini.WriteInteger('STAG','AutoCasVz',seCasVz.Value); end; procedure TfrmProperities.cbCreateBackupsClick(Sender: TObject); begin ini.WriteBool('STAG','CreateBackups',cbCreateBackups.Checked); end; procedure TfrmProperities.cbSaveToGVDClick(Sender: TObject); begin ini.WriteBool('STAG','WriteOldFormatGVD',cbSaveToGVD.Checked); end; procedure TfrmProperities.cbNiceMenuClick(Sender: TObject); begin ini.WriteBool('STAG','NiceMenu',cbNiceMenu.Checked); frmMain.XPMenu.Active:=cbNiceMenu.Checked; end; procedure TfrmProperities.cbBuzeraceClick(Sender: TObject); begin ini.WriteBool('STAG','BuzeracniDialog',cbBuzerace.Checked); end; end.
29.161491
77
0.728222
6af799375529d4ce388abe8c855e1296980b8d99
20,883
pas
Pascal
Source/CodeCoverage.Handler.pas
interestingitems/DelphiCodeCoveragePlugin
2bb32123ae1ea575f072d452d71fe68661a2b0c4
[ "MIT" ]
5
2021-10-21T04:30:29.000Z
2022-01-20T20:37:53.000Z
Source/CodeCoverage.Handler.pas
interestingitems/DelphiCodeCoveragePlugin
2bb32123ae1ea575f072d452d71fe68661a2b0c4
[ "MIT" ]
3
2021-10-21T09:20:10.000Z
2021-11-09T13:14:35.000Z
Source/CodeCoverage.Handler.pas
interestingitems/DelphiCodeCoveragePlugin
2bb32123ae1ea575f072d452d71fe68661a2b0c4
[ "MIT" ]
1
2021-10-21T04:32:39.000Z
2021-10-21T04:32:39.000Z
unit CodeCoverage.Handler; interface uses ToolsAPI, System.Classes, Vcl.Menus, Vcl.Graphics, Vcl.ImgList, CodeCoverage.ApiHelper, CodeCoverage.Types, CodeCoverage.SyntaxTypes, CodeCoverage.Notifier; type {$SCOPEDENUMS ON} TCoverState = (noncoverable, coverable, covered); {$SCOPEDENUMS OFF} type TCodeCoverage = class(TNotifierHost, ICodeCoverage) private const cBreakpointGroupName = 'CodeCoverage'; private FActive: Boolean; FCodeSyntaxTrees: TCodeSyntaxTrees; FCoveredLines: TCoveredLines; FCoveredMethods: TCoveredMethods; FCurFileName: string; FCurLineMax: Integer; FCurLineMin: Integer; FCurProcess: IOTAProcess; FCurrentMethodState: TCoverState; FFullRepaint: TStringList; FImageIndexCodeCoverage: Integer; FImageIndexNoCoverage: Integer; FImageList: TCustomImageList; FRunMenuItem: TMenuItem; FValid: Boolean; function AddBreakpoint(ALineNumber: Integer): IOTABreakpoint; procedure AddCoverage(const AFileName: string; ALineNumber, ACount: Integer); function AddLineTracker(const EditBuffer: IOTAEditBuffer; ALineNumber: Integer): Integer; procedure CalcCoverage(const AFileName: string; const Data: TCoveredMethod); procedure CheckCodeCoverage; function CheckFullRepaint(const EditView: IOTAEditView): Boolean; procedure ClearAllCodeCoverage; procedure CoverMethod(const AFileName: string; const Data: TCoveredMethod); function CreateEditLineNotifier(const Tracker: IOTAEditLineTracker): Integer; procedure CreateEditorNotifier(const Editor: IOTASourceEditor); procedure CreateEditViewNotifier(const View: IOTAEditView); procedure CreateModuleNotifier(const Module: IOTAModule); function CreateSyntaxTree(const Editor: IOTASourceEditor): TCodeSyntaxTree; procedure DrawImage(ACanvas: TCanvas; X, Y, Index: Integer); procedure EnableCodeCoverage(const AProcess: IOTAProcess); function FindCoveredLinesList(const EditView: IOTAEditView): TCoveredLinesList; function FindCoveredMethodList(const EditView: IOTAEditView): TCoveredMethodList; function FindEditLineNotifier(const Tracker: IOTAEditLineTracker): TEditLineNotifier; function FindMethod(const EditBuffer: IOTAEditBuffer; Line: Integer; out Data: TCoveredMethod): Boolean; function FindSourceEditor(const AFileName: string): IOTASourceEditor; function FindSyntaxTree(const AFileName: string): TCodeSyntaxTree; overload; function FindSyntaxTree(const Editor: IOTASourceEditor): TCodeSyntaxTree; overload; function GetHasCodeCoverage: Boolean; function GetImageIndexCodeCoverage: Integer; function GetImageIndexNoCoverage: Integer; function GetValid: Boolean; function HandleSourceLine(ALineNumber: Integer): Boolean; function HasNotifier<T>(const Target: T): Boolean; overload; procedure MarkFullRepaint(const AFileName: string); procedure MarkModified(const EditView: IOTAEditView); function MethodIdByLineNumber(const EditBuffer: IOTAEditBuffer; Line: Integer; out AID: TMethodID): Boolean; procedure ModuleRenamed(const OldName: string; const NewName: string); procedure RemoveEditLineNotifier(const Tracker: IOTAEditLineTracker); procedure RemoveEditor(const Editor: IOTASourceEditor); procedure RemoveLineTracker(const EditBuffer: IOTAEditBuffer); overload; procedure RemoveLineTracker(const EditBuffer: IOTAEditBuffer; ALineNumber, AID: Integer); overload; procedure RetrieveResults; function SelectCurrentMethod(const EditBuffer: IOTAEditBuffer; out AFileName, AMethodName: string; out LineMin, LineMax: Integer): Boolean; overload; function SelectMethod(const AFileName: string; const AMethod: TCoveredMethod; out LineMin, LineMax: Integer): Boolean; procedure TrackedLineChanged(const Tracker: IOTAEditLineTracker; OldLine, NewLine, Data: Integer); procedure UpdateCurrentMethodState; protected property Active: Boolean read FActive write FActive; property CodeSyntaxTrees: TCodeSyntaxTrees read FCodeSyntaxTrees; property CoveredLines: TCoveredLines read FCoveredLines; property CoveredMethods: TCoveredMethods read FCoveredMethods; property CurFileName: string read FCurFileName write FCurFileName; property CurLineMax: Integer read FCurLineMax write FCurLineMax; property CurLineMin: Integer read FCurLineMin write FCurLineMin; property CurProcess: IOTAProcess read FCurProcess write FCurProcess; property FullRepaint: TStringList read FFullRepaint; property Valid: Boolean read GetValid write FValid; public constructor Create; destructor Destroy; override; procedure Execute; procedure Initialize; function IsAvailable: Boolean; function SwitchCodeCoverage: Boolean; property CurrentMethodState: TCoverState read FCurrentMethodState; property HasCodeCoverage: Boolean read GetHasCodeCoverage; property ImageIndexCodeCoverage: Integer read GetImageIndexCodeCoverage write FImageIndexCodeCoverage; property ImageIndexNoCoverage: Integer read GetImageIndexNoCoverage write FImageIndexNoCoverage; property ImageList: TCustomImageList read FImageList write FImageList; property RunMenuItem: TMenuItem read FRunMenuItem write FRunMenuItem; end; implementation uses System.Math, System.StrUtils, System.Types, System.SysUtils, Vcl.Dialogs; function GetSourceLines(LineNum: Integer; ClientArg: Pointer): Integer pascal; begin Result := 0; if TCodeCoverage(ClientArg).HandleSourceLine(LineNum) then begin Result := 1; end; end; constructor TCodeCoverage.Create; begin inherited Create; FCoveredLines := TCoveredLines.Create(); FCoveredMethods := TCoveredMethods.Create(); FCodeSyntaxTrees := TCodeSyntaxTrees.Create(); FFullRepaint := TStringList.Create(dupIgnore, true, false); TDebuggerNotifier.Create(Self); TEditServicesNotifier.Create(Self); CreateEditViewNotifier(OTA.EditorServices.TopView); end; destructor TCodeCoverage.Destroy; begin FFullRepaint.Free; FCodeSyntaxTrees.Free; FCoveredMethods.Free; FCoveredLines.Free; inherited; end; procedure TCodeCoverage.DrawImage(ACanvas: TCanvas; X, Y, Index: Integer); begin ImageList.Draw(ACanvas, X, Y, Index); end; function TCodeCoverage.AddBreakpoint(ALineNumber: Integer): IOTABreakpoint; begin Result := OTA.DebuggerServices.NewSourceBreakpoint(CurFileName, ALineNumber, CurProcess); if Result <> nil then begin Result.DoBreak := false; Result.GroupName := cBreakpointGroupName; if ALineNumber = CurLineMin then begin Result.DoIgnoreExceptions := True; end else if ALineNumber = CurLineMax then begin Result.DoHandleExceptions := True; end else begin Result.PassCount := MaxInt; CoveredLines.Initialize(CurFileName, ALineNumber, 0); end; end; end; procedure TCodeCoverage.AddCoverage(const AFileName: string; ALineNumber, ACount: Integer); begin CoveredLines.Add(AFileName, ALineNumber, ACount); end; function TCodeCoverage.AddLineTracker(const EditBuffer: IOTAEditBuffer; ALineNumber: Integer): Integer; var Tracker: IOTAEditLineTracker; begin Tracker := EditBuffer.GetEditLineTracker; Result := CreateEditLineNotifier(Tracker); Tracker.AddLine(ALineNumber, Result); end; procedure TCodeCoverage.CalcCoverage(const AFileName: string; const Data: TCoveredMethod); var Count: Integer; covered: Integer; I: Integer; percent: Integer; total: Integer; begin total := 0; covered := 0; for I := Data.LineMin to Data.LineMax do begin Count := CoveredLines.Find(AFileName, I); if Count >= 0 then begin Inc(total); if Count > 0 then begin Inc(covered); end; end; end; if total = covered then begin percent := 100; end else if covered = 0 then begin percent := 0; end else begin percent := EnsureRange(Round(100*covered/total), 1, 99); end; CoveredMethods.UpdatePercent(AFileName, Data.ID, percent); end; procedure TCodeCoverage.CheckCodeCoverage; var bp: IOTABreakpoint; I: Integer; begin for I := 0 to OTA.DebuggerServices.SourceBkptCount - 1 do begin bp := OTA.DebuggerServices.SourceBkpts[I]; if MatchStr(bp.GroupName, [cBreakpointGroupName]) then begin if not (bp.DoHandleExceptions or bp.DoIgnoreExceptions) then begin AddCoverage(bp.FileName, bp.LineNumber, bp.CurPassCount); end; end; end; CoveredMethods.Iterate(CalcCoverage); Valid := true; end; function TCodeCoverage.CheckFullRepaint(const EditView: IOTAEditView): Boolean; var idx: Integer; begin Result := FullRepaint.Find(EditView.Buffer.FileName, idx); if Result then begin FullRepaint.Delete(idx); end; end; procedure TCodeCoverage.ClearAllCodeCoverage; var bp: IOTABreakpoint; I: Integer; begin for I := OTA.DebuggerServices.SourceBkptCount - 1 downto 0 do begin bp := OTA.DebuggerServices.SourceBkpts[I]; if bp.GroupName = cBreakpointGroupName then begin OTA.DebuggerServices.RemoveBreakpoint(bp); end; end; FCurProcess := nil; end; procedure TCodeCoverage.CoverMethod(const AFileName: string; const Data: TCoveredMethod); var I: Integer; begin if CurProcess.SourceIsDebuggable[AFileName] then begin if SelectMethod(AFileName, Data, FCurLineMin, FCurLineMax) then begin CoveredMethods.Update(AFileName, Data.ID, FCurLineMin + 1, FCurLineMax - 1); FCurFileName := AFileName; for I := FCurLineMin + 1 to FCurLineMax - 1 do begin CoveredLines.Initialize(FCurFileName, I, -1); end; CurProcess.GetSourceLines(FCurFileName, FCurLineMin, GetSourceLines, Self); end; end; end; function TCodeCoverage.CreateEditLineNotifier(const Tracker: IOTAEditLineTracker): Integer; var instance: TEditLineNotifier; begin if Tracker = nil then Exit(-1); { check if Tracker already has a notifier } instance := FindEditLineNotifier(Tracker); if instance = nil then begin instance := TEditLineNotifier.Create(Self, Tracker); end; Result := instance.NextID; end; procedure TCodeCoverage.CreateEditorNotifier(const Editor: IOTASourceEditor); begin if not HasNotifier(Editor) then begin TEditorNotifier.Create(Self, Editor); end; end; procedure TCodeCoverage.CreateEditViewNotifier(const View: IOTAEditView); begin if not HasNotifier(View) then begin TEditViewNotifier.Create(Self, View); end; end; procedure TCodeCoverage.CreateModuleNotifier(const Module: IOTAModule); begin if not HasNotifier(Module) then begin TModuleNotifier.Create(Self, Module); end; end; function TCodeCoverage.CreateSyntaxTree(const Editor: IOTASourceEditor): TCodeSyntaxTree; begin Result := CodeSyntaxTrees.Add(Editor); if Result <> nil then begin CreateEditorNotifier(Editor); CreateModuleNotifier(Editor.Module); end; end; procedure TCodeCoverage.EnableCodeCoverage(const AProcess: IOTAProcess); begin if not Active then Exit; CoveredLines.Clear; Valid := false; FCurProcess := AProcess; CoveredMethods.Iterate(CoverMethod); Active := not CoveredLines.IsEmpty; end; procedure TCodeCoverage.Execute; var builder: IOTAProjectBuilder; project: IOTAProject; begin project := OTA.ModuleServices.GetActiveProject; if project = nil then begin ShowMessage('No active project!'); Exit; end; ClearAllCodeCoverage; builder := project.ProjectBuilder; if builder = nil then begin ShowMessage('Active project has no project buidler!'); Exit; end; if builder.BuildProject(cmOTABuild, false, true) then begin // OTADebuggerServices.CreateProcess(project.ProjectOptions.TargetName, ''); if (RunMenuItem <> nil) and RunMenuItem.Enabled then begin Active := true; try RunMenuItem.Click; except Active := false; end; end; end; end; function TCodeCoverage.FindCoveredLinesList(const EditView: IOTAEditView): TCoveredLinesList; begin Result := CoveredLines.Find(EditView.Buffer.FileName); end; function TCodeCoverage.FindCoveredMethodList(const EditView: IOTAEditView): TCoveredMethodList; begin Result := CoveredMethods.Find(EditView.Buffer.FileName); end; function TCodeCoverage.FindEditLineNotifier(const Tracker: IOTAEditLineTracker): TEditLineNotifier; var instance: TEditLineNotifier; begin Result := nil; if Tracker = nil then Exit; if FindNotifier<TEditLineNotifier>( function(Arg: TEditLineNotifier): Boolean begin Result := Arg.HandlesTarget(Tracker); end, instance) then begin Result := instance; end; end; function TCodeCoverage.FindMethod(const EditBuffer: IOTAEditBuffer; Line: Integer; out Data: TCoveredMethod): Boolean; var curID: TMethodID; begin Result := MethodIdByLineNumber(EditBuffer, Line, curID) and CoveredMethods.Find(EditBuffer.FileName, curID, Data); end; function TCodeCoverage.FindSourceEditor(const AFileName: string): IOTASourceEditor; var Editor: IOTAEditor; I: Integer; module: IOTAModule; sourceEditor: IOTASourceEditor; begin Result := nil; module := OTA.ModuleServices.FindModule(AFileName); for I := 0 to module.ModuleFileCount - 1 do begin Editor := module.ModuleFileEditors[I]; if Supports(Editor, IOTASourceEditor, sourceEditor) then begin Exit(sourceEditor); end; end; end; function TCodeCoverage.FindSyntaxTree(const AFileName: string): TCodeSyntaxTree; begin if AFileName = '' then Exit(nil); if not CodeSyntaxTrees.Find(AFileName, Result) then begin Result := CreateSyntaxTree(FindSourceEditor(AFileName)); end; end; function TCodeCoverage.FindSyntaxTree(const Editor: IOTASourceEditor): TCodeSyntaxTree; begin if Editor = nil then Exit(nil); if not CodeSyntaxTrees.Find(Editor.FileName, Result) then begin Result := CreateSyntaxTree(Editor); end; end; function TCodeCoverage.GetHasCodeCoverage: Boolean; begin Result := IsAvailable and not CoveredMethods.IsEmpty; end; function TCodeCoverage.GetImageIndexCodeCoverage: Integer; begin Result := FImageIndexCodeCoverage; end; function TCodeCoverage.GetImageIndexNoCoverage: Integer; begin Result := FImageIndexNoCoverage; end; function TCodeCoverage.GetValid: Boolean; begin Result := FValid; end; function TCodeCoverage.HandleSourceLine(ALineNumber: Integer): Boolean; begin Result := false; if ALineNumber <= CurLineMax then begin AddBreakpoint(ALineNumber); Result := true; end; end; function TCodeCoverage.HasNotifier<T>(const Target: T): Boolean; begin Result := FindNotifier<TCodeCoverageNotifier<T>>( function(Arg: TCodeCoverageNotifier<T>): Boolean begin Result := Arg.HandlesTarget(Target); end); end; procedure TCodeCoverage.Initialize; var Editor: IOTAEditor; I: Integer; J: Integer; K: Integer; module: IOTAModule; moduleServices: IOTAModuleServices; sourceEditor: IOTASourceEditor; view: IOTAEditView; begin moduleServices := OTA.ModuleServices; for I := 0 to moduleServices.ModuleCount - 1 do begin module := moduleServices.Modules[I]; for J := 0 to module.ModuleFileCount - 1 do begin Editor := module.ModuleFileEditors[J]; if Supports(Editor, IOTASourceEditor, sourceEditor) then begin for K := 0 to sourceEditor.EditViewCount - 1 do begin view := sourceEditor.EditViews[K]; CreateEditViewNotifier(view); end; end; end; end; UpdateCurrentMethodState; end; function TCodeCoverage.IsAvailable: Boolean; var project: IOTAProject; begin Result := False; project := OTA.ModuleServices.GetActiveProject; if project = nil then Exit; if not MatchText(project.ApplicationType, [sApplication, sConsole]) then Exit; Result := true; end; procedure TCodeCoverage.MarkFullRepaint(const AFileName: string); begin FullRepaint.Add(AFileName); end; procedure TCodeCoverage.MarkModified(const EditView: IOTAEditView); begin CodeSyntaxTrees.Remove(EditView.Buffer.FileName); end; function TCodeCoverage.MethodIdByLineNumber(const EditBuffer: IOTAEditBuffer; Line: Integer; out AID: TMethodID): Boolean; var idx: Integer; Tracker: IOTAEditLineTracker; begin Result := false; if EditBuffer = nil then Exit; Tracker := EditBuffer.GetEditLineTracker; if Tracker = nil then Exit; idx := Tracker.IndexOfLine(Line); if idx < 0 then Exit; AID := Tracker.Data[idx]; Result := true; end; procedure TCodeCoverage.ModuleRenamed(const OldName, NewName: string); var idx: Integer; begin CoveredMethods.RenameFile(OldName, NewName); CoveredLines.RenameFile(OldName, NewName); CodeSyntaxTrees.RenameFile(OldName, NewName); if FullRepaint.Find(OldName, idx) then begin FullRepaint.Delete(idx); FullRepaint.Add(NewName); end; end; procedure TCodeCoverage.RemoveEditLineNotifier(const Tracker: IOTAEditLineTracker); var instance: TEditLineNotifier; begin instance := FindEditLineNotifier(Tracker); if instance <> nil then begin instance.Release; end; end; procedure TCodeCoverage.RemoveEditor(const Editor: IOTASourceEditor); var EditBuffer: IOTAEditBuffer; begin if Supports(Editor, IOTAEditBuffer, EditBuffer) then begin RemoveLineTracker(EditBuffer); end; CoveredLines.Remove(Editor.FileName); CoveredMethods.Remove(Editor.FileName); CodeSyntaxTrees.Remove(Editor.FileName); end; procedure TCodeCoverage.RemoveLineTracker(const EditBuffer: IOTAEditBuffer); var Tracker: IOTAEditLineTracker; begin Tracker := EditBuffer.GetEditLineTracker; RemoveEditLineNotifier(Tracker); end; procedure TCodeCoverage.RemoveLineTracker(const EditBuffer: IOTAEditBuffer; ALineNumber, AID: Integer); var idx: Integer; Tracker: IOTAEditLineTracker; begin Tracker := EditBuffer.GetEditLineTracker; idx := Tracker.IndexOfData(AID); if idx < 0 then begin idx := Tracker.IndexOfLine(ALineNumber); end; if idx >= 0 then begin Tracker.Delete(idx); end; end; procedure TCodeCoverage.RetrieveResults; begin if not Active then Exit; CheckCodeCoverage; ClearAllCodeCoverage; Active := false; end; function TCodeCoverage.SelectCurrentMethod(const EditBuffer: IOTAEditBuffer; out AFileName, AMethodName: string; out LineMin, LineMax: Integer): Boolean; var code: TCodeSyntaxTree; begin Result := false; code := FindSyntaxTree(EditBuffer); if code <> nil then begin AFileName := code.FileName; Result := code.FindCurrentMethod(EditBuffer.TopView, AMethodName, LineMin, LineMax); end; end; function TCodeCoverage.SelectMethod(const AFileName: string; const AMethod: TCoveredMethod; out LineMin, LineMax: Integer): Boolean; var code: TCodeSyntaxTree; begin Result := false; code := FindSyntaxTree(AFileName); if code <> nil then begin Result := code.SelectMethod(AMethod, LineMin, LineMax); end; end; function TCodeCoverage.SwitchCodeCoverage: Boolean; var curLine: TLineNumber; curMethod: string; Data: TCoveredMethod; EditBuffer: IOTAEditBuffer; FileName: string; ID: Integer; LineMax: Integer; LineMin: Integer; begin EditBuffer := OTA.EditorServices.TopBuffer; Result := SelectCurrentMethod(EditBuffer, FileName, curMethod, LineMin, LineMax); if Result then begin if FindMethod(EditBuffer, LineMin, Data) then begin CoveredMethods.Remove(FileName, Data.ID); CoveredLines.Remove(FileName, LineMin, LineMax); RemoveLineTracker(EditBuffer, Data.Line, Data.ID); FCurrentMethodState := TCoverState.coverable; end else begin curLine := LineMin; ID := AddLineTracker(EditBuffer, LineMin); CoveredMethods.Add(FileName, TCoveredMethod.Create(curMethod, curLine, ID)); FCurrentMethodState := TCoverState.covered; end; MarkFullRepaint(FileName); EditBuffer.TopView.Paint; end else begin ShowMessage('No method body found at cursor!'); FCurrentMethodState := TCoverState.noncoverable; end; end; procedure TCodeCoverage.TrackedLineChanged(const Tracker: IOTAEditLineTracker; OldLine, NewLine, Data: Integer); var FileName: string; ID: TMethodID; newLineNumber: TLineNumber; begin Valid := false; FileName := Tracker.GetEditBuffer.FileName; CoveredLines.Remove(FileName); ID := Data; newLineNumber := NewLine; CoveredMethods.ChangeLineNumber(FileName, ID, newLineNumber); end; procedure TCodeCoverage.UpdateCurrentMethodState; var curMethod: string; Data: TCoveredMethod; EditBuffer: IOTAEditBuffer; FileName: string; LineMax: Integer; LineMin: Integer; state: TCoverState; begin state := TCoverState.noncoverable; EditBuffer := OTA.EditorServices.TopBuffer; if SelectCurrentMethod(EditBuffer, FileName, curMethod, LineMin, LineMax) then begin state := TCoverState.coverable; if FindMethod(EditBuffer, LineMin, Data) then begin state := TCoverState.covered; end; end; FCurrentMethodState := state; end; end.
29.247899
118
0.757171
85d39e39228c6889981e7023bca1ee34be9b2146
348
lpr
Pascal
examples/lazarus/deprecated/example2-param/example2.lpr
DrPeaboss/vst24pas
0e3761c5add4c24600cf44ec4ec111e2a742148c
[ "MIT" ]
1
2022-02-22T17:20:19.000Z
2022-02-22T17:20:19.000Z
examples/lazarus/deprecated/example2-param/example2.lpr
DrPeaboss/vst24pas
0e3761c5add4c24600cf44ec4ec111e2a742148c
[ "MIT" ]
null
null
null
examples/lazarus/deprecated/example2-param/example2.lpr
DrPeaboss/vst24pas
0e3761c5add4c24600cf44ec4ec111e2a742148c
[ "MIT" ]
null
null
null
library example2; {$mode objfpc}{$H+} uses vst24pas.core, vst24pas.utils, umain; function VSTPluginMain(VstHost: TVSTHostCallback): PAEffect; cdecl; export; begin Result := DoVSTPluginMain(TMyPlugin, VstHost, 0, 1); end; exports VSTPluginMain Name 'VSTPluginMain', VSTPluginMain Name 'main'; begin end.
16.571429
78
0.678161
8381264fd8f993d5839b3e43c3bff718be588b94
193
pas
Pascal
samples/fpc/QuickConfig/ConfigToFileAndRegistry/QuickConfig.pas
egroups/QuickLib
03561de6268be1a0d3e60478d10bf09465b8fa5a
[ "Apache-2.0" ]
1
2019-02-24T06:34:40.000Z
2019-02-24T06:34:40.000Z
samples/fpc/QuickConfig/ConfigToFileAndRegistry/QuickConfig.pas
egroups/QuickLib
03561de6268be1a0d3e60478d10bf09465b8fa5a
[ "Apache-2.0" ]
null
null
null
samples/fpc/QuickConfig/ConfigToFileAndRegistry/QuickConfig.pas
egroups/QuickLib
03561de6268be1a0d3e60478d10bf09465b8fa5a
[ "Apache-2.0" ]
null
null
null
program QuickConfig; uses Forms, Interfaces, uMain in 'uMain.pas' {MainForm}; {$R *.res} begin Application.Initialize; Application.CreateForm(TForm1, Form1); Application.Run; end.
13.785714
40
0.720207
47cc4434b2850aab1eb95131c14c7a3573b137fe
10,688
pas
Pascal
components/jcl/source/prototypes/JclVectors.pas
padcom/delcos
dc9e8ac8545c0e6c0b4e963d5baf0dc7d72d2bf0
[ "Apache-2.0" ]
15
2016-08-24T07:32:49.000Z
2021-11-16T11:25:00.000Z
components/jcl/source/prototypes/JclVectors.pas
CWBudde/delcos
656384c43c2980990ea691e4e52752d718fb0277
[ "Apache-2.0" ]
1
2016-08-24T19:00:34.000Z
2016-08-25T19:02:14.000Z
components/jcl/source/prototypes/JclVectors.pas
CWBudde/delcos
656384c43c2980990ea691e4e52752d718fb0277
[ "Apache-2.0" ]
4
2016-10-16T17:52:49.000Z
2020-11-24T11:36:05.000Z
{**************************************************************************************************} { } { 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 Vector.pas. } { } { The Initial Developer of the Original Code is Jean-Philippe BEMPEL aka RDM. Portions created by } { Jean-Philippe BEMPEL are Copyright (C) Jean-Philippe BEMPEL (rdm_30 att yahoo dott com) } { All rights reserved. } { } { Contributors: } { Daniele Teti (dade2004) } { Robert Marquardt (marquardt) } { Robert Rossmair (rrossmair) } { Florent Ouchet (outchy) } { } {**************************************************************************************************} { } { The Delphi Container Library } { } {**************************************************************************************************} { } { Last modified: $Date:: 2010-08-10 18:13:22 +0200 (mar., 10 août 2010) $ } { Revision: $Rev:: 3296 $ } { Author: $Author:: outchy $ } { } {**************************************************************************************************} unit JclVectors; {$I jcl.inc} interface uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} JclAlgorithms, Classes, JclBase, JclAbstractContainers, JclContainerIntf, JclSynch; {$I containers\JclContainerCommon.imp} {$I containers\JclVectors.imp} {$I containers\JclVectors.int} type TItrStart = (isFirst, isLast); (*$JPPLOOP ALLTYPEINDEX ALLTYPECOUNT {$JPPEXPANDMACRO JCLVECTORINT(,,,,,,,,,,,,,,,)} {$JPPEXPANDMACRO JCLVECTORITRINT(,,,,,,,)} *) {$IFDEF SUPPORTS_GENERICS} TJclVectorIterator<T> = class; (*$JPPEXPANDMACRO JCLVECTORINT(TJclVector<T>,TJclAbstractContainer<T>,IJclCollection<T>,IJclList<T>,IJclArray<T>,IJclIterator<T>, IJclItemOwner<T>\, IJclEqualityComparer<T>\,, protected type TDynArray = array of T; TVectorIterator = TJclVectorIterator<T>; procedure MoveArray(var List: TDynArray; FromIndex, ToIndex, Count: Integer);,,; AOwnsItems: Boolean,const ,AItem,T,TDynArray,GetItem,SetItem)*) (*$JPPEXPANDMACRO JCLVECTORITRINT(TJclVectorIterator<T>,IJclIterator<T>,IJclList<T>,const ,AItem,T,GetItem,SetItem)*) // E = External helper to compare items for equality (GetHashCode is not used) TJclVectorE<T> = class(TJclVector<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE} IJclIntfCloneable, IJclCloneable, IJclPackable, IJclGrowable, IJclContainer, IJclCollection<T>, IJclList<T>, IJclArray<T>, IJclItemOwner<T>) private FEqualityComparer: IJclEqualityComparer<T>; protected procedure AssignPropertiesTo(Dest: TJclAbstractContainerBase); override; function CreateEmptyContainer: TJclAbstractContainerBase; override; public constructor Create(const AEqualityComparer: IJclEqualityComparer<T>; ACapacity: Integer; AOwnsItems: Boolean); { IJclEqualityComparer<T> } function ItemsEqual(const A, B: T): Boolean; override; property EqualityComparer: IJclEqualityComparer<T> read FEqualityComparer write FEqualityComparer; end; // F = Function to compare items for equality TJclVectorF<T> = class(TJclVector<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE} IJclIntfCloneable, IJclCloneable, IJclPackable, IJclGrowable, IJclContainer, IJclCollection<T>, IJclList<T>, IJclArray<T>, IJclItemOwner<T>) protected function CreateEmptyContainer: TJclAbstractContainerBase; override; public constructor Create(const AEqualityCompare: TEqualityCompare<T>; ACapacity: Integer; AOwnsItems: Boolean); end; // I = Items can compare themselves to an other for equality TJclVectorI<T: IEquatable<T>> = class(TJclVector<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE} IJclIntfCloneable, IJclCloneable, IJclPackable, IJclGrowable, IJclContainer, IJclCollection<T>, IJclList<T>, IJclArray<T>, IJclItemOwner<T>) protected function CreateEmptyContainer: TJclAbstractContainerBase; override; public { IJclEqualityComparer<T> } function ItemsEqual(const A, B: T): Boolean; override; end; {$ENDIF SUPPORTS_GENERICS} {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL: https://jcl.svn.sourceforge.net:443/svnroot/jcl/tags/JCL-2.2-Build3970/jcl/source/prototypes/JclVectors.pas $'; Revision: '$Revision: 3296 $'; Date: '$Date: 2010-08-10 18:13:22 +0200 (mar., 10 août 2010) $'; LogPath: 'JCL\source\common'; Extra: ''; Data: nil ); {$ENDIF UNITVERSIONING} implementation uses SysUtils; (*$JPPLOOP TRUETYPEINDEX TRUETYPECOUNT {$JPPEXPANDMACRO JCLVECTORIMP(,,,,,,,,,,,,,)} {$JPPEXPANDMACRO JCLVECTORITRIMP(,,,,,,,)} *) {$IFDEF SUPPORTS_GENERICS} (*$JPPEXPANDMACRO JCLVECTORIMP(TJclVector<T>,IJclCollection<T>,IJclList<T>,IJclIterator<T>,TVectorIterator,; AOwnsItems: Boolean,AOwnsItems,const ,AItem,T,Default(T),GetItem,SetItem,FreeItem)*) (*$JPPEXPANDMACRO JCLVECTORITRIMP(TJclVectorIterator<T>,IJclIterator<T>,IJclList<T>,const ,AItem,T,GetItem,SetItem)*) procedure TJclVector<T>.MoveArray(var List: TDynArray; FromIndex, ToIndex, Count: Integer); var I: Integer; begin if FromIndex < ToIndex then begin for I := Count - 1 downto 0 do List[ToIndex + I] := List[FromIndex + I]; if (ToIndex - FromIndex) < Count then // overlapped source and target for I := 0 to ToIndex - FromIndex - 1 do List[FromIndex + I] := Default(T) else // independant for I := 0 to Count - 1 do List[FromIndex + I] := Default(T); end else begin for I := 0 to Count - 1 do List[ToIndex + I] := List[FromIndex + I]; if (FromIndex - ToIndex) < Count then // overlapped source and target for I := Count - FromIndex + ToIndex to Count - 1 do List[FromIndex + I] := Default(T) else // independant for I := 0 to Count - 1 do List[FromIndex + I] := Default(T); end; end; //=== { TJclVectorE<T> } ===================================================== constructor TJclVectorE<T>.Create(const AEqualityComparer: IJclEqualityComparer<T>; ACapacity: Integer; AOwnsItems: Boolean); begin inherited Create(ACapacity, AOwnsItems); FEqualityComparer := AEqualityComparer; end; procedure TJclVectorE<T>.AssignPropertiesTo(Dest: TJclAbstractContainerBase); begin inherited AssignPropertiesTo(Dest); if Dest is TJclVectorE<T> then TJclVectorE<T>(Dest).FEqualityComparer := FEqualityComparer; end; function TJclVectorE<T>.CreateEmptyContainer: TJclAbstractContainerBase; begin Result := TJclVectorE<T>.Create(EqualityComparer, FSize, False); AssignPropertiesTo(Result); end; function TJclVectorE<T>.ItemsEqual(const A, B: T): Boolean; begin if EqualityComparer <> nil then Result := EqualityComparer.ItemsEqual(A, B) else Result := inherited ItemsEqual(A, B); end; //=== { TJclVectorF<T> } ===================================================== constructor TJclVectorF<T>.Create(const AEqualityCompare: TEqualityCompare<T>; ACapacity: Integer; AOwnsItems: Boolean); begin inherited Create(ACapacity, AOwnsItems); SetEqualityCompare(AEqualityCompare); end; function TJclVectorF<T>.CreateEmptyContainer: TJclAbstractContainerBase; begin Result := TJclVectorF<T>.Create(EqualityCompare, FSize, False); AssignPropertiesTo(Result); end; //=== { TJclVectorI<T> } ===================================================== function TJclVectorI<T>.CreateEmptyContainer: TJclAbstractContainerBase; begin Result := TJclVectorI<T>.Create(FSize, False); AssignPropertiesTo(Result); end; function TJclVectorI<T>.ItemsEqual(const A, B: T): Boolean; begin if Assigned(FEqualityCompare) then Result := FEqualityCompare(A, B) else if Assigned(FCompare) then Result := FCompare(A, B) = 0 else Result := A.Equals(B); end; {$ENDIF SUPPORTS_GENERICS} {$IFDEF UNITVERSIONING} initialization RegisterUnitVersion(HInstance, UnitVersioning); finalization UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
43.271255
194
0.534805
477d69f566a127e655441a52c85c7c2705978cb8
18,524
pas
Pascal
PROG_ADMIN/IngresoCompras.pas
carlosthieme/FerrePOS
54232bb0e02e4f7383c8d99ec6a9112b4e95b10e
[ "Unlicense" ]
null
null
null
PROG_ADMIN/IngresoCompras.pas
carlosthieme/FerrePOS
54232bb0e02e4f7383c8d99ec6a9112b4e95b10e
[ "Unlicense" ]
null
null
null
PROG_ADMIN/IngresoCompras.pas
carlosthieme/FerrePOS
54232bb0e02e4f7383c8d99ec6a9112b4e95b10e
[ "Unlicense" ]
null
null
null
unit IngresoCompras; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Db, DBTables, Grids, AdvGrid, StdCtrls, ComCtrls, Numedit, ExtCtrls, Menus, DBGrids, Buttons; type TIngresoComprasForm = class(TForm) Panel1: TPanel; Dig: TEdit; Rut: TNumEdit; Nombre: TEdit; Numero: TNumEdit; Fecha: TDateTimePicker; TipoDoc: TComboBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Grid: TAdvStringGrid; Proves: TTable; DSProves: TDataSource; Artics: TTable; DSArtics: TDataSource; Compras: TTable; DSCompras: TDataSource; ProvesRUT: TFloatField; ProvesDIG: TStringField; ProvesNOMBRE: TStringField; ArticsCODIGO: TStringField; ArticsALTER1: TStringField; ArticsALTER2: TStringField; ArticsNOMBRE: TStringField; ArticsMODIF: TBooleanField; ArticsDESC: TFloatField; ArticsPRECIO: TFloatField; ArticsSTOCK: TFloatField; ArticsVUCOMPRA: TFloatField; Status: TStatusBar; ProvesDESC01: TSmallintField; ProvesDESC02: TSmallintField; ProvesDESC03: TSmallintField; ProvesDESC04: TSmallintField; ProvesDESC05: TSmallintField; ProvesDESC06: TSmallintField; ProvesDESC07: TSmallintField; ProvesDESC08: TSmallintField; ProvesDESC09: TSmallintField; ProvesDESC10: TSmallintField; ProvesDESCPROMO: TSmallintField; ProvesDESCPP01: TSmallintField; ProvesDESCPP02: TSmallintField; ProvesDESCPP03: TSmallintField; ProvesDESCPP04: TSmallintField; PBusca: TPanel; EBusca: TEdit; GridBusca: TDBGrid; ComprasRUTPROVE: TFloatField; ComprasDOCUMENTO: TStringField; ComprasNUMERO: TStringField; ComprasFECHA: TDateField; ComprasITEM: TSmallintField; ComprasCODIGO: TStringField; ComprasCANTIDAD: TSmallintField; ComprasPRECIO: TFloatField; ComprasDE01: TSmallintField; ComprasDE02: TSmallintField; ComprasDE03: TSmallintField; ComprasDE04: TSmallintField; ComprasDE05: TSmallintField; ComprasDE06: TSmallintField; ComprasDE07: TSmallintField; ComprasDE08: TSmallintField; ComprasDE09: TSmallintField; ComprasDE10: TSmallintField; ComprasDEPR: TSmallintField; ComprasDEPP1: TSmallintField; ComprasDEPP2: TSmallintField; ComprasDEPP3: TSmallintField; ComprasDEPP4: TSmallintField; ComprasIMP01: TSmallintField; ComprasIMP02: TSmallintField; ComprasIMP03: TSmallintField; ComprasIMP04: TSmallintField; ComprasIMP05: TSmallintField; BtnGrabar: TSpeedButton; procedure RutKeyPress(Sender: TObject; var Key: Char); procedure GridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure GridGetAlignment(Sender: TObject; ARow, ACol: Integer; var AAlignment: TAlignment); procedure EBuscaChange(Sender: TObject); procedure EBuscaKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure GridBuscaKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure NumeroKeyPress(Sender: TObject; var Key: Char); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure BtnGrabarClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var IngresoComprasForm: TIngresoComprasForm; Existe : Boolean; Items : Integer; implementation uses MantProves; {$R *.DFM} procedure TIngresoComprasForm.RutKeyPress(Sender: TObject; var Key: Char); begin If Key = #13 Then Begin Proves.Open; Proves.SetKey; Try If Not Proves.FindKey([Rut.Text]) Then Begin {Proveedor No Existe} MantProveForm.ShowModal; End Else Begin Dig.Text := ProvesDig.AsString; Nombre.Text := ProvesNombre.AsString; Numero.SetFocus; End; Except On EConvertError Do Begin Rut.Text := ''; Rut.SetFocus; End; End;{Try} End; end; procedure TIngresoComprasForm.GridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); Var I : Integer; begin Status.Panels[2].Text := IntToStr(Key); If (Grid.Options = [goFixedVertLine,goFixedHorzLine,goVertLine,goHorzLine,goAlwaysShowEditor,goRowSelect]) Then Grid.Options := [goFixedVertLine,goFixedHorzLine,goVertLine,goHorzLine,goAlwaysShowEditor,goEditing]; Case Grid.Col Of 0 : Begin Case Key Of 13 : Begin If Grid.Cells[0, Grid.Row] = '' Then Begin PBusca.Visible := True; Artics.Active := True; EBusca.SetFocus; End Else Begin Artics.Open; Artics.IndexFieldNames := 'ALTER2'; Artics.SetKey; If Not Artics.FindKey([Grid.Cells[0, Grid.Row]]) Then Begin {Codigo No Existe} Artics.IndexFieldNames := 'ALTER1'; Artics.SetKey; If Not Artics.FindKey([Grid.Cells[0, Grid.Row]]) Then Begin {Codigo No Existe} End Else Begin Grid.Cells[0, Grid.Row] := ArticsCodigo.AsString; Grid.Cells[1, Grid.Row] := ArticsNombre.AsString; Grid.Cells[3, Grid.Row] := ArticsVUCompra.AsString; Grid.Cells[4, Grid.Row] := ArticsStock.AsString; Grid.Cells[5, Grid.Row] := ArticsPrecio.AsString; Grid.Cells[6, Grid.Row] := ArticsDesc.AsString; If (ArticsModif.Value = True) Then Grid.Cells[7, Grid.Row] := 'SI' Else Grid.Cells[7, Grid.Row] := 'NO'; Grid.Col := 2; End; End Else Begin Grid.Cells[0, Grid.Row] := ArticsCodigo.AsString; Grid.Cells[1, Grid.Row] := ArticsNombre.AsString; Grid.Cells[3, Grid.Row] := ArticsVUCompra.AsString; Grid.Cells[4, Grid.Row] := ArticsStock.AsString; Grid.Cells[5, Grid.Row] := ArticsPrecio.AsString; Grid.Cells[6, Grid.Row] := ArticsDesc.AsString; If (ArticsModif.Value = True) Then Grid.Cells[7, Grid.Row] := 'SI' Else Grid.Cells[7, Grid.Row] := 'NO'; Grid.Col := 2; End; End; End; End; {Case Key Of} End; {Columa 0, Codigo} 1 : Begin Grid.Col := 2; End; {Columna 1, Nombre Articulo} 2 : Begin Case Key Of 13 : Begin Grid.Col := 3; End; End; {Case Key Of} End; {Columna 2, Cantidad} 3 : Begin Case Key Of 13 : Begin Grid.Col := 5; End; End; {Case Key Of} End; {Columna 3, Precio Ultima Compra} 4 : Begin Grid.Col := 5; End; {Columna 4, Stock} 5 : Begin Case Key Of 13 : Begin Grid.Col := 6; End; End; {Case Key Of} End; {Columna 5, Precio Venta Publico} 6 : Begin Case Key Of 13 : Begin If (Grid.Cells[6, Grid.Row] = '') Then Begin Grid.Cells[6, Grid.Row] := '0'; End; Grid.Col := 7; End; End; {Case Key Of} End; {Columna 6, Descuento Precio Venta Publico} 7 : Begin Case Key Of 13 : Begin If Grid.Cells[7, Grid.Row] = '' Then Grid.Cells[7, Grid.Row] := 'NO'; Grid.Cells[8, Grid.Row] := ProvesDesc01.AsString; Grid.Cells[9, Grid.Row] := ProvesDesc02.AsString; Grid.Cells[10, Grid.Row] := ProvesDesc03.AsString; Grid.Cells[11, Grid.Row] := ProvesDesc04.AsString; Grid.Cells[12, Grid.Row] := ProvesDesc05.AsString; Grid.Cells[13, Grid.Row] := ProvesDesc06.AsString; Grid.Cells[14, Grid.Row] := ProvesDesc07.AsString; Grid.Cells[15, Grid.Row] := ProvesDesc08.AsString; Grid.Cells[16, Grid.Row] := ProvesDesc09.AsString; Grid.Cells[17, Grid.Row] := ProvesDesc10.AsString; Grid.Cells[18, Grid.Row] := ProvesDescPromo.AsString; Grid.Cells[19, Grid.Row] := ProvesDescPP01.AsString; Grid.Cells[20, Grid.Row] := ProvesDescPP02.AsString; Grid.Cells[21, Grid.Row] := ProvesDescPP03.AsString; Grid.Cells[22, Grid.Row] := ProvesDescPP04.AsString; Grid.Col := 0; Grid.Row := Grid.Row + 1; End; End; {Case Key Of} End; {Columna 7, Precio Venta modificable al Vender} End; {Case Key Of Columna} end; procedure TIngresoComprasForm.GridGetAlignment(Sender: TObject; ARow, ACol: Integer; var AAlignment: TAlignment); begin If (ARow = 0) And (ACol In [0..23]) Then AAlignment := taCenter; If (ARow > 0) And (ACol In[0, 2, 3, 4, 5, 6, 8..23]) Then AAlignment := taRightJustify; If (ARow > 0) And (ACol = 1) Then AAlignment := taLeftJustify; If (ARow > 0) And (ACol = 7) Then AAlignment := taCenter; end; procedure TIngresoComprasForm.EBuscaChange(Sender: TObject); begin Artics.IndexFieldNames := 'NOMBRE'; Artics.SetKey; ArticsNombre.Value := EBusca.Text; Artics.GotoNearest; end; procedure TIngresoComprasForm.EBuscaKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin Case Key Of 13 : Begin Grid.Cells[0, Grid.Row] := ArticsCodigo.AsString; Grid.Cells[1, Grid.Row] := ArticsNombre.AsString; Grid.Cells[3, Grid.Row] := ArticsVUCompra.AsString; Grid.Cells[4, Grid.Row] := ArticsStock.AsString; Grid.Cells[5, Grid.Row] := ArticsPrecio.AsString; Grid.Cells[6, Grid.Row] := ArticsDesc.AsString; If (ArticsModif.Value = True) Then Grid.Cells[7, Grid.Row] := 'SI' Else Grid.Cells[7, Grid.Row] := 'NO'; Grid.SetFocus; Grid.Col := 2; Artics.IndexFieldNames := 'ALTER2'; Artics.SetKey; Artics.Active := False; PBusca.Visible := False; End; 35 : Begin Artics.IndexFieldNames := 'ALTER2'; Artics.SetKey; Artics.Active := False; Grid.SetFocus; Grid.Col := 0; PBusca.Visible := False; End; 37..40 : Begin GridBusca.SetFocus; End; End; end; procedure TIngresoComprasForm.GridBuscaKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin Case Key Of 13 : Begin Grid.Cells[0, Grid.Row] := ArticsCodigo.AsString; Grid.Cells[1, Grid.Row] := ArticsNombre.AsString; Grid.Cells[3, Grid.Row] := ArticsVUCompra.AsString; Grid.Cells[4, Grid.Row] := ArticsStock.AsString; Grid.Cells[5, Grid.Row] := ArticsPrecio.AsString; Grid.Cells[6, Grid.Row] := ArticsDesc.AsString; If (ArticsModif.Value = True) Then Grid.Cells[7, Grid.Row] := 'SI' Else Grid.Cells[7, Grid.Row] := 'NO'; Grid.SetFocus; Grid.Col := 2; Artics.IndexFieldNames := 'ALTER2'; Artics.SetKey; Artics.Active := False; PBusca.Visible := False; PBusca.Visible := False; End; 35 : Begin Artics.IndexFieldNames := 'ALTER2'; Artics.SetKey; Artics.Active := False; Grid.SetFocus; Grid.Col := 0; End; 37, 39 : Begin EBusca.Text := ''; EBusca.SetFocus; End; End; end; procedure TIngresoComprasForm.NumeroKeyPress(Sender: TObject; var Key: Char); Var I : Integer; begin If Key = #13 Then Begin Existe := False; Grid.Row := 1; I := Grid.Row; Compras.Open; Compras.First; While Not Compras.EOF Do Begin If (ComprasNumero.Value = Numero.Text) And (ComprasRutProve.Value = StrToFloat(Rut.Text)) Then Begin Existe := True; TipoDoc.Text := ComprasDocumento.AsString; Fecha.Date := ComprasFecha.Value; Grid.Cells[0, I] := ComprasCodigo.AsString; Artics.Open; Artics.IndexFieldNames := 'CODIGO'; Artics.SetKey; If Artics.FindKey([ComprasCodigo.AsString]) Then Begin Grid.Cells[1, I] := ArticsNombre.AsString; Grid.Cells[4, I] := ArticsStock.AsString; Grid.Cells[5, I] := ArticsPrecio.AsString; Grid.Cells[6, I] := ArticsDesc.AsString; If (ArticsModif.Value = True) Then Grid.Cells[7, I] := 'SI' Else Grid.Cells[7, I] := 'NO'; End; Artics.Close; Grid.Cells[2, I] := ComprasCantidad.AsString; Grid.Cells[3, I] := ComprasPrecio.AsString; Grid.Cells[8, I] := ComprasDE01.AsString; Grid.Cells[9, I] := ComprasDE02.AsString; Grid.Cells[10, I] := ComprasDE03.AsString; Grid.Cells[11, I] := ComprasDE04.AsString; Grid.Cells[12, I] := ComprasDE05.AsString; Grid.Cells[13, I] := ComprasDE06.AsString; Grid.Cells[14, I] := ComprasDE07.AsString; Grid.Cells[15, I] := ComprasDE08.AsString; Grid.Cells[16, I] := ComprasDE09.AsString; Grid.Cells[17, I] := ComprasDE10.AsString; Grid.Cells[18, I] := ComprasDEPR.AsString; Grid.Cells[19, I] := ComprasDEPP1.AsString; Grid.Cells[20, I] := ComprasDEPP2.AsString; Grid.Cells[21, I] := ComprasDEPP3.AsString; Grid.Cells[22, I] := ComprasDEPP4.AsString; Compras.Next; Inc(I); End Else Begin Compras.Next; End; End; If Existe = True Then Begin Grid.Options := [goFixedVertLine,goFixedHorzLine,goVertLine,goHorzLine,goAlwaysShowEditor,goRowSelect]; End Else TipoDoc.SetFocus; End; end; procedure TIngresoComprasForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TIngresoComprasForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := True; end; procedure TIngresoComprasForm.BtnGrabarClick(Sender: TObject); Var I, J : Integer; begin Items := 0; For I := 1 To Grid.RowCount Do If (Grid.Cells[0, I] <> '') Then Inc(Items); For I := 1 To Items Do For J := 1 To 23 Do If Grid.Cells[J, I] = '' Then Begin Grid.Cells[J, I] := '0'; End; Compras.Open; For I := 1 To Items Do Begin Compras.Append; ComprasRutProve.Value := StrToFloat(Rut.Text); ComprasDocumento.Value := TipoDoc.Text; ComprasNumero.Value := Numero.Text; ComprasFecha.Value := Fecha.Date; ComprasItem.Value := I; ComprasCodigo.Value := Grid.Cells[0, I]; ComprasCantidad.Value := StrToInt(Grid.Cells[2, I]); ComprasPrecio.Value := StrToFloat(Grid.Cells[3, I]); ComprasDE01.Value := StrToInt(Grid.Cells[8, I]); ComprasDE02.Value := StrToInt(Grid.Cells[9, I]); ComprasDE03.Value := StrToInt(Grid.Cells[10, I]); ComprasDE04.Value := StrToInt(Grid.Cells[11, I]); ComprasDE05.Value := StrToInt(Grid.Cells[12, I]); ComprasDE06.Value := StrToInt(Grid.Cells[13, I]); ComprasDE07.Value := StrToInt(Grid.Cells[14, I]); ComprasDE08.Value := StrToInt(Grid.Cells[15, I]); ComprasDE09.Value := StrToInt(Grid.Cells[16, I]); ComprasDE10.Value := StrToInt(Grid.Cells[17, I]); ComprasDEPR.Value := StrToInt(Grid.Cells[18, I]); ComprasDEPP1.Value := StrToInt(Grid.Cells[19, I]); ComprasDEPP2.Value := StrToInt(Grid.Cells[20, I]); ComprasDEPP3.Value := StrToInt(Grid.Cells[21, I]); ComprasDEPP4.Value := StrToInt(Grid.Cells[22, I]); Compras.Post; Artics.Open; Artics.IndexFieldNames := 'CODIGO'; Artics.SetKey; If Not Artics.FindKey([Grid.Cells[0, I]]) Then Begin End Else Begin Artics.Edit; ArticsPrecio.Value := StrToFloat(Grid.Cells[5, I]); ArticsStock.Value := ArticsStock.Value + StrToFloat(Grid.Cells[2, I]); ArticsDesc.Value := StrToFloat(Grid.Cells[6, I]); ArticsVUCompra.Value := StrToFloat(Grid.Cells[3, I]); If Grid.Cells[7, I] = 'SI' Then ArticsModif.Value := True Else ArticsModif.Value := False; Artics.Post; Artics.Close; End; End; Grid.ClearNormalCells; Grid.Options := [goFixedVertLine,goFixedHorzLine,goVertLine,goHorzLine,goAlwaysShowEditor,goEditing]; Rut.Text := ''; Dig.Text := ''; Nombre.Text := ''; Numero.Text := ''; Grid.Row := 1; Grid.Col := 0; Rut.SetFocus; end; end.
35.829787
113
0.548694
6a67f36202b7bd263b4bf9c2ee184c79a7cf9b00
3,411
pas
Pascal
src/Tasks/Implementations/Deploy/Core/WebServer/Nginx/NginxWindowsVHostWriterImpl.pas
fanoframework/fano-cli
d790f304e54cd855f5887d93bf8b3b5c98da0b22
[ "MIT" ]
10
2018-11-10T22:58:49.000Z
2022-03-09T23:36:18.000Z
src/Tasks/Implementations/Deploy/Core/WebServer/Nginx/NginxWindowsVHostWriterImpl.pas
zamronypj/fano-cli
bf3bc68356302c03c5fde2e98edc4d04567c7101
[ "MIT" ]
8
2019-09-24T03:30:27.000Z
2021-09-14T02:15:06.000Z
src/Tasks/Implementations/Deploy/Core/WebServer/Nginx/NginxWindowsVHostWriterImpl.pas
fanoframework/fano-cli
d790f304e54cd855f5887d93bf8b3b5c98da0b22
[ "MIT" ]
2
2020-07-06T12:35:11.000Z
2021-11-30T05:35:09.000Z
(*!------------------------------------------------------------ * Fano CLI Application (https://fanoframework.github.io) * * @link https://github.com/fanoframework/fano-cli * @copyright Copyright (c) 2018 - 2020 Zamrony P. Juhara * @license https://github.com/fanoframework/fano-cli/blob/master/LICENSE (MIT) *------------------------------------------------------------- *) unit NginxWindowsVHostWriterImpl; interface {$MODE OBJFPC} {$H+} uses TaskOptionsIntf, TextFileCreatorIntf, ContentModifierIntf, VirtualHostWriterIntf, FileContentAppenderIntf; type (*!-------------------------------------- * Task that creates Nginx web server virtual host file * in Windows *------------------------------------------ * @author Zamrony P. Juhara <zamronypj@yahoo.com> *---------------------------------------*) TNginxWindowsVHostWriter = class(TInterfacedObject, IVirtualHostWriter) private fFileAppender : IFileContentAppender; fTextFileCreator : ITextFileCreator; procedure doWriteVhost( const serverName : string; const vhostTpl : string; const cntModifier : IContentModifier; const nginxDir : string ); public constructor create( const txtFileCreator : ITextFileCreator; const fileAppender : IFileContentAppender ); procedure writeVhost( const serverName : string; const vhostTpl : string; const cntModifier : IContentModifier ); end; implementation uses SysUtils; constructor TNginxWindowsVHostWriter.create( const txtFileCreator : ITextFileCreator; const fileAppender : IFileContentAppender ); begin fTextFileCreator := txtFileCreator; fFileAppender := fileAppender; end; procedure TNginxWindowsVHostWriter.doWriteVhost( const serverName : string; const vhostTpl : string; const cntModifier : IContentModifier; const nginxDir : string ); begin cntModifier.setVar('[[NGINX_LOG_DIR]]', nginxDir + '\logs'); fTextFileCreator.createTextFile( nginxDir + '\conf\' + serverName + '.conf', cntModifier.modify(vhostTpl) ); fFileAppender.append( nginxDir + '\conf\nginx.conf', 'include "' + nginxDir + '\conf\' + serverName + '.conf";' + LineEnding ); end; procedure TNginxWindowsVHostWriter.writeVhost( const serverName : string; const vhostTpl : string; const cntModifier : IContentModifier ); var nginxDir : string; begin nginxDir := getEnvironmentVariable('NGINX_DIR'); if (nginxDir = '') then begin nginxDir := 'C:\Program Files\nginx'; end; if (not directoryExists(nginxDir)) then begin nginxDir := 'C:\nginx'; end; if (directoryExists(nginxDir)) then begin nginxDir := ExcludeTrailingPathDelimiter(nginxDir); doWriteVhost(serverName,vhostTpl,cntModifier, nginxDir); end else begin writeln( 'Cannot find Nginx directory in ' + nginxDir + '. Set NGINX_DIR environment variable to correct directory' ); end; end; end.
28.190083
83
0.567282
474de3aed84936fe2ae1be4986c984be93cbc49e
197,378
pas
Pascal
source/Excel4Delphi.pas
FenixGit/Excel4Delphi
d294b33be69d7fb1ca2668fe9b8b14fa57e3e321
[ "Zlib" ]
14
2021-07-14T06:05:29.000Z
2022-03-23T14:11:36.000Z
source/Excel4Delphi.pas
FenixGit/Excel4Delphi
d294b33be69d7fb1ca2668fe9b8b14fa57e3e321
[ "Zlib" ]
null
null
null
source/Excel4Delphi.pas
FenixGit/Excel4Delphi
d294b33be69d7fb1ca2668fe9b8b14fa57e3e321
[ "Zlib" ]
1
2021-07-14T13:46:06.000Z
2021-07-14T13:46:06.000Z
unit Excel4Delphi; interface uses System.Classes, System.SysUtils, {$IFDEF FMX} FMX.Graphics, {$ELSE} Vcl.Graphics, {$ENDIF} {$IFDEF MSWINDOWS} Winapi.Windows, {$ENDIF} System.UITypes, System.Math, RegularExpressions, System.Generics.Collections, System.Generics.Defaults, Excel4Delphi.Xml; var ZE_XLSX_APPLICATION: string; // 1 (topographical point) = 0.3528 mm const _PointToMM: Real = 0.3528; {$IFDEF FMX} DEFAULT_CHARSET = 1; {$ENDIF} type TObjectList = TObjectList<TObject>; type /// <summary> /// Data type of cell /// </summary> TZCellType = (ZENumber, ZEDateTime, ZEBoolean, ZEString, ZEError, ZEGeneral); /// <summary> /// Style lines of the cell border /// </summary> TZBorderType = (ZENone, ZEContinuous, ZEHair, ZEDot, ZEDash, ZEDashDot, ZEDashDotDot, ZESlantDashDot, ZEDouble); /// <summary> /// Horizontal alignment /// </summary> TZHorizontalAlignment = (ZHAutomatic, ZHLeft, ZHCenter, ZHRight, ZHFill, ZHJustify, ZHCenterAcrossSelection, ZHDistributed, ZHJustifyDistributed); /// <summary> /// Vertical alignment /// </summary> TZVerticalAlignment = (ZVAutomatic, ZVTop, ZVBottom, ZVCenter, ZVJustify, ZVDistributed, ZVJustifyDistributed); /// <summary> /// Fill pattern of the cell /// </summary> TZCellPattern = (ZPNone, ZPSolid, ZPGray75, ZPGray50, ZPGray25, ZPGray125, ZPGray0625, ZPHorzStripe, ZPVertStripe, ZPReverseDiagStripe, ZPDiagStripe, ZPDiagCross, ZPThickDiagCross, ZPThinHorzStripe, ZPThinVertStripe, ZPThinReverseDiagStripe, ZPThinDiagStripe, ZPThinHorzCross, ZPThinDiagCross); /// <summary> /// Borders position. /// </summary> TZBordersPos = (bpLeft, bpTop, bpRight, bpBottom, bpDiagonalLeft, bpDiagonalRight); /// <summary> /// Vertical/horizontal split/freeze mode. /// </summary> TZSplitMode = (ZSplitNone, ZSplitFrozen, ZSplitSplit); /// <summary> /// View mode. /// </summary> TZViewMode = (zvmNormal, zvmPageBreakPreview); /// <summary> /// An angle of the rotation (direction) for a text within a cell. /// Nominative range is -90 .. +90, extended is -180 .. +180 (in degrees) /// </summary> TZCellTextRotate = -180 .. +359; TMediaRec = record FileName: string; Content: TBytes; end; TZSheet = class; TZStyle = class; TZFont = class; TZExcelColor = record RGB: TColor; // rgb Indexed: Byte; // 0 - not exists (deprecated but used) Theme: Byte; // 0 - not exists Tint: Double; // 0 - not exists procedure Load(const ARgb, AIndexed, ATheme, ATint: string); class operator Equal(const ALeft, ARight: TZExcelColor): Boolean; class operator NotEqual(const ALeft, ARight: TZExcelColor): Boolean; end; TRichString = class(TPersistent) private FText: string; FFont: TZFont; // FSCheme: string; // todo: add to TZFont or use "minor" for default public property Text: string read FText write FText; property Font: TZFont read FFont write FFont; destructor Destroy(); override; procedure Assign(Source: TPersistent); override; function GetHashCode(): Integer; override; function Equals(Obj: TObject): Boolean; override; end; TRichText = class(TPersistent) private FList: TList<TRichString>; public constructor Create(); virtual; destructor Destroy(); override; procedure Assign(Source: TPersistent); override; property List: TList<TRichString> read FList; function GetHashCode(): Integer; override; function Equals(Obj: TObject): Boolean; override; // function ToHtml(): string; // function ToString(): string; override; end; TRichTextComparer = class(TInterfacedObject, IEqualityComparer<TRichText>) public function Equals(const left, right: TRichText): Boolean; reintroduce; function GetHashCode(const Value: TRichText): Integer; reintroduce; end; /// <summary> /// Cell of spreadsheet. /// </summary> TZCell = class(TPersistent) private FFormula: string; FData: string; FHref: string; FHRefScreenTip: string; FComment: string; FCommentAuthor: string; FAlwaysShowComment: Boolean; // default = false; FShowComment: Boolean; // default = false FCellType: TZCellType; FCellStyle: Integer; FRichText: TRichText; FSheet: TZSheet; procedure ApplyStyleValue(proc: TProc<TZStyle>); function GetDataAsDouble: Double; procedure SetDataAsDouble(const Value: Double); procedure SetDataAsInteger(const Value: Integer); function GetDataAsInteger: Integer; function GetDataAsDateTime(): TDateTime; procedure SetDataAsDateTime(const Value: TDateTime); procedure SetDataAsString(const Value: string); function GetStyle(): TZStyle; function GetBgColor: TColor; function GetBorderColor(num: TZBordersPos): TColor; function GetBorderStyle(num: TZBordersPos): TZBorderType; function GetBorderWidht(num: TZBordersPos): Byte; function GetFontColor: TColor; function GetFontSize: Double; function GetFontStyle: TFontStyles; function GetHorizontalAlignment: TZHorizontalAlignment; function GetNumberFormat: string; function GetRotate: TZCellTextRotate; function GetVerticalAlignment: TZVerticalAlignment; function GetVerticalText: Boolean; function GetWrapText: Boolean; procedure SetBgColor(const Value: TColor); procedure SetBorderColor(num: TZBordersPos; const Value: TColor); procedure SetBorderStyle(num: TZBordersPos; const Value: TZBorderType); procedure SetBorderWidht(num: TZBordersPos; const Value: Byte); procedure SetFontColor(const Value: TColor); procedure SetFontSize(const Value: Double); procedure SetFontStyle(const Value: TFontStyles); procedure SetHorizontalAlignment(const Value: TZHorizontalAlignment); procedure SetNumberFormat(const Value: string); procedure SetRotate(const Value: TZCellTextRotate); procedure SetVerticalAlignment(const Value: TZVerticalAlignment); procedure SetVerticalText(const Value: Boolean); procedure SetWrapText(const Value: Boolean); public constructor Create(ASheet: TZSheet); virtual; destructor Destroy(); override; procedure Assign(Source: TPersistent); override; /// <summary> /// Clear cell data. /// </summary> procedure Clear(); /// <summary> /// Current sheet. /// </summary> property Sheet: TZSheet read FSheet; /// <summary> /// Current cell style. /// </summary> property Style: TZStyle read GetStyle; /// <summary> /// Always show comment. <br />False by default. /// </summary> property AlwaysShowComment: Boolean read FAlwaysShowComment write FAlwaysShowComment default false; /// <summary> /// Comment text. /// </summary> property Comment: string read FComment write FComment; /// <summary> /// Author of comment. /// </summary> property CommentAuthor: string read FCommentAuthor write FCommentAuthor; /// <summary> /// Cell style number. <br />-1 by default. /// </summary> property CellStyle: Integer read FCellStyle write FCellStyle default -1; /// <summary> /// Cell type. <br />ZEString by default. /// </summary> property CellType: TZCellType read FCellType write FCellType default ZEString; /// <summary> /// Specifies the value of this cell to show on screen. /// </summary> property Data: string read FData write FData; /// <summary> /// Formula in R1C1 style. /// </summary> property Formula: string read FFormula write FFormula; /// <summary> /// Specifies the URL to link this cell. /// </summary> property HRef: string read FHref write FHref; /// <summary> /// Displays the caption of URL to show on screen. /// </summary> property HRefScreenTip: string read FHRefScreenTip write FHRefScreenTip; /// <summary> /// Show comment. <br />False by default. /// </summary> property ShowComment: Boolean read FShowComment write FShowComment default false; /// <summary> /// Rich formated text. /// </summary> property RichText: TRichText read FRichText; /// <summary> /// Present cell data as double value /// </summary> property AsDouble: Double read GetDataAsDouble write SetDataAsDouble; /// <summary> /// Present cell data as integer value /// </summary> property AsInteger: Integer read GetDataAsInteger write SetDataAsInteger; /// <summary> /// Present cell data as TDateTime value /// </summary> property AsDateTime: TDateTime read GetDataAsDateTime write SetDataAsDateTime; /// <summary> /// Present cell data as string value /// </summary> property AsString: string read FData write SetDataAsString; /// <summary> /// Vertical content alignment /// </summary> property VerticalAlignment: TZVerticalAlignment read GetVerticalAlignment write SetVerticalAlignment; /// <summary> /// Horisontal content alignment /// </summary> property HorizontalAlignment: TZHorizontalAlignment read GetHorizontalAlignment write SetHorizontalAlignment; /// <summary> /// Background cell color /// </summary> property BgColor: TColor read GetBgColor write SetBgColor; /// <summary> /// Font color /// </summary> property FontColor: TColor read GetFontColor write SetFontColor; /// <summary> /// Font size /// </summary> property FontSize: Double read GetFontSize write SetFontSize; /// <summary> /// Font style /// </summary> property FontStyle: TFontStyles read GetFontStyle write SetFontStyle; /// <summary> /// Border style /// </summary> property BorderStyle[num: TZBordersPos]: TZBorderType read GetBorderStyle write SetBorderStyle; /// <summary> /// Border width /// </summary> property BorderWidht[num: TZBordersPos]: Byte read GetBorderWidht write SetBorderWidht; /// <summary> /// Border color /// </summary> property BorderColor[num: TZBordersPos]: TColor read GetBorderColor write SetBorderColor; /// <summary> /// Word wrap /// </summary> property WrapText: Boolean read GetWrapText write SetWrapText; /// <summary> /// Vertical text /// </summary> property VerticalText: Boolean read GetVerticalText write SetVerticalText; /// <summary> /// Text rotation /// </summary> property Rotate: TZCellTextRotate read GetRotate write SetRotate; /// <summary> /// Number format /// </summary> property NumberFormat: string read GetNumberFormat write SetNumberFormat; procedure SetBorderAround(borderWidth: Byte; BorderColor: TColor = TColorRec.Black; BorderStyle: TZBorderType = TZBorderType.ZEContinuous); end; /// <summary> /// Border's style. /// </summary> TZBorderStyle = class(TPersistent) private FLineStyle: TZBorderType; FWeight: Byte; FColor: TZExcelColor; procedure SetLineStyle(const Value: TZBorderType); procedure SetWeight(const Value: Byte); procedure SetColor(const Value: TColor); function GetColor: TColor; public constructor Create(); virtual; procedure Assign(Source: TPersistent); override; /// <returns> /// True, when border equal to Source. /// </returns> function IsEqual(Source: TPersistent): Boolean; virtual; /// <summary> /// Line style. /// </summary> property LineStyle: TZBorderType read FLineStyle write SetLineStyle default ZENone; /// <summary> /// Specifies the thickness of this border (0-3). /// </summary> property Weight: Byte read FWeight write SetWeight default 0; /// <summary> /// Specifies the color of this border. /// </summary> property Color: TColor read GetColor write SetColor; /// <summary> /// Specifies the inner color strucure of this border. /// </summary> property ExcelColor: TZExcelColor read FColor write FColor; end; /// <summary> /// Borders of cell. /// </summary> TZBorder = class(TPersistent) private FBorder: array [0 .. 5] of TZBorderStyle; procedure SetBorder(num: TZBordersPos; Const Value: TZBorderStyle); function GetBorder(num: TZBordersPos): TZBorderStyle; public constructor Create(); virtual; destructor Destroy(); override; procedure Assign(Source: TPersistent); override; /// <summary> /// Set border by border position. /// </summary> property Border[num: TZBordersPos]: TZBorderStyle read GetBorder write SetBorder; default; /// <returns> /// True when borders equal Source. /// </returns> function IsEqual(Source: TPersistent): Boolean; virtual; /// <summary> /// Left border. /// </summary> property left: TZBorderStyle index bpLeft read GetBorder write SetBorder; /// <summary> /// Top border. /// </summary> property Top: TZBorderStyle index bpTop read GetBorder write SetBorder; /// <summary> /// Right border. /// </summary> property right: TZBorderStyle index bpRight read GetBorder write SetBorder; /// <summary> /// Bottom border. /// </summary> property Bottom: TZBorderStyle index bpBottom read GetBorder write SetBorder; /// <summary> /// Diagonal from upper left to lower right. /// </summary> property DiagonalLeft: TZBorderStyle index bpDiagonalLeft read GetBorder write SetBorder; /// <summary> /// Diagonal from lower left to upper right. /// </summary> property DiagonalRight: TZBorderStyle index bpDiagonalRight read GetBorder write SetBorder; end; /// <summary> /// Specifies how text is aligned within the cell. /// </summary> TZAlignment = class(TPersistent) private FHorizontal: TZHorizontalAlignment; FVertical: TZVerticalAlignment; FIndent: Integer; FRotate: TZCellTextRotate; FWrapText: Boolean; FShrinkToFit: Boolean; FVerticalText: Boolean; procedure SetHorizontal(const Value: TZHorizontalAlignment); procedure SetIndent(const Value: Integer); procedure SetRotate(const Value: TZCellTextRotate); procedure SetShrinkToFit(const Value: Boolean); procedure SetVertical(const Value: TZVerticalAlignment); procedure SetVerticalText(const Value: Boolean); procedure SetWrapText(const Value: Boolean); public constructor Create(); virtual; procedure Assign(Source: TPersistent); override; /// <returns> /// True when all properties equal to Source's properties. /// </returns> function IsEqual(Source: TPersistent): Boolean; virtual; /// <summary> /// Specifies how text is aligned by horizontally within the cell. /// </summary> property Horizontal: TZHorizontalAlignment read FHorizontal write SetHorizontal default ZHAutomatic; /// <summary> /// Specifies how far the cell's text is indented. /// </summary> property Indent: Integer read FIndent write SetIndent default 0; /// <summary> /// Specifies the rotation of the text within the cell (from -90 to 90). /// </summary> property Rotate: TZCellTextRotate read FRotate write SetRotate; /// <summary> /// If True then the text size will shrunk so to all of the text fits within the cell. /// </summary> property ShrinkToFit: Boolean read FShrinkToFit write SetShrinkToFit default false; /// <summary> /// Specifies how text is aligned by vertically within the cell. /// </summary> property Vertical: TZVerticalAlignment read FVertical write SetVertical default ZVAutomatic; /// <summary> /// If True each letter is drawn horizontally, one above the other. /// </summary> property VerticalText: Boolean read FVerticalText write SetVerticalText default false; /// <summary> /// Specifies whether the text in cell should wrap at the cell boundary. /// </summary> property WrapText: Boolean read FWrapText write SetWrapText default false; end; /// <summary> /// Excel Font - https://docs.microsoft.com/ru-ru/office/vba/api/excel.font(object) /// </summary> TZFont = class(TPersistent) private // todo: double underLine FColor: TZExcelColor; FSize: Double; FCharset: TFontCharset; FName: TFontName; FStyle: TFontStyles; function GetColor: TColor; procedure SetColor(const Value: TColor); public constructor Create; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure AssignTo(Dest: TPersistent); override; function GetHashCode(): Integer; override; property Color: TColor read GetColor write SetColor; property Size: Double read FSize write FSize; property Charset: TFontCharset read FCharset write FCharset; property Name: TFontName read FName write FName; property Style: TFontStyles read FStyle write FStyle; property ExcelColor: TZExcelColor read FColor write FColor; end; /// <summary> /// Cell style. /// </summary> TZStyle = class(TPersistent) private FBorder: TZBorder; FAlignment: TZAlignment; FFont: TZFont; FBGColor: TZExcelColor; FPatternColor: TColor; FCellPattern: TZCellPattern; FNumberFormatId: Integer; FNumberFormat: string; FProtect: Boolean; FHideFormula: Boolean; FSuperscript: Boolean; FSubscript: Boolean; procedure SetFont(const Value: TZFont); procedure SetBorder(const Value: TZBorder); procedure SetAlignment(const Value: TZAlignment); procedure SetBgColor(const Value: TColor); procedure SetPatternColor(const Value: TColor); procedure SetCellPattern(const Value: TZCellPattern); procedure SetSuperscript(const Value: Boolean); procedure SetSubscript(const Value: Boolean); function GetBgColor: TColor; protected procedure SetNumberFormat(const Value: string); virtual; public constructor Create(); virtual; destructor Destroy(); override; procedure Assign(Source: TPersistent); override; /// <summary> /// True when style equal Source. /// </summary> function IsEqual(Source: TPersistent): Boolean; virtual; /// <summary> /// Cell font. /// </summary> property Font: TZFont read FFont write SetFont; /// <summary> /// Cell borders. /// </summary> property Border: TZBorder read FBorder write SetBorder; /// <summary> /// Specifies how text is aligned within the cell. /// </summary> property Alignment: TZAlignment read FAlignment write SetAlignment; /// <summary> /// Background color of the cell. <br />clWindow by default. /// </summary> property BgColor: TColor read GetBgColor write SetBgColor; /// <summary> /// Background color of the cell. <br />clWindow by default. /// </summary> property BGExcelColor: TZExcelColor read FBGColor write FBGColor; /// <summary> /// Color of fill pattern. <br />clWindow by default. /// </summary> property PatternColor: TColor read FPatternColor write SetPatternColor default TColorRec.cWINDOW; /// <summary> /// Indicates whether or not this cell is protected. <br />True by default. /// </summary> property Protect: Boolean read FProtect write FProtect default true; /// <summary> /// Indicates whether or not this cell's formula should be hidden when sheet protection is enabled. <br />False by default. /// </summary> property HideFormula: Boolean read FHideFormula write FHideFormula default false; /// <summary> /// Indicates whether or not the text is slightly above the baseline. <br />False by default. /// </summary> property Superscript: Boolean read FSuperscript write SetSuperscript default false; /// <summary> /// Indicates whether or not the text is slightly below the baseline. <br />False by default. /// </summary> property Subscript: Boolean read FSubscript write SetSubscript default false; /// <summary> /// Fill pattern of the cell. <br />ZPNone by default. /// </summary> property CellPattern: TZCellPattern read FCellPattern write SetCellPattern default ZPNone; /// <summary> /// Defines the number format that should be in cells referencing this style. /// </summary> property NumberFormat: string read FNumberFormat write SetNumberFormat; property NumberFormatId: Integer read FNumberFormatId write FNumberFormatId default -1; end; /// <summary> /// Contains styles of the document. /// </summary> TZStyles = class(TPersistent) private FDefaultStyle: TZStyle; FStyles: array of TZStyle; FCount: Integer; procedure SetDefaultStyle(const Value: TZStyle); function GetStyle(num: Integer): TZStyle; procedure SetStyle(num: Integer; const Value: TZStyle); procedure SetCount(const Value: Integer); public constructor Create(); virtual; destructor Destroy(); override; procedure Assign(Source: TPersistent); override; /// <summary> /// Add a Style. /// </summary> /// <param name="Style"> /// Style. /// </param> /// <param name="CheckMatch"> /// Checks the coincidence of this style with introduced in earlier styles. /// <br />Return number of added (or, if CheckMatch = True, previously introduced) style. /// </param> function Add(const Style: TZStyle; CheckMatch: Boolean = false): Integer; /// <summary> /// Delete all styles. /// </summary> procedure Clear(); virtual; /// <summary> /// Delete style num, styles with a larger number are shifting. /// </summary> /// <param name="num"> /// Style number /// </param> /// <returns> /// Return: 0 - if successfully deleted, -1 - can not delete style /// </returns> function DeleteStyle(num: Integer): Integer; virtual; /// <summary> /// Find number to match the Style introduced in earlier styles. /// </summary> /// <param name="Style"> /// Style. /// </param> /// <returns> /// Return: -2 - if style not found, -1 - if style = DefaultStyle, 0..Count-1 - Style /// </returns> function Find(const Style: TZStyle): Integer; /// <summary> /// Style num (-1 - DefaultStyle). /// </summary> property Items[num: Integer]: TZStyle read GetStyle write SetStyle; default; /// <summary> /// Count styles in the document. /// </summary> property Count: Integer read FCount write SetCount; /// <summary> /// Default style ( = Items[-1]). /// </summary> property DefaultStyle: TZStyle read FDefaultStyle write SetDefaultStyle; end; TZMergeArea = record left, Top, right, Bottom: Integer; constructor Create(ALeft, ATop, ARight, ABottom: Integer); end; /// <summary> /// Merged cells /// </summary> TZMergeCells = class private FSheet: TZSheet; FCount: Integer; FMergeArea: TArray<TZMergeArea>; function GetItem(num: Integer): TZMergeArea; procedure SetItem(num: Integer; const rect: TZMergeArea); public constructor Create(ASheet: TZSheet); virtual; destructor Destroy(); override; /// <summary> /// Adds a merged cell enclosed into rectangle. /// </summary> function AddRect(Rct: TZMergeArea): Byte; /// <summary> /// Adds a merged cell enclosed into rectangle /// </summary> function AddRectXY(left, Top, right, Bottom: Integer): Byte; /// <summary> /// Delete merged cell num. <br />Return True if the cell is successfully deleted. /// </summary> function DeleteItem(num: Integer): Boolean; /// <summary> /// Returns the number of merged cell, in which the cell [ACol, ARow] is top left. /// If returns a negative value - there is no such area. /// </summary> function InLeftTopCorner(ACol, ARow: Integer): Integer; /// <summary> /// Returns the number of merged cell that includes cell [ACol, ARow]. /// If returns a negative value - cell [ACol, ARow] is not contained in the Merged area. /// </summary> function InMergeRange(ACol, ARow: Integer): Integer; /// <summary> /// True if region cross with merged cells. /// </summary> function IsCrossWithArea(AID, AC1, AR1, AC2, AR2: Integer): Boolean; /// <summary> /// Rows count in merged region. /// </summary> function MergedRows(ACol, ARow: Integer): Integer; /// <summary> /// Columns count in merged region. /// </summary> function MergedCols(ACol, ARow: Integer): Integer; /// <summary> /// Removes all merged cells. /// </summary> procedure Clear(); /// <summary> /// Merged regions count. /// </summary> property Count: Integer read FCount; /// <summary> /// Current merged region. /// </summary> property Items[num: Integer]: TZMergeArea read GetItem write SetItem; default; end; TZCellColumn = array of TZCell; TZWorkBook = class; /// <summary> /// Common options for columns and rows. Ancestor for TZColOptions and TZRowOptions. /// </summary> TZRowColOptions = class(TPersistent) private FSheet: TZSheet; FHidden: Boolean; FStyleID: Integer; FSize: Real; FAuto: Boolean; FBreaked: Boolean; FOutlineLevel: Integer; protected function GetAuto(): Boolean; procedure SetAuto(Value: Boolean); function GetSizePoint(): Real; procedure SetSizePoint(Value: Real); function GetSizeMM(): Real; procedure SetSizeMM(Value: Real); function GetSizePix(): Integer; virtual; abstract; procedure SetSizePix(Value: Integer); virtual; abstract; public constructor Create(ASheet: TZSheet); virtual; procedure Assign(Source: TPersistent); override; /// <summary> /// True specifies that column or row is hidden. <br />False (not hidden) by default. /// </summary> property Hidden: Boolean read FHidden write FHidden default false; /// <summary> /// Specifies a style for column or row. <br />-1 by default. /// </summary> property StyleID: Integer read FStyleID write FStyleID default -1; /// <summary> /// Page break after column or row. <br />False (no break) by default. /// </summary> property Breaked: Boolean read FBreaked write FBreaked default false; property OutlineLevel: Integer read FOutlineLevel write FOutlineLevel; end; /// <summary> /// Column options. /// </summary> TZColOptions = class(TZRowColOptions) protected function GetSizePix(): Integer; override; procedure SetSizePix(Value: Integer); override; public constructor Create(ASheet: TZSheet); override; /// <summary> /// If True, it means that this column should be autosized. /// </summary> property AutoFitWidth: Boolean read GetAuto write SetAuto; /// <summary> /// Column width in points. /// </summary> property Width: Real read GetSizePoint write SetSizePoint; /// <summary> /// Column width in mm. /// </summary> property WidthMM: Real read GetSizeMM write SetSizeMM; /// <summary> /// Column width in pixels. /// </summary> property WidthPix: Integer read GetSizePix write SetSizePix; end; /// <summary> /// Row options. /// </summary> TZRowOptions = class(TZRowColOptions) protected function GetSizePix(): Integer; override; procedure SetSizePix(Value: Integer); override; public constructor Create(ASheet: TZSheet); override; /// <summary> /// If True, it means that this row should be autosized. /// </summary> property AutoFitHeight: Boolean read GetAuto write SetAuto; /// <summary> /// Row height in points (1 point = 1/72" = 0.3528 mm). /// </summary> property Height: Real read GetSizePoint write SetSizePoint; /// <summary> /// Row height in mm. /// </summary> property HeightMM: Real read GetSizeMM write SetSizeMM; /// <summary> /// Row height in pixels. /// </summary> property HeightPix: Integer read GetSizePix write SetSizePix; end; /// <summary> /// Repeating columns or rows when printing the sheet /// </summary> TZSheetPrintTitles = class(TPersistent) private FOwner: TZSheet; FColumns: Boolean; FActive: Boolean; FTill: word; FFrom: word; procedure SetActive(const Value: Boolean); procedure SetFrom(const Value: word); procedure SetTill(const Value: word); function Valid(const AFrom, ATill: word): Boolean; procedure RequireValid(const AFrom, ATill: word); public procedure Assign(Source: TPersistent); override; constructor Create(const owner: TZSheet; const ForColumns: Boolean); function ToString: string; override; property From: word read FFrom write SetFrom; property Till: word read FTill write SetTill; property Active: Boolean read FActive write SetActive; end; /// <summary> /// Footer or header margins. /// </summary> TZHeaderFooterMargins = class(TPersistent) private FMarginTopBottom: word; // Bottom or top margin FMarginLeft: word; FMarginRight: word; FHeight: word; FUseAutoFitHeight: Boolean; // If true then in LibreOffice Calc // in window "Page style settings" on tabs "Header" or "Footer" // check box "AutoFit height" will be checked. public constructor Create(); procedure Assign(Source: TPersistent); override; function IsEqual(Source: TPersistent): Boolean; virtual; /// <summary> /// Bottom / top margin of the footer / header in mm. <br />13 by default. /// </summary> property MarginTopBottom: word read FMarginTopBottom write FMarginTopBottom default 13; /// <summary> /// Left margin in mm. <br />0 by default. /// </summary> property MarginLeft: word read FMarginLeft write FMarginLeft default 0; /// <summary> /// Right margin in mm. <br />0 by default. /// </summary> property MarginRight: word read FMarginRight write FMarginRight default 0; /// <summary> /// Height of footer / header in mm. <br />7 by default. /// </summary> property Height: word read FHeight write FHeight default 7; /// <summary> /// Automatically fit height. <br />true by default. /// </summary> property UseAutoFitHeight: Boolean read FUseAutoFitHeight write FUseAutoFitHeight default true; end; /// <summary> /// Inherited from TPersistent. Sheet options. /// </summary> TZSheetOptions = class(TPersistent) private FActiveCol: word; FActiveRow: word; FMarginBottom: word; FMarginLeft: word; FMarginTop: word; FMarginRight: word; FHeaderMargins: TZHeaderFooterMargins; FFooterMargins: TZHeaderFooterMargins; FPortraitOrientation: Boolean; FCenterHorizontal: Boolean; FCenterVertical: Boolean; FStartPageNumber: Integer; FDifferentOddEven: Boolean; FDifferentFirst: Boolean; FHeader: string; // Header for all pages. When IsEvenFooterEqual = false - only for odd pages. FFooter: string; // Footer for all pages. When IsEvenFooterEqual = false - only for odd pages. FEvenHeader: string; // Header for even pages. Used only if IsEvenFooterEqual = false FEvenFooter: string; // Footer for even pages. Used only if IsEvenFooterEqual = false FFirstPageHeader: string; FFirstPageFooter: string; FHeaderBGColor: TColor; FFooterBGColor: TColor; FScaleToPercent: Integer; // Document must be scaled to percentage value (100 - no scale) FScaleToPages: Integer; // Document scaled to fit a number of pages (1 - no scale) FPaperSize: Byte; FPaperWidth: Integer; FPaperHeight: Integer; FFitToHeight: Integer; // Number of vertical pages to fit on FFitToWidth: Integer; // Number of horizontal pages to fit on FSplitVerticalMode: TZSplitMode; FSplitHorizontalMode: TZSplitMode; FSplitVerticalValue: Integer; // Вроде можно вводить отрицательные FSplitHorizontalValue: Integer; // Измеряться будут: // в пикселях, если SplitMode = ZSplitSplit // в кол-ве строк/столбцов, если SplitMode = ZSplitFrozen // Если SplitMode = ZSplitNone, то фиксация столбцов/ячеек не работает function GetHeaderMargin(): word; procedure SetHeaderMargin(Value: word); function GetFooterMargin(): word; procedure SetFooterMargin(Value: word); public constructor Create(); virtual; destructor Destroy(); override; procedure Assign(Source: TPersistent); override; /// <summary> /// Column number with active cell. <br />0 by default. /// </summary> property ActiveCol: word read FActiveCol write FActiveCol default 0; /// <summary> /// Row number with active cell. <br />0 by default. /// </summary> property ActiveRow: word read FActiveRow write FActiveRow default 0; /// <summary> /// Specifies the bottom margin on the page in millimeters. <br />25 mm by default. /// </summary> property MarginBottom: word read FMarginBottom write FMarginBottom default 25; /// <summary> /// Specifies the left margin on the page in millimeters 19mm (1.9sm) by default. /// </summary> property MarginLeft: word read FMarginLeft write FMarginLeft default 19; /// <summary> /// Specifies the top margin on the page in millimeters. <br />25 mm by default. /// </summary> property MarginTop: word read FMarginTop write FMarginTop default 25; /// <summary> /// Specifies the right margin on the page in millimeters. <br />20 mm by default. /// </summary> property MarginRight: word read FMarginRight write FMarginRight default 20; /// <summary> /// Paper Size (Paper size table). <br />9 (A4) by default. /// </summary> property PaperSize: Byte read FPaperSize write FPaperSize default 9; /// <summary> /// Paper width in mm. Used only when PaperSize = 0! /// </summary> property PaperWidth: Integer read FPaperWidth write FPaperWidth default 0; /// <summary> /// Paper height in mm. Used only when PaperSize = 0! /// </summary> property PaperHeight: Integer read FPaperHeight write FPaperHeight default 0; property FitToHeight: Integer read FFitToHeight write FFitToHeight default -1; property FitToWidth: Integer read FFitToWidth write FFitToWidth default -1; /// <summary> /// Specifies the orientation of the page (True - Portrait, False - Landscape). <br />True by default. /// </summary> property PortraitOrientation: Boolean read FPortraitOrientation write FPortraitOrientation default true; /// <summary> /// If True, the document should be centered horizontally on the page. <br />False by default. /// </summary> property CenterHorizontal: Boolean read FCenterHorizontal write FCenterHorizontal default false; /// <summary> /// If True, the document should be centered vertically on the page. <br />False by default. /// </summary> property CenterVertical: Boolean read FCenterVertical write FCenterVertical default false; /// <summary> /// Specifies the starting page number for print. <br />1 by default. /// </summary> property StartPageNumber: Integer read FStartPageNumber write FStartPageNumber default 1; /// <summary> /// The size of header in millimeters. <br />13 mm by default. <br /> /// </summary> /// <remarks> /// deprecated 'Use HeaderMargins.Height!' /// </remarks> property HeaderMargin: word read GetHeaderMargin write SetHeaderMargin default 13; // deprecated! /// <summary> /// The size of footer in millimeters. <br />13 mm by default. <br /> /// </summary> /// <remarks> /// deprecated 'Use FooterMargins.Height!' /// </remarks> property FooterMargin: word read GetFooterMargin write SetFooterMargin default 13; // deprecated! /// <summary> /// Sizes and margins for header in mm. /// </summary> property HeaderMargins: TZHeaderFooterMargins read FHeaderMargins; /// <summary> /// Sizes and margins for footer in mm. /// </summary> property FooterMargins: TZHeaderFooterMargins read FFooterMargins; /// <summary> /// /// </summary> property IsDifferentFirst: Boolean read FDifferentFirst write FDifferentFirst; /// <summary> /// /// </summary> property IsDifferentOddEven: Boolean read FDifferentOddEven write FDifferentOddEven; property Header: string read FHeader write FHeader; property Footer: string read FFooter write FFooter; property EvenHeader: string read FEvenHeader write FEvenHeader; property EvenFooter: string read FEvenFooter write FEvenFooter; property FirstPageHeader: string read FFirstPageHeader write FFirstPageHeader; property FirstPageFooter: string read FFirstPageFooter write FFirstPageFooter; /// <summary> /// Background color for header. <br />clWindow by default. /// </summary> property HeaderBGColor: TColor read FHeaderBGColor write FHeaderBGColor default TColorRec.cWINDOW; /// <summary> /// Background color for footer. <br />clWindow by default. /// </summary> property FooterBGColor: TColor read FFooterBGColor write FFooterBGColor default TColorRec.cWINDOW; /// <summary> /// Document must be scaled to percentage value (100 - no scale). <br />100 by default. /// </summary> property ScaleToPercent: Integer read FScaleToPercent write FScaleToPercent default 100; /// <summary> /// Document scaled to fit a number of pages (1 - no scale). <br />1 by default. /// </summary> property ScaleToPages: Integer read FScaleToPages write FScaleToPages default 1; /// <summary> /// Vertical columns split/freeze mode. /// Does the same thing as LibreOffice Calc commands "Window - Freeze"/ "Window - Split" <br />ZSplitNone by default. /// </summary> property SplitVerticalMode: TZSplitMode read FSplitVerticalMode write FSplitVerticalMode default ZSplitNone; /// <summary> /// Horizontal rows split/freeze mode. <br />ZSplitNone by default. /// </summary> property SplitHorizontalMode: TZSplitMode read FSplitHorizontalMode write FSplitHorizontalMode default ZSplitNone; /// <summary> /// If SplitVerticalMode = ZSplitFrozen then count of column for freeze. /// If SplitVerticalMode = ZSplitSplit then size in pixels. <br />0 by default. /// </summary> property SplitVerticalValue: Integer read FSplitVerticalValue write FSplitVerticalValue; /// <summary> /// If SplitHorizontalMode = ZSplitFrozen then count of rows for freeze. /// If SplitHorizontalMode = ZSplitSplit then size if pixels. <br />0 by default. /// </summary> property SplitHorizontalValue: Integer read FSplitHorizontalValue write FSplitHorizontalValue; end; /// <summary> /// Conditions /// </summary> TZCondition = (ZCFIsTrueFormula, ZCFCellContentIsBetween, ZCFCellContentIsNotBetween, ZCFCellContentOperator, ZCFNumberValue, ZCFString, ZCFBoolTrue, ZCFBoolFalse, ZCFFormula, ZCFContainsText, ZCFNotContainsText, ZCFBeginsWithText, ZCFEndsWithText, ZCFCellIsEmpty, ZCFDuplicate, ZCFUnique, ZCFAboveAverage, ZCFBellowAverage, ZCFAboveEqualAverage, ZCFBelowEqualAverage, ZCFTopElements, ZCFBottomElements, ZCFTopPercent, ZCFBottomPercent, ZCFIsError, ZCFIsNoError); // Оператор для условного форматирования TZConditionalOperator = (ZCFOpGT, // > (Greater Than) ZCFOpLT, // < (Less Than) ZCFOpGTE, // >= (Greater or Equal) ZCFOpLTE, // <= (Less or Equal) ZCFOpEqual, // = (Equal) ZCFOpNotEqual // <> (Not Equal) ); /// <summary> /// Conditional formatting /// </summary> TZConditionalStyleItem = class(TPersistent) private FCondition: TZCondition; // условие FConditionOperator: TZConditionalOperator; // Оператор FValue1: String; FValue2: String; FApplyStyleID: Integer; // номер применяемого стиля // Базовая ячейка (только для формул): FBaseCellPageIndex: Integer; // Номер страницы для адреса базовой ячейки // -1 - текущая страница FBaseCellRowIndex: Integer; // Номер строки FBaseCellColumnIndex: Integer; // Номер столбца public constructor Create(); virtual; procedure Clear(); procedure Assign(Source: TPersistent); override; function IsEqual(Source: TPersistent): Boolean; virtual; property ApplyStyleID: Integer read FApplyStyleID write FApplyStyleID; property BaseCellColumnIndex: Integer read FBaseCellColumnIndex write FBaseCellColumnIndex; property BaseCellPageIndex: Integer read FBaseCellPageIndex write FBaseCellPageIndex; property BaseCellRowIndex: Integer read FBaseCellRowIndex write FBaseCellRowIndex; property Condition: TZCondition read FCondition write FCondition; property ConditionOperator: TZConditionalOperator read FConditionOperator write FConditionOperator; property Value1: String read FValue1 write FValue1; property Value2: String read FValue2 write FValue2; end; /// <summary> /// Conditional formatting area /// </summary> TZConditionalAreaItem = class(TPersistent) private FRow: Integer; FColumn: Integer; FWidth: Integer; FHeight: Integer; procedure SetRow(Value: Integer); procedure SetColumn(Value: Integer); procedure SetWidth(Value: Integer); procedure SetHeight(Value: Integer); public constructor Create(); overload; virtual; constructor Create(ColumnNum, RowNum, AreaWidth, AreaHeight: Integer); overload; virtual; procedure Assign(Source: TPersistent); override; function IsEqual(Source: TPersistent): Boolean; virtual; property Row: Integer read FRow write SetRow; property Column: Integer read FColumn write SetColumn; property Width: Integer read FWidth write SetWidth; property Height: Integer read FHeight write SetHeight; end; // Области для применения условного форматирования TZConditionalAreas = class(TPersistent) private FCount: Integer; FItems: array of TZConditionalAreaItem; procedure SetCount(Value: Integer); function GetItem(num: Integer): TZConditionalAreaItem; procedure SetItem(num: Integer; Value: TZConditionalAreaItem); public constructor Create(); virtual; destructor Destroy(); override; function Add(): TZConditionalAreaItem; overload; function Add(ColumnNum, RowNum, AreaWidth, AreaHeight: Integer): TZConditionalAreaItem; overload; procedure Assign(Source: TPersistent); override; procedure Delete(num: Integer); function IsCellInArea(ColumnNum, RowNum: Integer): Boolean; function IsEqual(Source: TPersistent): Boolean; virtual; property Count: Integer read FCount write SetCount; property Items[num: Integer]: TZConditionalAreaItem read GetItem write SetItem; default; end; // Условное форматирование: список условий TZConditionalStyle = class(TPersistent) private FCount: Integer; // кол-во условий FMaxCount: Integer; FAreas: TZConditionalAreas; FConditions: array of TZConditionalStyleItem; function GetItem(num: Integer): TZConditionalStyleItem; procedure SetItem(num: Integer; Value: TZConditionalStyleItem); procedure SetCount(Value: Integer); procedure SetAreas(Value: TZConditionalAreas); public constructor Create(); virtual; destructor Destroy(); override; function Add(): TZConditionalStyleItem; overload; function Add(StyleItem: TZConditionalStyleItem): TZConditionalStyleItem; overload; procedure Delete(num: Integer); procedure Insert(num: Integer); overload; procedure Insert(num: Integer; StyleItem: TZConditionalStyleItem); overload; procedure Assign(Source: TPersistent); override; function IsEqual(Source: TPersistent): Boolean; virtual; property Areas: TZConditionalAreas read FAreas write SetAreas; property Count: Integer read FCount write SetCount; property Items[num: Integer]: TZConditionalStyleItem read GetItem write SetItem; default; end; TZConditionalFormatting = class(TPersistent) private FStyles: array of TZConditionalStyle; FCount: Integer; procedure SetCount(Value: Integer); function GetItem(num: Integer): TZConditionalStyle; procedure SetItem(num: Integer; Value: TZConditionalStyle); public constructor Create(); virtual; destructor Destroy(); override; function Add(): TZConditionalStyle; overload; function Add(Style: TZConditionalStyle): TZConditionalStyle; overload; function Add(ColumnNum, RowNum, AreaWidth, AreaHeight: Integer): TZConditionalStyle; overload; procedure Clear(); function Delete(num: Integer): Boolean; procedure Assign(Source: TPersistent); override; function IsEqual(Source: TPersistent): Boolean; virtual; property Count: Integer read FCount write SetCount; property Items[num: Integer]: TZConditionalStyle read GetItem write SetItem; default; end; // Transformations that can applied to a chart/image. TZETransform = class(TPersistent) private FRotate: Double; FScaleX: Double; FScaleY: Double; FSkewX: Double; FSkewY: Double; FTranslateX: Double; FTranslateY: Double; public constructor Create(); procedure Assign(Source: TPersistent); override; function IsEqual(const Source: TPersistent): Boolean; procedure Clear(); published property Rotate: Double read FRotate write FRotate; property ScaleX: Double read FScaleX write FScaleX; property ScaleY: Double read FScaleY write FScaleY; property SkewX: Double read FSkewX write FSkewX; property SkewY: Double read FSkewY write FSkewY; property TranslateX: Double read FTranslateX write FTranslateX; property TranslateY: Double read FTranslateY write FTranslateY; end; // Common frame ancestor for Charts and Images TZECommonFrameAncestor = class(TPersistent) private FX: Integer; FY: Integer; FWidth: Integer; FHeight: Integer; FTransform: TZETransform; protected procedure SetX(Value: Integer); virtual; procedure SetY(Value: Integer); virtual; procedure SetWidth(Value: Integer); virtual; procedure SetHeight(Value: Integer); virtual; procedure SetTransform(const Value: TZETransform); virtual; public constructor Create(); overload; virtual; constructor Create(AX, AY, AWidth, AHeight: Integer); overload; virtual; destructor Destroy(); override; procedure Assign(Source: TPersistent); override; function IsEqual(const Source: TPersistent): Boolean; virtual; property X: Integer read FX write SetX default 0; property Y: Integer read FY write SetY default 0; property Width: Integer read FWidth write SetWidth default 10; property Height: Integer read FHeight write SetHeight default 10; property Transform: TZETransform read FTransform write SetTransform; end; // Possible chart types TZEChartType = (ZEChartTypeArea, ZEChartTypeBar, ZEChartTypeBubble, ZEChartTypeCircle, ZEChartTypeGantt, ZEChartTypeLine, ZEChartTypeRadar, ZEChartTypeRing, ZEChartTypeScatter, ZEChartTypeStock, ZEChartTypeSurface); // Specifies the rendering of bars for 3D bar charts TZEChartSolidType = (ZEChartSolidTypeCone, ZEChartSolidTypeCuboid, ZEChartSolidTypeCylinder, ZEChartSolidTypePyramid); // Type of symbols for a data point in a chart TZEChartSymbolType = (ZEChartSymbolTypeNone, // No symbol should be used ZEChartSymbolTypeAutomatic, // Auto select from TZEChartSymbol ZEChartSymbolTypeNamedSymbol // Use selected from TZEChartSymbol // ZEChartSymbolTypeImage //not for now ); // Symbol to be used for a data point in a chart, used only for chart type = ZEChartSymbolTypeNamedSymbol TZEChartSymbol = (ZEChartSymbolArrowDown, ZEChartSymbolArrowUp, ZEChartSymbolArrowRight, ZEChartSymbolArrowLeft, ZEChartSymbolAsterisk, ZEChartSymbolCircle, ZEChartSymbolBowTie, ZEChartSymbolDiamond, ZEChartSymbolHorizontalBar, ZEChartSymbolHourglass, ZEChartSymbolPlus, ZEChartSymbolStar, ZEChartSymbolSquare, ZEChartSymbolX, ZEChartSymbolVerticalBar); // Position of Legend in chart TZEChartLegendPosition = (ZELegendBottom, // Legend below the plot area ZELegendEnd, // Legend on the right side of the plot area ZELegendStart, // Legend on the left side of the plot area ZELegendTop, // Legend above the plot area ZELegendBottomEnd, // Legend in the bottom right corner of the plot area ZELegendBottomStart, // Legend in the bottom left corner ZELegendTopEnd, // Legend in the top right corner ZELegendTopStart // Legend in the top left corner ); // Alignment of a legend TZELegendAlign = (ZELegengAlignStart, // Legend aligned at the beginning of a plot area (left or top) ZELegendAlignCenter, // Legend aligned at the center of a plot area ZELegendAlignEnd // Legend aligned at the end of a plot area (right or bottom) ); // Range item TZEChartRangeItem = class(TPersistent) private FSheetNum: Integer; FCol: Integer; FRow: Integer; FWidth: Integer; FHeight: Integer; public constructor Create(); overload; constructor Create(ASheetNum: Integer; ACol, ARow, AWidth, AHeight: Integer); overload; procedure Assign(Source: TPersistent); override; function IsEqual(const Source: TPersistent): Boolean; virtual; published property SheetNum: Integer read FSheetNum write FSheetNum; property Col: Integer read FCol write FCol; property Row: Integer read FRow write FRow; property Width: Integer read FWidth write FWidth; property Height: Integer read FHeight write FHeight; end; // Store for Range items TZEChartRange = class(TPersistent) private FItems: array of TZEChartRangeItem; FCount: Integer; protected function GetItem(num: Integer): TZEChartRangeItem; procedure SetItem(num: Integer; const Value: TZEChartRangeItem); public constructor Create(); destructor Destroy(); override; function Add(): TZEChartRangeItem; overload; function Add(const ItemForClone: TZEChartRangeItem): TZEChartRangeItem; overload; function Delete(num: Integer): Boolean; procedure Clear(); procedure Assign(Source: TPersistent); override; function IsEqual(const Source: TPersistent): Boolean; virtual; property Items[num: Integer]: TZEChartRangeItem read GetItem write SetItem; default; property Count: Integer read FCount; end; // Title or Subtitle for chart, axis etc TZEChartTitleItem = class(TPersistent) private FText: string; FFont: TZFont; FRotationAngle: Integer; FIsDisplay: Boolean; protected procedure SetFont(const Value: TZFont); public constructor Create(); virtual; destructor Destroy(); override; procedure Assign(Source: TPersistent); override; function IsEqual(const Source: TPersistent): Boolean; virtual; property Text: string read FText write FText; property Font: TZFont read FFont write SetFont; property RotationAngle: Integer read FRotationAngle write FRotationAngle default 0; property IsDisplay: Boolean read FIsDisplay write FIsDisplay default true; end; // Chart legend TZEChartLegend = class(TZEChartTitleItem) private FPosition: TZEChartLegendPosition; FAlign: TZELegendAlign; public constructor Create(); override; procedure Assign(Source: TPersistent); override; function IsEqual(const Source: TPersistent): Boolean; override; property Position: TZEChartLegendPosition read FPosition write FPosition; property Align: TZELegendAlign read FAlign write FAlign; end; // Chart axis TZEChartAxis = class(TZEChartTitleItem) private FLogarithmic: Boolean; FReverseDirection: Boolean; FScaleMin: Double; FScaleMax: Double; FAutoScaleMin: Boolean; FAutoScaleMax: Boolean; public constructor Create(); override; procedure Assign(Source: TPersistent); override; function IsEqual(const Source: TPersistent): Boolean; override; property Logarithmic: Boolean read FLogarithmic write FLogarithmic default false; property ReverseDirection: Boolean read FReverseDirection write FReverseDirection default false; property ScaleMin: Double read FScaleMin write FScaleMin; property ScaleMax: Double read FScaleMax write FScaleMax; property AutoScaleMin: Boolean read FAutoScaleMin write FAutoScaleMin; property AutoScaleMax: Boolean read FAutoScaleMax write FAutoScaleMax; end; // Chart/series settings TZEChartSettings = class(TPersistent) private FJapanCandle: Boolean; public constructor Create(); destructor Destroy(); override; procedure Assign(Source: TPersistent); override; function IsEqual(const Source: TPersistent): Boolean; virtual; property JapanCandle: Boolean read FJapanCandle write FJapanCandle; // True - japanese candle. Used only for ZEChartTypeStock chart type. end; // Chart series TZEChartSeries = class(TPersistent) private FChartType: TZEChartType; FSeriesName: string; FSeriesNameSheet: Integer; FSeriesNameRow: Integer; FSeriesNameCol: Integer; FRanges: TZEChartRange; public constructor Create(); destructor Destroy(); override; procedure Assign(Source: TPersistent); override; function IsEqual(const Source: TPersistent): Boolean; virtual; // For each series it's own ChartType property ChartType: TZEChartType read FChartType write FChartType; // If (SeriesNameRow >= 0) and (SeriesNameCol >= 0) then // text for Series label will be from cell[SeriesNameCol, SeriesNameRow] and // from property SeriesName otherwise. property SeriesName: string read FSeriesName write FSeriesName; // If SeriesNameSheet < 0 then uses current sheet for Series label property SeriesNameSheet: Integer read FSeriesNameSheet write FSeriesNameSheet; property SeriesNameRow: Integer read FSeriesNameRow write FSeriesNameRow; property SeriesNameCol: Integer read FSeriesNameCol write FSeriesNameCol; property Ranges: TZEChartRange read FRanges; end; // Chart item TZEChart = class(TZECommonFrameAncestor) private FTitle: TZEChartTitleItem; FSubtitle: TZEChartTitleItem; FFooter: TZEChartTitleItem; FLegend: TZEChartLegend; FAxisX: TZEChartAxis; FAxisY: TZEChartAxis; FAxisZ: TZEChartAxis; FSecondaryAxisX: TZEChartAxis; FSecondaryAxisY: TZEChartAxis; FSecondaryAxisZ: TZEChartAxis; FDefaultChartType: TZEChartType; FView3D: Boolean; FViewDeep: Boolean; protected procedure SetTitle(const Value: TZEChartTitleItem); procedure SetSubtitle(const Value: TZEChartTitleItem); procedure SetFooter(const Value: TZEChartTitleItem); procedure SetLegend(const Value: TZEChartLegend); procedure CommonInit(); procedure SetAxisX(const Value: TZEChartAxis); procedure SetAxisY(const Value: TZEChartAxis); procedure SetAxisZ(const Value: TZEChartAxis); procedure SetSecondaryAxisX(const Value: TZEChartAxis); procedure SetSecondaryAxisY(const Value: TZEChartAxis); procedure SetSecondaryAxisZ(const Value: TZEChartAxis); public constructor Create(); overload; override; constructor Create(AX, AY, AWidth, AHeight: Integer); overload; override; destructor Destroy(); override; procedure Assign(Source: TPersistent); override; function IsEqual(const Source: TPersistent): Boolean; override; property AxisX: TZEChartAxis read FAxisX write SetAxisX; property AxisY: TZEChartAxis read FAxisY write SetAxisY; property AxisZ: TZEChartAxis read FAxisZ write SetAxisZ; property SecondaryAxisX: TZEChartAxis read FSecondaryAxisX write SetSecondaryAxisX; property SecondaryAxisY: TZEChartAxis read FSecondaryAxisY write SetSecondaryAxisY; property SecondaryAxisZ: TZEChartAxis read FSecondaryAxisZ write SetSecondaryAxisZ; property DefaultChartType: TZEChartType read FDefaultChartType write FDefaultChartType; property Title: TZEChartTitleItem read FTitle write SetTitle; property Subtitle: TZEChartTitleItem read FSubtitle write SetSubtitle; property Footer: TZEChartTitleItem read FFooter write SetFooter; property Legend: TZEChartLegend read FLegend write SetLegend; property View3D: Boolean read FView3D write FView3D; property ViewDeep: Boolean read FViewDeep write FViewDeep; end; // Store for charts on a sheet TZEChartStore = class(TPersistent) private FCount: Integer; FItems: array of TZEChart; protected function GetItem(num: Integer): TZEChart; procedure SetItem(num: Integer; const Value: TZEChart); public constructor Create(); destructor Destroy(); override; function Add(): TZEChart; overload; function Add(const ItemForClone: TZEChart): TZEChart; overload; function Delete(num: Integer): Boolean; procedure Clear(); procedure Assign(Source: TPersistent); override; function IsEqual(const Source: TPersistent): Boolean; virtual; property Items[num: Integer]: TZEChart read GetItem write SetItem; default; property Count: Integer read FCount; end; TZCellAnchor = (ZACell, ZAAbsolute); // Picture item TZEPicture = class(TZECommonFrameAncestor) private FId: Integer; FRelId: Integer; FFileName: string; FTitle: string; FDescription: string; FCellAnchor: TZCellAnchor; FRow: Integer; FCol: Integer; // FHidden: Boolean; FFromCol: Integer; FFromColOff: Integer; FFromRow: Integer; FFromRowOff: Integer; FToCol: Integer; FToColOff: Integer; FToRow: Integer; FToRowOff: Integer; FFrmOffX: Integer; FFrmOffY: Integer; FFrmExtCX: Integer; FFrmExtCY: Integer; FSheet: TZSheet; function GetImage: TBytes; procedure SetImage(const Value: TBytes); protected procedure CommonInit(); public constructor Create(ASheet: TZSheet); destructor Destroy(); override; procedure Assign(Source: TPersistent); override; function IsEqual(const Source: TPersistent): Boolean; override; // through workbook property Id: Integer read FId write FId; // through worksheet property RelId: Integer read FRelId write FRelId; property Name: string read FFileName write FFileName; property Title: string read FTitle write FTitle; property Description: string read FDescription write FDescription; property Row: Integer read FRow write FRow; property Col: Integer read FCol write FCol; property CellAnchor: TZCellAnchor read FCellAnchor write FCellAnchor; property FromCol: Integer read FFromCol write FFromCol; property FromColOff: Integer read FFromColOff write FFromColOff; property FromRow: Integer read FFromRow write FFromRow; property FromRowOff: Integer read FFromRowOff write FFromRowOff; property ToCol: Integer read FToCol write FToCol; property ToColOff: Integer read FToColOff write FToColOff; property ToRow: Integer read FToRow write FToRow; property ToRowOff: Integer read FToRowOff write FToRowOff; property FrmOffX: Integer read FFrmOffX write FFrmOffX; property FrmOffY: Integer read FFrmOffY write FFrmOffY; property FrmExtCX: Integer read FFrmExtCX write FFrmExtCX; property FrmExtCY: Integer read FFrmExtCY write FFrmExtCY; property Image: TBytes read GetImage write SetImage; end; { Store pictures for worksheet } TZEDrawing = class(TPersistent) private FId: Integer; FItems: TObjectList; FSheet: TZSheet; function GetIsEmpty(): Boolean; function GetCount(): Integer; function GetItem(idx: Integer): TZEPicture; procedure SetItem(idx: Integer; const Value: TZEPicture); public constructor Create(ASheet: TZSheet); destructor Destroy(); override; procedure Assign(Source: TPersistent); override; function Add(): TZEPicture; overload; function Add(ARow, ACol: Integer; APicture: TBytes): TZEPicture; overload; procedure Delete(idx: Integer); procedure Clear(); property Count: Integer read GetCount; property Id: Integer read FId write FId; property IsEmpty: Boolean read GetIsEmpty; property Items[idx: Integer]: TZEPicture read GetItem write SetItem; default; end; TZRange = class; IZRange = interface; /// <summary> /// Inherited from TPersistent. Contains a sheet of the document. /// </summary> TZSheet = class(TPersistent) private FStore: TZWorkBook; FCells: array of TZCellColumn; FRows: array of TZRowOptions; FColumns: array of TZColOptions; FAutoFilter: string; FTitle: string; FRowCount: Integer; FColCount: Integer; FTabColor: TColor; // цвет закладки FFitToPage: Boolean; FDefaultRowHeight: Real; FDefaultColWidth: Real; FMergeCells: TZMergeCells; FProtect: Boolean; FRightToLeft: Boolean; FSheetOptions: TZSheetOptions; FSelected: Boolean; FPrintRows, FPrintCols: TZSheetPrintTitles; FCharts: TZEChartStore; FDrawing: TZEDrawing; FViewMode: TZViewMode; FSummaryBelow: Boolean; FSummaryRight: Boolean; FApplyStyles: Boolean; FDrawingRid: Integer; FOutlineLevelRow: Integer; FOutlineLevelCol: Integer; FRowBreaks: TArray<Integer>; FColBreaks: TArray<Integer>; FConditionalFormatting: TZConditionalFormatting; procedure SetConditionalFormatting(Value: TZConditionalFormatting); procedure SetCharts(const Value: TZEChartStore); procedure SetColumn(num: Integer; const Value: TZColOptions); function GetColumn(num: Integer): TZColOptions; procedure SetRow(num: Integer; const Value: TZRowOptions); function GetRow(num: Integer): TZRowOptions; function GetSheetOptions(): TZSheetOptions; procedure SetSheetOptions(Value: TZSheetOptions); procedure SetPrintCols(const Value: TZSheetPrintTitles); procedure SetPrintRows(const Value: TZSheetPrintTitles); protected procedure SetColWidth(num: Integer; const Value: Real); virtual; function GetColWidth(num: Integer): Real; virtual; procedure SetRowHeight(num: Integer; const Value: Real); virtual; function GetRowHeight(num: Integer): Real; virtual; procedure SetDefaultColWidth(const Value: Real); virtual; procedure SetDefaultRowHeight(const Value: Real); virtual; function GetCell(ACol, ARow: Integer): TZCell; virtual; procedure SetCell(ACol, ARow: Integer; const Value: TZCell); virtual; function GetCellRef(ACol: string; ARow: Integer): TZCell; virtual; procedure SetCellRef(ACol: string; ARow: Integer; const Value: TZCell); virtual; function GetRowCount: Integer; virtual; procedure SetRowCount(const Value: Integer); virtual; function GetColCount: Integer; virtual; procedure SetColCount(const Value: Integer); virtual; function GetRange(AC1, AR1, AC2, AR2: Integer): IZRange; virtual; // procedure SetRange(AC1,AR1,AC2,AR2: integer; const Value: TZRange); virtual; function GetRangeRef(AFromCol: string; AFromRow: Integer; AToCol: string; AToRow: Integer): IZRange; virtual; // procedure SetRangeRef(AFrom, ATo: string; const Value: TZRange); virtual; function GetSheetIndex(): Integer; public constructor Create(AStore: TZWorkBook); virtual; destructor Destroy(); override; procedure Assign(Source: TPersistent); override; procedure Clear(); virtual; procedure InsertRows(ARow, ACount: Integer); procedure CopyRows(ARowDst, ARowSrc, ACount: Integer); procedure SetCorrectTitle(const Value: string); function ColsWidth(AFrom, ATo: Integer): Real; function RowsHeight(AFrom, ATo: Integer): Real; /// <summary> /// Get or set the width (in points) of column num in the sheet. /// </summary> property ColWidths[num: Integer]: Real read GetColWidth write SetColWidth; /// <summary> /// Options of column num. /// </summary> property Columns[num: Integer]: TZColOptions read GetColumn write SetColumn; /// <summary> /// Specifies various properties of the Row num. /// </summary> property Rows[num: Integer]: TZRowOptions read GetRow write SetRow; /// <summary> /// Specifies various properties of the Cells range. /// </summary> property Range[AC1, AR1, AC2, AR2: Integer]: IZRange read GetRange { write SetRange }; /// <summary> /// Specifies various properties of the Cells range. /// </summary> property RangeRef[AFromCol: string; AFromRow: Integer; AToCol: string; AToRow: Integer]: IZRange read GetRangeRef { write SetRangeRef }; /// <summary> /// Get or set the height (in points) of row num in the sheet. /// </summary> property RowHeights[num: Integer]: Real read GetRowHeight write SetRowHeight; /// <summary> /// Default column width. /// </summary> property DefaultColWidth: Real read FDefaultColWidth write SetDefaultColWidth; // default 48; /// <summary> /// Default row height. /// </summary> property DefaultRowHeight: Real read FDefaultRowHeight write SetDefaultRowHeight; // default 12.75; /// <summary> /// Cell at the intersection of column ACol and row ARow. /// </summary> property Cell[ACol, ARow: Integer]: TZCell read GetCell write SetCell; default; /// <summary> /// Cell at the intersection of column by "A1" reference. /// </summary> property CellRef[ACol: string; ARow: Integer]: TZCell read GetCellRef write SetCellRef; property AutoFilter: string read FAutoFilter write FAutoFilter; /// <summary> /// Indicates whether or not this sheet is protected. <br />False by default. /// </summary> property Protect: Boolean read FProtect write FProtect default false; property TabColor: TColor read FTabColor write FTabColor default TColorRec.cWINDOW; property FitToPage: Boolean read FFitToPage write FFitToPage default false; property SummaryBelow: Boolean read FSummaryBelow write FSummaryBelow; property SummaryRight: Boolean read FSummaryRight write FSummaryRight; property ApplyStyles: Boolean read FApplyStyles write FApplyStyles; property DrawingRid: Integer read FDrawingRid write FDrawingRid; property OutlineLevelRow: Integer read FOutlineLevelRow write FOutlineLevelRow; property OutlineLevelCol: Integer read FOutlineLevelCol write FOutlineLevelCol; /// <summary> /// Sheet title. /// </summary> property Title: string read FTitle write SetCorrectTitle; /// <summary> /// Sheet index in the workbook. /// </summary> property SheetIndex: Integer read GetSheetIndex; /// <summary> /// Specifies the number of rows in the sheet. /// </summary> property RowCount: Integer read GetRowCount write SetRowCount; /// <summary> /// If True, the window displays from right to left else window displays from left to right. <br />False by default. /// </summary> property RightToLeft: Boolean read FRightToLeft write FRightToLeft default false; /// <summary> /// Specifies the number of columns in the sheet. /// </summary> property ColCount: Integer read GetColCount write SetColCount; /// <summary> /// Merged cells. /// </summary> property MergeCells: TZMergeCells read FMergeCells write FMergeCells; /// <summary> /// Specifies various properties of the sheet. /// </summary> property SheetOptions: TZSheetOptions read GetSheetOptions write SetSheetOptions; /// <summary> /// Indicates whether or not this sheet is selecteded. /// </summary> property Selected: Boolean read FSelected write FSelected; property WorkBook: TZWorkBook read FStore; property RowsToRepeat: TZSheetPrintTitles read FPrintRows write SetPrintRows; property ColsToRepeat: TZSheetPrintTitles read FPrintCols write SetPrintCols; /// <summary> /// Conditional formatting for sheet. /// </summary> property ConditionalFormatting: TZConditionalFormatting read FConditionalFormatting write SetConditionalFormatting; property Charts: TZEChartStore read FCharts write SetCharts; property Drawing: TZEDrawing read FDrawing; property ViewMode: TZViewMode read FViewMode write FViewMode; property RowBreaks: TArray<Integer> read FRowBreaks write FRowBreaks; property ColBreaks: TArray<Integer> read FColBreaks write FColBreaks; end; /// <summary> /// Document sheets. /// </summary> TZSheets = class(TPersistent) private FStore: TZWorkBook; FSheets: array of TZSheet; FCount: Integer; procedure SetSheetCount(const Value: Integer); procedure SetSheet(num: Integer; Const Value: TZSheet); function GetSheet(num: Integer): TZSheet; public constructor Create(AStore: TZWorkBook); virtual; destructor Destroy(); override; procedure Assign(Source: TPersistent); override; /// <summary> /// Number of sheets in the document. /// </summary> property Count: Integer read FCount write SetSheetCount; /// <summary> /// Document's sheet num. /// </summary> property Sheet[num: Integer]: TZSheet read GetSheet write SetSheet; default; /// <summary> /// Add new sheet to the workbook. /// </summary> function Add(const ATitle: string = ''): TZSheet; end; IZRange = interface(IInterface) function HasStyle: Boolean; procedure ApplyStyleValue(proc: TProc<TZStyle>); function GetVerticalAlignment(): TZVerticalAlignment; procedure SetVerticalAlignment(const Value: TZVerticalAlignment); function GetHorizontalAlignment(): TZHorizontalAlignment; procedure SetHorizontalAlignment(const Value: TZHorizontalAlignment); function GetRotate(): TZCellTextRotate; procedure SetRotate(const Value: TZCellTextRotate); function GetBgColor(): TColor; procedure SetBgColor(const Value: TColor); function GetFontColor(): TColor; procedure SetFontColor(const Value: TColor); function GetFontSize(): Double; procedure SetFontSize(const Value: Double); function GetFontStyle(): TFontStyles; procedure SetFontStyle(const Value: TFontStyles); function GetBorderStyle(num: TZBordersPos): TZBorderType; procedure SetBorderStyle(num: TZBordersPos; const Value: TZBorderType); function GetBorderWidht(num: TZBordersPos): Byte; procedure SetBorderWidht(num: TZBordersPos; const Value: Byte); function GetBorderColor(num: TZBordersPos): TColor; procedure SetBorderColor(num: TZBordersPos; const Value: TColor); function GetBordersStyle(): TZBorderType; procedure SetBordersStyle(const Value: TZBorderType); function GetBordersWidht(): Byte; procedure SetBordersWidht(const Value: Byte); function GetBordersColor(): TColor; procedure SetBordersColor(const Value: TColor); function GetWrapText(): Boolean; procedure SetWrapText(const Value: Boolean); function GetVerticalText(): Boolean; procedure SetVerticalText(const Value: Boolean); function GetNumberFormat(): string; procedure SetNumberFormat(const Value: string); // property VerticalAlignment: TZVerticalAlignment read GetVerticalAlignment write SetVerticalAlignment; property HorizontalAlignment: TZHorizontalAlignment read GetHorizontalAlignment write SetHorizontalAlignment; property BgColor: TColor read GetBgColor write SetBgColor; property FontColor: TColor read GetFontColor write SetFontColor; property FontSize: Double read GetFontSize write SetFontSize; property FontStyle: TFontStyles read GetFontStyle write SetFontStyle; property BorderStyle[num: TZBordersPos]: TZBorderType read GetBorderStyle write SetBorderStyle; property BorderWidht[num: TZBordersPos]: Byte read GetBorderWidht write SetBorderWidht; property BorderColor[num: TZBordersPos]: TColor read GetBorderColor write SetBorderColor; property BordersStyle: TZBorderType read GetBordersStyle write SetBordersStyle; property BordersWidht: Byte read GetBordersWidht write SetBordersWidht; property BordersColor: TColor read GetBordersColor write SetBordersColor; property WrapText: Boolean read GetWrapText write SetWrapText; property VerticalText: Boolean read GetVerticalText write SetVerticalText; property Rotate: TZCellTextRotate read GetRotate write SetRotate; property NumberFormat: string read GetNumberFormat write SetNumberFormat; procedure SetBorderAround(borderWidth: Byte; BorderColor: TColor = TColorRec.Black; BorderStyle: TZBorderType = TZBorderType.ZEContinuous); procedure Merge(); procedure Clear(); end; TZRange = class(TInterfacedObject, IZRange) private FSheet: TZSheet; FLeft, FTop, FRight, FBottom: Integer; function HasStyle: Boolean; procedure ApplyStyleValue(proc: TProc<TZStyle>); function GetVerticalAlignment(): TZVerticalAlignment; procedure SetVerticalAlignment(const Value: TZVerticalAlignment); function GetHorizontalAlignment(): TZHorizontalAlignment; procedure SetHorizontalAlignment(const Value: TZHorizontalAlignment); function GetRotate(): TZCellTextRotate; procedure SetRotate(const Value: TZCellTextRotate); function GetBgColor(): TColor; procedure SetBgColor(const Value: TColor); function GetFontColor(): TColor; procedure SetFontColor(const Value: TColor); function GetFontSize(): Double; procedure SetFontSize(const Value: Double); function GetFontStyle(): TFontStyles; procedure SetFontStyle(const Value: TFontStyles); function GetBorderStyle(num: TZBordersPos): TZBorderType; procedure SetBorderStyle(num: TZBordersPos; const Value: TZBorderType); function GetBorderWidht(num: TZBordersPos): Byte; procedure SetBorderWidht(num: TZBordersPos; const Value: Byte); function GetBorderColor(num: TZBordersPos): TColor; procedure SetBorderColor(num: TZBordersPos; const Value: TColor); function GetBordersStyle(): TZBorderType; procedure SetBordersStyle(const Value: TZBorderType); function GetBordersWidht(): Byte; procedure SetBordersWidht(const Value: Byte); function GetBordersColor(): TColor; procedure SetBordersColor(const Value: TColor); function GetWrapText(): Boolean; procedure SetWrapText(const Value: Boolean); function GetVerticalText(): Boolean; procedure SetVerticalText(const Value: Boolean); function GetNumberFormat(): string; procedure SetNumberFormat(const Value: string); protected public constructor Create(ASheet: TZSheet; ALeft, ATop, ARight, ABottom: Integer); virtual; procedure Assign(Source: TZRange); destructor Destroy(); override; property VerticalAlignment: TZVerticalAlignment read GetVerticalAlignment write SetVerticalAlignment; property HorizontalAlignment: TZHorizontalAlignment read GetHorizontalAlignment write SetHorizontalAlignment; property BgColor: TColor read GetBgColor write SetBgColor; property FontColor: TColor read GetFontColor write SetFontColor; property FontSize: Double read GetFontSize write SetFontSize; property FontStyle: TFontStyles read GetFontStyle write SetFontStyle; property BorderStyle[num: TZBordersPos]: TZBorderType read GetBorderStyle write SetBorderStyle; property BorderWidht[num: TZBordersPos]: Byte read GetBorderWidht write SetBorderWidht; property BorderColor[num: TZBordersPos]: TColor read GetBorderColor write SetBorderColor; property BordersStyle: TZBorderType read GetBordersStyle write SetBordersStyle; property BordersWidht: Byte read GetBordersWidht write SetBordersWidht; property BordersColor: TColor read GetBordersColor write SetBordersColor; property WrapText: Boolean read GetWrapText write SetWrapText; property VerticalText: Boolean read GetVerticalText write SetVerticalText; property Rotate: TZCellTextRotate read GetRotate write SetRotate; property NumberFormat: string read GetNumberFormat write SetNumberFormat; procedure SetBorderAround(borderWidth: Byte; BorderColor: TColor = TColorRec.Black; BorderStyle: TZBorderType = TZBorderType.ZEContinuous); procedure Merge(); procedure Clear(); end; /// <summary> /// Document properties /// </summary> TZEXMLDocumentProperties = class(TPersistent) private FAuthor: string; FLastAuthor: string; FCreated: TDateTime; FCompany: string; FVersion: string; // - should be integer by Spec but hardcoded float in real MS Office apps FWindowHeight: word; FWindowWidth: word; FWindowTopX: Integer; FWindowTopY: Integer; FModeR1C1: Boolean; protected procedure SetAuthor(const Value: string); procedure SetLastAuthor(const Value: string); procedure SetCompany(const Value: string); procedure SetVersion(const Value: string); public constructor Create(); virtual; procedure Assign(Source: TPersistent); override; /// <summary> /// Author of the document /// </summary> property Author: string read FAuthor write SetAuthor; /// <summary> /// Author of last changes in the document /// </summary> property LastAuthor: string read FLastAuthor write SetLastAuthor; /// <summary> /// Date and time of document creation /// </summary> property Created: TDateTime read FCreated write FCreated; /// <summary> /// Company name /// </summary> property Company: string read FCompany write SetCompany; /// <summary> /// Document version /// </summary> property Version: string read FVersion write SetVersion; /// <summary> /// Enabled R1C1 style in Excel. <br />False by default /// </summary> property ModeR1C1: Boolean read FModeR1C1 write FModeR1C1 default false; property WindowHeight: word read FWindowHeight write FWindowHeight default 20000; property WindowWidth: word read FWindowWidth write FWindowWidth default 20000; property WindowTopX: Integer read FWindowTopX write FWindowTopX default 150; property WindowTopY: Integer read FWindowTopY write FWindowTopY default 150; end; TDefinedName = record LocalSheetId: Integer; Name: string; Body: string; end; /// <summary> /// Contains spreadsheet document /// </summary> TZWorkBook = class(TComponent) private FSheets: TZSheets; FDocumentProperties: TZEXMLDocumentProperties; FStyles: TZStyles; FHorPixelSize: Real; FVertPixelSize: Real; FDefaultSheetOptions: TZSheetOptions; FMediaList: TArray<TMediaRec>; procedure SetHorPixelSize(Value: Real); procedure SetVertPixelSize(Value: Real); function GetDefaultSheetOptions(): TZSheetOptions; procedure SetDefaultSheetOptions(Value: TZSheetOptions); public FDefinedNames: TArray<TDefinedName>; constructor Create(AOwner: TComponent); override; destructor Destroy(); override; procedure Assign(Source: TPersistent); override; {$IFNDEF FMX} procedure GetPixelSize(hdc: THandle); {$ENDIF} property Sheets: TZSheets read FSheets write FSheets; property MediaList: TArray<TMediaRec> read FMediaList write FMediaList; function AddMediaContent(AFileName: string; AContent: TBytes; ACheckByName: Boolean): Integer; function GetDrawing(num: Integer): TZEDrawing; function GetDrawingSheetNum(Value: TZEDrawing): Integer; property Styles: TZStyles read FStyles write FStyles; property DefaultSheetOptions: TZSheetOptions read GetDefaultSheetOptions write SetDefaultSheetOptions; property DocumentProperties: TZEXMLDocumentProperties read FDocumentProperties write FDocumentProperties; property HorPixelSize: Real read FHorPixelSize write SetHorPixelSize; // размер пикселя по горизонтали property VertPixelSize: Real read FVertPixelSize write SetVertPixelSize; // размер пикселя по вертикали end; /// <summary> /// Convert TColor to Hex RGB /// </summary> function ColorToHTMLHex(Color: TColor): string; /// <summary> /// Convert Hex RGB (string) to TColor /// </summary> function HTMLHexToColor(Value: string): TColor; /// <summary> /// Convert ARGB (string) to TColor /// </summary> function ARGBToColor(Value: string): TColor; /// <summary> /// Convert pixels to point /// </summary> function PixelToPoint(inPixel: Integer; PixelSizeMM: Real = 0.265): Real; /// <summary> /// Convert typographical point to pixels. /// </summary> function PointToPixel(inPoint: Real; PixelSizeMM: Real = 0.265): Integer; /// <summary> /// Convert typographical point to mm. /// </summary> function PointToMM(inPoint: Real): Real; /// <summary> /// Convert mm to typographical point. /// </summary> function MMToPoint(inMM: Real): Real; /// <summary> /// Checks is Font1 equal Font2 /// </summary> function ZEIsFontsEquals(const Font1, Font2: TZFont): Boolean; overload; /// <summary> /// Checks is Font1 equal Font2 /// </summary> function ZEIsFontsEquals(const Font1, Font2: TFont): Boolean; overload; /// <summary> /// Convert datetime value to string (YYYY-MM-DDTHH:MM:SS[.mmm]). /// </summary> function ZEDateTimeToStr(ATime: TDateTime; Addmms: Boolean = false): string; /// <summary> /// Try convert string (YYYY-MM-DDTHH:MM:SS[.mmm]) to datetime /// </summary> function TryZEStrToDateTime(const AStrDateTime: string; out retDateTime: TDateTime): Boolean; /// <summary> /// Convert the number to string min count NullCount /// </summary> function IntToStrN(Value: Integer; NullCount: Integer): string; function IsIdenticalByteArray(Src, Dst: TBytes): Boolean; implementation uses Excel4Delphi.Formula; var invariantFormatSertting: TFormatSettings; function IsIdenticalByteArray(Src, Dst: TBytes): Boolean; var i: Integer; begin if Length(Src) <> Length(Dst) then exit(false); for i := Low(Src) to High(Src) do begin if Src[i] <> Dst[i] then exit(false); end; Result := true; end; function IntToStrN(Value: Integer; NullCount: Integer): string; var t, k: Integer; begin t := Value; k := 0; if (t = 0) then k := 1; while t > 0 do begin Inc(k); t := t div 10; end; Result := IntToStr(Value); for t := 1 to (NullCount - k) do Result := '0' + Result; end; function ZEDateTimeToStr(ATime: TDateTime; Addmms: Boolean = false): string; var HH, MM, SS, MS: word; begin DecodeDate(ATime, HH, MM, SS); Result := IntToStrN(HH, 4) + '-' + IntToStrN(MM, 2) + '-' + IntToStrN(SS, 2) + 'T'; DecodeTime(ATime, HH, MM, SS, MS); Result := Result + IntToStrN(HH, 2) + ':' + IntToStrN(MM, 2) + ':' + IntToStrN(SS, 2); if (Addmms) then Result := Result + '.' + IntToStrN(MS, 3); end; function TryZEStrToDateTime(const AStrDateTime: string; out retDateTime: TDateTime): Boolean; var a: array [0 .. 10] of word; i, l: Integer; s, SS: string; Count: Integer; ch: char; datedelimeters: Integer; istimesign: Boolean; timedelimeters: Integer; istimezone: Boolean; lastdateindex: Integer; tmp: Integer; msindex: Integer; tzindex: Integer; timezonemul: Integer; _ms: word; function TryAddToArray(const ST: string): Boolean; begin if (Count > 10) then begin Result := false; exit; end; Result := TryStrToInt(ST, tmp); if (Result) then begin a[Count] := word(tmp); Inc(Count); end end; procedure _CheckDigits(); var _l: Integer; begin _l := Length(s); if (_l > 0) then begin if (_l > 4) then begin // it is not good if (istimesign) then begin // HHMMSS? if (_l = 6) then begin SS := copy(s, 1, 2); if (TryAddToArray(SS)) then begin SS := copy(s, 3, 2); if (TryAddToArray(SS)) then begin SS := copy(s, 5, 2); if (not TryAddToArray(SS)) then Result := false; end else Result := false; end else Result := false end else Result := false; end else begin // YYYYMMDD? if (_l = 8) then begin SS := copy(s, 1, 4); if (not TryAddToArray(SS)) then Result := false else begin SS := copy(s, 5, 2); if (not TryAddToArray(SS)) then Result := false else begin SS := copy(s, 7, 2); if (not TryAddToArray(SS)) then Result := false; end; end; end else Result := false; end; end else if (not TryAddToArray(s)) then Result := false; end; // if if (Count > 10) then Result := false; s := ''; end; procedure _processDigit(); begin s := s + ch; end; procedure _processTimeSign(); begin istimesign := true; if (Count > 0) then lastdateindex := Count; _CheckDigits(); end; procedure _processTimeDelimiter(); begin _CheckDigits(); Inc(timedelimeters) end; procedure _processDateDelimiter(); begin _CheckDigits(); if (istimesign) then begin tzindex := Count; istimezone := true; timezonemul := -1; end else Inc(datedelimeters); end; procedure _processMSDelimiter(); begin _CheckDigits(); msindex := Count; end; procedure _processTimeZoneSign(); begin _CheckDigits(); istimezone := true; end; procedure _processTimeZonePlus(); begin _CheckDigits(); istimezone := true; timezonemul := -1; end; function _TryGetDateTime(): Boolean; var _time, _date: TDateTime; begin // Result := true; if (msindex >= 0) then _ms := a[msindex]; if (lastdateindex >= 0) then begin Result := TryEncodeDate(a[0], a[1], a[2], _date); if (Result) then begin Result := TryEncodeTime(a[lastdateindex + 1], a[lastdateindex + 2], a[lastdateindex + 3], _ms, _time); if (Result) then retDateTime := _date + _time; end; end else Result := TryEncodeTime(a[lastdateindex + 1], a[lastdateindex + 2], a[lastdateindex + 3], _ms, retDateTime); end; function _TryGetDate(): Boolean; begin if (datedelimeters = 0) and (timedelimeters >= 2) then begin if (msindex >= 0) then _ms := a[msindex]; Result := TryEncodeTime(a[0], a[1], a[2], _ms, retDateTime); end else if (Count >= 3) then Result := TryEncodeDate(a[0], a[1], a[2], retDateTime) else Result := false; end; begin Result := true; datedelimeters := 0; istimesign := false; timedelimeters := 0; istimezone := false; lastdateindex := -1; msindex := -1; tzindex := -1; timezonemul := 0; _ms := 0; FillChar(a, sizeof(a), 0); l := Length(AStrDateTime); s := ''; Count := 0; for i := 1 to l do begin ch := AStrDateTime[i]; case (ch) of '0' .. '9': _processDigit(); 't', 'T': _processTimeSign(); '-': _processDateDelimiter(); ':': _processTimeDelimiter(); '.', ',': _processMSDelimiter(); 'z', 'Z': _processTimeZoneSign(); '+': _processTimeZonePlus(); end; if (not Result) then break end; if (Result and (s <> '')) then _CheckDigits(); if (Result) then begin if (istimesign) then Result := _TryGetDateTime() else Result := _TryGetDate(); end; end; // TryZEStrToDateTime function ZEIsFontsEquals(const Font1, Font2: TZFont): Boolean; begin Result := Assigned(Font1) and (Assigned(Font2)); if (Result) then begin Result := false; if (Font1.Color <> Font2.Color) then exit; if (Font1.Name <> Font2.Name) then exit; if (Font1.Size <> Font2.Size) then exit; if (Font1.Style <> Font2.Style) then exit; Result := true; end; end; function ZEIsFontsEquals(const Font1, Font2: TFont): Boolean; begin Result := Assigned(Font1) and (Assigned(Font2)); if Result then begin Result := false; {$IFDEF FMX} if (Font1.Family <> Font2.Family) then exit; {$ELSE} if (Font1.Color <> Font2.Color) then exit; if (Font1.Name <> Font2.Name) then exit; {$ENDIF} if (Font1.Size <> Font2.Size) then exit; if (Font1.Style <> Font2.Style) then exit; Result := true; end; end; function ColorToHTMLHex(Color: TColor): string; var _RGB: Integer; begin _RGB := TColorRec.ColorToRGB(Color); // result := IntToHex(GetRValue(_RGB), 2) + IntToHex(GetGValue(_RGB), 2) + IntToHex(GetBValue(_RGB), 2); Result := IntToHex(Byte(_RGB), 2) + IntToHex(Byte(_RGB shr 8), 2) + IntToHex(Byte(_RGB shr 16), 2); end; function HTMLHexToColor(Value: string): TColor; var a: array [0 .. 2] of Integer; i, n, t: Integer; begin Result := 0; if Value > '' then begin Value := UpperCase(Value); {$HINTS OFF} FillChar(a, sizeof(a), 0); {$HINTS ON} n := 0; if Value[1] = '#' then Delete(Value, 1, 1); // А что, если будут цвета типа "black"? {tut} for i := 1 to Length(Value) do begin if n > 2 then break; case Value[i] of '0' .. '9': t := ord(Value[i]) - 48; 'A' .. 'F': t := 10 + ord(Value[i]) - 65; else t := 0; end; a[n] := a[n] * 16 + t; if i mod 2 = 0 then Inc(n); end; Result := a[2] shl 16 or a[1] shl 8 or a[0]; end; end; function ARGBToColor(Value: string): TColor; var a: array [0 .. 2] of Integer; i, n, t: Integer; begin Result := 0; if Value > '' then begin Value := UpperCase(Value); {$HINTS OFF} FillChar(a, sizeof(a), 0); {$HINTS ON} n := 0; if Value[1] = '#' then Delete(Value, 1, 1); for i := 3 to Length(Value) do begin if n > 2 then break; case Value[i] of '0' .. '9': t := ord(Value[i]) - 48; 'A' .. 'F': t := 10 + ord(Value[i]) - 65; else t := 0; end; a[n] := a[n] * 16 + t; if i mod 2 = 0 then Inc(n); end; Result := a[2] shl 16 or a[1] shl 8 or a[0]; end; end; function PixelToPoint(inPixel: Integer; PixelSizeMM: Real = 0.265): Real; begin Result := inPixel * PixelSizeMM / _PointToMM; // и оставим 2 знака после запятой ^_^ Result := round(Result * 100) / 100; end; function PointToPixel(inPoint: Real; PixelSizeMM: Real = 0.265): Integer; begin Result := round(inPoint * _PointToMM / PixelSizeMM); end; function PointToMM(inPoint: Real): Real; begin Result := round(inPoint * _PointToMM * 100) / 100; end; function MMToPoint(inMM: Real): Real; begin Result := round(inMM / _PointToMM * 100) / 100; end; /// /::::::::::::: TZBorderStyle ::::::::::::::::://// constructor TZBorderStyle.Create(); begin FWeight := 0; FColor.RGB := TColorRec.Black; FColor.Indexed := 0; FColor.Theme := 0; FColor.Tint := 0; FLineStyle := ZENone; end; procedure TZBorderStyle.Assign(Source: TPersistent); begin if Source is TZBorderStyle then begin Weight := (Source as TZBorderStyle).Weight; Color := (Source as TZBorderStyle).Color; LineStyle := (Source as TZBorderStyle).LineStyle; end else inherited Assign(Source); end; function TZBorderStyle.IsEqual(Source: TPersistent): Boolean; var zSource: TZBorderStyle; begin Result := false; if not(Source is TZBorderStyle) then exit; zSource := Source as TZBorderStyle; if Self.LineStyle <> zSource.LineStyle then exit; if (Self.FColor <> zSource.FColor) then exit; if Self.Weight <> zSource.Weight then exit; Result := true; end; procedure TZBorderStyle.SetLineStyle(const Value: TZBorderType); begin FLineStyle := Value; end; procedure TZBorderStyle.SetWeight(const Value: Byte); begin FWeight := min(3, Value); end; function TZBorderStyle.GetColor: TColor; begin Result := FColor.RGB; end; procedure TZBorderStyle.SetColor(const Value: TColor); begin if FColor.RGB <> Value then begin FColor.RGB := Value; FColor.Indexed := 0; FColor.Theme := 0; FColor.Tint := 0; end; end; /// /::::::::::::: TZBorder ::::::::::::::::://// constructor TZBorder.Create(); var i: Integer; begin for i := 0 to 5 do FBorder[i] := TZBorderStyle.Create(); end; destructor TZBorder.Destroy(); var i: Integer; begin for i := 0 to 5 do FreeAndNil(FBorder[i]); inherited Destroy; end; procedure TZBorder.Assign(Source: TPersistent); var zSource: TZBorder; i: TZBordersPos; begin if (Source is TZBorder) then begin zSource := Source as TZBorder; for i := bpLeft to bpDiagonalRight do Border[i].Assign(zSource.Border[i]); end else inherited Assign(Source); end; function TZBorder.IsEqual(Source: TPersistent): Boolean; var zSource: TZBorder; i: TZBordersPos; begin Result := false; if not(Source is TZBorder) then exit; zSource := Source as TZBorder; for i := bpLeft to bpDiagonalRight do if not FBorder[ord(i)].IsEqual(zSource.Border[i]) then exit; Result := true; end; procedure TZBorder.SetBorder(num: TZBordersPos; Const Value: TZBorderStyle); begin if (num >= bpLeft) and (num <= bpDiagonalRight) then Border[num].Assign(Value); end; function TZBorder.GetBorder(num: TZBordersPos): TZBorderStyle; begin if (num >= bpLeft) and (num <= bpDiagonalRight) then Result := FBorder[ord(num)] else Result := nil; end; /// /::::::::::::: TZAlignment ::::::::::::::::://// constructor TZAlignment.Create(); begin FIndent := 0; FRotate := 0; FHorizontal := ZHAutomatic; FShrinkToFit := false; FVertical := ZVAutomatic; FVerticalText := false; FWrapText := false; end; procedure TZAlignment.Assign(Source: TPersistent); var zSource: TZAlignment; begin if (Source is TZAlignment) then begin zSource := Source as TZAlignment; FHorizontal := zSource.Horizontal; FIndent := zSource.Indent; FRotate := zSource.Rotate; FShrinkToFit := zSource.ShrinkToFit; FVertical := zSource.Vertical; FVerticalText := zSource.VerticalText; FWrapText := zSource.WrapText; end else inherited Assign(Source); end; function TZAlignment.IsEqual(Source: TPersistent): Boolean; var zSource: TZAlignment; begin Result := true; if (Source is TZAlignment) then begin zSource := Source as TZAlignment; if Horizontal <> zSource.Horizontal then exit(false); if Indent <> zSource.Indent then exit(false); if Rotate <> zSource.Rotate then exit(false); if ShrinkToFit <> zSource.ShrinkToFit then exit(false); if Vertical <> zSource.Vertical then exit(false); if VerticalText <> zSource.VerticalText then exit(false); if WrapText <> zSource.WrapText then exit(false); end else Result := false; end; procedure TZAlignment.SetHorizontal(const Value: TZHorizontalAlignment); begin FHorizontal := Value; end; procedure TZAlignment.SetIndent(const Value: Integer); begin FIndent := Value; end; procedure TZAlignment.SetRotate(const Value: TZCellTextRotate); begin FRotate := Value; end; procedure TZAlignment.SetShrinkToFit(const Value: Boolean); begin FShrinkToFit := Value; end; procedure TZAlignment.SetVertical(const Value: TZVerticalAlignment); begin FVertical := Value; end; procedure TZAlignment.SetVerticalText(const Value: Boolean); begin FVerticalText := Value; end; procedure TZAlignment.SetWrapText(const Value: Boolean); begin FWrapText := Value; end; /// /::::::::::::: TZFont ::::::::::::::::://// constructor TZFont.Create; begin inherited; FColor.RGB := TColorRec.cWindowText; FColor.Indexed := 0; FColor.Theme := 0; FColor.Tint := 0; FSize := 8; FCharset := DEFAULT_CHARSET; FName := 'MS Sans Serif'; FStyle := []; end; destructor TZFont.Destroy; begin inherited; end; function TZFont.GetColor: TColor; begin Result := FColor.RGB; end; procedure TZFont.SetColor(const Value: TColor); begin if Value <> FColor.RGB then begin FColor.RGB := Value; FColor.Indexed := 0; FColor.Theme := 0; FColor.Tint := 0; end; end; function TZFont.GetHashCode: Integer; var ST: Integer; begin ST := 0; if TFontStyle.fsBold in FStyle then Inc(ST, 1); if TFontStyle.fsItalic in FStyle then Inc(ST, 2); if TFontStyle.fsUnderline in FStyle then Inc(ST, 4); if TFontStyle.fsStrikeOut in FStyle then Inc(ST, 8); Result := 17; Result := Result * 23 + Integer(FColor.RGB); Result := Result * 23 + Integer(FColor.Indexed); Result := Result * 23 + Integer(FColor.Theme); Result := Result * 23 + trunc(FColor.Tint * 100000.0); Result := Result * 23 + trunc(FSize * 1000.0); Result := Result * 23 + Integer(FCharset); Result := Result * 23 + string(FName).GetHashCode(); Result := Result * 23 + ST; end; procedure TZFont.Assign(Source: TPersistent); var zSource: TZFont; srcFont: TFont; begin if Source is TZFont then begin zSource := Source as TZFont; FColor := zSource.ExcelColor; FSize := zSource.Size; FCharset := zSource.Charset; FName := zSource.Name; FStyle := zSource.Style; end else if Source is TFont then begin srcFont := Source as TFont; {$IFDEF FMX} FName := srcFont.Family; {$ELSE} FColor.RGB := srcFont.Color; FColor.Indexed := 0; FColor.Theme := 0; FColor.Tint := 0; FCharset := srcFont.Charset; FName := srcFont.Name; {$ENDIF} FSize := srcFont.Size; FStyle := srcFont.Style; end else inherited Assign(Source); end; procedure TZFont.AssignTo(Dest: TPersistent); var dstFont: TFont; begin if Dest is TZFont then TZFont(Dest).Assign(Self) else if Dest is TFont then begin dstFont := Dest as TFont; // А.А.Валуев Свойства, которых нет в TZFont сбрасываем на значения по умолчанию. dstFont.Size := Round(FSize); dstFont.Style := FStyle; {$IFDEF FMX} dstFont.Family := FName; {$ELSE} dstFont.Color := FColor.RGB; dstFont.Pitch := fpDefault; dstFont.Orientation := 0; dstFont.Charset := FCharset; dstFont.Name := FName; {$ENDIF} end else inherited AssignTo(Dest); end; /// /::::::::::::: TZStyle ::::::::::::::::://// // about default font in Excel - http://support.microsoft.com/kb/214123 constructor TZStyle.Create(); begin FFont := TZFont.Create(); FFont.Size := 10; FFont.Name := 'Arial'; FFont.Color := TColorRec.Black; FBorder := TZBorder.Create(); FAlignment := TZAlignment.Create(); FBGColor.RGB := TColorRec.cWindow; FPatternColor := TColorRec.cWindow; FCellPattern := ZPNone; FNumberFormat := ''; FNumberFormatId := -1; FProtect := true; FHideFormula := false; FSuperscript := false; FSubscript := false; end; destructor TZStyle.Destroy(); begin FreeAndNil(FFont); FreeAndNil(FBorder); FreeAndNil(FAlignment); inherited Destroy(); end; procedure TZStyle.Assign(Source: TPersistent); var zSource: TZStyle; begin if Source is TZStyle then begin zSource := Source as TZStyle; FFont.Assign(zSource.Font); FBorder.Assign(zSource.Border); FAlignment.Assign(zSource.Alignment); FBGColor := zSource.FBGColor; FPatternColor := zSource.PatternColor; FCellPattern := zSource.CellPattern; FNumberFormat := zSource.NumberFormat; FNumberFormatId := zSource.NumberFormatId; FProtect := zSource.Protect; FHideFormula := zSource.HideFormula; FSuperscript := zSource.Superscript; FSubscript := zSource.Subscript; end else inherited Assign(Source); end; function TZStyle.IsEqual(Source: TPersistent): Boolean; var zSource: TZStyle; begin Result := false; if not(Source is TZStyle) then exit; zSource := Source as TZStyle; if not Border.IsEqual(zSource.Border) then exit; if not Self.Alignment.IsEqual(zSource.Alignment) then exit; if BgColor <> zSource.BgColor then exit; if PatternColor <> zSource.PatternColor then exit; if CellPattern <> zSource.CellPattern then exit; if NumberFormat <> zSource.NumberFormat then exit; if NumberFormatId <> zSource.NumberFormatId then exit; if Protect <> zSource.Protect then exit; if HideFormula <> zSource.HideFormula then exit; if Superscript <> zSource.Superscript then exit; if Subscript <> zSource.Subscript then exit; Result := ZEIsFontsEquals(FFont, zSource.Font); end; procedure TZStyle.SetFont(const Value: TZFont); begin FFont.Assign(Value); end; procedure TZStyle.SetBorder(const Value: TZBorder); begin FBorder.Assign(Value); end; procedure TZStyle.SetAlignment(const Value: TZAlignment); begin FAlignment.Assign(Value); end; function TZStyle.GetBgColor: TColor; begin Result := FBGColor.RGB; end; procedure TZStyle.SetBgColor(const Value: TColor); begin if FBGColor.RGB <> Value then begin FBGColor.RGB := Value; FBGColor.Indexed := 0; FBGColor.Theme := 0; FBGColor.Tint := 0; end; end; procedure TZStyle.SetPatternColor(const Value: TColor); begin FPatternColor := Value; end; procedure TZStyle.SetCellPattern(const Value: TZCellPattern); begin FCellPattern := Value; end; procedure TZStyle.SetSuperscript(const Value: Boolean); begin if FSuperscript <> Value then begin FSuperscript := Value; if FSuperscript then FSubscript := false; end; end; procedure TZStyle.SetSubscript(const Value: Boolean); begin if FSubscript <> Value then begin FSubscript := Value; if FSubscript then FSuperscript := false; end; end; procedure TZStyle.SetNumberFormat(const Value: string); begin FNumberFormat := Value; FNumberFormatId := -1; end; /// /::::::::::::: TZStyles ::::::::::::::::://// constructor TZStyles.Create(); begin FDefaultStyle := TZStyle.Create(); FCount := 0; end; destructor TZStyles.Destroy(); var i: Integer; begin FreeAndNil(FDefaultStyle); for i := 0 to FCount - 1 do FreeAndNil(FStyles[i]); SetLength(FStyles, 0); FStyles := nil; inherited Destroy(); end; function TZStyles.Find(const Style: TZStyle): Integer; var i: Integer; begin Result := -2; if DefaultStyle.IsEqual(Style) then exit(-1); for i := 0 to Count - 1 do if Items[i].IsEqual(Style) then begin exit(i); end; end; function TZStyles.Add(const Style: TZStyle; CheckMatch: Boolean = false): Integer; begin Result := -2; if CheckMatch then Result := Find(Style); if Result = -2 then begin Count := Count + 1; Items[Count - 1].Assign(Style); Result := Count - 1; end; end; procedure TZStyles.Assign(Source: TPersistent); var srcStyles: TZStyles; i: Integer; begin if Source is TZStyles then begin srcStyles := Source as TZStyles; FDefaultStyle.Assign(srcStyles.DefaultStyle); Count := srcStyles.Count; for i := 0 to Count - 1 do FStyles[i].Assign(srcStyles[i]); end else inherited Assign(Source); end; procedure TZStyles.SetDefaultStyle(const Value: TZStyle); begin if Assigned(Value) then FDefaultStyle.Assign(Value); end; procedure TZStyles.SetCount(const Value: Integer); var i: Integer; begin if FCount < Value then begin SetLength(FStyles, Value); for i := FCount to Value - 1 do begin FStyles[i] := TZStyle.Create; FStyles[i].Assign(FDefaultStyle); end; end else begin for i := Value to FCount - 1 do FreeAndNil(FStyles[i]); SetLength(FStyles, Value); end; FCount := Value; end; function TZStyles.GetStyle(num: Integer): TZStyle; begin if (num >= 0) and (num < Count) then Result := FStyles[num] else Result := DefaultStyle; end; procedure TZStyles.SetStyle(num: Integer; const Value: TZStyle); begin if (num >= 0) and (num < Count) then FStyles[num].Assign(Value) else if num = -1 then DefaultStyle.Assign(Value); end; function TZStyles.DeleteStyle(num: Integer): Integer; begin if (num >= 0) and (num < Count) then begin FreeAndNil(FStyles[num]); System.Move(FStyles[num + 1], FStyles[num], (Count - num - 1) * sizeof(FStyles[num])); FStyles[Count - 1] := nil; Dec(FCount); SetLength(FStyles, FCount); // при удалении глянуть на ячейки - изменить num на 0, остальные сдвинуть. Result := 0; end else Result := -1; end; procedure TZStyles.Clear(); var i: Integer; begin for i := 0 to FCount - 1 do FreeAndNil(FStyles[i]); SetLength(FStyles, 0); FCount := 0; end; /// /::::::::::::: TZCell ::::::::::::::::://// constructor TZCell.Create(ASheet: TZSheet); begin FSheet := ASheet; FFormula := ''; FData := ''; FHref := ''; FComment := ''; FCommentAuthor := ''; FHRefScreenTip := ''; FCellType := ZEString; FCellStyle := -1; // по дефолту FAlwaysShowComment := false; FShowComment := false; FRichText := TRichText.Create(); end; destructor TZCell.Destroy; begin FRichText.Free(); inherited; end; procedure TZCell.Assign(Source: TPersistent); var zSource: TZCell; begin if Source is TZCell then begin zSource := Source as TZCell; FFormula := zSource.Formula; FData := zSource.Data; FHref := zSource.HRef; FComment := zSource.Comment; FCommentAuthor := zSource.CommentAuthor; FCellStyle := zSource.CellStyle; FCellType := zSource.CellType; FAlwaysShowComment := zSource.AlwaysShowComment; FShowComment := zSource.ShowComment; FRichText.Assign(zSource.FRichText); end else inherited Assign(Source); end; procedure TZCell.Clear(); begin FFormula := ''; FData := ''; FHref := ''; FComment := ''; FCommentAuthor := ''; FHRefScreenTip := ''; FCellType := ZEString; FCellStyle := -1; FAlwaysShowComment := false; FShowComment := false; end; procedure TZCell.ApplyStyleValue(proc: TProc<TZStyle>); var Style: TZStyle; begin Style := TZStyle.Create(); try Style.Assign(Self.Style); proc(Style); FCellStyle := FSheet.FStore.Styles.Add(Style, true); finally Style.Free(); end; end; procedure TZCell.SetBorderAround(borderWidth: Byte; BorderColor: TColor; BorderStyle: TZBorderType); var Style: TZStyle; bp: TZBordersPos; begin Style := TZStyle.Create(); try Style.Assign(Self.Style); for bp := TZBordersPos.bpLeft to TZBordersPos.bpBottom do begin Style.FBorder[bp].LineStyle := BorderStyle; Style.FBorder[bp].Weight := borderWidth; Style.FBorder[bp].Color := BorderColor; end; FCellStyle := FSheet.FStore.Styles.Add(Style, true); finally Style.Free(); end; end; function TZCell.GetStyle: TZStyle; begin Result := nil; if FCellStyle > -1 then Result := FSheet.FStore.FStyles[FCellStyle] else if FSheet.FStore.FStyles.Count > 0 then Result := FSheet.FStore.FStyles[0]; end; function TZCell.GetBgColor: TColor; begin Result := 0; if FCellStyle > -1 then Result := Style.BgColor; end; function TZCell.GetBorderColor(num: TZBordersPos): TColor; begin Result := 0; if FCellStyle > -1 then Result := Style.Border[num].Color; end; function TZCell.GetBorderStyle(num: TZBordersPos): TZBorderType; begin Result := TZBorderType.ZENone; if FCellStyle > -1 then Result := Style.Border[num].LineStyle; end; function TZCell.GetBorderWidht(num: TZBordersPos): Byte; begin Result := 0; if FCellStyle > -1 then Result := Style.Border[num].Weight; end; function TZCell.GetFontColor: TColor; begin Result := 0; if FCellStyle > -1 then Result := Style.Font.Color; end; function TZCell.GetFontSize: Double; begin Result := 0; if FCellStyle > -1 then Result := Style.Font.Size; end; function TZCell.GetFontStyle: TFontStyles; begin Result := []; if FCellStyle > -1 then Result := Style.Font.Style; end; function TZCell.GetHorizontalAlignment: TZHorizontalAlignment; begin Result := TZHorizontalAlignment.ZHAutomatic; if FCellStyle > -1 then Result := Style.Alignment.Horizontal; end; function TZCell.GetNumberFormat: string; begin Result := ''; if FCellStyle > -1 then Result := Style.NumberFormat; end; function TZCell.GetRotate: TZCellTextRotate; begin Result := 0; if FCellStyle > -1 then Result := Style.Alignment.Rotate; end; function TZCell.GetVerticalAlignment: TZVerticalAlignment; begin Result := TZVerticalAlignment.ZVAutomatic; if FCellStyle > -1 then Result := Style.Alignment.Vertical; end; function TZCell.GetVerticalText: Boolean; begin Result := false; if FCellStyle > -1 then Result := Style.Alignment.VerticalText; end; function TZCell.GetWrapText: Boolean; begin Result := false; if FCellStyle > -1 then Result := Style.Alignment.WrapText; end; procedure TZCell.SetFontColor(const Value: TColor); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Font.Color := Value; end); end; procedure TZCell.SetFontSize(const Value: Double); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Font.Size := Value; end); end; procedure TZCell.SetFontStyle(const Value: TFontStyles); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Font.Style := Value; end); end; procedure TZCell.SetBgColor(const Value: TColor); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.BgColor := Value; end); end; procedure TZCell.SetBorderColor(num: TZBordersPos; const Value: TColor); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Border[num].Color := Value; end); end; procedure TZCell.SetBorderStyle(num: TZBordersPos; const Value: TZBorderType); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Border[num].LineStyle := Value; end); end; procedure TZCell.SetBorderWidht(num: TZBordersPos; const Value: Byte); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Border[num].Weight := Value; end); end; procedure TZCell.SetHorizontalAlignment(const Value: TZHorizontalAlignment); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Alignment.Horizontal := Value; end); end; procedure TZCell.SetNumberFormat(const Value: string); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.NumberFormat := Value; end); end; procedure TZCell.SetRotate(const Value: TZCellTextRotate); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Alignment.Rotate := Value; end); end; procedure TZCell.SetVerticalAlignment(const Value: TZVerticalAlignment); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Alignment.Vertical := Value; end); end; procedure TZCell.SetVerticalText(const Value: Boolean); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Alignment.VerticalText := Value; end); end; procedure TZCell.SetWrapText(const Value: Boolean); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Alignment.WrapText := Value; end); end; function TZCell.GetDataAsInteger: Integer; begin Result := StrToInt(Data); end; procedure TZCell.SetDataAsDateTime(const Value: TDateTime); begin FCellType := ZEDateTime; // FData := ZEDateTimeToStr(Value, true); FData := FloatToStr(Value).Replace(',', '.'); end; function TZCell.GetDataAsDouble: Double; var err: Integer; b: Boolean; _dt: TDateTime; begin Val(FData, Result, err); // need old-school to ignore regional settings if err > 0 then begin b := true; // If datetime ... if CellType = ZEDateTime then b := not TryZEStrToDateTime(FData, _dt); if b then Raise EConvertError.Create('ZxCell: Cannot cast data to number') else Result := _dt; end; end; function TZCell.GetDataAsDateTime(): TDateTime; var b: Boolean; begin b := false; if FData = '' then Result := 0 else if not TryZEStrToDateTime(FData, Result) then begin // If cell type is number then try convert "float" to datetime if CellType = ZENumber then Result := AsDouble else b := true; end; if (b) then Raise EConvertError.Create('ZxCell: Cannot cast data to DateTime');; end; procedure TZCell.SetDataAsInteger(const Value: Integer); begin Data := Trim(IntToStr(Value)); CellType := ZENumber; // Val adds the prepending space, maybe some I2S implementation would adds too // and Excel dislikes it. Better safe than sorry. end; procedure TZCell.SetDataAsDouble(const Value: Double); begin CellType := ZENumber; FData := FloatToStr(Value, invariantFormatSertting).ToUpper; end; procedure TZCell.SetDataAsString(const Value: string); begin FData := Value; CellType := ZEString; end; /// /::::::::::::: TZMergeCells ::::::::::::::::://// constructor TZMergeCells.Create(ASheet: TZSheet); begin FSheet := ASheet; FCount := 0; end; destructor TZMergeCells.Destroy(); begin Clear(); inherited Destroy(); end; procedure TZMergeCells.Clear(); begin SetLength(FMergeArea, 0); FCount := 0; end; function TZMergeCells.GetItem(num: Integer): TZMergeArea; begin if (num >= 0) and (num < Count) then Result := FMergeArea[num] else begin Result.left := 0; Result.Top := 0; Result.right := 0; Result.Bottom := 0; end; end; procedure TZMergeCells.SetItem(num: Integer; const rect: TZMergeArea); begin FMergeArea[num] := rect; end; function TZMergeCells.AddRect(Rct: TZMergeArea): Byte; var i: Integer; function IsCross(rct1, rct2: TZMergeArea): Boolean; begin Result := (((rct1.left >= rct2.left) and (rct1.left <= rct2.right)) or ((rct1.right >= rct2.left) and (rct1.right <= rct2.right))) and (((rct1.Top >= rct2.Top) and (rct1.Top <= rct2.Bottom)) or ((rct1.Bottom >= rct2.Top) and (rct1.Bottom <= rct2.Bottom))); end; begin if Rct.left > Rct.right then begin i := Rct.left; Rct.left := Rct.right; Rct.right := i; end; if Rct.Top > Rct.Bottom then begin i := Rct.Top; Rct.Top := Rct.Bottom; Rct.Bottom := i; end; if (Rct.left < 0) or (Rct.Top < 0) then begin Result := 1; exit; end; if (Rct.right - Rct.left = 0) and (Rct.Bottom - Rct.Top = 0) then begin Result := 3; exit; end; for i := 0 to Count - 1 do if IsCross(FMergeArea[i], Rct) or IsCross(Rct, FMergeArea[i]) then begin Result := 2; exit; end; // если надо, увеличиваем кол-во строк/столбцов в хранилище if Assigned(FSheet) then begin if Rct.right > FSheet.ColCount - 1 then FSheet.ColCount := Rct.right { + 1 }; if Rct.Bottom > FSheet.RowCount - 1 then FSheet.RowCount := Rct.Bottom { + 1 }; end; Inc(FCount); SetLength(FMergeArea, FCount); FMergeArea[FCount - 1] := Rct; Result := 0; end; function TZMergeCells.InLeftTopCorner(ACol, ARow: Integer): Integer; var i: Integer; begin Result := -1; for i := 0 to FCount - 1 do if (ACol = FMergeArea[i].left) and (ARow = FMergeArea[i].Top) then begin Result := i; break; end; end; function TZMergeCells.InMergeRange(ACol, ARow: Integer): Integer; var i: Integer; begin Result := -1; for i := 0 to FCount - 1 do if (ACol >= FMergeArea[i].left) and (ACol <= FMergeArea[i].right) and (ARow >= FMergeArea[i].Top) and (ARow <= FMergeArea[i].Bottom) then begin Result := i; break; end; end; function TZMergeCells.IsCrossWithArea(AID, AC1, AR1, AC2, AR2: Integer): Boolean; begin Result := (((Items[AID].left >= AC1) and (Items[AID].left <= AC2)) or ((Items[AID].right >= AC1) and (Items[AID].right <= AC2))) and (((Items[AID].Top >= AR1) and (Items[AID].Top <= AR2)) or ((Items[AID].Bottom >= AR1) and (Items[AID].Bottom <= AR2))); end; function TZMergeCells.MergedCols(ACol, ARow: Integer): Integer; var i: Integer; begin Result := 1; for i := 0 to FCount - 1 do begin if (ACol >= FMergeArea[i].left) and (ACol <= FMergeArea[i].right) and (ARow >= FMergeArea[i].Top) and (ARow <= FMergeArea[i].Bottom) then begin Result := (FMergeArea[i].right - FMergeArea[i].left) + 1; break; end; end; end; function TZMergeCells.MergedRows(ACol, ARow: Integer): Integer; var i: Integer; begin Result := 1; for i := 0 to FCount - 1 do begin if (ACol >= FMergeArea[i].left) and (ACol <= FMergeArea[i].right) and (ARow >= FMergeArea[i].Top) and (ARow <= FMergeArea[i].Bottom) then begin Result := (FMergeArea[i].Bottom - FMergeArea[i].Top) + 1; break; end; end; end; function TZMergeCells.DeleteItem(num: Integer): Boolean; var i: Integer; begin if (num > Count - 1) or (num < 0) then begin Result := false; exit; end; for i := num to Count - 2 do FMergeArea[i] := FMergeArea[i + 1]; Dec(FCount); SetLength(FMergeArea, FCount); Result := true; end; function TZMergeCells.AddRectXY(left, Top, right, Bottom: Integer): Byte; var Rct: TZMergeArea; begin Rct.left := left; Rct.Top := Top; Rct.right := right; Rct.Bottom := Bottom; Result := AddRect(Rct); end; /// /::::::::::::: TZRowColOptions ::::::::::::::::://// constructor TZRowColOptions.Create(ASheet: TZSheet); begin inherited Create(); FSheet := ASheet; FHidden := false; FAuto := true; FStyleID := -1; FBreaked := false; FOutlineLevel := 0; end; procedure TZRowColOptions.Assign(Source: TPersistent); begin if Source is TZRowColOptions then begin Hidden := (Source as TZRowColOptions).Hidden; StyleID := (Source as TZRowColOptions).StyleID; FSize := (Source as TZRowColOptions).FSize; FAuto := (Source as TZRowColOptions).FAuto; FBreaked := (Source as TZRowColOptions).Breaked; FOutlineLevel := (Source as TZRowColOptions).FOutlineLevel; end else inherited Assign(Source); end; function TZRowColOptions.GetAuto(): Boolean; begin Result := FAuto; end; procedure TZRowColOptions.SetAuto(Value: Boolean); begin FAuto := Value; end; function TZRowColOptions.GetSizePoint(): Real; begin Result := FSize; end; procedure TZRowColOptions.SetSizePoint(Value: Real); begin if Value >= 0 then FSize := Value; end; function TZRowColOptions.GetSizeMM(): Real; begin Result := PointToMM(FSize); end; procedure TZRowColOptions.SetSizeMM(Value: Real); begin FSize := MMToPoint(Value); end; /// /::::::::::::: TZRowOptions ::::::::::::::::://// constructor TZRowOptions.Create(ASheet: TZSheet); begin inherited Create(ASheet); FSize := 48; end; function TZRowOptions.GetSizePix(): Integer; var t: Real; begin t := 0.265; if Assigned(FSheet) and Assigned(FSheet.FStore) then t := FSheet.FStore.HorPixelSize; Result := PointToPixel(FSize, t); end; procedure TZRowOptions.SetSizePix(Value: Integer); var t: Real; begin if Value < 0 then exit; t := 0.265; if Assigned(FSheet) and Assigned(FSheet.FStore) then t := FSheet.FStore.HorPixelSize; FSize := PixelToPoint(Value, t); end; /// /::::::::::::: TZColOptions ::::::::::::::::://// constructor TZColOptions.Create(ASheet: TZSheet); begin inherited Create(ASheet); FSize := 12.75; end; function TZColOptions.GetSizePix(): Integer; var t: Real; begin t := 0.265; if Assigned(FSheet) and Assigned(FSheet.FStore) then t := FSheet.FStore.VertPixelSize; Result := PointToPixel(FSize, t); end; procedure TZColOptions.SetSizePix(Value: Integer); var t: Real; begin if Value < 0 then exit; t := 0.265; if Assigned(FSheet) and Assigned(FSheet.FStore) then t := FSheet.FStore.VertPixelSize; FSize := PixelToPoint(Value, t); end; /// /::::::::::::: TZHeaderFooterMargins ::::::::::::::::://// constructor TZHeaderFooterMargins.Create(); begin FMarginTopBottom := 13; FMarginLeft := 0; FMarginRight := 0; FHeight := 7; FUseAutoFitHeight := true; end; procedure TZHeaderFooterMargins.Assign(Source: TPersistent); var t: TZHeaderFooterMargins; begin if Source is TZHeaderFooterMargins then begin t := Source as TZHeaderFooterMargins; FMarginTopBottom := t.MarginTopBottom; FMarginLeft := t.MarginLeft; FMarginRight := t.MarginRight; FHeight := t.Height; FUseAutoFitHeight := t.UseAutoFitHeight; end else inherited Assign(Source); end; function TZHeaderFooterMargins.IsEqual(Source: TPersistent): Boolean; var t: TZHeaderFooterMargins; begin Result := false; if Assigned(Source) and (Source is TZHeaderFooterMargins) then begin t := Source as TZHeaderFooterMargins; Result := (FMarginTopBottom = t.MarginTopBottom) and (FMarginLeft = t.MarginLeft) and (FMarginRight = t.MarginRight) and (FHeight = t.FHeight) and (FUseAutoFitHeight = t.UseAutoFitHeight); end; end; /// /::::::::::::: TZSheetOptions ::::::::::::::::://// constructor TZSheetOptions.Create(); begin inherited; FHeaderMargins := TZHeaderFooterMargins.Create(); FFooterMargins := TZHeaderFooterMargins.Create(); FActiveCol := 0; FActiveRow := 0; FMarginBottom := 25; FMarginLeft := 20; FMarginTop := 25; FMarginRight := 20; FPortraitOrientation := true; FCenterHorizontal := false; FCenterVertical := false; FStartPageNumber := 1; HeaderMargin := 13; FooterMargin := 13; FPaperSize := 9; FFitToHeight := -1; FFitToWidth := -1; FDifferentFirst := false; FDifferentOddEven := false; FHeader := ''; FFooter := ''; FEvenHeader := ''; FEvenFooter := ''; FFirstPageHeader := ''; FFirstPageFooter := ''; FHeaderBGColor := TColorRec.cWindow; FFooterBGColor := TColorRec.cWindow; FSplitVerticalMode := ZSplitNone; FSplitHorizontalMode := ZSplitNone; FSplitVerticalValue := 0; FSplitHorizontalValue := 0; FPaperWidth := 0; FPaperHeight := 0; FScaleToPercent := 100; FScaleToPages := 1; end; destructor TZSheetOptions.Destroy(); begin FreeAndNil(FHeaderMargins); FreeAndNil(FFooterMargins); inherited; end; function TZSheetOptions.GetHeaderMargin(): word; begin Result := FHeaderMargins.Height; end; procedure TZSheetOptions.SetHeaderMargin(Value: word); begin FHeaderMargins.Height := Value; end; function TZSheetOptions.GetFooterMargin(): word; begin Result := FFooterMargins.Height; end; procedure TZSheetOptions.SetFooterMargin(Value: word); begin FFooterMargins.Height := Value; end; procedure TZSheetOptions.Assign(Source: TPersistent); var t: TZSheetOptions; begin if Source is TZSheetOptions then begin t := Source as TZSheetOptions; ActiveCol := t.ActiveCol; ActiveRow := t.ActiveRow; MarginBottom := t.MarginBottom; MarginLeft := t.MarginLeft; MarginTop := t.MarginTop; MarginRight := t.MarginRight; PortraitOrientation := t.PortraitOrientation; CenterHorizontal := t.CenterHorizontal; CenterVertical := t.CenterVertical; StartPageNumber := t.StartPageNumber; PaperSize := t.PaperSize; FitToHeight := t.FitToHeight; FitToWidth := t.FitToWidth; SplitVerticalMode := t.SplitVerticalMode; SplitHorizontalMode := t.SplitHorizontalMode; SplitVerticalValue := t.SplitVerticalValue; SplitHorizontalValue := t.SplitHorizontalValue; Footer := t.Footer; Header := t.Header; EvenHeader := t.EvenHeader; EvenFooter := t.EvenFooter; FirstPageHeader := t.FirstPageHeader; FirstPageFooter := t.FirstPageFooter; HeaderBGColor := t.HeaderBGColor; FooterBGColor := t.FooterBGColor; IsDifferentFirst := t.IsDifferentFirst; IsDifferentOddEven := t.IsDifferentOddEven; ScaleToPercent := t.ScaleToPercent; ScaleToPages := t.ScaleToPages; HeaderMargins.Assign(t.HeaderMargins); FooterMargins.Assign(t.FooterMargins); end else inherited Assign(Source); end; /// /::::::::::::: TZSheet ::::::::::::::::://// constructor TZSheet.Create(AStore: TZWorkBook); var i, j: Integer; begin FStore := AStore; FRowCount := 0; FColCount := 0; FDefaultRowHeight := 12.75; // 16; FDefaultColWidth := 48; // 60; FMergeCells := TZMergeCells.Create(Self); SetLength(FCells, FColCount); FTabColor := TColorRec.cWindow; FProtect := false; FRightToLeft := false; FSelected := false; FSummaryBelow := true; FSummaryRight := true; FApplyStyles := false; FOutlineLevelRow := 0; FOutlineLevelCol := 0; FDrawingRid := 0; SetLength(FRows, FRowCount); SetLength(FColumns, FColCount); for i := 0 to FColCount - 1 do begin SetLength(FCells[i], FRowCount); for j := 0 to FRowCount - 1 do FCells[i, j] := TZCell.Create(Self); FColumns[i] := TZColOptions.Create(Self); FColumns[i].Width := DefaultColWidth; end; for i := 0 to FRowCount - 1 do begin FRows[i] := TZRowOptions.Create(Self); FRows[i].Height := DefaultRowHeight; end; FSheetOptions := TZSheetOptions.Create(); if Assigned(FStore) and Assigned(FStore.DefaultSheetOptions) then FSheetOptions.Assign(FStore.DefaultSheetOptions); FPrintRows := TZSheetPrintTitles.Create(Self, false); FPrintCols := TZSheetPrintTitles.Create(Self, true); FConditionalFormatting := TZConditionalFormatting.Create(); FCharts := TZEChartStore.Create(); FDrawing := TZEDrawing.Create(Self); end; destructor TZSheet.Destroy(); begin try FreeAndNil(FMergeCells); FreeAndNil(FSheetOptions); FPrintRows.Free; FPrintCols.Free; Clear(); FCells := nil; FRows := nil; FColumns := nil; FreeAndNil(FConditionalFormatting); FreeAndNil(FCharts); FreeAndNil(FDrawing); finally inherited Destroy(); end; end; procedure TZSheet.Assign(Source: TPersistent); var zSource: TZSheet; i, j: Integer; begin if Source is TZSheet then begin zSource := Source as TZSheet; /// ///////////////////////////// RowCount := zSource.RowCount; ColCount := zSource.ColCount; TabColor := zSource.TabColor; FitToPage := zSource.FitToPage; Title := zSource.Title; Protect := zSource.Protect; RightToLeft := zSource.RightToLeft; DefaultRowHeight := zSource.DefaultRowHeight; DefaultColWidth := zSource.DefaultColWidth; FViewMode := zSource.FViewMode; FRowBreaks := zSource.FRowBreaks; FColBreaks := zSource.FColBreaks; FDrawingRid := zSource.FDrawingRid; FSummaryBelow := zSource.FSummaryBelow; FSummaryRight := zSource.FSummaryRight; FApplyStyles := zSource.FApplyStyles; FOutlineLevelRow := zSource.FOutlineLevelRow; FOutlineLevelCol := zSource.FOutlineLevelCol; for i := 0 to RowCount - 1 do Rows[i] := zSource.Rows[i]; for i := 0 to ColCount - 1 do begin Columns[i] := zSource.Columns[i]; for j := 0 to RowCount - 1 do Cell[i, j] := zSource.Cell[i, j]; end; FSelected := zSource.Selected; SheetOptions.Assign(zSource.SheetOptions); MergeCells.Clear(); for i := 0 to zSource.MergeCells.Count - 1 do MergeCells.AddRect(zSource.MergeCells.GetItem(i)); ConditionalFormatting.Assign(zSource.ConditionalFormatting); // На этой строке перезаписывается указатель на объект TZEDrawing, // но старый объект не удаляется, т.е. происходит утечка памяти. // FDrawing := TZEDrawing.Create(); FDrawing.Assign(zSource.FDrawing); RowsToRepeat.Assign(zSource.RowsToRepeat); ColsToRepeat.Assign(zSource.ColsToRepeat); end else inherited Assign(Source); end; procedure TZSheet.SetConditionalFormatting(Value: TZConditionalFormatting); begin if Assigned(Value) then FConditionalFormatting.Assign(Value); end; procedure TZSheet.SetCharts(const Value: TZEChartStore); begin if Assigned(Value) then FCharts.Assign(Value); end; function TZSheet.GetSheetIndex: Integer; var i: Integer; begin Result := 0; for i := 0 to WorkBook.FSheets.Count - 1 do if WorkBook.FSheets[i] = Self then exit(i); end; function TZSheet.GetSheetOptions(): TZSheetOptions; begin Result := FSheetOptions; end; procedure TZSheet.InsertRows(ARow, ACount: Integer); var r, c: Integer; begin // resize SetRowCount(FRowCount + ACount); // append and reloc cells for r := Length(FRows) - 1 downto ARow do begin // reloc rows if (r - ACount) < ARow then begin FRows[r] := TZRowOptions.Create(Self); FRows[r].Height := DefaultRowHeight; end else begin FRows[r] := FRows[r - ACount]; end; // reloc cells for c := 0 to ColCount - 1 do begin if (r - ACount) < ARow then begin FCells[c][r].Clear(); end else begin FCells[c][r].Assign(FCells[c][r - ACount]); end; end; end; // reloc merged areas for r := 0 to MergeCells.Count - 1 do begin if MergeCells[r].Top >= ARow then begin MergeCells.Items[r] := TZMergeArea.Create(MergeCells.Items[r].left, MergeCells.Items[r].Top + ACount, MergeCells.Items[r].right, MergeCells.Items[r].Bottom + ACount); end; end; end; function TZSheet.ColsWidth(AFrom, ATo: Integer): Real; begin Result := 0; while (AFrom < ColCount) and (AFrom < ATo) do begin Result := Result + ColWidths[AFrom]; Inc(AFrom); end; end; function TZSheet.RowsHeight(AFrom, ATo: Integer): Real; begin Result := 0; while (AFrom < RowCount) and (AFrom < ATo) do begin Result := Result + RowHeights[AFrom]; Inc(AFrom); end; end; procedure TZSheet.CopyRows(ARowDst, ARowSrc, ACount: Integer); var r, c, delta: Integer; begin // copy row and cell info for r := 0 to ACount - 1 do begin FRows[ARowDst + r].Assign(FRows[ARowSrc + r]); for c := 0 to FColCount - 1 do begin FCells[c][ARowDst + r].Assign(FCells[c][ARowSrc + r]); end; end; delta := ARowDst - ARowSrc; // reloc merged areas for r := 0 to MergeCells.Count - 1 do begin if (MergeCells[r].Top >= ARowSrc) and (MergeCells[r].Bottom < ARowSrc + ACount) then begin MergeCells.AddRect(TZMergeArea.Create(MergeCells.Items[r].left, MergeCells.Items[r].Top + delta, MergeCells.Items[r].right, MergeCells.Items[r].Bottom + delta)); end; end; end; procedure TZSheet.SetSheetOptions(Value: TZSheetOptions); begin if Assigned(Value) then FSheetOptions.Assign(Value); end; procedure TZSheet.SetCorrectTitle(const Value: string); var i: Integer; suffix, newTitle: string; sheetNames: TDictionary<string, string>; regEx: TRegEx; begin newTitle := Trim(Value); if newTitle.Length > 31 then newTitle := newTitle.Substring(0, 31); regEx := TRegEx.Create('[\\/\*\[\]\?:]'); newTitle := regEx.Replace(newTitle, ' '); if newTitle.Trim.IsEmpty then newTitle := 'Лист1'; if Assigned(WorkBook) then begin sheetNames := TDictionary<string, string>.Create; try for i := 0 to Self.WorkBook.Sheets.Count - 1 do if Self <> WorkBook.Sheets[i] then sheetNames.AddOrSetValue(Self.WorkBook.Sheets[i].Title.ToLower, ''); i := 1; suffix := ''; repeat if i > 1 then suffix := ' (' + IntToStr(i) + ')'; if newTitle.Length + suffix.Length > 31 then newTitle := newTitle.Substring(0, 31 - suffix.Length); Inc(i); until not sheetNames.ContainsKey(newTitle.ToLower + suffix); newTitle := newTitle + suffix; finally sheetNames.Free; end; end; Self.FTitle := newTitle; end; procedure TZSheet.SetColumn(num: Integer; const Value: TZColOptions); begin if (num >= 0) and (num < FColCount) then FColumns[num].Assign(Value); end; function TZSheet.GetColumn(num: Integer): TZColOptions; begin if (num >= 0) and (num < FColCount) then Result := FColumns[num] else Result := nil; end; { procedure TZSheet.SetRange(AC1,AR1,AC2,AR2: integer; const Value: TZRange); begin end; procedure TZSheet.SetRangeRef(AFrom, ATo: string; const Value: TZRange); begin end; } function TZSheet.GetRange(AC1, AR1, AC2, AR2: Integer): IZRange; begin Result := TZRange.Create(Self, AC1, AR1, AC2, AR2); end; function TZSheet.GetRangeRef(AFromCol: string; AFromRow: Integer; AToCol: string; AToRow: Integer): IZRange; var AC1, AR1, AC2, AR2: Integer; begin AC1 := ZEGetColByA1(AFromCol); AR1 := AFromRow; AC2 := ZEGetColByA1(AToCol); AR2 := AToRow; Result := TZRange.Create(Self, AC1, AR1, AC2, AR2); end; procedure TZSheet.SetRow(num: Integer; const Value: TZRowOptions); begin if (num >= 0) and (num < FRowCount) then FRows[num].Assign(Value); end; function TZSheet.GetRow(num: Integer): TZRowOptions; begin if (num >= 0) and (num < FRowCount) then Result := FRows[num] else Result := nil; end; procedure TZSheet.SetColWidth(num: Integer; const Value: Real); begin if (num < ColCount) and (num >= 0) and (Value >= 0) then if FColumns[num] <> nil then FColumns[num].Width := Value; end; function TZSheet.GetColWidth(num: Integer): Real; begin Result := 0; if (num < ColCount) and (num >= 0) then if Assigned(FColumns[num]) then Result := FColumns[num].Width end; procedure TZSheet.SetRowHeight(num: Integer; const Value: Real); begin if (num < RowCount) and (num >= 0) and (Value >= 0) then if Assigned(FRows[num]) then FRows[num].Height := Value; end; function TZSheet.GetRowHeight(num: Integer): Real; begin Result := 0; if (num < RowCount) and (num >= 0) then if Assigned(FRows[num]) then Result := FRows[num].Height end; procedure TZSheet.SetDefaultColWidth(const Value: Real); begin if Value >= 0 then FDefaultColWidth := round(Value * 100) / 100; end; procedure TZSheet.SetDefaultRowHeight(const Value: Real); begin if Value >= 0 then FDefaultRowHeight := round(Value * 100) / 100; end; procedure TZSheet.SetPrintCols(const Value: TZSheetPrintTitles); begin FPrintCols.Assign(Value); end; procedure TZSheet.SetPrintRows(const Value: TZSheetPrintTitles); begin FPrintRows.Assign(Value); end; procedure TZSheet.Clear(); var i, j: Integer; begin for i := 0 to FColCount - 1 do begin for j := 0 to FRowCount - 1 do FreeAndNil(FCells[i][j]); SetLength(FCells[i], 0); FColumns[i].Free; FCells[i] := nil; end; for i := 0 to FRowCount - 1 do FRows[i].Free; SetLength(FCells, 0); FRowCount := 0; FColCount := 0; SetLength(FRows, 0); SetLength(FColumns, 0); end; procedure TZSheet.SetCell(ACol, ARow: Integer; const Value: TZCell); begin if (ACol >= 0) and (ACol < FColCount) and (ARow >= 0) and (ARow < FRowCount) then FCells[ACol, ARow].Assign(Value); end; procedure TZSheet.SetCellRef(ACol: string; ARow: Integer; const Value: TZCell); begin SetCell(ZEGetColByA1(ACol), ARow, Value); end; function TZSheet.GetCell(ACol, ARow: Integer): TZCell; begin Result := nil; if (ACol >= 0) and (ACol < FColCount) and (ARow >= 0) and (ARow < FRowCount) then Result := FCells[ACol, ARow]; end; function TZSheet.GetCellRef(ACol: string; ARow: Integer): TZCell; begin Result := GetCell(ZEGetColByA1(ACol), ARow); end; procedure TZSheet.SetColCount(const Value: Integer); var i, j: Integer; begin if Value < 0 then exit; if FColCount > Value then begin // todo Repeatable columns may be affected for i := Value to FColCount - 1 do begin for j := 0 to FRowCount - 1 do FreeAndNil(FCells[i][j]); SetLength(FCells[i], 0); FreeAndNil(FColumns[i]); end; SetLength(FCells, Value); SetLength(FColumns, Value); end else begin SetLength(FCells, Value); SetLength(FColumns, Value); for i := FColCount to Value - 1 do begin SetLength(FCells[i], FRowCount); FColumns[i] := TZColOptions.Create(Self); FColumns[i].Width := DefaultColWidth; for j := 0 to FRowCount - 1 do FCells[i][j] := TZCell.Create(Self); end; end; FColCount := Value; end; function TZSheet.GetColCount: Integer; begin Result := FColCount; end; procedure TZSheet.SetRowCount(const Value: Integer); var i, j: Integer; begin if Value < 0 then exit; if FRowCount > Value then begin // todo Repeatable rows may be affected for i := 0 to FColCount - 1 do begin for j := Value to FRowCount - 1 do FreeAndNil(FCells[i][j]); SetLength(FCells[i], Value); end; for i := Value to FRowCount - 1 do FreeAndNil(FRows[i]); SetLength(FRows, Value); end else begin for i := 0 to FColCount - 1 do begin SetLength(FCells[i], Value); for j := FRowCount to Value - 1 do FCells[i][j] := TZCell.Create(Self); end; SetLength(FRows, Value); for i := FRowCount to Value - 1 do begin FRows[i] := TZRowOptions.Create(Self); FRows[i].Height := DefaultRowHeight; end; end; FRowCount := Value; end; function TZSheet.GetRowCount: Integer; begin Result := FRowCount; end; /// /::::::::::::: TZSheets ::::::::::::::::://// constructor TZSheets.Create(AStore: TZWorkBook); begin FStore := AStore; FCount := 0; SetLength(FSheets, 0); end; destructor TZSheets.Destroy(); var i: Integer; begin for i := 0 to FCount - 1 do FreeAndNil(FSheets[i]); SetLength(FSheets, 0); FSheets := nil; FStore := nil; inherited Destroy(); end; function TZSheets.Add(const ATitle: string = ''): TZSheet; begin Result := TZSheet.Create(FStore); Result.Title := ATitle; SetLength(FSheets, Length(FSheets) + 1); FSheets[High(FSheets)] := Result; Inc(FCount); end; procedure TZSheets.Assign(Source: TPersistent); var t: TZSheets; i: Integer; begin if Source is TZSheets then begin t := Source as TZSheets; Count := t.Count; for i := 0 to Count - 1 do Sheet[i].Assign(t.Sheet[i]); end else inherited Assign(Source); end; procedure TZSheets.SetSheetCount(const Value: Integer); var i: Integer; begin if Count < Value then begin SetLength(FSheets, Value); for i := Count to Value - 1 do FSheets[i] := TZSheet.Create(FStore); end else begin for i := Value to Count - 1 do FreeAndNil(FSheets[i]); SetLength(FSheets, Value); end; FCount := Value; end; procedure TZSheets.SetSheet(num: Integer; Const Value: TZSheet); begin if (num < Count) and (num >= 0) then FSheets[num].Assign(Value); end; function TZSheets.GetSheet(num: Integer): TZSheet; begin if (num < Count) and (num >= 0) then Result := FSheets[num] else Result := nil; end; /// /::::::::::::: TZEXMLDocumentProperties ::::::::::::::::://// constructor TZEXMLDocumentProperties.Create(); begin FAuthor := 'none'; FLastAuthor := 'none'; FCompany := 'none'; FVersion := '11.9999'; FCreated := Now(); FWindowHeight := 20000; FWindowWidth := 20000; FWindowTopX := 150; FWindowTopY := 150; FModeR1C1 := false; end; procedure TZEXMLDocumentProperties.SetAuthor(const Value: string); begin FAuthor := Value; end; procedure TZEXMLDocumentProperties.SetLastAuthor(const Value: string); begin FLastAuthor := Value; end; procedure TZEXMLDocumentProperties.SetCompany(const Value: string); begin FCompany := Value; end; procedure TZEXMLDocumentProperties.SetVersion(const Value: string); begin FVersion := Value; end; procedure TZEXMLDocumentProperties.Assign(Source: TPersistent); var props: TZEXMLDocumentProperties; begin if Source is TZEXMLDocumentProperties then begin props := Source as TZEXMLDocumentProperties; Author := props.Author; LastAuthor := props.LastAuthor; Created := props.Created; Company := props.Company; Version := props.Version; WindowHeight := props.WindowHeight; WindowWidth := props.WindowWidth; WindowTopX := props.WindowTopX; WindowTopY := props.WindowTopY; ModeR1C1 := props.ModeR1C1; end else inherited Assign(Source); end; /// /::::::::::::: TZWorkBook ::::::::::::::::://// constructor TZWorkBook.Create(AOwner: TComponent); begin inherited Create(AOwner); FDocumentProperties := TZEXMLDocumentProperties.Create; FStyles := TZStyles.Create(); FSheets := TZSheets.Create(Self); FHorPixelSize := 0.265; FVertPixelSize := 0.265; FDefaultSheetOptions := TZSheetOptions.Create(); end; destructor TZWorkBook.Destroy(); begin FreeAndNil(FDefaultSheetOptions); FreeAndNil(FDocumentProperties); FreeAndNil(FStyles); FreeAndNil(FSheets); inherited Destroy(); end; function TZWorkBook.AddMediaContent(AFileName: string; AContent: TBytes; ACheckByName: Boolean): Integer; var i: Integer; begin if ACheckByName then begin for i := 0 to High(FMediaList) do begin if FMediaList[i].FileName.ToUpper = AFileName.ToUpper then exit(i); end; end else begin for i := 0 to High(FMediaList) do begin if IsIdenticalByteArray(FMediaList[i].Content, AContent) then exit(i); end; end; SetLength(FMediaList, Length(FMediaList) + 1); FMediaList[High(FMediaList)].FileName := AFileName; FMediaList[High(FMediaList)].Content := AContent; Result := High(FMediaList); end; procedure TZWorkBook.Assign(Source: TPersistent); var t: TZWorkBook; begin if Source is TZWorkBook then begin t := Source as TZWorkBook; FMediaList := t.FMediaList; FDefinedNames := t.FDefinedNames; Styles.Assign(t.Styles); Sheets.Assign(t.Sheets); end else if Source is TZStyles then Styles.Assign(Source as TZStyles) else if Source is TZSheets then Sheets.Assign(Source as TZSheets) else inherited Assign(Source); end; procedure TZWorkBook.SetHorPixelSize(Value: Real); begin if Value > 0 then FHorPixelSize := Value; end; procedure TZWorkBook.SetVertPixelSize(Value: Real); begin if Value > 0 then FVertPixelSize := Value; end; {$IFNDEF FMX} procedure TZWorkBook.GetPixelSize(hdc: THandle); begin // горизонтальный размер пикселя в миллиметрах HorPixelSize := GetDeviceCaps(hdc, HORZSIZE) / GetDeviceCaps(hdc, HORZRES); // вертикальный размер пикселя в миллиметрах VertPixelSize := GetDeviceCaps(hdc, VERTSIZE) / GetDeviceCaps(hdc, VERTRES); end; {$ENDIF} function TZWorkBook.GetDefaultSheetOptions(): TZSheetOptions; begin Result := FDefaultSheetOptions; end; procedure TZWorkBook.SetDefaultSheetOptions(Value: TZSheetOptions); begin if Assigned(Value) then FDefaultSheetOptions.Assign(Value); end; function TZWorkBook.GetDrawing(num: Integer): TZEDrawing; var i, n: Integer; begin Result := nil; n := 0; for i := 0 to Sheets.Count - 1 do begin if not Sheets[i].Drawing.IsEmpty then begin if n = num then begin Result := Sheets[i].Drawing; exit; end; Inc(n); end; end; end; function TZWorkBook.GetDrawingSheetNum(Value: TZEDrawing): Integer; var i: Integer; begin Result := 0; for i := 0 to Sheets.Count - 1 do begin if Value = Sheets[i].Drawing then begin Result := i; exit; end; end; end; { TZSheetPrintTitles } procedure TZSheetPrintTitles.Assign(Source: TPersistent); var f, t: word; a: Boolean; begin if Source is TZSheetPrintTitles then begin f := TZSheetPrintTitles(Source).From; t := TZSheetPrintTitles(Source).Till; a := TZSheetPrintTitles(Source).Active; if a then RequireValid(f, t); FFrom := f; FTill := t; FActive := a; end else inherited; end; constructor TZSheetPrintTitles.Create(const owner: TZSheet; const ForColumns: Boolean); begin if nil = owner then raise Exception.Create(Self.ClassName + ' requires an existing worksheet for owners.'); Self.FOwner := owner; Self.FColumns := ForColumns; end; procedure TZSheetPrintTitles.SetActive(const Value: Boolean); begin if Value then RequireValid(FFrom, FTill); FActive := Value end; procedure TZSheetPrintTitles.SetFrom(const Value: word); begin if Active then RequireValid(Value, FTill); FFrom := Value; end; procedure TZSheetPrintTitles.SetTill(const Value: word); begin if Active then RequireValid(FFrom, Value); FTill := Value; end; function TZSheetPrintTitles.ToString: string; var c: char; begin If Active then begin if FColumns then c := 'C' else c := 'R'; Result := c + IntToStr(From + 1) + ':' + c + IntToStr(Till + 1); end else Result := ''; end; procedure TZSheetPrintTitles.RequireValid(const AFrom, ATill: word); begin if not Valid(AFrom, ATill) then raise Exception.Create('Invalid printable titles for the worksheet.'); end; function TZSheetPrintTitles.Valid(const AFrom, ATill: word): Boolean; var UpperLimit: word; begin Result := false; if AFrom > ATill then exit; if FColumns then UpperLimit := FOwner.ColCount else UpperLimit := FOwner.RowCount; if ATill >= UpperLimit then exit; Result := true; end; /// /::::::::::::: TZConditionalStyleItem ::::::::::::::::://// constructor TZConditionalStyleItem.Create(); begin Clear(); end; procedure TZConditionalStyleItem.Clear(); begin FCondition := ZCFCellContentOperator; FConditionOperator := ZCFOpEqual; FApplyStyleID := -1; FValue1 := ''; FValue2 := ''; FBaseCellPageIndex := -1; FBaseCellRowIndex := 0; FBaseCellColumnIndex := 0; end; procedure TZConditionalStyleItem.Assign(Source: TPersistent); var t: TZConditionalStyleItem; begin if (Source is TZConditionalStyleItem) then begin t := (Source as TZConditionalStyleItem); Condition := t.Condition; ConditionOperator := t.ConditionOperator; Value1 := t.Value1; Value2 := t.Value2; ApplyStyleID := t.ApplyStyleID; BaseCellColumnIndex := t.BaseCellColumnIndex; BaseCellPageIndex := t.BaseCellPageIndex; BaseCellRowIndex := t.BaseCellRowIndex; end else inherited Assign(Source); end; function TZConditionalStyleItem.IsEqual(Source: TPersistent): Boolean; var t: TZConditionalStyleItem; begin Result := false; if (Source is TZConditionalStyleItem) then begin t := (Source as TZConditionalStyleItem); if (Condition <> t.Condition) then exit; if (ConditionOperator <> t.ConditionOperator) then exit; if (ApplyStyleID <> t.ApplyStyleID) then exit; if (BaseCellColumnIndex <> t.BaseCellColumnIndex) then exit; if (BaseCellPageIndex <> t.BaseCellPageIndex) then exit; if (BaseCellRowIndex <> t.BaseCellRowIndex) then exit; if (Value1 <> t.Value1) then exit; if (Value2 <> t.Value2) then exit; Result := true; end; end; /// /::::::::::::: TZConditionalStyle ::::::::::::::::://// constructor TZConditionalStyle.Create(); var i: Integer; begin FCount := 0; FMaxCount := 3; SetLength(FConditions, FMaxCount); for i := 0 to FMaxCount - 1 do FConditions[i] := TZConditionalStyleItem.Create(); FAreas := TZConditionalAreas.Create(); end; destructor TZConditionalStyle.Destroy(); var i: Integer; begin for i := 0 to FMaxCount - 1 do if (Assigned(FConditions[i])) then FreeAndNil(FConditions[i]); SetLength(FConditions, 0); FConditions := nil; FreeAndNil(FAreas); inherited; end; procedure TZConditionalStyle.Assign(Source: TPersistent); var t: TZConditionalStyle; i: Integer; begin if (Source is TZConditionalStyle) then begin t := Source as TZConditionalStyle; Count := t.Count; FAreas.Assign(t.Areas); for i := 0 to Count - 1 do FConditions[i].Assign(t.Items[i]); end else inherited Assign(Source); end; function TZConditionalStyle.IsEqual(Source: TPersistent): Boolean; var t: TZConditionalStyle; i: Integer; begin Result := false; if (Source is TZConditionalStyle) then begin t := Source as TZConditionalStyle; if (Count <> t.Count) then exit; for i := 0 to Count - 1 do if (not FConditions[i].IsEqual(t.Items[i])) then exit; Result := true; end; end; function TZConditionalStyle.GetItem(num: Integer): TZConditionalStyleItem; begin Result := nil; if (num >= 0) and (num < Count) then Result := FConditions[num]; end; procedure TZConditionalStyle.SetItem(num: Integer; Value: TZConditionalStyleItem); begin if (num >= 0) and (num < Count) then FConditions[num].Assign(Value); end; procedure TZConditionalStyle.SetCount(Value: Integer); var i: Integer; begin // TODO: нужно ли ограничение на максимальное кол-во? if (Value >= 0) then begin if (Value < FCount) then begin for i := Value to FCount - 1 do FConditions[i].Clear(); end else if (Value > FMaxCount) then begin SetLength(FConditions, Value); for i := FMaxCount to Value - 1 do FConditions[i] := TZConditionalStyleItem.Create(); FMaxCount := Value; end; FCount := Value; end; end; procedure TZConditionalStyle.SetAreas(Value: TZConditionalAreas); begin if (Assigned(Value)) then FAreas.Assign(Value); end; function TZConditionalStyle.Add(): TZConditionalStyleItem; begin Count := Count + 1; Result := FConditions[Count - 1]; end; function TZConditionalStyle.Add(StyleItem: TZConditionalStyleItem): TZConditionalStyleItem; begin Result := Add(); if (Assigned(StyleItem)) then Result.Assign(StyleItem); end; procedure TZConditionalStyle.Delete(num: Integer); var i: Integer; t: TZConditionalStyleItem; begin if (num >= 0) and (num < Count) then begin t := FConditions[num]; for i := num to Count - 2 do FConditions[i] := FConditions[i + 1]; if (Count > 0) then FConditions[Count - 1] := t; Count := Count - 1; end; end; procedure TZConditionalStyle.Insert(num: Integer); begin Insert(num, nil); end; procedure TZConditionalStyle.Insert(num: Integer; StyleItem: TZConditionalStyleItem); var i: Integer; t: TZConditionalStyleItem; begin if (num >= 0) and (num < Count) then begin Add(); t := FConditions[Count - 1]; for i := Count - 1 downto num + 1 do FConditions[i] := FConditions[i - 1]; FConditions[num] := t; if (Assigned(StyleItem)) then FConditions[num].Assign(StyleItem); end; end; /// /::::::::::::: TZConditionalAreaItem ::::::::::::::::://// constructor TZConditionalAreaItem.Create(); begin Create(0, 0, 1, 1); end; constructor TZConditionalAreaItem.Create(ColumnNum, RowNum, AreaWidth, AreaHeight: Integer); begin Row := RowNum; Column := ColumnNum; Width := AreaWidth; Height := AreaHeight; end; procedure TZConditionalAreaItem.SetRow(Value: Integer); begin if Value >= 0 then FRow := Value; end; procedure TZConditionalAreaItem.SetColumn(Value: Integer); begin if Value >= 0 then FColumn := Value; end; procedure TZConditionalAreaItem.SetWidth(Value: Integer); begin if Value >= 0 then FWidth := Value; end; procedure TZConditionalAreaItem.SetHeight(Value: Integer); begin if Value >= 0 then FHeight := Value; end; procedure TZConditionalAreaItem.Assign(Source: TPersistent); var t: TZConditionalAreaItem; begin if (Source is TZConditionalAreaItem) then begin t := Source as TZConditionalAreaItem; Row := t.Row; Column := t.Column; Height := t.Height; Width := t.Width; end else inherited Assign(Source); end; function TZConditionalAreaItem.IsEqual(Source: TPersistent): Boolean; var t: TZConditionalAreaItem; begin Result := false; if (Source is TZConditionalAreaItem) then begin t := Source as TZConditionalAreaItem; if (FRow <> t.Row) then exit; if (FColumn <> t.Column) then exit; if (FWidth <> t.Width) then exit; if (FHeight <> t.Height) then exit; Result := true; end; end; /// /::::::::::::: TZConditionalAreas ::::::::::::::::://// constructor TZConditionalAreas.Create(); begin FCount := 1; SetLength(FItems, FCount); FItems[0] := TZConditionalAreaItem.Create(); end; destructor TZConditionalAreas.Destroy(); var i: Integer; begin for i := 0 to FCount - 1 do if (Assigned(FItems[i])) then FreeAndNil(FItems[i]); SetLength(FItems, 0); FItems := nil; inherited; end; procedure TZConditionalAreas.SetCount(Value: Integer); var i: Integer; begin if ((Value >= 0) and (Value <> Count)) then begin if (Value < Count) then begin for i := Value to Count - 1 do if (Assigned(FItems[i])) then FreeAndNil(FItems[i]); SetLength(FItems, Value); end else if (Value > Count) then begin SetLength(FItems, Value); for i := Count to Value - 1 do FItems[i] := TZConditionalAreaItem.Create(); end; FCount := Value; end; end; function TZConditionalAreas.GetItem(num: Integer): TZConditionalAreaItem; begin Result := nil; if ((num >= 0) and (num < FCount)) then Result := FItems[num]; end; procedure TZConditionalAreas.SetItem(num: Integer; Value: TZConditionalAreaItem); begin if ((num >= 0) and (num < Count)) then if (Assigned(Value)) then FItems[num].Assign(Value); end; function TZConditionalAreas.Add(): TZConditionalAreaItem; begin SetCount(FCount + 1); Result := FItems[FCount - 1]; end; function TZConditionalAreas.Add(ColumnNum, RowNum, AreaWidth, AreaHeight: Integer): TZConditionalAreaItem; begin Result := Add(); Result.Row := RowNum; Result.Column := ColumnNum; Result.Width := AreaWidth; Result.Height := AreaHeight; end; procedure TZConditionalAreas.Assign(Source: TPersistent); var t: TZConditionalAreas; i: Integer; begin if (Source is TZConditionalAreas) then begin t := Source as TZConditionalAreas; Count := t.Count; for i := 0 to Count - 1 do FItems[i].Assign(t.Items[i]); end else inherited Assign(Source); end; procedure TZConditionalAreas.Delete(num: Integer); var t: TZConditionalAreaItem; i: Integer; begin if ((num >= 0) and (num < Count)) then begin t := FItems[num]; for i := num to Count - 2 do FItems[i] := FItems[i + 1]; FItems[Count - 1] := t; Count := Count - 1; end; end; // Определяет, находится ли ячейка в области // INPUT // ColumnNum: integer - номер столбца ячейки // RowNum: integer - номер строки ячейки // RETURN // boolean - true - ячейка входит в область function TZConditionalAreas.IsCellInArea(ColumnNum, RowNum: Integer): Boolean; var i, X, Y, xx, yy: Integer; begin Result := false; for i := 0 to Count - 1 do begin X := FItems[i].Column; Y := FItems[i].Row; xx := X + FItems[i].Width; yy := Y + FItems[i].Height; if ((ColumnNum >= X) and (ColumnNum < xx) and (RowNum >= Y) and (RowNum < yy)) then begin Result := true; break; end; end; end; function TZConditionalAreas.IsEqual(Source: TPersistent): Boolean; var t: TZConditionalAreas; i: Integer; begin Result := false; if (Source is TZConditionalAreas) then begin t := Source as TZConditionalAreas; if (Count <> t.Count) then exit; for i := 0 to Count - 1 do if (not FItems[i].IsEqual(t.Items[i])) then exit; Result := true; end; end; /// /::::::::::::: TConditionalFormatting ::::::::::::::::://// constructor TZConditionalFormatting.Create(); begin FCount := 0; SetLength(FStyles, 0); end; destructor TZConditionalFormatting.Destroy(); var i: Integer; begin for i := 0 to FCount - 1 do if (Assigned(FStyles[i])) then FreeAndNil(FStyles[i]); SetLength(FStyles, 0); FStyles := nil; inherited; end; procedure TZConditionalFormatting.SetCount(Value: Integer); var i: Integer; begin if Value >= 0 then begin if Value < FCount then begin for i := Value to FCount - 1 do FreeAndNil(FStyles[i]); SetLength(FStyles, Value); end else if Value > FCount then begin SetLength(FStyles, Value); for i := FCount to Value - 1 do FStyles[i] := TZConditionalStyle.Create(); end; FCount := Value; end; end; function TZConditionalFormatting.Add(): TZConditionalStyle; begin Result := Add(nil); end; function TZConditionalFormatting.GetItem(num: Integer): TZConditionalStyle; begin Result := nil; if (num >= 0) and (num < Count) then Result := FStyles[num]; end; procedure TZConditionalFormatting.SetItem(num: Integer; Value: TZConditionalStyle); begin if (num >= 0) and (num < Count) then if Assigned(Value) then FStyles[num].Assign(Value); end; function TZConditionalFormatting.Add(Style: TZConditionalStyle): TZConditionalStyle; begin Count := Count + 1; Result := FStyles[Count - 1]; if Assigned(Style) then Result.Assign(Style); end; // Добавить условное форматирование с областью // INPUT // ColumnNum: integer - номер колонки // RowNum: integer - номер строки // AreaWidth: integer - ширина области // AreaHeight: integer - высота области // RETURN // TZConditionalStyle - добавленный стиль function TZConditionalFormatting.Add(ColumnNum, RowNum, AreaWidth, AreaHeight: Integer): TZConditionalStyle; var t: TZConditionalAreaItem; begin Result := Add(nil); t := Result.Areas[0]; t.Row := RowNum; t.Column := ColumnNum; t.Width := AreaWidth; t.Height := AreaHeight; end; procedure TZConditionalFormatting.Clear(); begin SetCount(0); end; // Delete condition formatting item // INPUT // num: integer - number of CF item // RETURN // boolean - true - item deleted function TZConditionalFormatting.Delete(num: Integer): Boolean; var i: Integer; begin Result := false; if (num >= 0) and (num < Count) then begin FreeAndNil(FStyles[num]); for i := num to FCount - 2 do FStyles[num] := FStyles[num + 1]; Dec(FCount); end; end; procedure TZConditionalFormatting.Assign(Source: TPersistent); var t: TZConditionalFormatting; i: Integer; begin if Source is TZConditionalFormatting then begin t := Source as TZConditionalFormatting; FCount := t.Count; for i := 0 to FCount - 1 do FStyles[i].Assign(t.Items[i]); end else inherited Assign(Source); end; function TZConditionalFormatting.IsEqual(Source: TPersistent): Boolean; var t: TZConditionalFormatting; i: Integer; begin Result := false; if Source is TZConditionalFormatting then begin t := Source as TZConditionalFormatting; if (Count <> t.Count) then exit; for i := 0 to Count - 1 do if (not FStyles[i].IsEqual(t.Items[i])) then exit; Result := true; end; end; /// /::::::::::::: TZECommonFrameAncestor ::::::::::::::::://// constructor TZECommonFrameAncestor.Create(); begin FX := 0; FY := 0; FWidth := 10; FHeight := 10; FTransform := TZETransform.Create(); end; constructor TZECommonFrameAncestor.Create(AX, AY, AWidth, AHeight: Integer); begin FX := AX; FY := AY; FWidth := AWidth; FHeight := AHeight; FTransform := TZETransform.Create(); end; destructor TZECommonFrameAncestor.Destroy(); begin FreeAndNil(FTransform); inherited; end; function TZECommonFrameAncestor.IsEqual(const Source: TPersistent): Boolean; var tmp: TZECommonFrameAncestor; begin Result := false; if Assigned(Source) and (Source is TZECommonFrameAncestor) then begin tmp := Source as TZECommonFrameAncestor; Result := (FX = tmp.X) and (FY = tmp.Y) and (FWidth = tmp.Width) and (FHeight = tmp.Height); if (Result) then Result := FTransform.IsEqual(tmp.Transform); end; end; procedure TZECommonFrameAncestor.Assign(Source: TPersistent); var b: Boolean; tmp: TZECommonFrameAncestor; begin b := Assigned(Source); if b then b := Source is TZECommonFrameAncestor; if b then begin tmp := Source as TZECommonFrameAncestor; FX := tmp.X; FY := tmp.Y; FWidth := tmp.Width; FHeight := tmp.Height; FTransform.Assign(tmp.Transform); end else inherited Assign(Source); end; procedure TZECommonFrameAncestor.SetHeight(Value: Integer); begin FHeight := Value; end; procedure TZECommonFrameAncestor.SetTransform(const Value: TZETransform); begin if Assigned(Value) then FTransform.Assign(Value); end; procedure TZECommonFrameAncestor.SetWidth(Value: Integer); begin FWidth := Value; end; procedure TZECommonFrameAncestor.SetX(Value: Integer); begin FX := Value; end; procedure TZECommonFrameAncestor.SetY(Value: Integer); begin FY := Value; end; /// /::::::::::::: TZETransform ::::::::::::::::://// constructor TZETransform.Create(); begin Clear(); end; procedure TZETransform.Assign(Source: TPersistent); var b: Boolean; tmp: TZETransform; begin b := Assigned(Source); if b then b := Source is TZETransform; if b then begin tmp := Source as TZETransform; FRotate := tmp.Rotate; FScaleX := tmp.ScaleX; FScaleY := tmp.ScaleY; FSkewX := tmp.SkewX; FSkewY := tmp.SkewY; FTranslateX := tmp.TranslateX; FTranslateY := tmp.TranslateY; end else inherited Assign(Source); end; procedure TZETransform.Clear(); begin FRotate := 0; FScaleX := 1; FScaleY := 1; FSkewX := 0; FSkewY := 0; FTranslateX := 0; FTranslateY := 0; end; function TZETransform.IsEqual(const Source: TPersistent): Boolean; var tmp: TZETransform; begin Result := Assigned(Source); if (Result) then Result := Source is TZETransform; if (Result) then begin tmp := Source as TZETransform; Result := (FRotate = tmp.Rotate) and (FScaleX = tmp.ScaleX) and (FScaleY = tmp.ScaleY) and (FSkewX = tmp.SkewX) and (FSkewY = tmp.SkewY) and (FTranslateX = tmp.TranslateX) and (FTranslateY = tmp.TranslateY); end; end; /// /::::::::::::: TZEChartRangeItem ::::::::::::::::://// constructor TZEChartRangeItem.Create(); begin FSheetNum := -1; FRow := 0; FCol := 0; FWidth := 1; FHeight := 1; end; constructor TZEChartRangeItem.Create(ASheetNum: Integer; ACol, ARow, AWidth, AHeight: Integer); begin FSheetNum := ASheetNum; FRow := ARow; FCol := ACol; FWidth := AWidth; FHeight := AHeight; end; procedure TZEChartRangeItem.Assign(Source: TPersistent); var tmp: TZEChartRangeItem; b: Boolean; begin b := Assigned(Source); if b then begin b := Source is TZEChartRangeItem; if b then begin tmp := Source as TZEChartRangeItem; FSheetNum := tmp.SheetNum; FRow := tmp.Row; FCol := tmp.Col; FWidth := tmp.Width; FHeight := tmp.Height; end; end; if not b then inherited Assign(Source); end; function TZEChartRangeItem.IsEqual(const Source: TPersistent): Boolean; var tmp: TZEChartRangeItem; begin Result := Assigned(Source); if Result then begin Result := Source is TZEChartRangeItem; if Result then begin tmp := Source as TZEChartRangeItem; Result := (FSheetNum = tmp.SheetNum) and (FCol = tmp.Col) and (FRow = tmp.Row) and (FHeight = tmp.Height) and (FWidth = tmp.Width); end; end; end; /// /::::::::::::: TZEChartRange ::::::::::::::::://// constructor TZEChartRange.Create(); begin FCount := 0; end; destructor TZEChartRange.Destroy(); begin Clear(); inherited; end; function TZEChartRange.GetItem(num: Integer): TZEChartRangeItem; begin Result := nil; if (num >= 0) and (num < FCount) then Result := FItems[num]; end; procedure TZEChartRange.SetItem(num: Integer; const Value: TZEChartRangeItem); begin if (num >= 0) and (num < FCount) then FItems[num].Assign(Value); end; function TZEChartRange.Add(): TZEChartRangeItem; begin SetLength(FItems, FCount + 1); Result := TZEChartRangeItem.Create(); FItems[FCount] := Result; Inc(FCount); end; function TZEChartRange.Add(const ItemForClone: TZEChartRangeItem): TZEChartRangeItem; begin Result := Add(); if Assigned(ItemForClone) then Result.Assign(ItemForClone); end; function TZEChartRange.Delete(num: Integer): Boolean; var i: Integer; begin Result := (num >= 0) and (num < FCount); if Result then begin FreeAndNil(FItems[num]); for i := num to FCount - 2 do FItems[i] := FItems[i + 1]; Dec(FCount); SetLength(FItems, FCount); end; end; procedure TZEChartRange.Clear(); var i: Integer; begin for i := 0 to FCount - 1 do FreeAndNil(FItems[i]); FCount := 0; SetLength(FItems, 0); end; procedure TZEChartRange.Assign(Source: TPersistent); var tmp: TZEChartRange; b: Boolean; i: Integer; begin b := Assigned(Source); if b then begin b := Source is TZEChartRange; if b then begin tmp := Source as TZEChartRange; if FCount > tmp.Count then begin for i := tmp.Count to FCount - 1 do FreeAndNil(FItems[i]); FCount := tmp.Count; SetLength(FItems, FCount); end else if FCount < tmp.Count then begin SetLength(FItems, tmp.Count); for i := FCount to tmp.Count - 1 do FItems[i] := TZEChartRangeItem.Create(); FCount := tmp.Count; SetLength(FItems, FCount); end; for i := 0 to FCount - 1 do FItems[i].Assign(tmp.Items[i]); end; end; if not b then inherited Assign(Source); end; function TZEChartRange.IsEqual(const Source: TPersistent): Boolean; var tmp: TZEChartRange; i: Integer; begin Result := Assigned(Source); if Result then begin Result := Source is TZEChartRange; if Result then begin tmp := Source as TZEChartRange; Result := FCount = tmp.Count; if Result then for i := 0 to FCount - 1 do if not FItems[i].IsEqual(tmp.Items[i]) then begin Result := false; break; end; end; end; end; /// /::::::::::::: TZEChartTitleItem ::::::::::::::::://// constructor TZEChartTitleItem.Create(); begin FFont := TZFont.Create(); FText := ''; FRotationAngle := 0; FIsDisplay := true; end; destructor TZEChartTitleItem.Destroy(); begin FreeAndNil(FFont); inherited; end; procedure TZEChartTitleItem.Assign(Source: TPersistent); var tmp: TZEChartTitleItem; b: Boolean; begin b := Assigned(Source); if (b) then begin b := Source is TZEChartTitleItem; if (b) then begin tmp := Source as TZEChartTitleItem; FFont.Assign(tmp.Font); FText := tmp.Text; FRotationAngle := tmp.RotationAngle; FIsDisplay := tmp.IsDisplay; end; end; if (not b) then inherited Assign(Source); end; function TZEChartTitleItem.IsEqual(const Source: TPersistent): Boolean; var tmp: TZEChartTitleItem; begin Result := Assigned(Source); if (Result) then begin Result := Source is TZEChartTitleItem; if (Result) then begin tmp := Source as TZEChartTitleItem; Result := false; if (FIsDisplay = tmp.IsDisplay) then if (FRotationAngle = tmp.RotationAngle) then if (FText = tmp.Text) then Result := ZEIsFontsEquals(FFont, tmp.Font); end; end; end; procedure TZEChartTitleItem.SetFont(const Value: TZFont); begin if (Assigned(Value)) then FFont.Assign(Value); end; /// /::::::::::::: TZEChartLegend ::::::::::::::::://// constructor TZEChartLegend.Create(); begin inherited; FPosition := ZELegendStart; FAlign := ZELegendAlignCenter; end; procedure TZEChartLegend.Assign(Source: TPersistent); var tmp: TZEChartLegend; begin inherited Assign(Source); if Assigned(Source) and (Source is TZEChartLegend) then begin tmp := Source as TZEChartLegend; FAlign := tmp.Align; FPosition := tmp.Position; end; end; function TZEChartLegend.IsEqual(const Source: TPersistent): Boolean; var tmp: TZEChartLegend; begin Result := inherited IsEqual(Source); if (Result) then begin Result := false; if (Source is TZEChartLegend) then begin tmp := Source as TZEChartLegend; Result := (FPosition = tmp.Position) and (FAlign = tmp.Align); end; end; end; /// /::::::::::::: TZEChartAxis ::::::::::::::::://// constructor TZEChartAxis.Create(); begin inherited; FLogarithmic := false; FReverseDirection := false; FScaleMin := 0; FScaleMax := 20000; FAutoScaleMin := true; FAutoScaleMax := true; end; procedure TZEChartAxis.Assign(Source: TPersistent); var tmp: TZEChartAxis; begin inherited Assign(Source); if (Source is TZEChartAxis) then begin tmp := Source as TZEChartAxis; FLogarithmic := tmp.Logarithmic; FReverseDirection := tmp.ReverseDirection; FScaleMin := tmp.ScaleMin; FScaleMax := tmp.ScaleMax; FAutoScaleMin := tmp.AutoScaleMin; FAutoScaleMax := tmp.AutoScaleMax; end end; function TZEChartAxis.IsEqual(const Source: TPersistent): Boolean; var tmp: TZEChartAxis; begin Result := inherited IsEqual(Source); if (Result) then begin Result := Source is TZEChartAxis; if (Result) then begin tmp := Source as TZEChartAxis; Result := (FLogarithmic = tmp.FLogarithmic) and (FReverseDirection = tmp.FReverseDirection) and (FAutoScaleMin = tmp.AutoScaleMin) and (FAutoScaleMax = tmp.AutoScaleMax); if (Result) then begin // TODO: for comparsion double values need check observational errors? if (not FAutoScaleMin) then Result := FScaleMin <> tmp.ScaleMin; if (Result and (not FAutoScaleMin)) then Result := FScaleMax <> tmp.ScaleMax; end; end; end; end; /// /::::::::::::: TZEChartSettings ::::::::::::::::://// constructor TZEChartSettings.Create(); begin FJapanCandle := true; end; destructor TZEChartSettings.Destroy(); begin inherited; end; procedure TZEChartSettings.Assign(Source: TPersistent); var tmp: TZEChartSettings; b: Boolean; begin b := Source <> nil; if (b) then begin b := Source is TZEChartSettings; if (b) then begin tmp := Source as TZEChartSettings; FJapanCandle := tmp.JapanCandle; end; end; if (not b) then inherited Assign(Source); end; function TZEChartSettings.IsEqual(const Source: TPersistent): Boolean; var tmp: TZEChartSettings; begin Result := Assigned(Source); if (Result) then begin Result := Source is TZEChartSettings; if (Result) then begin tmp := Source as TZEChartSettings; Result := FJapanCandle = tmp.JapanCandle; end; end; end; /// /::::::::::::: TZEChartSeries ::::::::::::::::://// constructor TZEChartSeries.Create(); begin FChartType := ZEChartTypeBar; FSeriesName := ''; FSeriesNameSheet := -1; FSeriesNameRow := -1; FSeriesNameCol := -1; FRanges := TZEChartRange.Create(); end; destructor TZEChartSeries.Destroy(); begin FreeAndNil(FRanges); inherited; end; procedure TZEChartSeries.Assign(Source: TPersistent); var tmp: TZEChartSeries; b: Boolean; begin b := Assigned(Source); if (b) then begin b := Source is TZEChartSeries; if (b) then begin tmp := TZEChartSeries.Create(); FChartType := tmp.ChartType; FSeriesName := tmp.SeriesName; FSeriesNameSheet := tmp.SeriesNameSheet; FSeriesNameRow := tmp.SeriesNameRow; FSeriesNameCol := tmp.SeriesNameCol; FRanges.Assign(tmp.Ranges); end; end; if (not b) then inherited Assign(Source); end; function TZEChartSeries.IsEqual(const Source: TPersistent): Boolean; var tmp: TZEChartSeries; begin Result := Source <> nil; if (Result) then Result := Source is TZEChartSeries; if (Result) then begin tmp := TZEChartSeries.Create(); Result := (FChartType = tmp.ChartType) and (FSeriesNameSheet = tmp.SeriesNameSheet); if (Result) then begin if (((FSeriesNameRow < 0) or (FSeriesNameCol < 0)) and (tmp.SeriesNameRow < 0) or (tmp.SeriesNameCol < 0)) then Result := tmp.SeriesName = FSeriesName else Result := (tmp.SeriesNameRow = FSeriesNameRow) and (tmp.SeriesNameCol = FSeriesNameCol); end; if (Result) then Result := FRanges.IsEqual(tmp.Ranges); end; end; /// /::::::::::::: TZEChart ::::::::::::::::://// procedure TZEChart.CommonInit(); begin FTitle := TZEChartTitleItem.Create(); FSubtitle := TZEChartTitleItem.Create(); FLegend := TZEChartLegend.Create(); FFooter := TZEChartTitleItem.Create(); FAxisX := TZEChartAxis.Create(); FAxisY := TZEChartAxis.Create(); FAxisZ := TZEChartAxis.Create(); FSecondaryAxisX := TZEChartAxis.Create(); FSecondaryAxisY := TZEChartAxis.Create(); FSecondaryAxisZ := TZEChartAxis.Create(); FDefaultChartType := ZEChartTypeBar; FView3D := false; FViewDeep := false; end; constructor TZEChart.Create(AX, AY, AWidth, AHeight: Integer); begin inherited; CommonInit(); X := AX; Y := AY; Width := AWidth; Height := AHeight; end; constructor TZEChart.Create(); begin inherited; CommonInit(); end; destructor TZEChart.Destroy(); begin FreeAndNil(FSubtitle); FreeAndNil(FTitle); FreeAndNil(FLegend); FreeAndNil(FFooter); FreeAndNil(FAxisX); FreeAndNil(FAxisY); FreeAndNil(FAxisZ); FreeAndNil(FSecondaryAxisX); FreeAndNil(FSecondaryAxisY); FreeAndNil(FSecondaryAxisZ); inherited; end; function TZEChart.IsEqual(const Source: TPersistent): Boolean; var tmp: TZEChart; begin Result := inherited IsEqual(Source); if Result and (Source is TZEChart) then begin tmp := Source as TZEChart; Result := inherited IsEqual(Source); if (Result) then Result := FSubtitle.IsEqual(tmp.Subtitle) and FTitle.IsEqual(tmp.Title) and FLegend.IsEqual(tmp.Legend) and FAxisX.IsEqual(tmp.AxisX) and FAxisY.IsEqual(tmp.AxisY) and FAxisZ.IsEqual(tmp.AxisZ) and FSecondaryAxisX.IsEqual(tmp.SecondaryAxisX) and FSecondaryAxisY.IsEqual(tmp.SecondaryAxisY) and FSecondaryAxisZ.IsEqual(tmp.SecondaryAxisZ) and (FView3D = tmp.View3D) and (FViewDeep = tmp.ViewDeep); end; end; procedure TZEChart.SetAxisX(const Value: TZEChartAxis); begin if (Assigned(Value)) then FAxisX.Assign(Value); end; procedure TZEChart.SetAxisY(const Value: TZEChartAxis); begin if (Assigned(Value)) then FAxisY.Assign(Value); end; procedure TZEChart.SetAxisZ(const Value: TZEChartAxis); begin if (Assigned(Value)) then FAxisZ.Assign(Value); end; procedure TZEChart.SetSecondaryAxisX(const Value: TZEChartAxis); begin if (Assigned(Value)) then FSecondaryAxisX.Assign(Value); end; procedure TZEChart.SetSecondaryAxisY(const Value: TZEChartAxis); begin if (Assigned(Value)) then FSecondaryAxisY.Assign(Value); end; procedure TZEChart.SetSecondaryAxisZ(const Value: TZEChartAxis); begin if (Assigned(Value)) then FSecondaryAxisZ.Assign(Value); end; procedure TZEChart.SetFooter(const Value: TZEChartTitleItem); begin if (Assigned(Value)) then FFooter.Assign(Value); end; procedure TZEChart.SetLegend(const Value: TZEChartLegend); begin if (Assigned(Value)) then FLegend.Assign(Value); end; procedure TZEChart.SetSubtitle(const Value: TZEChartTitleItem); begin if (Assigned(Value)) then FSubtitle.Assign(Value); end; procedure TZEChart.SetTitle(const Value: TZEChartTitleItem); begin if (Assigned(Value)) then FTitle.Assign(Value); end; procedure TZEChart.Assign(Source: TPersistent); var tmp: TZEChart; begin inherited; if Assigned(Source) and (Source is TZEChart) then begin tmp := Source as TZEChart; FSubtitle.Assign(tmp.Subtitle); FTitle.Assign(tmp.Title); FLegend.Assign(tmp.Legend); FAxisX.Assign(tmp.AxisX); FAxisY.Assign(tmp.AxisY); FAxisZ.Assign(tmp.AxisZ); FSecondaryAxisX.Assign(tmp.SecondaryAxisX); FSecondaryAxisY.Assign(tmp.SecondaryAxisY); FSecondaryAxisZ.Assign(tmp.SecondaryAxisZ); FView3D := tmp.View3D; FViewDeep := tmp.ViewDeep; end; end; /// /::::::::::::: TZEChartStore ::::::::::::::::://// constructor TZEChartStore.Create(); begin FCount := 0; SetLength(FItems, 0); end; destructor TZEChartStore.Destroy(); begin Clear(); inherited; end; function TZEChartStore.Add(): TZEChart; begin Result := TZEChart.Create(); SetLength(FItems, FCount + 1); FItems[FCount] := Result; Inc(FCount); end; function TZEChartStore.Add(const ItemForClone: TZEChart): TZEChart; begin Result := Add(); Result.Assign(ItemForClone); end; procedure TZEChartStore.Assign(Source: TPersistent); var tmp: TZEChartStore; b: Boolean; i: Integer; begin b := Assigned(Source); if (b) then begin b := Source is TZEChartStore; if (b) then begin tmp := Source as TZEChartStore; if (FCount > tmp.Count) then begin for i := tmp.Count to FCount - 1 do FreeAndNil(FItems[i]); SetLength(FItems, tmp.Count); end else if (FCount < tmp.Count) then begin SetLength(FItems, tmp.Count); for i := FCount to tmp.Count - 1 do FItems[i] := TZEChart.Create(); end; FCount := tmp.Count; for i := 0 to FCount - 1 do FItems[i].Assign(tmp[i]); end; end; if (not b) then inherited Assign(Source); end; function TZEChartStore.Delete(num: Integer): Boolean; var i: Integer; begin Result := (num >= 0) and (num < FCount); if (Result) then begin FreeAndNil(FItems[num]); for i := num to FCount - 2 do FItems[i] := FItems[i + 1]; Dec(FCount); SetLength(FItems, FCount); end; end; procedure TZEChartStore.Clear(); var i: Integer; begin for i := 0 to FCount - 1 do FreeAndNil(FItems[i]); FCount := 0; SetLength(FItems, 0); end; function TZEChartStore.GetItem(num: Integer): TZEChart; begin Result := nil; if ((num >= 0) and (num < FCount)) then Result := FItems[num]; end; procedure TZEChartStore.SetItem(num: Integer; const Value: TZEChart); begin if ((num >= 0) and (num < FCount)) then FItems[num].Assign(Value); end; function TZEChartStore.IsEqual(const Source: TPersistent): Boolean; var tmp: TZEChartStore; i: Integer; begin Result := Assigned(Source); if (Result) then begin Result := Source is TZEChartStore; if (Result) then begin tmp := Source as TZEChartStore; Result := FCount = tmp.Count; if (Result) then for i := 0 to FCount - 1 do if (not FItems[i].IsEqual(tmp[i])) then begin Result := false; break; end; end; end; end; /// /::::::::::::: TZEPicture ::::::::::::::::://// procedure TZEPicture.Assign(Source: TPersistent); var tmp: TZEPicture; begin inherited; if Assigned(Source) and (Source is TZEPicture) then begin tmp := Source as TZEPicture; FId := tmp.FId; FRelId := tmp.FRelId; FTitle := tmp.Title; FDescription := tmp.Description; FCellAnchor := tmp.FCellAnchor; FFileName := tmp.FFileName; FRow := tmp.Row; FCol := tmp.Col; FFromCol := tmp.FFromCol; FFromColOff := tmp.FFromColOff; FFromRow := tmp.FFromRow; FFromRowOff := tmp.FFromRowOff; FToCol := tmp.FToCol; FToColOff := tmp.FToColOff; FToRow := tmp.FToRow; FToRowOff := tmp.FToRowOff; FFrmOffX := tmp.FFrmOffX; FFrmOffY := tmp.FFrmOffY; FFrmExtCX := tmp.FFrmExtCX; FFrmExtCY := tmp.FFrmExtCY; FSheet := tmp.FSheet; end; end; procedure TZEPicture.CommonInit(); begin FId := 0; FRelId := 0; FTitle := ''; FDescription := ''; FRow := 0; FCol := 0; FCellAnchor := ZACell; end; constructor TZEPicture.Create(ASheet: TZSheet); begin inherited Create; FSheet := ASheet; CommonInit(); end; destructor TZEPicture.Destroy; begin FSheet := nil; inherited; end; function TZEPicture.GetImage: TBytes; begin Result := FSheet.WorkBook.MediaList[Self.RelId - 1].Content; end; procedure TZEPicture.SetImage(const Value: TBytes); begin // FSheet.WorkBook.MediaList end; function TZEPicture.IsEqual(const Source: TPersistent): Boolean; var tmp: TZEPicture; begin Result := inherited IsEqual(Source); if (Result) and (Source is TZEPicture) then begin tmp := Source as TZEPicture; Result := (FId = tmp.Id) and (FTitle = tmp.Title) and (FDescription = tmp.Description) // and (FHidden = tmp.Hidden); // TODO: compare filename/streams end; end; { TZEDrawing } procedure TZEDrawing.Clear; begin FItems.Clear(); end; constructor TZEDrawing.Create(ASheet: TZSheet); begin inherited Create; FItems := TObjectList.Create(true); FSheet := ASheet; end; procedure TZEDrawing.Delete(idx: Integer); begin FItems.Delete(idx); end; destructor TZEDrawing.Destroy(); begin FItems.Clear(); FItems.Free(); inherited; end; procedure TZEDrawing.Assign(Source: TPersistent); var tmp: TZEDrawing; b: Boolean; i: Integer; begin b := Assigned(Source); if b then begin b := Source is TZEDrawing; if b then begin tmp := Source as TZEDrawing; Self.FId := tmp.FId; for i := 0 to tmp.FItems.Count - 1 do Add.Assign(TZEPicture(tmp.FItems[i])); end; end; if not b then inherited Assign(Source); end; function TZEDrawing.Add(ARow, ACol: Integer; APicture: TBytes): TZEPicture; begin Result := TZEPicture.Create(FSheet); FItems.Add(Result); Result.Image := APicture; Result.RelId := FItems.Count; Result.Row := ARow; Result.Col := ACol; Result.CellAnchor := ZACell; end; function TZEDrawing.Add: TZEPicture; begin Result := TZEPicture.Create(FSheet); Result.CellAnchor := ZACell; FItems.Add(Result); end; function TZEDrawing.GetCount: Integer; begin Result := FItems.Count; end; function TZEDrawing.GetIsEmpty(): Boolean; begin Result := FItems.Count = 0; end; function TZEDrawing.GetItem(idx: Integer): TZEPicture; begin Result := TZEPicture(FItems[idx]); end; procedure TZEDrawing.SetItem(idx: Integer; const Value: TZEPicture); begin TZEPicture(FItems[idx]).Assign(Value); end; { TZRange } procedure TZRange.Assign(Source: TZRange); var Src: TZRange; r, c, Id: Integer; Style: TZStyle; rect: TZMergeArea; begin inherited; if Source is TZRange then begin Src := TZRange(Source); // resize columns or rows if need if FSheet.RowCount <= Max(Src.FBottom, FBottom) then FSheet.RowCount := Max(Src.FBottom, FBottom); if FSheet.ColCount <= Max(Src.FRight, FRight) then FSheet.ColCount := Max(Src.FRight, FRight); Style := TZStyle.Create(); try // copy cells and styles for c := 0 to Src.FRight - Src.FLeft do begin for r := 0 to Src.FBottom - Src.FTop do begin FSheet.Cell[FLeft + c, FTop + r].Assign(Src.FSheet.Cell[Src.FLeft + c, Src.FTop + r]); Id := FSheet.Cell[FLeft + c, FTop + r].CellStyle; if Id > -1 then begin // style must copy from source sheet Style.Assign(Src.FSheet.WorkBook.Styles[Id]); Id := FSheet.WorkBook.Styles.Add(Style, true); FSheet.Cell[FLeft + c, FTop + r].CellStyle := Id; end; end; end; finally Style.Free(); end; // remove cross merges for Id := FSheet.MergeCells.Count - 1 downto 0 do begin if FSheet.MergeCells.IsCrossWithArea(Id, FLeft, FTop, FLeft + (Src.FRight - Src.FLeft), FTop + (Src.FBottom - Src.FTop)) then FSheet.MergeCells.DeleteItem(Id); end; // copy and reloc merges for Id := 0 to Src.FSheet.MergeCells.Count - 1 do begin if Src.FSheet.MergeCells.IsCrossWithArea(Id, Src.FLeft, Src.FTop, Src.FRight, Src.FBottom) then begin rect := Src.FSheet.MergeCells[Id]; FSheet.MergeCells.AddRectXY(FLeft + (rect.left - Src.FLeft), FTop + (rect.Top - Src.FTop), FRight + (rect.right - Src.FRight), FBottom + (rect.Bottom - Src.FBottom)); end; end; end; end; constructor TZRange.Create(ASheet: TZSheet; ALeft, ATop, ARight, ABottom: Integer); begin FSheet := ASheet; FLeft := ALeft; FTop := ATop; FRight := ARight; FBottom := ABottom; end; destructor TZRange.Destroy; begin FSheet := nil; FLeft := 0; FTop := 0; FRight := 0; FBottom := 0; inherited; end; function TZRange.HasStyle: Boolean; begin Result := FSheet.Cell[FLeft, FTop].FCellStyle > -1; end; procedure TZRange.Merge(); var i: Integer; begin for i := FSheet.MergeCells.Count - 1 downto 0 do begin if FSheet.MergeCells.IsCrossWithArea(i, FLeft, FTop, FRight, FBottom) then FSheet.MergeCells.DeleteItem(i); end; FSheet.MergeCells.AddRectXY(FLeft, FTop, FRight, FBottom); end; procedure TZRange.SetBorderAround(borderWidth: Byte; BorderColor: TColor = TColorRec.Black; BorderStyle: TZBorderType = TZBorderType.ZEContinuous); var Row, Col: Integer; Style: TZStyle; begin for Row := FTop to FBottom do begin for Col := FLeft to FRight do begin if (Col = FLeft) or (Row = FTop) or (Col = FRight) or (Row = FBottom) then begin Style := TZStyle.Create(); try Style.Assign(FSheet.Cell[Col, Row].Style); if Col = FLeft then begin Style.Border[bpLeft].LineStyle := BorderStyle; Style.Border[bpLeft].Weight := borderWidth; Style.Border[bpLeft].Color := BorderColor; end; if Row = FTop then begin Style.Border[bpTop].LineStyle := BorderStyle; Style.Border[bpTop].Weight := borderWidth; Style.Border[bpTop].Color := BorderColor; end; if Col = FRight then begin Style.Border[bpRight].LineStyle := BorderStyle; Style.Border[bpRight].Weight := borderWidth; Style.Border[bpRight].Color := BorderColor; end; if Row = FBottom then begin Style.Border[bpBottom].LineStyle := BorderStyle; Style.Border[bpBottom].Weight := borderWidth; Style.Border[bpBottom].Color := BorderColor; end; FSheet.Cell[Col, Row].CellStyle := FSheet.FStore.Styles.Add(Style, true); finally Style.Free(); end; end; end; end; end; procedure TZRange.ApplyStyleValue(proc: TProc<TZStyle>); var Col, Row, Id: Integer; Style: TZStyle; begin for Col := FLeft to FRight do begin for Row := FTop to FBottom do begin Style := TZStyle.Create(); try Id := FSheet.Cell[Col, Row].CellStyle; if Id > -1 then Style.Assign(FSheet.FStore.Styles[Id]) else if (FSheet.FStore.Styles.Count > 0) then Style.Assign(FSheet.FStore.Styles[0]); proc(Style); Id := FSheet.FStore.Styles.Add(Style, true); FSheet.Cell[Col, Row].CellStyle := Id; finally Style.Free(); end; end; end; end; procedure TZRange.Clear(); var Col, Row: Integer; begin for Col := FLeft to FRight do begin for Row := FTop to FBottom do begin FSheet.Cell[Col, Row].Data := ''; FSheet.Cell[Col, Row].Formula := ''; FSheet.Cell[Col, Row].Comment := ''; FSheet.Cell[Col, Row].CommentAuthor := ''; end; end; end; function TZRange.GetBgColor(): TColor; begin Result := 0; if HasStyle then Result := FSheet.FStore.FStyles[FSheet.Cell[FLeft, FTop].FCellStyle].BgColor; end; function TZRange.GetBorderColor(num: TZBordersPos): TColor; begin Result := 0; if HasStyle then Result := FSheet.FStore.FStyles[FSheet.Cell[FLeft, FTop].FCellStyle].Border[num].Color; end; function TZRange.GetBordersStyle(): TZBorderType; begin Result := TZBorderType.ZENone; if HasStyle then Result := FSheet.FStore.FStyles[FSheet.Cell[FLeft, FTop].FCellStyle].Border[bpLeft].LineStyle; end; function TZRange.GetBordersWidht(): Byte; begin Result := 0; if HasStyle then Result := FSheet.FStore.FStyles[FSheet.Cell[FLeft, FTop].FCellStyle].Border[bpLeft].Weight; end; function TZRange.GetBordersColor(): TColor; begin Result := 0; if HasStyle then Result := FSheet.FStore.FStyles[FSheet.Cell[FLeft, FTop].FCellStyle].Border[bpLeft].Color; end; function TZRange.GetBorderStyle(num: TZBordersPos): TZBorderType; begin Result := TZBorderType.ZENone; if HasStyle then Result := FSheet.FStore.FStyles[FSheet.Cell[FLeft, FTop].FCellStyle].Border[num].LineStyle; end; function TZRange.GetBorderWidht(num: TZBordersPos): Byte; begin Result := 0; if HasStyle then Result := FSheet.FStore.FStyles[FSheet.Cell[FLeft, FTop].FCellStyle].Border[num].Weight; end; function TZRange.GetFontColor(): TColor; begin Result := 0; if HasStyle then Result := FSheet.FStore.FStyles[FSheet.Cell[FLeft, FTop].FCellStyle].Font.Color; end; function TZRange.GetFontSize(): Double; begin Result := 0; if HasStyle then Result := FSheet.FStore.FStyles[FSheet.Cell[FLeft, FTop].FCellStyle].Font.Size; end; function TZRange.GetFontStyle(): TFontStyles; begin Result := []; if HasStyle then Result := FSheet.FStore.FStyles[FSheet.Cell[FLeft, FTop].FCellStyle].Font.Style; end; function TZRange.GetHorizontalAlignment(): TZHorizontalAlignment; begin Result := TZHorizontalAlignment.ZHAutomatic; if HasStyle then Result := FSheet.FStore.FStyles[FSheet.Cell[FLeft, FTop].FCellStyle].Alignment.Horizontal; end; function TZRange.GetNumberFormat(): string; begin Result := ''; if HasStyle then Result := FSheet.FStore.FStyles[FSheet.Cell[FLeft, FTop].FCellStyle].NumberFormat; end; function TZRange.GetRotate(): TZCellTextRotate; begin Result := 0; if HasStyle then Result := FSheet.FStore.FStyles[FSheet.Cell[FLeft, FTop].FCellStyle].Alignment.Rotate; end; function TZRange.GetVerticalAlignment(): TZVerticalAlignment; begin Result := TZVerticalAlignment.ZVAutomatic; if HasStyle then Result := FSheet.FStore.FStyles[FSheet.Cell[FLeft, FTop].FCellStyle].Alignment.Vertical; end; function TZRange.GetVerticalText(): Boolean; begin Result := false; if HasStyle then Result := FSheet.FStore.FStyles[FSheet.Cell[FLeft, FTop].FCellStyle].Alignment.VerticalText; end; function TZRange.GetWrapText(): Boolean; begin Result := false; if HasStyle then Result := FSheet.FStore.FStyles[FSheet.Cell[FLeft, FTop].FCellStyle].Alignment.WrapText; end; procedure TZRange.SetBgColor(const Value: TColor); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.BgColor := Value; end); end; procedure TZRange.SetBorderColor(num: TZBordersPos; const Value: TColor); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Border[num].Color := Value; end); end; procedure TZRange.SetBorderStyle(num: TZBordersPos; const Value: TZBorderType); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Border[num].LineStyle := Value; end); end; procedure TZRange.SetBorderWidht(num: TZBordersPos; const Value: Byte); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Border[num].Weight := Value; end); end; procedure TZRange.SetBordersColor(const Value: TColor); var Style: TZStyle; Col, Row: Integer; begin Style := TZStyle.Create(); try for Row := FTop to FBottom do begin for Col := FLeft to FRight do begin Style.Assign(FSheet[Col, Row].Style); Style.Border[bpLeft].Color := Value; Style.Border[bpTop].Color := Value; Style.Border[bpRight].Color := Value; Style.Border[bpBottom].Color := Value; FSheet[Col, Row].CellStyle := FSheet.FStore.Styles.Add(Style, true); end; end; finally Style.Free(); end; end; procedure TZRange.SetBordersStyle(const Value: TZBorderType); var Style: TZStyle; Col, Row: Integer; begin Style := TZStyle.Create(); try for Row := FTop to FBottom do begin for Col := FLeft to FRight do begin Style.Assign(FSheet[Col, Row].Style); Style.Border[bpLeft].LineStyle := Value; Style.Border[bpTop].LineStyle := Value; Style.Border[bpRight].LineStyle := Value; Style.Border[bpBottom].LineStyle := Value; FSheet[Col, Row].CellStyle := FSheet.FStore.Styles.Add(Style, true); end; end; finally Style.Free(); end; end; procedure TZRange.SetBordersWidht(const Value: Byte); var Style: TZStyle; Col, Row: Integer; begin Style := TZStyle.Create(); try for Row := FTop to FBottom do begin for Col := FLeft to FRight do begin Style.Assign(FSheet[Col, Row].Style); Style.Border[bpLeft].Weight := Value; Style.Border[bpTop].Weight := Value; Style.Border[bpRight].Weight := Value; Style.Border[bpBottom].Weight := Value; FSheet[Col, Row].CellStyle := FSheet.FStore.Styles.Add(Style, true); end; end; finally Style.Free(); end; end; procedure TZRange.SetFontColor(const Value: TColor); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Font.Color := Value; end); end; procedure TZRange.SetFontSize(const Value: Double); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Font.Size := Value; end); end; procedure TZRange.SetFontStyle(const Value: TFontStyles); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Font.Style := Value; end); end; procedure TZRange.SetHorizontalAlignment(const Value: TZHorizontalAlignment); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Alignment.Horizontal := Value; end); end; procedure TZRange.SetNumberFormat(const Value: string); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.NumberFormat := Value; end); end; procedure TZRange.SetRotate(const Value: TZCellTextRotate); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Alignment.Rotate := Value; end); end; procedure TZRange.SetVerticalAlignment(const Value: TZVerticalAlignment); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Alignment.Vertical := Value; end); end; procedure TZRange.SetVerticalText(const Value: Boolean); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Alignment.VerticalText := Value; end); end; procedure TZRange.SetWrapText(const Value: Boolean); begin ApplyStyleValue( procedure(Style: TZStyle) begin Style.Alignment.WrapText := Value; end); end; { TRichText } constructor TRichText.Create(); begin FList := TList<TRichString>.Create(); end; destructor TRichText.Destroy(); var i: Integer; begin for i := 0 to FList.Count - 1 do FList[i].Free(); FList.Clear(); FList.Free(); end; function TRichText.Equals(Obj: TObject): Boolean; var i: Integer; begin if Assigned(Obj) and (Obj is TRichText) then begin if Self.FList.Count <> ((Obj as TRichText).List.Count) then exit(false); for i := 0 to Self.FList.Count - 1 do if not Self.FList[i].Equals((Obj as TRichText).FList[i]) then exit(false); end; Result := true; end; procedure TRichText.Assign(Source: TPersistent); var i: Integer; begin if Source is TRichText then begin FList.Clear(); for i := 0 to TRichText(Source).FList.Count - 1 do FList.Add(TRichText(Source).FList[i]); end; end; function TRichText.GetHashCode(): Integer; var i: Integer; begin Result := 17; for i := 0 to FList.Count - 1 do Result := Result * 23 + FList[i].GetHashCode(); end; { TRichString } destructor TRichString.Destroy(); begin if Assigned(FFont) then FFont.Free(); end; function TRichString.Equals(Obj: TObject): Boolean; begin if Assigned(Obj) and (Obj is TRichString) then begin if Self.FText <> (Obj as TRichString).FText then exit(false); if Assigned(Self.FFont) <> Assigned((Obj as TRichString).FFont) then exit(false); if not ZEIsFontsEquals(Self.FFont, (Obj as TRichString).FFont) then exit(false) end; Result := true; end; procedure TRichString.Assign(Source: TPersistent); begin if Source is TRichString then begin FText := TRichString(Source).FText; if Assigned(TRichString(Source).FFont) then FFont.Assign(TRichString(Source).FFont); end; end; function TRichString.GetHashCode(): Integer; begin Result := 17; Result := Result * 23 + FText.GetHashCode(); if Assigned(FFont) then Result := Result * 23 + FFont.GetHashCode(); end; { TRichTextComparer } function TRichTextComparer.Equals(const left, right: TRichText): Boolean; begin Result := Assigned(left) and Assigned(right) and left.Equals(right); end; function TRichTextComparer.GetHashCode(const Value: TRichText): Integer; begin Result := Value.GetHashCode(); end; { TZExcelColor } class operator TZExcelColor.Equal(const ALeft, ARight: TZExcelColor): Boolean; begin Result := (ALeft.RGB = ARight.RGB) and (ALeft.Indexed = ARight.Indexed) and (ALeft.Theme = ARight.Theme) and SameValue(ALeft.Tint, ARight.Tint); end; procedure TZExcelColor.Load(const ARgb, AIndexed, ATheme, ATint: string); begin Indexed := StrToIntDef(ARgb, 0); Theme := StrToIntDef(ATheme, 0); Tint := StrToFloatDef(ATint, 0, TFormatSettings.Invariant); if ARgb.IsEmpty then RGB := 0 else RGB := ARGBToColor(ARgb); end; class operator TZExcelColor.NotEqual(const ALeft, ARight: TZExcelColor): Boolean; begin Result := not((ALeft.RGB = ARight.RGB) and (ALeft.Indexed = ARight.Indexed) and (ALeft.Theme = ARight.Theme) and SameValue(ALeft.Tint, ARight.Tint)); end; { TZMegeCell } constructor TZMergeArea.Create(ALeft, ATop, ARight, ABottom: Integer); begin Top := ATop; left := ALeft; right := ARight; Bottom := ABottom; end; initialization invariantFormatSertting := TFormatSettings.Create(); invariantFormatSertting.DecimalSeparator := '.'; end.
27.467019
147
0.681697
f104fcf86b8a4b9ff65234b04060222264332e5e
45,247
pas
Pascal
Image32/source/Img32.Panels.pas
YWtheGod/SVGIconImageList
76090ecd0a2972ccdfcd6c53cf46e22288e386a1
[ "Apache-2.0" ]
201
2020-05-24T13:50:03.000Z
2022-03-26T18:23:43.000Z
Image32/source/Img32.Panels.pas
YWtheGod/SVGIconImageList
76090ecd0a2972ccdfcd6c53cf46e22288e386a1
[ "Apache-2.0" ]
186
2020-05-25T18:33:48.000Z
2022-03-29T14:57:45.000Z
Image32/source/Img32.Panels.pas
YWtheGod/SVGIconImageList
76090ecd0a2972ccdfcd6c53cf46e22288e386a1
[ "Apache-2.0" ]
64
2020-05-25T08:28:12.000Z
2022-03-18T17:13:10.000Z
unit Img32.Panels; (******************************************************************************* * Author : Angus Johnson * * Version : 3.3 * * Date : 21 September 2021 * * Website : http://www.angusj.com * * Copyright : Angus Johnson 2019-2021 * * Purpose : Component that displays images on a TPanel descendant * * License : http://www.boost.org/LICENSE_1_0.txt * *******************************************************************************) interface uses SysUtils, Classes, Windows, Messages, Types, Graphics, Controls, Forms, ExtCtrls, Themes, uxTheme, Math, ShellApi, ClipBrd, Img32; {$I Img32.inc} const WM_MOUSEHWHEEL = $020E; type TShowScrollBtns = (ssbFocused, ssAlways, ssNever); //TDrawImageEvent: template for TBaseImgPanel's OnDrawImage event property. //nb: with scaling, srcRect & dstRect may have different widths +/- heights. TDrawImageEvent = procedure (Sender: TObject; dstCanvas: TCanvas; const srcRect, dstRect: TRect) of Object; TFileDropEvent = procedure (Sender: TObject; const filename: string) of Object; //TPanelScrollbar: used internally by TBaseImgPanel and TImage32Panel TPanelScrollbar = record btnSize : integer; //in dst coords btnDelta : double; //how much src moves for each px of the ScrollBar srcOffset : integer; //offset in unscaled src coords maxSrcOffset : double; //max offset in unscaled src coords MouseOver : Boolean; MouseDown : Boolean; MouseDownPos : integer; end; TBaseImgPanel = class(TPanel) private fImageSize : TSize; fScale : double; fScaleMin : double; fScaleMax : double; fFocusedColor : TColor; fUnfocusedColor : TColor; fMouseDown : Boolean; fScrollbarVert : TPanelScrollbar; fScrollbarHorz : TPanelScrollbar; fAutoCenter : Boolean; fAllowZoom : Boolean; fAllowKeyScroll : Boolean; fAllowScrnScroll: Boolean; fShowScrollBtns : TShowScrollBtns; fOnKeyDown : TKeyEvent; fOnKeyUp : TKeyEvent; fOnScrolling : TNotifyEvent; fOnZooming : TNotifyEvent; fOnMouseWheel : TMouseWheelEvent; {$IFDEF GESTURES} fLastDistance: integer; fLastLocation: TPoint; {$ENDIF} procedure UpdateOffsetDelta(resetOrigin: Boolean); function GetMinScrollBtnSize: integer; function GetDstOffset: TPoint; function GetInnerMargin: integer; function GetOffset: TPoint; procedure SetOffset(const value: TPoint); function GetInnerClientRect: TRect; procedure SetScale(scale: double); procedure SetScaleMin(value: double); procedure SetScaleMax(value: double); function GetColor: TColor; procedure SetColor(acolor: TColor); procedure SetAutoCenter(value: Boolean); procedure SetAllowZoom(value: Boolean); procedure SetShowScrollButtons(value: TShowScrollBtns); {$IFDEF GESTURES} procedure Gesture(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean); {$ENDIF} procedure WMSize(var Message: TWMSize); message WM_SIZE; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; procedure WMEraseBkgnd(var message: TMessage); message WM_ERASEBKGND; procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE; procedure WMMouseHWheel(var Message: TCMMouseWheel); message WM_MOUSEHWHEEL; protected function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; override; function DoMouseHWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure DrawToPanelCanvas(const srcRect, dstRect: TRect); virtual; procedure Paint; override; procedure WMKeyDown(var Message: TWMKey); message WM_KEYDOWN; procedure WMKeyUp(var Message: TWMKey); message WM_KEYUP; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure CMFocusChanged(var Message: TMessage); message CM_FOCUSCHANGED; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ScaleToFit; function IsEmpty: Boolean; function IsScaledToFit: Boolean; function ClientToImage(const clientPt: TPoint): TPoint; function ImageToClient(const surfacePt: TPoint): TPoint; function RecenterImageAt(const imagePt: TPoint): Boolean; //ScaleAtPoint: zooms in or out keeping 'pt' stationary relative to display procedure ScaleAtPoint(scaleDelta: double; const pt: TPoint); property InnerClientRect: TRect read GetInnerClientRect; property InnerMargin: integer read GetInnerMargin; property Offset: TPoint read GetOffset write SetOffset; property ScrollbarHorz: TPanelScrollbar read fScrollbarHorz write fScrollbarHorz; property ScrollbarVert: TPanelScrollbar read fScrollbarVert write fScrollbarVert; published //AutoCenter: centers the image when its size is less than the display size property AutoCenter: Boolean read fAutoCenter write SetAutoCenter; property Color: TColor read GetColor write SetColor; //FocusedColor: colour of the border when the panel is focused property FocusedColor: TColor read fFocusedColor write fFocusedColor; property UnFocusedColor: TColor read fUnfocusedColor write fUnfocusedColor; //Scale: image scale (between ScaleMin and ScaleMax) if AllowZoom is enabled property Scale: double read fScale write SetScale; property ScaleMin: double read fScaleMin write SetScaleMin; property ScaleMax: double read fScaleMax write SetScaleMax; //ShowScrollButtons: defaults to ssbFocused (ie only when Panel has focus) property ShowScrollButtons : TShowScrollBtns read fShowScrollBtns write SetShowScrollButtons; property AllowKeyScroll: Boolean read fAllowKeyScroll write fAllowKeyScroll; property AllowScrnScroll: Boolean read fAllowScrnScroll write fAllowScrnScroll; property AllowZoom: Boolean read fAllowZoom write SetAllowZoom; //OnKeyDown: optional event for custom keyboard actions property OnKeyDown: TKeyEvent read fOnKeyDown write fOnKeyDown; property OnKeyUp: TKeyEvent read fOnKeyUp write fOnKeyUp; property OnMouseWheel: TMouseWheelEvent read FOnMouseWheel write FOnMouseWheel; property OnScrolling: TNotifyEvent read fOnScrolling write fOnScrolling; property OnZooming: TNotifyEvent read fOnZooming write fOnZooming; end; TImage32Panel = class(TBaseImgPanel) private fImage : TImage32; fAllowCopyPaste : Boolean; fOnFileDrop : TFileDropEvent; fAllowFileDrop : Boolean; fOnPaste : TNotifyEvent; procedure SetAllowFileDrop(value: Boolean); procedure WMKeyDown(var Message: TWMKey); message WM_KEYDOWN; protected procedure CreateWnd; override; procedure DestroyWnd; override; procedure WMDropFiles(var Msg: TMessage); message WM_DROPFILES; procedure DrawToPanelCanvas(const srcRect, dstRect: TRect); override; procedure ImageChanged(Sender: TObject); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ClearImage; //CopyToImage: avoids a full redraw procedure CopyToImage(srcImg: TImage32; const rec: TRect); function CopyToClipboard: Boolean; function PasteFromClipboard: Boolean; property Image: TImage32 read fImage; property AllowCopyPaste: Boolean read fAllowCopyPaste write fAllowCopyPaste; property AllowFileDrop: Boolean read fAllowFileDrop write SetAllowFileDrop; property OnFileDrop: TFileDropEvent read fOnFileDrop write fOnFileDrop; property OnPaste: TNotifyEvent read fOnPaste write fOnPaste; end; procedure Register; implementation procedure Register; begin RegisterComponents('Image32 Panels', [TImage32Panel]); end; type TNotifyImage32 = class(TImage32) protected fImage32Panel: TImage32Panel; procedure Changed; override; public constructor Create(owner: TImage32Panel); end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ var //The minimum width for scrolling buttons. If borders are too narrow //to properly display scroll buttons then scroll buttons will be disabled. MinBorderWidth: integer = 0; //see initialization const MinImageScale = 0.001; MaxImageScale = 1000; tolerance = 0.01; type PColor32 = ^TColor32; TColor32 = Cardinal; TARGB = record case boolean of false: (B, G, R, A: byte); true: (color: TColor); end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ function RgbColor(rgb: TColor): TColor; var res: TARGB absolute Result; begin if rgb < 0 then result := GetSysColor(rgb and $FFFFFF) else result := rgb; end; //------------------------------------------------------------------------------ function Size(cx, cy: Integer): TSize; begin Result.cx := cx; Result.cy := cy; end; //------------------------------------------------------------------------------ procedure ScaleRect(var R: TRect; scale: double); begin if scale = 1.0 then Exit; R.Left := Round(R.Left * scale); R.Right := Round(R.Right * scale); R.Top := Round(R.Top * scale); R.Bottom := Round(R.Bottom * scale); end; //------------------------------------------------------------------------------ procedure InflateRect(var R: TRect; dx, dy: double); begin R.Left := Round(R.Left - dx); R.Right := Round(R.Right + dx); R.Top := Round(R.Top - dy); R.Bottom := Round(R.Bottom + dy); end; //------------------------------------------------------------------------------ procedure SetRectWidth(var rec: TRect; width: integer); {$IFDEF INLINE} inline; {$ENDIF} begin rec.Right := rec.Left + width; end; //------------------------------------------------------------------------------ procedure SetRectHeight(var rec: TRect; height: integer); {$IFDEF INLINE} inline; {$ENDIF} begin rec.Bottom := rec.Top + height; end; //------------------------------------------------------------------------------ function IsEmptyRect(const rec: TRect): Boolean; {$IFDEF INLINE} inline; {$ENDIF} begin Result := (rec.Right <= rec.Left) or (rec.Bottom <= rec.Top); end; //------------------------------------------------------------------------------ function HasThemeManifest: boolean; begin result := FindResource(hInstance, makeintresource(1), MakeIntResource(24)) > 0; end; //------------------------------------------------------------------------------ function GetThemeColor(const className: widestring; part, state, propID: integer; out Color: TColor): boolean; var thmHdl: HTheme; clrRef: COLORREF ABSOLUTE Color; begin result := false; {$IFDEF STYLESERVICES} if not StyleServices.Enabled or not HasThemeManifest then exit; {$ELSE} if not ThemeServices.ThemesEnabled or not HasThemeManifest then exit; {$ENDIF} thmHdl := OpenThemeData(0, LPCWSTR(className)); if thmHdl <> 0 then try result := Succeeded(uxTheme.GetThemeColor(thmHdl, part, state, propID, clrRef)); finally CloseThemeData(thmHdl); end; end; //------------------------------------------------------------------------------ function OffsetPoint(const pt: TPoint; dx, dy: integer): TPoint; begin Result.X := pt.X + dx; Result.Y := pt.Y + dy; end; //------------------------------------------------------------------------------ function LeftMouseBtnDown: Boolean; begin Result := (GetKeyState(VK_LBUTTON) shr 8 > 0); end; //------------------------------------------------------------------------------ function MakeDarker(color: TColor; percent: integer): TColor; var hsl: THsl; begin hsl := RgbToHsl(Color32(color)); hsl.lum := ClampByte(hsl.lum - (percent/100 * hsl.lum)); Result := HslToRgb(hsl) and $FFFFFF; end; //------------------------------------------------------------------------------ // TLayerNotifyImage32 //------------------------------------------------------------------------------ constructor TNotifyImage32.Create(owner: TImage32Panel); begin inherited Create; fImage32Panel := owner; end; //------------------------------------------------------------------------------ procedure TNotifyImage32.Changed; begin if (Self.UpdateCount = 0) then fImage32Panel.ImageChanged(Self); inherited; end; //------------------------------------------------------------------------------ // TBaseImgPanel //------------------------------------------------------------------------------ constructor TBaseImgPanel.Create(AOwner: TComponent); begin inherited; Height := 200; Width := 200; BevelWidth := 1; BorderWidth := 12; BevelInner := bvLowered; DoubleBuffered := true; TabStop := true; {$IFDEF GESTURES} OnGesture := Gesture; Touch.InteractiveGestures := [igPressAndTap, igZoom, igPan]; {$ENDIF} fShowScrollBtns := ssbFocused; fAllowScrnScroll := true; fAllowKeyScroll := true; fAllowZoom := true; fAutoCenter := true; fFocusedColor := RgbColor(clActiveCaption); fUnfocusedColor := clBtnFace; fScale := 1.0; fScaleMin := 0.05; fScaleMax := 20; fImageSize := Size(200,200); end; //------------------------------------------------------------------------------ destructor TBaseImgPanel.Destroy; begin inherited; end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.WMSize(var Message: TWMSize); begin inherited; UpdateOffsetDelta(true); end; //------------------------------------------------------------------------------ function TBaseImgPanel.GetDstOffset: TPoint; begin if not fAutoCenter then Result := Point(0,0) else with GetInnerClientRect do begin Result.X := Max(0, ((Right -Left) -Round(fImageSize.cx * fScale)) div 2); Result.Y := Max(0, ((Bottom -Top) -Round(fImageSize.cy * fScale)) div 2); end; end; //------------------------------------------------------------------------------ function TBaseImgPanel.GetInnerMargin: integer; begin //nb: BorderWidth is the space between outer and inner bevels Result := DpiAware(BorderWidth); if BevelInner <> bvNone then inc(result, BevelWidth); if BevelOuter <> bvNone then inc(result, BevelWidth); //BorderStyle changes the OUTSIDE of the panel so won't affect InnerMargin. end; //------------------------------------------------------------------------------ function TBaseImgPanel.GetInnerClientRect: TRect; var marg: integer; begin marg := GetInnerMargin; result := ClientRect; InflateRect(result, -marg, -marg); end; //------------------------------------------------------------------------------ function TBaseImgPanel.GetOffset: TPoint; begin with fScrollbarHorz do Result.X := srcOffset; with fScrollbarVert do Result.Y := srcOffset; end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.SetOffset(const value: TPoint); begin fScrollbarHorz.srcOffset := value.X; fScrollbarVert.srcOffset := value.Y; Invalidate; end; //------------------------------------------------------------------------------ function TBaseImgPanel.IsEmpty: Boolean; begin Result := (fImageSize.cx = 0) or (fImageSize.cy = 0); end; //------------------------------------------------------------------------------ function TBaseImgPanel.IsScaledToFit: Boolean; var rec: TRect; h,w: integer; begin rec := GetInnerClientRect; h := RectHeight(rec); w := RectWidth(rec); Result := (abs(fImageSize.cx * fScale - w) < 1) or (abs(fImageSize.cy * fScale - h) < 1); end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.ScaleToFit; var rec: TRect; h,w: integer; begin if IsEmpty then Exit; fScale := 1; fScrollbarHorz.srcOffset := 0; fScrollbarVert.srcOffset := 0; rec := GetInnerClientRect; h := RectHeight(rec); w := RectWidth(rec); if w / fImageSize.cx < h / fImageSize.cy then SetScale(w / fImageSize.cx) else SetScale(h / fImageSize.cy); end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.ScaleAtPoint(scaleDelta: double; const pt: TPoint); var marg: integer; p,q: double; pt1, pt2: TPoint; begin p := scaleDelta * fScale; if p < fScaleMin then begin if fScale <= fScaleMin then Exit; scaleDelta := fScaleMin/fScale; end else if p > fScaleMax then begin if fScale >= fScaleMax then Exit; scaleDelta := fScaleMax/fScale; end; q := 1 - 1/scaleDelta; marg := GetInnerMargin; pt1 := ClientToImage(pt); pt2 := ClientToImage(Point(marg, marg)); SetScale(fScale * scaleDelta); with fScrollbarHorz do inc(srcOffset, Round((pt1.X - pt2.X) * q)); with fScrollbarVert do inc(srcOffset, Round((pt1.Y - pt2.Y) * q)); end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.SetScale(scale: double); begin if scale < fScaleMin then scale := fScaleMin else if scale > fScaleMax then scale := fScaleMax; if (fScale = scale) then Exit; fScale := scale; UpdateOffsetDelta(false); if Assigned(fOnZooming) then fOnZooming(Self); Invalidate; end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.SetScaleMin(value: double); begin fScaleMin := Max(MinImageScale, Min(fScaleMax, value)); end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.SetScaleMax(value: double); begin fScaleMax := Max(fScaleMin, Min(MaxImageScale, value)); end; //------------------------------------------------------------------------------ function TBaseImgPanel.GetColor: TColor; begin Result := inherited Color; end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.SetColor(acolor: TColor); begin if inherited Color = acolor then Exit; ParentBackground := false; ParentColor := false; inherited Color := acolor end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.SetAutoCenter(value: Boolean); begin if value = fAutoCenter then Exit; fAutoCenter := value; Invalidate; end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.SetAllowZoom(value: Boolean); begin if value = fAllowZoom then Exit; fAllowZoom := value; if not value then Exit; fAllowScrnScroll := true; fAllowKeyScroll := true; end; //------------------------------------------------------------------------------ function TBaseImgPanel.GetMinScrollBtnSize: integer; begin Result := Max(1, GetInnerMargin - DpiAware(5)); end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.UpdateOffsetDelta(resetOrigin: Boolean); var innerRec: TRect; innerClientW, innerClientH, btnMin: integer; scaledW, scaledH: double; begin //we need to determine 2 things: // 1. scroll button size // 2. how much a 1px button move moves the scaled image if (fImageSize.cx = 0) or (fImageSize.cy = 0) then Exit; btnMin := GetMinScrollBtnSize; innerRec := GetInnerClientRect; innerClientW := innerRec.Right - innerRec.Left; innerClientH := innerRec.Bottom - innerRec.Top; scaledW := fImageSize.cx * fScale; scaledH := fImageSize.cy * fScale; with fScrollbarVert do begin if resetOrigin then srcOffset := 0; if (scaledH < innerClientH + tolerance) then //no scroll button needed begin btnSize := 0; btnDelta := 0; maxSrcOffset := 0; end else begin btnSize := Max(btnMin, Round(innerClientH * innerClientH / scaledH)); maxSrcOffset := (scaledH - innerClientH) / fScale; btnDelta := (innerClientH - btnSize) / maxSrcOffset; end; end; with fScrollbarHorz do begin if resetOrigin then srcOffset := 0; if (scaledW < innerClientW + tolerance) then //no scroll button needed begin btnSize := 0; btnDelta := 0; maxSrcOffset := 0; end else begin btnSize := Max(btnMin, Round(innerClientW * innerClientW / scaledW)); maxSrcOffset := (scaledW - innerClientW) / fScale; btnDelta := (innerClientW - btnSize) / maxSrcOffset; end; end; end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.CMFontChanged(var Message: TMessage); begin inherited; Canvas.Font.Assign(Self.Font); Invalidate; end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.SetShowScrollButtons(value: TShowScrollBtns); begin if value = fShowScrollBtns then Exit; fShowScrollBtns := value; Invalidate; end; //------------------------------------------------------------------------------ function TBaseImgPanel.ClientToImage(const clientPt: TPoint): TPoint; var marg: integer; pt: TPoint; begin pt := GetDstOffset; marg := GetInnerMargin; Result.X := Round((clientPt.X -pt.X -marg)/fScale) +fScrollbarHorz.srcOffset; Result.Y := Round((clientPt.Y -pt.Y -marg)/fScale) +fScrollbarVert.srcOffset; end; //------------------------------------------------------------------------------ function TBaseImgPanel.ImageToClient(const surfacePt: TPoint): TPoint; var marg: integer; pt: TPoint; begin pt := GetDstOffset; marg := GetInnerMargin; Result.X := Round((surfacePt.X -fScrollbarHorz.srcOffset)*fScale +marg +pt.X); Result.Y := Round((surfacePt.Y -fScrollbarVert.srcOffset)*fScale +marg +pt.Y); end; //------------------------------------------------------------------------------ function TBaseImgPanel.RecenterImageAt(const imagePt: TPoint): Boolean; var scaledW, scaledH: Double; marg, innerW, innerH: Integer; pt1, pt2: TPoint; q, maxOffset: double; begin Result := (fScrollbarHorz.maxSrcOffset > 0) or (fScrollbarVert.maxSrcOffset = 0); if not Result then Exit; scaledW := fImageSize.cx * fScale; scaledH := fImageSize.cy * fScale; marg := GetInnerMargin; innerW := ClientWidth - marg*2; innerH := ClientHeight - marg*2; pt1 := imagePt; pt2 := ClientToImage(Point(marg + innerW div 2, marg + innerH div 2)); with fScrollbarHorz do begin q := (pt1.X - pt2.X); maxOffset := (scaledW - innerW) / fScale; srcOffset := Round(Max(0,Min(maxOffset, q))); end; with fScrollbarVert do begin q := (pt1.Y - pt2.Y); maxOffset := (scaledH - innerH) / fScale; srcOffset := Round(Max(0,Min(maxOffset, q))); end; Invalidate; end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var rec: TRect; begin if fAllowScrnScroll or fAllowKeyScroll then begin fMouseDown := true; fScrollbarHorz.MouseDownPos := X; fScrollbarVert.MouseDownPos := Y; rec := GetInnerClientRect; if (X > rec.Right) and (Y > rec.Top) and (Y < rec.Bottom) and (fScrollbarVert.btnSize > 0) then begin fScrollbarVert.MouseDown := true; end else if (Y > rec.Bottom) and (X > rec.Left) and (X < rec.Right) and (fScrollbarHorz.btnSize > 0) then begin fScrollbarHorz.MouseDown := true; end; end; if not (fScrollbarHorz.MouseDown or fScrollbarVert.MouseDown) then inherited; if TabStop and not Focused and CanFocus then begin SetFocus; Invalidate; end; end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.MouseMove(Shift: TShiftState; X, Y: Integer); var rec: TRect; inDrawRegion: Boolean; begin rec := GetInnerClientRect; inDrawRegion := PtInRect(rec, Point(X,Y)); if inDrawRegion and not (fScrollbarHorz.MouseDown or fScrollbarVert.MouseDown) then begin if fScrollbarVert.MouseOver or fScrollbarHorz.MouseOver then begin Invalidate; fScrollbarHorz.MouseOver := false; fScrollbarVert.MouseOver := false; end; cursor := crDefault; inherited; Exit; end; if not fMouseDown then begin if (BorderWidth >= MinBorderWidth) and ((fShowScrollBtns = ssAlways) or (focused and (fShowScrollBtns = ssbFocused))) then begin if (X >= rec.Right) and (fScrollbarVert.btnSize > 0) then begin if (Y < rec.Bottom) then begin cursor := crSizeNS; if not fScrollbarVert.MouseOver then Invalidate; fScrollbarVert.MouseOver := true; end else cursor := crDefault; end else if (Y >= rec.Bottom) and (fScrollbarHorz.btnSize > 0) then begin Cursor := crSizeWE; if not fScrollbarHorz.MouseOver then Invalidate; fScrollbarHorz.MouseOver := true; end else cursor := crDefault; end; Exit; end; fScrollbarHorz.MouseOver := false; fScrollbarVert.MouseOver := false; if not (fAllowScrnScroll or fAllowKeyScroll) then Exit; if fScrollbarVert.MouseDown then begin //dragging vertical scrollbar with fScrollbarVert do begin inc(srcOffset, Round((Y - MouseDownPos) / btnDelta)); MouseDownPos := Y; end; end else if fScrollbarHorz.MouseDown then begin //dragging horizontal scrollbar with fScrollbarHorz do begin inc(srcOffset, Round((X - MouseDownPos) / btnDelta)); MouseDownPos := X; end; end else if fAllowScrnScroll then begin //click and drag the drawing image with fScrollbarVert do if btnDelta > 0 then begin dec(srcOffset, Round((Y - MouseDownPos) / fScale)); MouseDownPos := Y; end; with fScrollbarHorz do if btnDelta > 0 then begin dec(srcOffset, Round((X - MouseDownPos) / fScale)); MouseDownPos := X; end; end else begin Exit; //ie exit here if NOT scrolling end; if assigned(fOnScrolling) then fOnScrolling(self); Invalidate; end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if not fMouseDown then Exit; inherited; fMouseDown := false; fScrollbarHorz.MouseDown := false; fScrollbarVert.MouseDown := false; Invalidate; end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.CMMouseLeave(var Message: TMessage); begin inherited; if fScrollbarHorz.MouseOver then fScrollbarHorz.MouseOver := false else if fScrollbarVert.MouseOver then fScrollbarVert.MouseOver := false else Exit; Invalidate; end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.CMFocusChanged(var Message: TMessage); begin inherited; Invalidate; end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.WMEraseBkgnd(var message: TMessage); begin message.Result := 0; //ie don't bother erasing background end; //------------------------------------------------------------------------------ type TControl = class(Controls.TControl); //access protected Color property procedure TBaseImgPanel.DrawToPanelCanvas(const srcRect, dstRect: TRect); begin end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.Paint; procedure DrawFrame(rec: TRect; tlColor, brColor: TColor; width: integer); var bl, tr: TPoint; begin dec(rec.Right); dec(rec.Bottom); Canvas.Pen.Width := 1; while width > 0 do begin tr := Point(rec.Right, rec.Top); bl := Point(rec.Left, rec.Bottom); Canvas.Pen.Color := tlColor; Canvas.PolyLine([bl, rec.TopLeft, tr]); Canvas.Pen.Color := brColor; Canvas.PolyLine([tr, rec.BottomRight, bl]); InflateRect(rec, -1, -1); dec(width); end; end; procedure DrawScrollButton(const rec: TRect); begin Canvas.FillRect(rec); Canvas.Pen.Color := clBtnHighlight; Canvas.MoveTo(rec.Left, rec.Bottom); Canvas.LineTo(rec.Left, rec.Top); Canvas.LineTo(rec.Right, rec.Top); Canvas.Pen.Color := cl3DDkShadow; Canvas.LineTo(rec.Right, rec.Bottom); Canvas.LineTo(rec.Left, rec.Bottom); end; var marg, btnMin, dpiAwareBW: integer; tmpRec, innerRec, srcRec, dstRec: TRect; backgroundPainted: Boolean; pt: TPoint; begin //calculate un-scaled source rectangle that corresponds with dstRec marg := GetInnerMargin; innerRec := GetInnerClientRect; dpiAwareBW := DpiAware(BorderWidth); dstRec := innerRec; srcRec := dstRec; OffsetRect(srcRec, -marg, -marg); ScaleRect(srcRec, 1/fScale); //if the scaled drawing is smaller than InnerClientRect then center it pt := GetDstOffset; if pt.X > 0 then begin inc(dstRec.Left, pt.X); dec(dstRec.Right, pt.X); fScrollbarHorz.srcOffset := 0; srcRec.Left := 0; srcRec.Right := fImageSize.cx; end; if pt.Y > 0 then begin inc(dstRec.Top, pt.Y); dec(dstRec.Bottom, pt.Y); fScrollbarVert.srcOffset := 0; srcRec.Top := 0; srcRec.Bottom := fImageSize.cy; end; //calc offsets with fScrollbarHorz do if (srcOffset < 0) or (btnSize = 0) then srcOffset := 0; with fScrollbarVert do if (srcOffset < 0) or (btnSize = 0) then srcOffset := 0; if fScrollbarVert.srcOffset > fScrollbarVert.maxSrcOffset then fScrollbarVert.srcOffset := Round(fScrollbarVert.maxSrcOffset); if fScrollbarHorz.srcOffset > fScrollbarHorz.maxSrcOffset then fScrollbarHorz.srcOffset := Round(fScrollbarHorz.maxSrcOffset); OffsetRect(srcRec, fScrollbarHorz.srcOffset, fScrollbarVert.srcOffset); //paint innerRec background backgroundPainted := ParentBackground and {$IFDEF STYLESERVICES} StyleServices.Enabled and (seClient in StyleElements) and {$ELSE} ThemeServices.ThemesEnabled and {$ENDIF} Succeeded(DrawThemeParentBackground(Handle, Canvas.Handle, @innerRec)); if (csDesigning in ComponentState) or not backgroundPainted then begin if ParentColor then Canvas.Brush.Color := TControl(parent).Color else Canvas.Brush.Color := self.Color; Canvas.FillRect(innerRec); end; //draw the image DrawToPanelCanvas(srcRec, dstRec); //prevent recursive paints (in case Invalidate etc called in fOnDrawImage) RedrawWindow(Handle, nil, 0, RDW_NOERASE or RDW_NOINTERNALPAINT or RDW_VALIDATE); //paint the outer bevel tmpRec := ClientRect; case BevelOuter of bvLowered: DrawFrame(tmpRec, clBtnShadow, clBtnHighlight, BevelWidth); bvRaised: DrawFrame(tmpRec, clBtnHighlight, clBtnShadow, BevelWidth); end; //paint the border InflateRect(tmpRec, -BevelWidth, -BevelWidth); if Focused then DrawFrame(tmpRec, fFocusedColor, fFocusedColor, dpiAwareBW) else DrawFrame(tmpRec, fUnfocusedColor, fUnfocusedColor, dpiAwareBW); InflateRect(tmpRec, -dpiAwareBW, -dpiAwareBW); //paint the inner bevel case BevelInner of bvLowered: DrawFrame(tmpRec, clBtnShadow, clBtnHighlight, BevelWidth); bvRaised: DrawFrame(tmpRec, clBtnHighlight, clBtnShadow, BevelWidth); end; if (BorderWidth >= MinBorderWidth) and (fAllowScrnScroll or fAllowKeyScroll) and ((fShowScrollBtns = ssAlways) or (Focused and (fShowScrollBtns = ssbFocused))) then begin btnMin := GetMinScrollBtnSize; //draw vertical scrollbar with fScrollbarVert do if (btnSize > 0) then begin tmpRec.Top := marg + Round(srcOffset * btnDelta); tmpRec.Bottom := tmpRec.Top + btnSize; tmpRec.Right := ClientWidth - DpiAware(3); tmpRec.Left := tmpRec.Right - btnMin; if MouseOver or MouseDown then Canvas.Brush.Color := clHotLight else if Focused then Canvas.Brush.Color := MakeDarker(fFocusedColor, 20) else Canvas.Brush.Color := MakeDarker(Color, 20); DrawScrollButton(tmpRec); end; //draw horizontal scrollbar with fScrollbarHorz do if (btnSize > 0) then begin tmpRec.Left := marg + Round(srcOffset * btnDelta); tmpRec.Right := tmpRec.Left + btnSize; tmpRec.Bottom := ClientHeight - DpiAware(3); tmpRec.Top := tmpRec.Bottom - btnMin; if MouseOver or MouseDown then Canvas.Brush.Color := clHotLight else if Focused then Canvas.Brush.Color := MakeDarker(fFocusedColor, 20) else Canvas.Brush.Color := MakeDarker(Color, 20); DrawScrollButton(tmpRec); end; end; end; //------------------------------------------------------------------------------ {$IFDEF GESTURES} procedure TBaseImgPanel.Gesture(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean); var p: double; begin inherited; case EventInfo.GestureID of igiZoom: begin if not fAllowZoom then Exit; if not (gfBegin in EventInfo.Flags) then begin p := 1 + (EventInfo.Distance - FLastDistance)/fImageSize.cx; ScaleAtPoint(p, EventInfo.Location); end; FLastDistance := EventInfo.Distance; Handled := true; end; igiPan: begin if not (fAllowScrnScroll or fAllowKeyScroll) then Exit; if not (gfBegin in EventInfo.Flags) then begin with fScrollbarHorz do inc(srcOffset, Round((FLastLocation.X - EventInfo.Location.X) * btnDelta)); with fScrollbarVert do inc(srcOffset, Round((FLastLocation.Y - EventInfo.Location.Y) * btnDelta)); Invalidate; end; FLastLocation := EventInfo.Location; if assigned(fOnScrolling) then fOnScrolling(self); Handled := true; end; end; end; //------------------------------------------------------------------------------ {$ENDIF} function TBaseImgPanel.DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; var isZooming: Boolean; begin Result := false; if Assigned(FOnMouseWheel) then fOnMouseWheel(Self, Shift, WheelDelta, MousePos, Result); if not Result then Result := inherited DoMouseWheel(Shift, WheelDelta, MousePos); if Result then Exit; isZooming := (ssCtrl in Shift) and fAllowZoom; if not isZooming and not (fAllowScrnScroll or fAllowKeyScroll) then Exit; {$IFNDEF FPC} MousePos := ScreenToClient(MousePos); {$ENDIF} if isZooming then begin if WheelDelta > 0 then ScaleAtPoint(1.1, MousePos) else ScaleAtPoint(0.9, MousePos); end else begin dec(fScrollbarVert.srcOffset, Round(WheelDelta / fScale)); Invalidate; end; Result := true; end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.WMMouseHWheel(var Message: TCMMouseWheel); begin with Message do begin if DoMouseHWheel(ShiftState, WheelDelta, SmallPointToPoint(Pos)) then Message.Result := 1 else Message.Result := 0; end; end; //------------------------------------------------------------------------------ function TBaseImgPanel.DoMouseHWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; begin Result := focused and (fAllowScrnScroll or fAllowKeyScroll); if not Result then Exit; {$IFNDEF FPC} MousePos := ScreenToClient(MousePos); {$ENDIF} inc(fScrollbarHorz.srcOffset, Round(WheelDelta / fScale)); Invalidate; end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.WMGetDlgCode(var Message: TWMGetDlgCode); begin inherited; if not TabStop then Exit; Message.Result := Message.Result or DLGC_WANTCHARS or DLGC_WANTARROWS; end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.WMKeyDown(var Message: TWMKey); var mul: integer; midPoint: TPoint; charCode: Word; shiftState: TShiftState; begin inherited; if not fAllowZoom and not fAllowKeyScroll then Exit; shiftState := KeyDataToShiftState(Message.KeyData); if Assigned(fOnKeyDown) then begin charCode := Message.CharCode; fOnKeyDown(Self, charCode, shiftState); if charCode = 0 then Exit; end; case Message.CharCode of VK_LEFT..VK_DOWN: begin if ssCtrl in shiftState then begin if not fAllowZoom then Exit; //zoom in and out with CTRL+UP and CTRL+DOWN respectively midPoint := Point(ClientWidth div 2, ClientHeight div 2); case Message.CharCode of VK_UP: ScaleAtPoint(1.1, midPoint); VK_DOWN: ScaleAtPoint(0.9, midPoint); else Exit; end; end else begin if not fAllowKeyScroll then Exit; //otherwise scroll the image with the arrow keys if ssShift in shiftState then mul := 5 else //ie scrolls 5 times faster with Shift key down mul := 1; case Message.CharCode of VK_LEFT: with fScrollbarHorz do dec(srcOffset, 5 * mul); VK_RIGHT: with fScrollbarHorz do inc(srcOffset, 5 * mul); VK_UP: with fScrollbarVert do dec(srcOffset, 5 * mul); VK_DOWN: with fScrollbarVert do inc(srcOffset, 5 * mul); end; if assigned(fOnScrolling) then fOnScrolling(self); end; Invalidate; end; Ord('0'): if fAllowZoom and not (ssCtrl in shiftState) then begin ScaleToFit; end; Ord('1')..Ord('9'): if not (ssCtrl in shiftState) then begin if not AllowZoom then Exit else if ssShift in shiftState then SetScale((Message.CharCode - Ord('0')) /10) else SetScale(Message.CharCode - Ord('0')); end; end; end; //------------------------------------------------------------------------------ procedure TBaseImgPanel.WMKeyUp(var Message: TWMKey); var charCode: Word; shiftState: TShiftState; begin if Assigned(fOnKeyUp) then begin shiftState := KeyDataToShiftState(Message.KeyData); charCode := Message.CharCode; fOnKeyUp(Self, charCode, shiftState); if charCode = 0 then Exit; end; inherited; end; //------------------------------------------------------------------------------ // TBitmapPanel //------------------------------------------------------------------------------ constructor TImage32Panel.Create(AOwner: TComponent); begin inherited; Color := clWhite; fImage := TNotifyImage32.Create(Self); fImage.Resampler := rBicubicResampler; fImage.SetSize(200,200); fAllowCopyPaste := true; end; //------------------------------------------------------------------------------ destructor TImage32Panel.Destroy; begin if fAllowFileDrop and HandleAllocated then DragAcceptFiles(Handle, False); fImage.Free; inherited; end; //------------------------------------------------------------------------------ procedure TImage32Panel.ImageChanged(Sender: TObject); begin if (fImageSize.cx <> Image.Width) or (fImageSize.cy <> Image.Height) then begin fImageSize.cx := Image.Width; fImageSize.cy := Image.Height; fScale := 1.0; UpdateOffsetDelta(true); end; Invalidate; end; //------------------------------------------------------------------------------ procedure TImage32Panel.DrawToPanelCanvas(const srcRect, dstRect: TRect); begin fImage.CopyToDc(srcRect, dstRect, canvas.Handle); end; //------------------------------------------------------------------------------ procedure TImage32Panel.ClearImage; begin fImage.Clear; Invalidate; end; //------------------------------------------------------------------------------ procedure TImage32Panel.CopyToImage(srcImg: TImage32; const rec: TRect); var srcRect, dstRect: TRect; begin fImage.BlockNotify; try dstRect.TopLeft := ImageToClient(rec.TopLeft); dstRect.BottomRight := ImageToClient(rec.BottomRight); fImage.Copy(srcImg, rec, rec); Types.IntersectRect(dstRect, dstRect, InnerClientRect); srcRect.TopLeft := ClientToImage(dstRect.TopLeft); srcRect.BottomRight := ClientToImage(dstRect.BottomRight); fImage.CopyToDc(srcRect, dstRect, canvas.Handle); finally fImage.UnblockNotify; end; end; //------------------------------------------------------------------------------ procedure TImage32Panel.CreateWnd; begin inherited; if fAllowFileDrop then DragAcceptFiles(Handle, True); end; //------------------------------------------------------------------------------ procedure TImage32Panel.DestroyWnd; begin if fAllowFileDrop then begin DragAcceptFiles(Handle, False); fAllowFileDrop := false; end; inherited; end; //------------------------------------------------------------------------------ procedure TImage32Panel.SetAllowFileDrop(value: Boolean); begin if (fAllowFileDrop = value) then Exit; if not (csDesigning in ComponentState) and HandleAllocated then begin if fAllowFileDrop then DragAcceptFiles(Handle, false) else DragAcceptFiles(Handle, true); end; fAllowFileDrop := value; end; //------------------------------------------------------------------------------ procedure TImage32Panel.WMDropFiles(var Msg: TMessage); var hDrop: THandle; filenameLen: Integer; filename: string; begin Msg.Result := 0; hDrop:= Msg.wParam; filenameLen := DragQueryFile(hDrop, 0, nil, 0); SetLength(filename, filenameLen); DragQueryFile(hDrop, 0, Pointer(filename), filenameLen+1); DragFinish(hDrop); if assigned(fOnFileDrop) then fOnFileDrop(Self, filename) else if (Lowercase(ExtractFileExt(filename)) = '.bmp') then try fImage.LoadFromFile(filename); except end; end; //------------------------------------------------------------------------------ procedure TImage32Panel.WMKeyDown(var Message: TWMKey); var shiftState: TShiftState; begin inherited; shiftState := KeyDataToShiftState(Message.KeyData); case Message.CharCode of Ord('C'): if (ssCtrl in shiftState) and fAllowCopyPaste and not fImage.IsEmpty then fImage.CopyToClipboard; Ord('V'): if (ssCtrl in shiftState) and fAllowCopyPaste and fImage.CanPasteFromClipBoard then begin if fImage.PasteFromClipboard and assigned(fOnPaste) then fOnPaste(self); end; end; end; //------------------------------------------------------------------------------ function TImage32Panel.CopyToClipboard: Boolean; begin Result := fAllowCopyPaste and Image.CopyToClipBoard; end; //------------------------------------------------------------------------------ function TImage32Panel.PasteFromClipboard: Boolean; begin Result := fAllowCopyPaste and Image.PasteFromClipBoard; if Result and assigned(fOnPaste) then fOnPaste(self); end; //------------------------------------------------------------------------------ initialization MinBorderWidth := 10; end.
32.458393
84
0.577629
83000eba38db990cb4595de36bba41ac49c5a2ac
1,327
pas
Pascal
delphi/0051.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
11
2015-12-12T05:13:15.000Z
2020-10-14T13:32:08.000Z
delphi/0051.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
null
null
null
delphi/0051.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
8
2017-05-05T05:24:01.000Z
2021-07-03T20:30:09.000Z
{ // DBPICGRD.PAS (C) 1995 W. Raike // ALL RIGHTS RESERVED. // // DESCRIPTION: // Data-aware grid that can display graphic fields. // REVISION HISTORY: // 15/04/95 Created. W. Raike } unit DBPicGrd; interface uses DBGrids, DB, DBTables, Grids, WinTypes, Classes, Graphics; type TDBPicGrid = class(TDBGrid) protected procedure DrawDataCell(const Rect: TRect; Field: TField; State: TGridDrawState); override; public constructor Create(AOwner : TComponent); override; published property DefaultDrawing default False; end; procedure Register; implementation constructor TDBPicGrid.Create(AOwner : TComponent); begin inherited Create(AOwner); DefaultDrawing := False; end; procedure TDBPicGrid.DrawDataCell(const Rect: TRect; Field: TField; State: TGridDrawState); var bmp : TBitmap; begin with Canvas do begin FillRect(Rect); if Field is TGraphicField then try bmp := TBitmap.Create; bmp.Assign(Field); Draw(Rect.Left, Rect.Top, bmp); finally bmp.Free; end else TextOut(Rect.Left, Rect.Top, Field.Text); end; end; procedure Register; begin RegisterComponents('Custom', [TDBPicGrid]); end; end. 
19.80597
68
0.633007
cda8cbec9ed5d9739d9cac5b120c8ce6ef114454
3,568
pas
Pascal
trunk/View/Initializer.SSDLabelListRefresh.pas
ebangin127/nstools
2a0bb4e6fd3688afd74afd4c7d69eeb46f096a99
[ "MIT" ]
15
2016-02-12T14:55:53.000Z
2021-08-17T09:44:12.000Z
trunk/View/Initializer.SSDLabelListRefresh.pas
ebangin127/nstools
2a0bb4e6fd3688afd74afd4c7d69eeb46f096a99
[ "MIT" ]
1
2020-10-28T12:19:56.000Z
2020-10-28T12:19:56.000Z
trunk/View/Initializer.SSDLabelListRefresh.pas
ebangin127/nstools
2a0bb4e6fd3688afd74afd4c7d69eeb46f096a99
[ "MIT" ]
7
2016-08-21T23:57:47.000Z
2022-02-14T03:26:21.000Z
unit Initializer.SSDLabelListRefresh; interface uses Classes, Forms, SysUtils, Generics.Collections, Windows, ShellAPI, Global.LanguageString, OS.EnvironmentVariable, Form.Alert, Device.PhysicalDrive, Getter.PhysicalDrive.ListChange, Component.SSDLabel, Component.SSDLabel.List; type TSSDLabelListRefresher = class private SSDLabel: TSSDLabelList; ChangesList: TChangesList; procedure AddByAddedList; procedure AddDevice(const Entry: IPhysicalDrive); procedure AlertAndExecuteNewDiagnosisInstance; procedure DeleteAndAddDevicesByResultList; procedure DeleteByDeletedList; procedure DeleteDevice(const Path: String); procedure FreeChangesList; function ChangeExists: Boolean; function IsNoSupportedDriveExists: Boolean; procedure RefreshMainFormAndSetNewSelection; procedure SetChangesList; procedure SetFirstDeviceAsSelected; procedure SetFirstDeviceAsSelectedIfNoDeviceSelected; public procedure RefreshDrives(const SSDLabelToRefresh: TSSDLabelList); end; implementation uses Form.Main; type THackMainform = TForm; procedure TSSDLabelListRefresher.AlertAndExecuteNewDiagnosisInstance; begin AlertCreate(fMain, AlrtNoSupport[CurrLang]); ShellExecute(0, 'open', PChar(EnvironmentVariable.AppPath + 'SSDTools.exe'), PChar('/diag'), nil, SW_SHOW); end; procedure TSSDLabelListRefresher.FreeChangesList; begin FreeAndNil(ChangesList.Added); FreeAndNil(ChangesList.Deleted); end; procedure TSSDLabelListRefresher.SetChangesList; var ListChangeGetter: TListChangeGetter; begin ListChangeGetter := TListChangeGetter.Create; ListChangeGetter.IsOnlyGetSupportedDrives := true; ChangesList := ListChangeGetter.RefreshListWithResultFrom(fMain.IdentifiedDriveList); FreeAndNil(ListChangeGetter); end; function TSSDLabelListRefresher.IsNoSupportedDriveExists: Boolean; begin result := fMain.IdentifiedDriveList.Count = 0; end; procedure TSSDLabelListRefresher.DeleteAndAddDevicesByResultList; begin DeleteByDeletedList; AddByAddedList; end; procedure TSSDLabelListRefresher.DeleteByDeletedList; var CurrentEntry: String; begin for CurrentEntry in ChangesList.Deleted do DeleteDevice(CurrentEntry); end; procedure TSSDLabelListRefresher.AddByAddedList; var CurrentEntry: IPhysicalDrive; begin for CurrentEntry in ChangesList.Added do AddDevice(CurrentEntry); end; procedure TSSDLabelListRefresher.DeleteDevice(const Path: String); begin if not SSDLabel.IsExistsByPath(Path) then exit; SSDLabel.Delete(SSDLabel.IndexOfByPath(Path)); end; procedure TSSDLabelListRefresher.AddDevice(const Entry: IPhysicalDrive); begin SSDLabel.Add(TSSDLabel.Create(Entry)); end; function TSSDLabelListRefresher.ChangeExists: Boolean; begin result := (ChangesList.Added.Count > 0) or (ChangesList.Deleted.Count > 0); end; procedure TSSDLabelListRefresher.SetFirstDeviceAsSelected; begin SSDLabel[0].OnClick(SSDLabel[0]); end; procedure TSSDLabelListRefresher.SetFirstDeviceAsSelectedIfNoDeviceSelected; begin if ChangeExists then SetFirstDeviceAsSelected; end; procedure TSSDLabelListRefresher.RefreshMainFormAndSetNewSelection; begin DeleteAndAddDevicesByResultList; SetFirstDeviceAsSelectedIfNoDeviceSelected; end; procedure TSSDLabelListRefresher.RefreshDrives( const SSDLabelToRefresh: TSSDLabelList); begin SSDLabel := SSDLabelToRefresh; SetChangesList; if IsNoSupportedDriveExists then AlertAndExecuteNewDiagnosisInstance else RefreshMainFormAndSetNewSelection; FreeChangesList; end; end.
25.304965
76
0.813341
47a4873f54c90924ba1e4da6974b0734bde3b4d2
507
pas
Pascal
sdk/boost_1_30_0/libs/spirit/example/application/pascal/test_files/t1.pas
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
2
2020-01-30T12:51:49.000Z
2020-08-31T08:36:49.000Z
sdk/boost_1_30_0/libs/spirit/example/application/pascal/test_files/t1.pas
acidicMercury8/ixray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
null
null
null
sdk/boost_1_30_0/libs/spirit/example/application/pascal/test_files/t1.pas
acidicMercury8/ixray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
null
null
null
{ program 0.1 assuming annual inflation rates of 7, 8, and 10 per cent, find the factor by which the frank, dollar, pound sterling, mark, or guilder will have been devalued in 1, 2, ... n years.} program inflation(output); const n = 10; var i : integer; w1, w2, w3 : real; begin i := 0; w1 := 1.0; w2 := 1.0; w3 := 1.0; repeat i := i + 1; w1 := w1 * 1.07; w2 := w2 * 1.08; w3 := w3 * 1.10; writeln(i, w1, w2, w3); until i=n end.
17.482759
60
0.526627
474442b24e37d9191ba72c5b005f95104ae145de
10,976
pas
Pascal
windows/src/ext/jedi/jwa/branches/2.3/Win32API/JwaIssPer16.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
219
2017-06-21T03:37:03.000Z
2022-03-27T12:09:28.000Z
windows/src/ext/jedi/jwa/branches/2.3/Win32API/JwaIssPer16.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
4,451
2017-05-29T02:52:06.000Z
2022-03-31T23:53:23.000Z
windows/src/ext/jedi/jwa/branches/2.3/Win32API/JwaIssPer16.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
72
2017-05-26T04:08:37.000Z
2022-03-03T10:26:20.000Z
{******************************************************************************} { } { Security Package Error Codes API interface Unit for Object Pascal } { } { Portions created by Microsoft are Copyright (C) 1995-2001 Microsoft } { Corporation. All Rights Reserved. } { } { The original file is: issper16.h, released June 2000. The original Pascal } { code is: IssPer16.pas, released December 2000. The initial developer of the } { Pascal code is Marcel van Brakel (brakelm att chello dott nl). } { } { Portions created by Marcel van Brakel are Copyright (C) 1999-2001 } { Marcel van Brakel. All Rights Reserved. } { } { Obtained through: Joint Endeavour of Delphi Innovators (Project JEDI) } { } { You may retrieve the latest version of this file at the Project JEDI } { APILIB home page, located at http://jedi-apilib.sourceforge.net } { } { The contents of this file are used with permission, 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/MPL-1.1.html } { } { Software distributed under the License is distributed on an "AS IS" basis, } { WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for } { the specific language governing rights and limitations under the License. } { } { Alternatively, the contents of this file may be used under the terms of the } { 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 } { } {******************************************************************************} // $Id: JwaIssPer16.pas,v 1.7 2007/09/14 06:48:46 marquardt Exp $ {$IFNDEF JWA_OMIT_SECTIONS} unit JwaIssPer16; {$WEAKPACKAGEUNIT} {$ENDIF JWA_OMIT_SECTIONS} {$HPPEMIT ''} {$HPPEMIT '#include "issper16.h"'} {$HPPEMIT ''} {$IFNDEF JWA_OMIT_SECTIONS} {$I ..\Includes\JediAPILib.inc} interface uses JwaSSPI; {$ENDIF JWA_OMIT_SECTIONS} {$IFNDEF JWA_IMPLEMENTATIONSECTION} // Define the severities // // Values are 32 bit values layed out as follows: // // 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 // 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 // +---+-+-+-----------------------+-------------------------------+ // |Sev|C|R| Facility | Code | // +---+-+-+-----------------------+-------------------------------+ // // where // // Sev - is the severity code // // 00 - Success // 01 - Informational // 10 - Warning // 11 - Error // // C - is the Customer code flag // // R - is a reserved bit // // Facility - is the facility code // // Code - is the facility's status code // // // Define the facility codes // const {$IFNDEF JWA_INCLUDEMODE} FACILITY_SECURITY = $9; {$EXTERNALSYM FACILITY_SECURITY} FACILITY_NULL = 0; {$EXTERNALSYM FACILITY_NULL} // // Define the severity codes // STATUS_SEVERITY_SUCCESS = $0; {$EXTERNALSYM STATUS_SEVERITY_SUCCESS} {$ENDIF JWA_INCLUDEMODE} STATUS_SEVERITY_COERROR = $2; {$EXTERNALSYM STATUS_SEVERITY_COERROR} {$IFNDEF JWA_INCLUDEMODE} // // MessageId: SEC_E_INSUFFICIENT_MEMORY // // MessageText: // // Not enough memory is available to complete this request // SEC_E_INSUFFICIENT_MEMORY = SECURITY_STATUS($1300); {$EXTERNALSYM SEC_E_INSUFFICIENT_MEMORY} // // MessageId: SEC_E_INVALID_HANDLE // // MessageText: // // The handle specified is invalid // SEC_E_INVALID_HANDLE = SECURITY_STATUS($1301); {$EXTERNALSYM SEC_E_INVALID_HANDLE} // // MessageId: SEC_E_UNSUPPORTED_FUNCTION // // MessageText: // // The function requested is not supported // SEC_E_UNSUPPORTED_FUNCTION = SECURITY_STATUS($1302); {$EXTERNALSYM SEC_E_UNSUPPORTED_FUNCTION} // // MessageId: SEC_E_TARGET_UNKNOWN // // MessageText: // // The specified target is unknown or unreachable // SEC_E_TARGET_UNKNOWN = SECURITY_STATUS($1303); {$EXTERNALSYM SEC_E_TARGET_UNKNOWN} // // MessageId: SEC_E_INTERNAL_ERROR // // MessageText: // // The Local Security Authority cannot be contacted // SEC_E_INTERNAL_ERROR = SECURITY_STATUS($1304); {$EXTERNALSYM SEC_E_INTERNAL_ERROR} // // MessageId: SEC_E_SECPKG_NOT_FOUND // // MessageText: // // The requested security package does not exist // SEC_E_SECPKG_NOT_FOUND = SECURITY_STATUS($1305); {$EXTERNALSYM SEC_E_SECPKG_NOT_FOUND} // // MessageId: SEC_E_NOT_OWNER // // MessageText: // // The caller is not the owner of the desired credentials // SEC_E_NOT_OWNER = SECURITY_STATUS($1306); {$EXTERNALSYM SEC_E_NOT_OWNER} // // MessageId: SEC_E_CANNOT_INSTALL // // MessageText: // // The security package failed to initialize, and cannot be installed // SEC_E_CANNOT_INSTALL = SECURITY_STATUS($1307); {$EXTERNALSYM SEC_E_CANNOT_INSTALL} // // MessageId: SEC_E_INVALID_TOKEN // // MessageText: // // The token supplied to the function is invalid // SEC_E_INVALID_TOKEN = SECURITY_STATUS($1308); {$EXTERNALSYM SEC_E_INVALID_TOKEN} // // MessageId: SEC_E_CANNOT_PACK // // MessageText: // // The security package is not able to marshall the logon buffer, // so the logon attempt has failed // SEC_E_CANNOT_PACK = SECURITY_STATUS($1309); {$EXTERNALSYM SEC_E_CANNOT_PACK} // // MessageId: SEC_E_QOP_NOT_SUPPORTED // // MessageText: // // The per-message Quality of Protection is not supported by the // security package // SEC_E_QOP_NOT_SUPPORTED = SECURITY_STATUS($130A); {$EXTERNALSYM SEC_E_QOP_NOT_SUPPORTED} // // MessageId: SEC_E_NO_IMPERSONATION // // MessageText: // // The security context does not allow impersonation of the client // SEC_E_NO_IMPERSONATION = SECURITY_STATUS($130B); {$EXTERNALSYM SEC_E_NO_IMPERSONATION} // // MessageId: SEC_E_LOGON_DENIED // // MessageText: // // The logon attempt failed // SEC_E_LOGON_DENIED = SECURITY_STATUS($130C); {$EXTERNALSYM SEC_E_LOGON_DENIED} // // MessageId: SEC_E_UNKNOWN_CREDENTIALS // // MessageText: // // The credentials supplied to the package were not // recognized // SEC_E_UNKNOWN_CREDENTIALS = SECURITY_STATUS($130D); {$EXTERNALSYM SEC_E_UNKNOWN_CREDENTIALS} // // MessageId: SEC_E_NO_CREDENTIALS // // MessageText: // // No credentials are available in the security package // SEC_E_NO_CREDENTIALS = SECURITY_STATUS($130E); {$EXTERNALSYM SEC_E_NO_CREDENTIALS} // // MessageId: SEC_E_MESSAGE_ALTERED // // MessageText: // // The message supplied for verification has been altered // SEC_E_MESSAGE_ALTERED = SECURITY_STATUS($130F); {$EXTERNALSYM SEC_E_MESSAGE_ALTERED} // // MessageId: SEC_E_OUT_OF_SEQUENCE // // MessageText: // // The message supplied for verification is out of sequence // SEC_E_OUT_OF_SEQUENCE = SECURITY_STATUS($1310); {$EXTERNALSYM SEC_E_OUT_OF_SEQUENCE} // // MessageId: SEC_E_NO_AUTHENTICATING_AUTHORITY // // MessageText: // // No authority could be contacted for authentication. // SEC_E_NO_AUTHENTICATING_AUTHORITY = SECURITY_STATUS($1311); {$EXTERNALSYM SEC_E_NO_AUTHENTICATING_AUTHORITY} // MessageId: SEC_E_CONTEXT_EXPIRED // // MessageText: // // The context has expired and can no longer be used. // SEC_E_CONTEXT_EXPIRED = SECURITY_STATUS($1312); {$EXTERNALSYM SEC_E_CONTEXT_EXPIRED} // // MessageId: SEC_E_INCOMPLETE_MESSAGE // // MessageText: // // The supplied message is incomplete. The signature was not verified. // SEC_E_INCOMPLETE_MESSAGE = SECURITY_STATUS($1313); {$EXTERNALSYM SEC_E_INCOMPLETE_MESSAGE} // // MessageId: SEC_I_CONTINUE_NEEDED // // MessageText: // // The function completed successfully, but must be called // again to complete the context // SEC_I_CONTINUE_NEEDED = SECURITY_STATUS($1012); {$EXTERNALSYM SEC_I_CONTINUE_NEEDED} // // MessageId: SEC_I_COMPLETE_NEEDED // // MessageText: // // The function completed successfully, but CompleteToken // must be called // SEC_I_COMPLETE_NEEDED = SECURITY_STATUS($1013); {$EXTERNALSYM SEC_I_COMPLETE_NEEDED} // // MessageId: SEC_I_COMPLETE_AND_CONTINUE // // MessageText: // // The function completed successfully, but both CompleteToken // and this function must be called to complete the context // SEC_I_COMPLETE_AND_CONTINUE = SECURITY_STATUS($1014); {$EXTERNALSYM SEC_I_COMPLETE_AND_CONTINUE} // // MessageId: SEC_I_LOCAL_LOGON // // MessageText: // // The logon was completed, but no network authority was // available. The logon was made using locally known information // SEC_I_LOCAL_LOGON = SECURITY_STATUS($1015); {$EXTERNALSYM SEC_I_LOCAL_LOGON} // // MessageId: SEC_E_OK // // MessageText: // // Call completed successfully // SEC_E_OK = SECURITY_STATUS($0000); {$EXTERNALSYM SEC_E_OK} // // Older error names for backwards compatibility // SEC_E_NOT_SUPPORTED = SEC_E_UNSUPPORTED_FUNCTION; {$EXTERNALSYM SEC_E_NOT_SUPPORTED} SEC_E_NO_SPM = SEC_E_INTERNAL_ERROR; {$EXTERNALSYM SEC_E_NO_SPM} SEC_E_BAD_PKGID = SEC_E_SECPKG_NOT_FOUND; {$EXTERNALSYM SEC_E_BAD_PKGID} {$ENDIF JWA_INCLUDEMODE} {$ENDIF JWA_IMPLEMENTATIONSECTION} {$IFNDEF JWA_OMIT_SECTIONS} implementation //uses ... {$ENDIF JWA_OMIT_SECTIONS} {$IFNDEF JWA_INTERFACESECTION} //your implementation here {$ENDIF JWA_INTERFACESECTION} {$IFNDEF JWA_OMIT_SECTIONS} end. {$ENDIF JWA_OMIT_SECTIONS}
25.886792
80
0.635022
47d1a4db7f8761249c460fdb3231cff1b299e3ac
5,281
dfm
Pascal
Demos/SqlClient/TSqlClientQuery/Aggregates/fAggregates.dfm
CrystalNet-Tech/ADONetDAC4Delphi_Tutorials
7b0ad4f962b5d2075a90e451b57257596b41ed62
[ "Apache-2.0" ]
1
2020-09-24T23:26:35.000Z
2020-09-24T23:26:35.000Z
Demos/SqlClient/TSqlClientQuery/Aggregates/fAggregates.dfm
CrystalNet-Tech/ADONetDAC4Delphi_Tutorials
7b0ad4f962b5d2075a90e451b57257596b41ed62
[ "Apache-2.0" ]
null
null
null
Demos/SqlClient/TSqlClientQuery/Aggregates/fAggregates.dfm
CrystalNet-Tech/ADONetDAC4Delphi_Tutorials
7b0ad4f962b5d2075a90e451b57257596b41ed62
[ "Apache-2.0" ]
null
null
null
inherited frmAggregates: TfrmAggregates Caption = 'Aggregates' PixelsPerInch = 96 TextHeight = 13 inherited pnlTitle: TPanel inherited lblTitle: TLabel Width = 119 Caption = 'Aggregates' ExplicitWidth = 119 end end inherited pnlMain: TPanel inherited pnl1: TPanel inherited pgcMain: TPageControl ActivePage = tsData inherited tsData: TTabSheet ExplicitLeft = 4 ExplicitTop = 27 ExplicitWidth = 578 ExplicitHeight = 308 object pnl2: TPanel Left = 0 Top = 0 Width = 578 Height = 146 Align = alTop BevelOuter = bvNone ParentColor = True TabOrder = 0 object lbledtExpression: TLabeledEdit Left = 99 Top = 91 Width = 121 Height = 21 EditLabel.Width = 66 EditLabel.Height = 13 EditLabel.Caption = 'Expression = ' LabelPosition = lpLeft TabOrder = 0 end object lbledtMax: TLabeledEdit Left = 99 Top = 64 Width = 121 Height = 21 EditLabel.Width = 70 EditLabel.Height = 13 EditLabel.Caption = 'Max(UnitPrice)' LabelPosition = lpLeft ReadOnly = True TabOrder = 1 end object lbledtAvg: TLabeledEdit Left = 334 Top = 64 Width = 121 Height = 21 EditLabel.Width = 83 EditLabel.Height = 13 EditLabel.Caption = 'Avg(UnitPrice) = ' LabelPosition = lpLeft ReadOnly = True TabOrder = 2 end object lbledtSum: TLabeledEdit Left = 334 Top = 91 Width = 121 Height = 21 EditLabel.Width = 84 EditLabel.Height = 13 EditLabel.Caption = 'Sum(UnitPrice) = ' LabelPosition = lpLeft ReadOnly = True TabOrder = 4 end object lbledtExprResult: TLabeledEdit Left = 99 Top = 118 Width = 121 Height = 21 EditLabel.Width = 44 EditLabel.Height = 13 EditLabel.Caption = 'Result = ' LabelPosition = lpLeft TabOrder = 3 end object mmo1: TMemo Left = 0 Top = 0 Width = 578 Height = 57 Align = alTop Color = clInfoBk Lines.Strings = ( 'Open the query by clicking on the Open Query Button.' 'Press Compute Button for evaluation of the aggregrate functions.' 'Type an aggregate expression in the "Expression" edit box and pr' + 'ess the Compute Button for evaluation.' '') TabOrder = 5 end object lbledtFilter: TLabeledEdit Left = 334 Top = 118 Width = 121 Height = 21 EditLabel.Width = 38 EditLabel.Height = 13 EditLabel.Caption = 'Filter = ' LabelPosition = lpLeft TabOrder = 6 end object btn1: TButton Left = 461 Top = 63 Width = 75 Height = 25 Caption = 'Compute' TabOrder = 7 OnClick = btn1Click end end object dbgrd1: TDBGrid Left = 0 Top = 146 Width = 578 Height = 162 Align = alClient DataSource = dsOrderDetails TabOrder = 1 TitleFont.Charset = DEFAULT_CHARSET TitleFont.Color = clWindowText TitleFont.Height = -11 TitleFont.Name = 'Tahoma' TitleFont.Style = [] end end inherited tsOptions: TTabSheet ExplicitLeft = 4 ExplicitTop = 27 ExplicitWidth = 578 ExplicitHeight = 308 inherited pnlTree: TPanel inherited grp2: TGroupBox inherited chkReadOnly: TCheckBox Enabled = False end inherited chkRequestLive: TCheckBox Enabled = False end end end end end end end object dsOrderDetails: TDataSource DataSet = SqlClientQueryAggregates Left = 288 Top = 360 end object SqlClientQueryAggregates: TSqlClientQuery Connection = SqlClientConnection1 UpdateOptions.ReadOnly = True UpdateOptions.RequestLive = False Parameters = <> SQL.Strings = ( 'SELECT * FROM [Order Details]') Left = 428 Top = 351 end end
30.177143
87
0.458815
47844d8f4bcfa7459b90c2d4efa025d9d5638e10
8,464
pas
Pascal
tests/38_OrderedFor/test_38_OrderedFor.pas
LordVampir1983/OmniThreadLibrary
ce6cb96297181cbed84ce0ad6e9f220b24636cb2
[ "BSD-3-Clause" ]
386
2015-04-16T21:28:31.000Z
2022-03-16T00:23:23.000Z
tests/38_OrderedFor/test_38_OrderedFor.pas
fatihtsp/OmniThreadLibrary
e65f1923b3e4cf6444425a20035c926855a54112
[ "BSD-3-Clause" ]
120
2015-04-16T21:54:23.000Z
2022-03-11T15:25:09.000Z
tests/38_OrderedFor/test_38_OrderedFor.pas
fatihtsp/OmniThreadLibrary
e65f1923b3e4cf6444425a20035c926855a54112
[ "BSD-3-Clause" ]
152
2015-04-17T13:20:50.000Z
2022-03-09T16:14:53.000Z
unit test_38_OrderedFor; { TODO 1 -ogabr : Test results in all demoes. } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, Spin, OtlThreadPool; type TfrmOderedForDemo = class(TForm) btnUnorderedPrimes1: TButton; lbLog: TListBox; btnOrderedPrimes: TButton; btnUnorderedPrimes2: TButton; btnUnorderedCancel: TButton; cbRepeatTest: TCheckBox; Timer1: TTimer; StatusBar1: TStatusBar; btnSGPrimes: TButton; btnOrderedSGPrimes: TButton; lblNumSGTasks: TLabel; inpNumSGTasks: TSpinEdit; btnAggregatedSGPrimes: TButton; procedure btnUnorderedPrimes1Click(Sender: TObject); procedure btnOrderedPrimesClick(Sender: TObject); procedure btnUnorderedPrimes2Click(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure btnSGPrimesClick(Sender: TObject); private function IsPrime(i: integer): boolean; function MultiThreadedSGPrimes(numTasks: integer): integer; function MultiThreadedAggregatedSGPrimes(numTasks: integer): integer; function MultiThreadedOrderedSGPrimes(numTasks: integer): integer; function NumCores: integer; procedure RepeatTest; function SingleThreadedSGPrimes: integer; procedure VerifyResult; public end; var frmOderedForDemo: TfrmOderedForDemo; implementation uses DSiWin32, GpStuff, GpLists, OtlCommon, OtlSync, OtlCollections, OtlParallel; {$R *.dfm} const CMaxTest = 20000; CMaxSGPrimeTest = 2000000; function TfrmOderedForDemo.IsPrime(i: integer): boolean; var j: integer; begin Result := false; if i <= 1 then Exit; for j := 2 to Round(Sqrt(i)) do if (i mod j) = 0 then Exit; Result := true; end; function TfrmOderedForDemo.MultiThreadedSGPrimes(numTasks: integer): integer; var numSGPrimes: TOmniAlignedInt32; begin numSGPrimes.Value := 0; Parallel.ForEach(1, CMaxSGPrimeTest).NumTasks(numTasks).Execute( procedure (const value: integer) begin if IsPrime(value) and IsPrime(2*value + 1) then numSGPrimes.Increment; end ); Result := numSGPrimes.Value; end; function TfrmOderedForDemo.MultiThreadedAggregatedSGPrimes(numTasks: integer): integer; begin Result := Parallel.ForEach(1, CMaxSGPrimeTest).NumTasks(numTasks).AggregateSum .Execute( procedure (const value: integer; var result: TOmniValue) begin if IsPrime(value) and IsPrime(2*value + 1) then result := 1; end ); end; function TfrmOderedForDemo.MultiThreadedOrderedSGPrimes(numTasks: integer): integer; var numSGPrimes: TOmniAlignedInt32; begin numSGPrimes.Value := 0; Parallel.ForEach(1, CMaxSGPrimeTest).NumTasks(numTasks).PreserveOrder.Execute( procedure (const value: integer) begin if IsPrime(value) and IsPrime(2*value + 1) then numSGPrimes.Increment; end ); Result := numSGPrimes.Value; end; function TfrmOderedForDemo.NumCores: integer; begin Result := Random(Environment.Process.Affinity.Count*2) + 1; lbLog.Items.Add(Format('Running on %d cores', [Result])); end; procedure TfrmOderedForDemo.RepeatTest; begin case Random(3) of 0: btnUnorderedPrimes1.Click; 1: btnUnorderedPrimes2.Click; 2: btnOrderedPrimes.Click; end; end; function TfrmOderedForDemo.SingleThreadedSGPrimes: integer; var iTest: integer; begin Result := 0; for iTest := 1 to CMaxSGPrimeTest do if IsPrime(iTest) and IsPrime(2*iTest + 1) then Inc(Result); end; procedure TfrmOderedForDemo.Timer1Timer(Sender: TObject); begin Timer1.Enabled := false; RepeatTest; end; procedure TfrmOderedForDemo.VerifyResult; var iItem: integer; order: string; value: integer; value2: integer; primes: TGpIntegerList; error: boolean; begin if lbLog.Items.Count <= 1 then lbLog.Items.Add('Error, empty result list!') else begin error := false; order := 'ordered'; value := StrToInt(lbLog.Items[1]); primes := TGpIntegerList.Create; try primes.Add(value); for iItem := 2 to lbLog.Items.Count - 1 do begin value2 := StrToInt(lbLog.Items[iItem]); if value2 <= value then order := 'unordered'; primes.Add(value2); value := value2; end; primes.Sort; for iItem := 1 to CMaxTest do begin if IsPrime(iItem) then begin if not primes.Contains(iItem) then begin error := true; break; //for end end else if primes.Contains(iItem) then begin error := true; break; //for end; end; //for if error then lbLog.Items.Add('ERROR, list is ' + order) else begin lbLog.Items.Add('OK, list is ' + order); if cbRepeatTest.Checked then Timer1.Enabled := true; end; finally FreeAndNil(primes); end; end; lbLog.ItemIndex := lbLog.Items.Count - 1; end; procedure TfrmOderedForDemo.btnSGPrimesClick(Sender: TObject); var numSGPrimes: integer; time : int64; begin time := DSiTimeGetTime64; if inpNumSGTasks.Value = 0 then numSGPrimes := SingleThreadedSGPrimes else if Sender = btnOrderedSGPrimes then numSGPrimes := MultiThreadedOrderedSGPrimes(inpNumSGTasks.Value) else if Sender = btnAggregatedSGPrimes then numSGPrimes := MultiThreadedAggregatedSGPrimes(inpNumSGTasks.Value) else numSGPrimes := MultiThreadedSGPrimes(inpNumSGTasks.Value); time := DSiElapsedTime64(time); lbLog.ItemIndex := lbLog.Items.Add(Format( '%d Sophie Germain primes from 1 to %d, calculation on %d threads took %s seconds', [numSGPrimes, CMaxSGPrimeTest, inpNumSGTasks.Value, FormatDateTime('ss.zzz', time/MSecsPerDay)])); end; procedure TfrmOderedForDemo.btnUnorderedPrimes1Click(Sender: TObject); var prime : TOmniValue; primeQueue: IOmniBlockingCollection; begin btnUnorderedPrimes1.Enabled := false; lbLog.Clear; primeQueue := TOmniBlockingCollection.Create; Parallel.ForEach(1, CMaxTest).NumTasks(NumCores).NoWait .OnStop( procedure begin primeQueue.CompleteAdding; end) .Execute( procedure (const value: integer) begin if IsPrime(value) then begin primeQueue.Add(value); // Sleep(200); // enable to see how results from different threads are added during the calculation end; end); for prime in primeQueue do begin lbLog.Items.Add(IntToStr(prime)); lbLog.Update; end; VerifyResult; btnUnorderedPrimes1.Enabled := true; end; procedure TfrmOderedForDemo.btnUnorderedPrimes2Click(Sender: TObject); var prime : TOmniValue; primeQueue: IOmniBlockingCollection; begin btnUnorderedPrimes2.Enabled := false; lbLog.Clear; primeQueue := TOmniBlockingCollection.Create; Parallel.ForEach(1, CMaxTest).NoWait.NumTasks(NumCores).Into(primeQueue).Execute( procedure (const value: integer; var res: TOmniValue) begin if IsPrime(value) then res := value; // Sleep(200); // enable to see how results from different threads are added during the calculation end); for prime in primeQueue do begin lbLog.Items.Add(IntToStr(prime)); lbLog.Update; end; VerifyResult; btnUnorderedPrimes2.Enabled := true; end; procedure TfrmOderedForDemo.btnOrderedPrimesClick(Sender: TObject); var prime : TOmniValue; primeQueue: IOmniBlockingCollection; begin (Sender as TButton).Enabled := false; lbLog.Clear; primeQueue := TOmniBlockingCollection.Create; Parallel.ForEach(1, CMaxTest) .CancelWith(GOmniCancellationToken) .NumTasks(NumCores) .PreserveOrder .NoWait .Into(primeQueue) .Execute( procedure (const value: integer; var res: TOmniValue) begin if IsPrime(value) then res := value; if (Sender = btnUnorderedCancel) and (value = 511 {arbitrary}) then GOmniCancellationToken.Signal; end); for prime in primeQueue do begin lbLog.Items.Add(IntToStr(prime)); lbLog.Update; end; VerifyResult; GOmniCancellationToken.Clear; (Sender as TButton).Enabled := true; end; end.
27.303226
107
0.675685
83adc9207c93e9cff43f445be30ed930f1d26d85
13,622
pas
Pascal
vcl/SrcXLS/xpgPXMLUtils.pas
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
vcl/SrcXLS/xpgPXMLUtils.pas
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
vcl/SrcXLS/xpgPXMLUtils.pas
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
unit xpgPXMLUtils; interface uses Classes, SysUtils, {$ifndef BABOON} Windows, {$endif} xpgPUtils; // TODO Fix overflow check const AX_XML_MAX_ATTRIBUTES = $FF; // TODO Move to other unit type Ax8Char = AnsiChar; type Ax8String = AnsiString; type TXpgAssigned = (xaElements,xaAttributes,xaContent,xaRead); type TXpgAssigneds = set of TXpgAssigned; type TXpgXMLString = record pStart: PAnsiChar; pEnd: PAnsiChar; end; type TXpgXMLUCString = record pStart: AxPUCChar; pEnd: AxPUCChar; end; type PXpgXmlAttribute = ^TXpgXmlAttribute; TXpgXmlAttribute = record Attribute: TXpgXMLString; Value: TXpgXMLString; sAttr,sVal: AxUCString; Flag: integer; end; type TXpgXmlAttributeArray = array of TXpgXmlAttribute; type TXpgXMLAttributeList = class(TObject) private function GetAttributes(Index: integer): AxUCString; function GetValues(Index: integer): AxUCString; function GetHashA(Index: integer): longword; function GetHashB(Index: integer): longword; function GetHashC(Index: integer): longword; function GetHashD(Index: integer): longword; protected FSortList: TList; FSorted: boolean; FCount: integer; FSnatching: boolean; FBadEnumValue: string; function GetAsString(const Str: TXpgXMLString): AxUCString; function GetAsStringUTF8(const Str: TXpgXMLString): AxUCString; procedure MakeStrings; procedure Sort; public FAttributes: TXpgXmlAttributeArray; constructor Create; destructor Destroy; override; procedure Clear; procedure ClearNamespace; procedure Assign(AAttributes: TXpgXmlAttributeArray; ACount: integer); function Count: integer; function Find(const AName: AxUCString): integer; overload; function Find(const AName: AxUCString; out AValue: AxUCString): boolean; overload; procedure CollectPrefixed(APrefix: string; AList: TStrings); procedure BeginSnatch; procedure EndSnatch(BadAttributes: TStrings); function AsString(const AName: AxUCString): AxUCString; // Error in AST, these names can't be overloaded. Probably because there is no parameter in the first. function AsXmlText: AxUCString; function AsXmlText2(AIndex: integer): AxUCString; function AsBoolDef(const AName: AxUCString; ADefault: boolean): boolean; function AsIntegerDef(const AName: AxUCString; ADefault: integer): integer; function AsStringDef(const AName: AxUCString; const ADefault: AxUCString): AxUCString; function AsEnumDef(const AName: AxUCString; AEnums: array of AxUCString; ADefault: integer): integer; function EnumError: AxUCString; procedure Add(AAttributes: TXpgXmlAttributeArray; ACount: integer); overload; procedure Add(const AName,AValue: AxUCString); overload; property Attributes[Index: integer]: AxUCString read GetAttributes; default; property Values[Index: integer]: AxUCString read GetValues; property HashA[Index: integer]: longword read GetHashA; property HashB[Index: integer]: longword read GetHashB; property HashC[Index: integer]: longword read GetHashC; property HashD[Index: integer]: longword read GetHashD; end; implementation // uses Windows; { TAxXMLAttributeList } procedure TXpgXMLAttributeList.Add(AAttributes: TXpgXmlAttributeArray; ACount: integer); begin Clear; FAttributes := AAttributes; FCount := ACount; MakeStrings; end; procedure TXpgXMLAttributeList.Add(const AName, AValue: AxUCString); begin if Length(FAttributes) <= FCount then SetLength(FAttributes,Length(FAttributes) + AX_XML_MAX_ATTRIBUTES); FAttributes[FCount].sAttr := AName; FAttributes[FCount].sVal := AValue; FAttributes[FCount].Flag := 0; Inc(FCount); end; function TXpgXMLAttributeList.AsBoolDef(const AName: AxUCString; ADefault: boolean): boolean; var S: AxUCString; begin if Find(AName,S) then begin S := Lowercase(S); if S = 'true' then Result := True else if S = 'false' then Result := False else Result := ADefault; end else Result := ADefault; end; function TXpgXMLAttributeList.AsEnumDef(const AName: AxUCString; AEnums: array of AxUCString; ADefault: integer): integer; var S: AxUCString; begin if Find(AName,S) then begin if FSnatching then FBadEnumValue := ''; for Result := 0 to High(AEnums) do begin if S = AEnums[Result] then Exit; end; if FSnatching then FBadEnumValue := S; Result := ADefault; end else Result := ADefault; end; function TXpgXMLAttributeList.AsIntegerDef(const AName: AxUCString; ADefault: integer): integer; var S: AxUCString; begin if not Find(AName,S) then Result := ADefault else begin if S = 'unbounded' then Result := MAXINT else Result := StrToIntDef(S,ADefault); end; end; procedure TXpgXMLAttributeList.Assign(AAttributes: TXpgXmlAttributeArray; ACount: integer); var i: integer; begin for i := 0 to ACount - 1 do Add(AAttributes[i].sAttr,AAttributes[i].sVal); end; function TXpgXMLAttributeList.AsString(const AName: AxUCString): AxUCString; begin if not Find(AName,Result) then Result := ''; end; function TXpgXMLAttributeList.AsStringDef(const AName, ADefault: AxUCString): AxUCString; begin if not Find(AName,Result) then Result := ADefault; end; function TXpgXMLAttributeList.AsXmlText2(AIndex: integer): AxUCString; begin Result := FAttributes[AIndex].sAttr + '="' + FAttributes[AIndex].sVal + '"' end; function TXpgXMLAttributeList.AsXmlText: AxUCString; var i: integer; begin Result := ''; for i := 0 to FCount - 1 do Result := Result + AsXmlText2(i) + ' '; Result := Trim(Result); end; procedure TXpgXMLAttributeList.BeginSnatch; begin FSnatching := True; end; procedure TXpgXMLAttributeList.Clear; begin FCount := 0; FSorted := False; end; procedure TXpgXMLAttributeList.ClearNamespace; var i,j: integer; S: AxUCString; P1,P2: PAnsiChar; begin for i := 0 to FCount - 1 do begin S := FAttributes[i].sAttr; j := CPos(':',S); if j > 1 then FAttributes[i].sAttr := Copy(S,j + 1,MAXINT); P1 := FAttributes[i].Attribute.pStart; P2 := FAttributes[i].Attribute.pEnd; while (P1 < P2) and (P1^ <> ':') do Inc(P1); FAttributes[i].Attribute.pStart := P1 + 1; end; end; procedure TXpgXMLAttributeList.CollectPrefixed(APrefix: string; AList: TStrings); var i: integer; S,S2: AxUCString; begin for i := 0 to Count - 1 do begin S := FAttributes[i].sAttr; S2 := SplitAtChar(':',S); if Copy(S2,1,Length(APrefix)) = APrefix then begin AList.Add(FAttributes[i].sAttr + '=' + FAttributes[i].sVal); if FSnatching then FAttributes[i].Flag := 1; end; end; end; function TXpgXMLAttributeList.Count: integer; begin Result := FCount; end; constructor TXpgXMLAttributeList.Create; begin FSortList := TList.Create; end; destructor TXpgXMLAttributeList.Destroy; begin FSortList.Free; inherited; end; procedure TXpgXMLAttributeList.EndSnatch(BadAttributes: TStrings); var i: integer; begin FSnatching := False; BadAttributes.Clear; for i := 0 to FCount - 1 do begin if FAttributes[i].Flag = 0 then BadAttributes.Add(FAttributes[i].sAttr); end; end; function TXpgXMLAttributeList.EnumError: AxUCString; begin Result := FBadEnumValue; FBadEnumValue := ''; end; function TXpgXMLAttributeList.Find(const AName: AxUCString; out AValue: AxUCString): boolean; var i: integer; begin i := Find(AName); Result := i >= 0; if Result then // TODO are spaces permitted at beginning/end of values? AValue := Trim(PXpgXmlAttribute(FSortList[i]).sVal); end; function TXpgXMLAttributeList.Find(const AName: AxUCString): integer; function BinSearch: integer; var L, H: Integer; mid, cmp: Integer; begin Result := -1; L := 0; H := FCount - 1; while L <= H do begin mid := L + (H - L) shr 1; cmp := CompareStr(PXpgXmlAttribute(FSortList[mid]).sAttr,AName); if cmp < 0 then L := mid + 1 else begin H := mid - 1; if cmp = 0 then begin Result := mid; Exit; end; end; end; end; begin if not FSorted then Sort; Result := BinSearch; if (Result >= 0) and FSnatching then PXpgXmlAttribute(FSortList[Result]).Flag := 1; end; function TXpgXMLAttributeList.GetAsString(const Str: TXpgXMLString): AxUCString; var i,L: integer; begin L := Integer(Str.pEnd) - Integer(Str.pStart) + 1; SetLength(Result,L); if L = 1 then Result[1] := AxUCChar(Str.pStart[0]) else begin for i := 1 to L do Result[i] := AxUCChar(Str.pStart[i - 1]); end; end; function TXpgXMLAttributeList.GetAsStringUTF8(const Str: TXpgXMLString): AxUCString; var L: integer; Hash: longword; P,pDest: PAnsiChar; pCheck: PAnsiChar; begin // Entity conversion also in xpgPXML P := Str.pStart; pDest := P; while P <= Str.pEnd do begin if P^ = '&' then begin Hash := 0; pCheck := P; Inc(pCheck); while pCheck <= Str.pEnd do begin if pCheck^ = ';' then begin case Hash of 318: begin // &amp; " pDest^ := '&'; Inc(pDest); Inc(P,5); end; 435: begin // &apos; ' pDest^ := ''''; Inc(pDest); Inc(P,6); end; 219: begin // &gt; > pDest^ := '>'; Inc(pDest); Inc(P,4); end; 224: begin // &lt; < pDest^ := '<'; Inc(pDest); Inc(P,4); end; 457: begin // &quot; " pDest^ := '"'; Inc(pDest); Inc(P,6); end; else begin P := pCheck; Inc(P); end; end; if P^ = '&' then begin Hash := 0; pCheck := P; Inc(pCheck); Continue; end else Break; end else begin Inc(Hash,Byte(pCheck^)); Inc(pCheck); end; end; end; pDest^ := P^; Inc(P); Inc(pDest); end; L := Integer(Str.pEnd) - Integer(Str.pStart) + 1 - (Integer(P) - Integer(pDest)); // L := Integer(Str.pEnd) - Integer(Str.pStart) + 1; SetLength(Result,L * 2); {$ifdef BABOON} L := Utf8ToUnicode(PWideChar(Result),Length(Result),Str.pStart,L) - 1; {$else} L := MultiByteToWideChar(CP_UTF8,0,Str.pStart,L,PWideChar(Result),L * 2); {$endif} SetLength(Result,L); end; function TXpgXMLAttributeList.GetAttributes(Index: integer): AxUCString; begin Result := FAttributes[Index].sAttr; end; function TXpgXMLAttributeList.GetHashA(Index: integer): longword; var P: PAnsiChar; pEnd: PAnsiChar; begin Result := 0; P := FAttributes[Index].Attribute.pStart; pEnd := FAttributes[Index].Attribute.pEnd; while P <= pEnd do begin Inc(Result,Ord(P^)); Inc(P); end; end; function TXpgXMLAttributeList.GetHashB(Index: integer): longword; var a : cardinal; P: PAnsiChar; pEnd: PAnsiChar; begin Result := 0; a := 63689; P := FAttributes[Index].Attribute.pStart; pEnd := FAttributes[Index].Attribute.pEnd; while P <= pEnd do begin Result := Result * a + Ord(P^); a := a * 378551; Inc(P); end; end; function TXpgXMLAttributeList.GetHashC(Index: integer): longword; var P: PAnsiChar; pEnd: PAnsiChar; begin Result := 1315423911; P := FAttributes[Index].Attribute.pStart; pEnd := FAttributes[Index].Attribute.pEnd; while P <= pEnd do begin Result := Result xor ((Result shl 5) + Ord(P^) + (Result shr 2)); Inc(P); end; end; function TXpgXMLAttributeList.GetHashD(Index: integer): longword; var i: integer; P: PAnsiChar; pEnd: PAnsiChar; begin Result := $AAAAAAAA; P := FAttributes[Index].Attribute.pStart; pEnd := FAttributes[Index].Attribute.pEnd; i := 1; while P <= pEnd do begin if ((i - 1) and 1) = 0 then Result := Result xor ((Result shl 7) xor Ord(P^) * (Result shr 3)) else Result := Result xor (not((Result shl 11) + Ord(P^) xor (Result shr 5))); Inc(P); Inc(i); end; end; function TXpgXMLAttributeList.GetValues(Index: integer): AxUCString; begin // TODO are spaces permitted at beginning/end of values? Result := FAttributes[Index].sVal; end; procedure TXpgXMLAttributeList.MakeStrings; var i: integer; begin for i := 0 to FCount - 1 do begin FAttributes[i].sAttr := GetAsString(FAttributes[i].Attribute); FAttributes[i].sVal := GetAsStringUTF8(FAttributes[i].Value); end; end; function ListSortCompare(Item1, Item2: Pointer): Integer; begin Result := CompareStr(PXpgXmlAttribute(Item1).sAttr,PXpgXmlAttribute(Item2).sAttr); end; procedure TXpgXMLAttributeList.Sort; var i: integer; begin FSortList.Clear; for i := 0 to FCount - 1 do FSortList.Add(@FAttributes[i]); FSortList.Sort(ListSortCompare); FSorted := True; end; end.
25.414179
123
0.630084
47152f55d7968b32a3ebb38ce58e0c5dc1c77a4d
802
pas
Pascal
Controller/uController.Cliente.pas
FranlleyGomes/ProjetoMVC
f353a08b5f801cbf5ba3c9753fda8817baaafb14
[ "MIT" ]
null
null
null
Controller/uController.Cliente.pas
FranlleyGomes/ProjetoMVC
f353a08b5f801cbf5ba3c9753fda8817baaafb14
[ "MIT" ]
null
null
null
Controller/uController.Cliente.pas
FranlleyGomes/ProjetoMVC
f353a08b5f801cbf5ba3c9753fda8817baaafb14
[ "MIT" ]
null
null
null
unit uController.Cliente; interface uses uModel.Cliente, FireDAC.Comp.Client; type TControllerCliente = class private FModelCliente: TModelCliente; public property ModelCliente: TModelCliente read FModelCliente write FModelCliente; function persistir: Boolean; function selecionar: TFDQuery; constructor Create; destructor Destroy; override; end; implementation constructor TControllerCliente.Create; begin FModelCliente := TModelCliente.Create; inherited Create; end; destructor TControllerCliente.Destroy; begin FModelCliente.Free; inherited; end; function TControllerCliente.persistir: Boolean; begin Result := FModelCliente.persistir; end; function TControllerCliente.selecionar: TFDQuery; begin Result := FModelCliente.selecionar; end; end.
17.06383
80
0.784289
83a3c21e791c017dd8b43d59d6e53a69fe82d49f
1,806
pas
Pascal
samples/angular/server/WebModuleU.pas
compubinkie/delphimvcframework
a4381ec71984f941d44210d615df821c062a736f
[ "Apache-2.0" ]
3
2020-04-23T04:15:18.000Z
2021-11-16T11:24:54.000Z
samples/angular/dmvcframeworkserver/WebModuleU.pas
darckbleu/danieleteti-delphimvcframework
674c9feac96a777cfeca0ed34bdb364bcbb4bade
[ "Apache-2.0" ]
null
null
null
samples/angular/dmvcframeworkserver/WebModuleU.pas
darckbleu/danieleteti-delphimvcframework
674c9feac96a777cfeca0ed34bdb364bcbb4bade
[ "Apache-2.0" ]
1
2020-03-22T15:06:54.000Z
2020-03-22T15:06:54.000Z
unit WebModuleU; interface uses System.SysUtils, System.Classes, Web.HTTPApp, MVCFramework, MVCFramework.Middleware.CORS; type TMyWebModule = class(TWebModule) procedure WebModuleCreate(Sender: TObject); procedure WebModuleDestroy(Sender: TObject); private FMVC: TMVCEngine; public { Public declarations } end; var WebModuleClass: TComponentClass = TMyWebModule; implementation {$R *.dfm} uses CustomersControllerU, MVCFramework.Commons; procedure TMyWebModule.WebModuleCreate(Sender: TObject); begin FMVC := TMVCEngine.Create(Self, procedure(Config: TMVCConfig) begin // enable static files Config[TMVCConfigKey.DocumentRoot] := ExtractFilePath(GetModuleName(HInstance)) + 'www'; // session timeout (0 means session cookie) Config[TMVCConfigKey.SessionTimeout] := '0'; // default content-type Config[TMVCConfigKey.DefaultContentType] := TMVCConstants.DEFAULT_CONTENT_TYPE; // default content charset Config[TMVCConfigKey.DefaultContentCharset] := TMVCConstants.DEFAULT_CONTENT_CHARSET; // unhandled actions are permitted? Config[TMVCConfigKey.AllowUnhandledAction] := 'false'; // default view file extension Config[TMVCConfigKey.DefaultViewFileExtension] := 'html'; // view path Config[TMVCConfigKey.ViewPath] := 'templates'; // Enable Server Signature in response Config[TMVCConfigKey.ExposeServerSignature] := 'true'; // Define a default URL for requests that don't map to a route or a file Config[TMVCConfigKey.FallbackResource] := 'index.html'; end); FMVC.AddController(TCustomersController); FMVC.AddMiddleware(TCORSMiddleware.Create); end; procedure TMyWebModule.WebModuleDestroy(Sender: TObject); begin FMVC.Free; end; end.
27.363636
94
0.730343
f1c6ce023732c0de57ee0e1a51125b0a2f642646
9,299
pas
Pascal
references/jcl/jcl/install/JediInstallConfigIni.pas
zekiguven/alcinoe
e55c5368ee8bfe7cd6d92424c29ab07d8a3e844c
[ "Apache-2.0" ]
851
2018-02-05T09:54:56.000Z
2022-03-24T23:13:10.000Z
references/jcl/jcl/install/JediInstallConfigIni.pas
zekiguven/alcinoe
e55c5368ee8bfe7cd6d92424c29ab07d8a3e844c
[ "Apache-2.0" ]
200
2018-02-06T18:52:39.000Z
2022-03-24T19:59:14.000Z
references/jcl/jcl/install/JediInstallConfigIni.pas
zekiguven/alcinoe
e55c5368ee8bfe7cd6d92424c29ab07d8a3e844c
[ "Apache-2.0" ]
197
2018-03-20T20:49:55.000Z
2022-03-21T17:38:14.000Z
{**************************************************************************************************} { } { Project JEDI Code Library (JCL) extension } { } { 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 JediInstallConfigIni.pas. } { } { The Initial Developer of the Original Code is Florent Ouchet. Portions created by Florent Ouchet } { are Copyright (C) of Florent Ouchet. All Rights Reserved. } { } { Contributors: } { } {**************************************************************************************************} { } { Storage facility into an ini file for the installer core } { } {**************************************************************************************************} { } { Last modified: $Date:: $ } { Revision: $Rev:: $ } { Author: $Author:: $ } { } {**************************************************************************************************} unit JediInstallConfigIni; {$I jcl.inc} {$I crossplatform.inc} interface uses JediInstall, IniFiles; type TJediConfigIni = class(TInterfacedObject, IJediConfiguration) private FIniFile: TMemIniFile; public constructor Create; destructor Destroy; override; // IJediConfiguration function GetSections: TStringArray; function GetOptions(const Section: string): TOptionArray; function GetOptionAsBool(const Section: string; Id: Integer): Boolean; procedure SetOptionAsBool(const Section: string; Id: Integer; Value: Boolean); function GetOptionAsBoolByName(const Section: string; const Name: string): Boolean; procedure SetOptionAsBoolByName(const Section: string; const Name: string; Value: Boolean); function GetOptionAsString(const Section: string; Id: Integer): string; procedure SetOptionAsString(const Section: string; Id: Integer; const Value: string); function GetOptionAsStringByName(const Section: string; const Name: string): string; procedure SetOptionAsStringByName(const Section: string; const Name: string; const Value: string); procedure Clear; procedure DeleteSection(const Section: string); procedure DeleteOption(const Section: string; Id: Integer); function SectionExists(const Section: string): Boolean; function ValueExists(const Section: string; Id: Integer): Boolean; overload; function ValueExists(const Section: string; const Name: string): Boolean; overload; property Sections: TStringArray read GetSections; property Options[const Section: string]: TOptionArray read GetOptions; property OptionAsBool[const Section: string; Id: Integer]: Boolean read GetOptionAsBool write SetOptionAsBool; property OptionAsBoolByName[const Section: string; const Name: string]: Boolean read GetOptionAsBoolByName write SetOptionAsBoolByName; property OptionAsString[const Section: string; Id: Integer]: string read GetOptionAsString write SetOptionAsString; property OptionAsStringByName[const Section: string; const Name: string]: string read GetOptionAsStringByName write SetOptionAsStringByName; end; function CreateConfigIni: IJediConfiguration; implementation uses SysUtils, Classes, JclSysInfo, JclFileUtils; const DefaultIniFileName = 'JCL-install.ini'; function CreateConfigIni: IJediConfiguration; begin Result := TJediConfigIni.Create; end; //=== { TJediConfigIni } ===================================================== procedure TJediConfigIni.Clear; begin FIniFile.Clear; end; constructor TJediConfigIni.Create; var AFileName: string; begin inherited Create; AFileName := ''; if not GetEnvironmentVar('JCL_INSTALL_INI', AFileName) then AFileName := ''; if AFileName = '' then AFileName := DefaultIniFileName; if not PathIsAbsolute(AFileName) then AFileName := ExtractFilePath(ParamStr(0)) + AFileName; FIniFile := TMemIniFile.Create(AFileName); end; procedure TJediConfigIni.DeleteOption(const Section: string; Id: Integer); begin FIniFile.DeleteKey(Section, InstallCore.InstallOptionName[Id]); end; procedure TJediConfigIni.DeleteSection(const Section: string); begin FIniFile.EraseSection(Section); end; destructor TJediConfigIni.Destroy; begin FIniFile.UpdateFile; FIniFile.Free; inherited Destroy; end; function TJediConfigIni.GetOptionAsBool(const Section: string; Id: Integer): Boolean; begin Result := FIniFile.ReadBool(Section, InstallCore.InstallOptionName[Id], False); end; function TJediConfigIni.GetOptionAsBoolByName(const Section, Name: string): Boolean; begin Result := FIniFile.ReadBool(Section, Name, False); end; function TJediConfigIni.GetOptionAsString(const Section: string; Id: Integer): string; begin Result := FIniFile.ReadString(Section, InstallCore.InstallOptionName[Id], ''); end; function TJediConfigIni.GetOptionAsStringByName(const Section, Name: string): string; begin Result := FIniFile.ReadString(Section, Name, ''); end; function TJediConfigIni.GetOptions(const Section: string): TOptionArray; var Values: TStrings; Index: Integer; Name: string; begin Values := TStringList.Create; try FIniFile.ReadSectionValues(Section, Values); SetLength(Result, Values.Count); for Index := 0 to Values.Count - 1 do begin Name := Values.Names[Index]; Result[Index].Name := Name; Result[Index].Value := Values.Values[Name]; end; finally Values.Free; end; end; function TJediConfigIni.GetSections: TStringArray; var Sections: TStrings; Index: Integer; begin Sections := TStringList.Create; try FIniFile.ReadSections(Sections); SetLength(Result, Sections.Count); for Index := 0 to Sections.Count - 1 do Result[Index] := Sections.Strings[Index]; finally Sections.Free; end; end; function TJediConfigIni.SectionExists(const Section: string): Boolean; begin Result := FIniFile.SectionExists(Section); end; procedure TJediConfigIni.SetOptionAsBool(const Section: string; Id: Integer; Value: Boolean); begin FIniFile.WriteBool(Section, InstallCore.InstallOptionName[Id], Value); end; procedure TJediConfigIni.SetOptionAsBoolByName(const Section, Name: string; Value: Boolean); begin FIniFile.WriteBool(Section, Name, Value); end; procedure TJediConfigIni.SetOptionAsString(const Section: string; Id: Integer; const Value: string); begin FIniFile.WriteString(Section, InstallCore.InstallOptionName[Id], Value); end; procedure TJediConfigIni.SetOptionAsStringByName(const Section, Name, Value: string); begin FIniFile.WriteString(Section, Name, Value); end; function TJediConfigIni.ValueExists(const Section: string; Id: Integer): Boolean; begin Result := FIniFile.ValueExists(Section, InstallCore.InstallOptionName[Id]); end; function TJediConfigIni.ValueExists(const Section, Name: string): Boolean; begin Result := FIniFile.ValueExists(Section, Name); end; initialization InstallCore.ConfigurationCreator := CreateConfigIni; end.
37.647773
103
0.560168
f1e959374bbf73df4a5a0a309a970b46901d91af
124,725
pas
Pascal
dependencies/Log4D/Log4D.pas
CloudDelphi/Logging4Delphi
047abe5fda7b7cf3938bb426e82360a46ebb0198
[ "Apache-2.0" ]
null
null
null
dependencies/Log4D/Log4D.pas
CloudDelphi/Logging4Delphi
047abe5fda7b7cf3938bb426e82360a46ebb0198
[ "Apache-2.0" ]
null
null
null
dependencies/Log4D/Log4D.pas
CloudDelphi/Logging4Delphi
047abe5fda7b7cf3938bb426e82360a46ebb0198
[ "Apache-2.0" ]
1
2019-05-19T12:22:23.000Z
2019-05-19T12:22:23.000Z
unit Log4D; { 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/MPL-1.1.html 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. } { Logging for Delphi. Based on log4j Java package from Apache (http://jakarta.apache.org/log4j/docs/index.html). Currently based on log4j 1.2.12 Written by Keith Wood (kbwood@iprimus.com.au). Version 1.0 - 29 April 2001. Version 1.2 - 9 September 2003. Version 1.3 - 24 July 2004. Version 1.2.12 - 6 October 2009 changes by adasen: - added threshold option to TLogCustomAppender (as in SkeletonAppender.java) - use fmShareDenyWrite instead of fmShareExclusive in TLogFileAppender - added TLogRollingFileAppender (as in RollingFileAppender.java) changes by mhoenemann: - reopen a newly created file stream in TLogFileAppender to get fmShareDenyWrite on a new logfile (due to a bug in SysUtils.FileCreate()) changes by aweber: - changed TLogRollingFileAppender.RollOver from protected to public so that it can be called on purpose (as in Java) - added ILogRollingFileAppender in order to be able to use RollOver - moved all methods of TLogCustomAppender from private to protected in order to be able to subclass it properly changes by ahesse: - add jedi.inc for compiler version switches - add trace methods like in log4j 1.2.12 - change version back to 1.2.12 to reflect log4j version - add Encoding to TLogCustomAppender - make TLogLevel.Create() public to add User defined Log Levels - TLogLogger.IsEnabledFor() must use the same logic as TLogLogger.Log() } interface {$I Defines.inc} uses Classes, {$IFDEF LINUX} SyncObjs, {$ELSE} Windows, {$ENDIF} {$IFDEF DELPHI5_UP} Contnrs, {$ENDIF} SysUtils; const Log4DVersion = '1.2.12'; { Default pattern string for log output. Shows the application supplied message. } DefaultPattern = '%m%n'; { A conversion pattern equivalent to the TTCC layout. Shows runtime, thread, level, logger, NDC, and message. } TTCCPattern = '%r [%t] %p %c %x - %m%n'; { Common prefix for option names in an initialisation file. Note that the search for all option names is case sensitive. } KeyPrefix = 'log4d'; { Specify the additivity of a logger's appenders. } AdditiveKey = KeyPrefix + '.additive.'; { Define a named appender. } AppenderKey = KeyPrefix + '.appender.'; { Nominate a factory to use to generate loggers. This factory must have been registered with RegisterLoggerFactory. If none is specified, then the default factory is used. } LoggerFactoryKey = KeyPrefix + '.loggerFactory'; { Define a new logger, and set its logging level and appenders. } LoggerKey = KeyPrefix + '.logger.'; { Defining this value as true makes log4d print internal debug statements to debug output. } DebugKey = KeyPrefix + '.configDebug'; { Specify the error handler to be used with an appender. } ErrorHandlerKey = '.errorHandler'; { Specify the filters to be used with an appender. } FilterKey = '.filter'; { Specify the layout to be used with an appender. } LayoutKey = '.layout'; { Associate an object renderer with the class to be rendered. } RendererKey = KeyPrefix + '.renderer.'; { Set the logging level and appenders for the root. } RootLoggerKey = KeyPrefix + '.rootLogger'; { Set the overall logging level. } ThresholdKey = KeyPrefix + '.threshold'; { Special level value signifying inherited behaviour. } InheritedLevel = 'inherited'; { Threshold option for TLogCustomAppender. } ThresholdOpt = 'threshold'; { Encoding option for TLogCustomAppender. } EncodingOpt = 'encoding'; { Accept option for TLog*Filter. } AcceptMatchOpt = 'acceptOnMatch'; { Appending option for TLogFileAppender. } AppendOpt = 'append'; { Common date format option for layouts. } DateFormatOpt = 'dateFormat'; { File name option for TLogFileAppender. } FileNameOpt = 'fileName'; { Case-sensitivity option for TLogStringFilter. } IgnoreCaseOpt = 'ignoreCase'; { Match string option for TLogLevelMatchFilter and TLogStringFilter. } MatchOpt = 'match'; { Maximum string option for TLogLevelRangeFilter. } MaxOpt = 'maximum'; { Minimum string option for TLogLevelRangeFilter. } MinOpt = 'minimum'; { Pattern option for TLogPatternLayout. } PatternOpt = 'pattern'; { Title option for TLogHTMLLayout. } TitleOpt = 'title'; { Maximum file size option for TLogRollingFileAppender } MaxFileSizeOpt = 'maxFileSize'; { Maximum number of backup files option for TLogRollingFileAppender } MaxBackupIndexOpt = 'maxBackupIndex'; DEFAULT_MAX_FILE_SIZE = 10*1024*1024; DEFAULT_MAX_BACKUP_INDEX = 1; type {$IFDEF DELPHI4} TClassList = TList; TObjectList = TList; {$ENDIF} {$IFDEF LINUX} TRTLCriticalSection = TCriticalSection; {$ENDIF} { Log-specific exceptions. } ELogException = class(Exception); { Allow for initialisation of a dynamically created object. } ILogDynamicCreate = interface(IUnknown) ['{287DAA34-3A9F-45C6-9417-1B0D4DFAC86C}'] procedure Init; end; { Get/set arbitrary options on an object. } ILogOptionHandler = interface(ILogDynamicCreate) ['{AC1C0E30-2DBF-4C55-9C2E-9A0F1A3E4F58}'] function GetOption(const Name: string): string; procedure SetOption(const Name, Value: string); property Options[const Name: string]: string read GetOption write SetOption; end; { Base class for handling options. } TLogOptionHandler = class(TInterfacedObject, ILogOptionHandler) private FOptions: TStringList; protected function GetOption(const Name: string): string; virtual; procedure SetOption(const Name, Value: string); virtual; public constructor Create; virtual; destructor Destroy; override; property Options[const Name: string]: string read GetOption write SetOption; procedure Init; virtual; end; { Levels ----------------------------------------------------------------------} { Levels of messages for logging. The Level property identifies increasing severity of messages. All those above or equal to a particular setting are logged. } TLogLevel = class(TObject) private FLevel: Integer; FName: string; public constructor Create(Name: string; Level: Integer); property Level: Integer read FLevel; property Name: string read FName; function IsGreaterOrEqual(LogLevel: TLogLevel): Boolean; { Retrieve a level object given its level. } class function GetLevel(LogLevel: Integer): TLogLevel; overload; { Retrieve a level object given its level, or default if not valid. } class function GetLevel(LogLevel: Integer; DefaultLevel: TLogLevel): TLogLevel; overload; { Retrieve a level object given its name. } class function GetLevel(Name: string): TLogLevel; overload; { Retrieve a level object given its name, or default if not valid. } class function GetLevel(Name: string; DefaultLevel: TLogLevel): TLogLevel; overload; end; const { Levels of logging as integer values. } OffValue = High(Integer); FatalValue = 50000; ErrorValue = 40000; WarnValue = 30000; InfoValue = 20000; DebugValue = 10000; TraceValue = 5000; AllValue = Low(Integer); var { Standard levels are automatically created (in decreasing severity): Off, Fatal, Error, Warn, Info, Debug, All. } Off: TLogLevel; Fatal: TLogLevel; Error: TLogLevel; Warn: TLogLevel; Info: TLogLevel; Debug: TLogLevel; Trace: TLogLevel; All: TLogLevel; { NDC -------------------------------------------------------------------------} type { Keep track of the nested diagnostic context (NDC). } TLogNDC = class(TObject) private class function GetNDCIndex: Integer; class function GetThreadId: string; public class procedure Clear; class procedure CloneStack(const Context: TStringList); class function GetDepth: Integer; class procedure Inherit(const Context: TStringList); class function Peek: string; class function Pop: string; class procedure Push(const Context: string); class procedure Remove; class procedure SetMaxDepth(const MaxDepth: Integer); end; { Events ----------------------------------------------------------------------} TLogLogger = class; { An event to be logged. } TLogEvent = class(TPersistent) private FError: Exception; FLevel: TLogLevel; FLogger: TLogLogger; FMessage: string; FTimeStamp: TDateTime; function GetElapsedTime: LongInt; function GetErrorClass: string; function GetErrorMessage: string; function GetLoggerName: string; function GetNDC: string; function GetThreadId: LongInt; public constructor Create(const Logger: TLogLogger; const Level: TLogLevel; const Message: string; const Err: Exception; const TimeStamp: TDateTime = 0); overload; constructor Create(const Logger: TLogLogger; const Level: TLogLevel; const Message: TObject; const Err: Exception; const TimeStamp: TDateTime = 0); overload; property ElapsedTime: LongInt read GetElapsedTime; property Error: Exception read FError; property ErrorClass: string read GetErrorClass; property ErrorMessage: string read GetErrorMessage; property Level: TLogLevel read FLevel; property LoggerName: string read GetLoggerName; property Message: string read FMessage; property NDC: string read GetNDC; property ThreadId: LongInt read GetThreadId; property TimeStamp: TDateTime read FTimeStamp; end; { Logger factory --------------------------------------------------------------} { Factory for creating loggers. } ILogLoggerFactory = interface(IUnknown) ['{AEE5E86C-B708-45B2-BEAD-B370D71CAA2F}'] function MakeNewLoggerInstance(const Name: string): TLogLogger; end; { Default implementation of a logger factory. } TLogDefaultLoggerFactory = class(TInterfacedObject, ILogLoggerFactory) public function MakeNewLoggerInstance(const Name: string): TLogLogger; end; { Loggers ---------------------------------------------------------------------} ILogAppender = interface; ILogRenderer = interface; TLogHierarchy = class; { This is the central class in the Log4D package. One of the distinctive features of Log4D is hierarchical loggers and their evaluation. } TLogLogger = class(TLogOptionHandler, ILogOptionHandler) private FAdditive: Boolean; FAppenders: TInterfaceList; FHierarchy: TLogHierarchy; FLevel: TLogLevel; FName: string; FParent: TLogLogger; protected FCriticalLogger: TRTLCriticalSection; procedure CallAppenders(const Event: TLogEvent); procedure CloseAllAppenders; function CountAppenders: Integer; procedure DoLog(const LogLevel: TLogLevel; const Message: string; const Err: Exception = nil); overload; virtual; procedure DoLog(const LogLevel: TLogLevel; const Message: TObject; const Err: Exception = nil); overload; virtual; function GetLevel: TLogLevel; virtual; public constructor Create(const Name: string); reintroduce; destructor Destroy; override; property Additive: Boolean read FAdditive write FAdditive; property Appenders: TInterfaceList read FAppenders; property Hierarchy: TLogHierarchy read FHierarchy write FHierarchy; property Level: TLogLevel read GetLevel write FLevel; property Name: string read FName; property Parent: TLogLogger read FParent; procedure AddAppender(const Appender: ILogAppender); procedure AssertLog(const Assertion: Boolean; const Message: string); overload; procedure AssertLog(const Assertion: Boolean; const Message: TObject); overload; procedure Debug(const Message: string; const Err: Exception = nil); overload; virtual; procedure Debug(const Message: TObject; const Err: Exception = nil); overload; virtual; procedure Error(const Message: string; const Err: Exception = nil); overload; virtual; procedure Error(const Message: TObject; const Err: Exception = nil); overload; virtual; procedure Fatal(const Message: string; const Err: Exception = nil); overload; virtual; procedure Fatal(const Message: TObject; const Err: Exception = nil); overload; virtual; function GetAppender(const Name: string): ILogAppender; class function GetLogger(const Clazz: TClass; const Factory: ILogLoggerFactory = nil): TLogLogger; overload; class function GetLogger(const Name: string; const Factory: ILogLoggerFactory = nil): TLogLogger; overload; class function GetRootLogger: TLogLogger; procedure Info(const Message: string; const Err: Exception = nil); overload; virtual; procedure Info(const Message: TObject; const Err: Exception = nil); overload; virtual; function IsAppender(const Appender: ILogAppender): Boolean; function IsDebugEnabled: Boolean; function IsEnabledFor(const LogLevel: TLogLevel): Boolean; function IsErrorEnabled: Boolean; function IsFatalEnabled: Boolean; function IsInfoEnabled: Boolean; function IsWarnEnabled: Boolean; function IsTraceEnabled: Boolean; procedure LockLogger; procedure Log(const LogLevel: TLogLevel; const Message: string; const Err: Exception = nil); overload; procedure Log(const LogLevel: TLogLevel; const Message: TObject; const Err: Exception = nil); overload; procedure RemoveAllAppenders; procedure RemoveAppender(const Appender: ILogAppender); overload; procedure RemoveAppender(const Name: string); overload; procedure Trace(const Message: string; const Err: Exception = nil); overload; virtual; procedure Trace(const Message: TObject; const Err: Exception = nil); overload; virtual; procedure UnlockLogger; procedure Warn(const Message: string; const Err: Exception = nil); overload; virtual; procedure Warn(const Message: TObject; const Err: Exception = nil); overload; virtual; end; { The specialised root logger - cannot have a nil level. } TLogRoot = class(TLogLogger) private procedure SetLevel(const Level: TLogLevel); public constructor Create(const Level: TLogLevel); property Level: TLogLevel read GetLevel write SetLevel; end; { Specialised logger for internal logging. } TLogLog = class(TLogLogger) private FInternalDebugging: Boolean; protected procedure DoLog(const LogLevel: TLogLevel; const Message: string; const Err: Exception); override; procedure DoLog(const LogLevel: TLogLevel; const Message: TObject; const Err: Exception); override; public constructor Create; property InternalDebugging: Boolean read FInternalDebugging write FInternalDebugging; end; { Hierarchy -------------------------------------------------------------------} { Listen to events occuring within a hierarchy. } ILogHierarchyEventListener = interface ['{A216D50F-B9A5-4871-8EE3-CB55C41E138B}'] procedure AddAppenderEvent(const Logger: TLogLogger; const Appender: ILogAppender); procedure RemoveAppenderEvent(const Logger: TLogLogger; const Appender: ILogAppender); end; { This class is specialised in retreiving loggers by name and also maintaining the logger hierarchy. The casual user should not have to deal with this class directly. The structure of the logger hierachy is maintained by the GetInstance method. The hierarchy is such that children link to their parent but parents do not have any pointers to their children. Moreover, loggers can be instantiated in any order, in particular descendant before ancestor. In case a descendant is created before a particular ancestor, then it creates an empty node for the ancestor and adds itself to it. Other descendants of the same ancestor add themselves to the previously created node. } TLogHierarchy = class(TObject) private FEmittedNoAppenderWarning: Boolean; FListeners: TInterfaceList; FLoggers: TStringList; FRenderedClasses: TClassList; FRenderers: TInterfaceList; FRoot: TLogLogger; FThreshold: TLogLevel; procedure SetThresholdProp(const Level: TLogLevel); procedure UpdateParent(const Logger: TLogLogger); protected FCriticalHierarchy: TRTLCriticalSection; public constructor Create(Root: TLogLogger); destructor Destroy; override; property Root: TLogLogger read FRoot; property Threshold: TLogLevel read FThreshold write SetThresholdProp; procedure AddHierarchyEventListener( const Listener: ILogHierarchyEventListener); procedure AddRenderer(RenderedClass: TClass; Renderer: ILogRenderer); procedure Clear; procedure EmitNoAppenderWarning(const Logger: TLogLogger); function Exists(const Name: string): TLogLogger; procedure FireAppenderEvent(const Adding: Boolean; const Logger: TLogLogger; const Appender: ILogAppender); procedure GetCurrentLoggers(const List: TStringList); function GetLogger(const Name: string; const Factory: ILogLoggerFactory = nil): TLogLogger; function GetRenderer(const RenderedClass: TClass): ILogRenderer; function IsDisabled(const LogLevel: Integer): Boolean; procedure RemoveHierarchyEventListener( const Listener: ILogHierarchyEventListener); procedure ResetConfiguration; procedure SetThreshold(const Name: string); procedure Shutdown; end; { Layouts ---------------------------------------------------------------------} { Functional requirements for a layout. } ILogLayout = interface(ILogOptionHandler) ['{87FDD680-96D7-45A0-A135-CB88ABAD5519}'] function Format(const Event: TLogEvent): string; function GetContentType: string; function GetFooter: string; function GetHeader: string; function IgnoresException: Boolean; property ContentType: string read GetContentType; property Footer: string read GetFooter; property Header: string read GetHeader; end; { Abstract base for layouts. Subclasses must at least override Format. Accepts the following options: # Format for date and time stamps, string, optional, defaults to ShortDateFormat # See FormatDateTime function for more details log4d.appender.<name>.layout.dateFormat=yyyy/mm/dd hh:nn:ss.zzz } TLogCustomLayout = class(TLogOptionHandler, ILogDynamicCreate, ILogOptionHandler, ILogLayout) private FDateFormat: string; protected property DateFormat: string read FDateFormat write FDateFormat; function GetContentType: string; virtual; function GetHeader: string; virtual; function GetFooter: string; virtual; procedure SetOption(const Name, Value: string); override; public property ContentType: string read GetContentType; property Footer: string read GetFooter; property Header: string read GetHeader; function Format(const Event: TLogEvent): string; virtual; abstract; function IgnoresException: Boolean; virtual; procedure Init; override; end; { Basic implementation of a layout. } TLogSimpleLayout = class(TLogCustomLayout) public function Format(const Event: TLogEvent): string; override; end; { This layout outputs events in a HTML table. Accepts the following options: # Title for HTML page, string, optional log4d.appender.<name>.layout.title=Logging Messages } TLogHTMLLayout = class(TLogCustomLayout) private FTitle: string; protected function GetContentType: string; override; function GetFooter: string; override; function GetHeader: string; override; procedure SetOption(const Name, Value: string); override; public property Title: string read FTitle write FTitle; function Format(const Event: TLogEvent): string; override; function IgnoresException: Boolean; override; end; { Layout based on specified pattern. Accepts the following options: # Format for rendering the log event, string, optional, defaults to %m%n # See comments of Format method for more details log4d.appender.<name>.layout.pattern=%r [%t] %p %c %x - %m%n } TLogPatternLayout = class(TLogCustomLayout) private FPattern: string; FPatternParts: TStringList; procedure SetPattern(const Pattern: string); protected procedure SetOption(const Name, Value: string); override; public constructor Create(const Pattern: string = DefaultPattern); reintroduce; destructor Destroy; override; property Pattern: string read FPattern write SetPattern; function Format(const Event: TLogEvent): string; override; procedure Init; override; end; { Renderers -------------------------------------------------------------------} { Renderers transform an object into a string message for display. } ILogRenderer = interface(ILogOptionHandler) ['{169B03C6-E2C7-4F62-AD19-17408AB30681}'] function Render(const Message: TObject): string; end; { Abstract base class for renderers - handles basic option setting. Subclasses must at least override Render. } TLogCustomRenderer = class(TLogOptionHandler, ILogDynamicCreate, ILogOptionHandler, ILogRenderer) public function Render(const Message: TObject): string; virtual; abstract; end; { ErrorHandler ----------------------------------------------------------------} { Appenders may delegate their error handling to ErrorHandlers. Error handling is a particularly tedious to get right because by definition errors are hard to predict and to reproduce. } ILogErrorHandler = interface(ILogOptionHandler) ['{B902C52A-5E4E-47A8-B291-BE8E7660F754}'] procedure SetAppender(const Appender: ILogAppender); procedure SetBackupAppender(const BackupAppender: ILogAppender); procedure SetLogger(const Logger: TLogLogger); { The appender for which errors are handled. } property Appender: ILogAppender write SetAppender; { The appender to use in case of failure. } property BackupAppender: ILogAppender write SetBackupAppender; { The logger that the failing appender might be attached to. } property Logger: TLogLogger write SetLogger; { This method prints the error message passed as a parameter. } procedure Error(const Message: string); overload; { This method should handle the error. Information about the error condition is passed a parameter. } procedure Error(const Message: string; const Err: Exception; const ErrorCode: Integer; const Event: TLogEvent = nil); overload; end; { Abstract base class for error handlers - handles basic option setting. Subclasses must at least override Error. } TLogCustomErrorHandler = class(TLogOptionHandler, ILogDynamicCreate, ILogOptionHandler, ILogErrorHandler) private FAppender: ILogAppender; FBackupAppender: ILogAppender; FLogger: TLogLogger; protected procedure SetAppender(const Appender: ILogAppender); virtual; procedure SetBackupAppender(const BackupAppender: ILogAppender); virtual; procedure SetLogger(const Logger: TLogLogger); virtual; public property Appender: ILogAppender write SetAppender; property BackupAppender: ILogAppender write SetBackupAppender; property Logger: TLogLogger write SetLogger; procedure Error(const Message: string); overload; virtual; abstract; procedure Error(const Message: string; const Err: Exception; const ErrorCode: Integer; const Event: TLogEvent = nil); overload; virtual; abstract; end; { Fallback on an alternative appender if an error arises. } TLogFallbackErrorHandler = class(TLogCustomErrorHandler) private FLoggers: TObjectList; protected procedure SetLogger(const Logger: TLogLogger); override; public constructor Create; override; destructor Destroy; override; procedure Error(const Message: string); overload; override; procedure Error(const Message: string; const Err: Exception; const ErrorCode: Integer; const Event: TLogEvent = nil); overload; override; end; { Displays only the first error sent to it to debugging output. } TLogOnlyOnceErrorHandler = class(TLogCustomErrorHandler) private FSeenError: Boolean; public procedure Error(const Message: string); overload; override; procedure Error(const Message: string; const Err: Exception; const ErrorCode: Integer; const Event: TLogEvent = nil); overload; override; end; { Filters ---------------------------------------------------------------------} TLogFilterDecision = (fdDeny, fdNeutral, fdAccept); { Filters can control to a finer degree of detail which messages get logged. } ILogFilter = interface(ILogOptionHandler) ['{B28213D7-ACE2-4C44-B820-D9437D44F8DA}'] function Decide(const Event: TLogEvent): TLogFilterDecision; end; { Abstract base class for filters - handles basic option setting. Subclasses must at least override Decide. Accepts the following options: # Class identification log4d.appender.<name>.filter1=TLogCustomFilter # Accept or reject the log event when deciding, Boolean, optional, default true log4d.appender.<name>.filter1.acceptOnMatch=true } TLogCustomFilter = class(TLogOptionHandler, ILogDynamicCreate, ILogOptionHandler, ILogFilter) private FAcceptOnMatch: Boolean; protected property AcceptOnMatch: Boolean read FAcceptOnMatch write FAcceptOnMatch; procedure SetOption(const Name, Value: string); override; public constructor Create(const AcceptOnMatch: Boolean = True); reintroduce; function Decide(const Event: TLogEvent): TLogFilterDecision; virtual; abstract; end; { Deny all messages. } TLogDenyAllFilter = class(TLogCustomFilter) public property AcceptOnMatch; function Decide(const Event: TLogEvent): TLogFilterDecision; override; end; { Filter by the message's level. Accepts the following options (as well as the standard acceptOnMatch one): # Class identification log4d.appender.<name>.filter1=TLogLevelMatchFilter # Logging level to match on, Level, mandatory log4d.appender.<name>.filter1.match=warn } TLogLevelMatchFilter = class(TLogCustomFilter) private FMatchLevel: TLogLevel; protected procedure SetOption(const Name, Value: string); override; public constructor Create(const MatchLevel: TLogLevel; const AcceptOnMatch: Boolean = True); reintroduce; property AcceptOnMatch; property MatchLevel: TLogLevel read FMatchLevel write FMatchLevel; function Decide(const Event: TLogEvent): TLogFilterDecision; override; end; { Filter by the message's level being within a range. Accepts the following options (as well as the standard acceptOnMatch one): # Class identification log4d.appender.<name>.filter1=TLogLevelRangeFilter # Minimum logging level to match on, Level, mandatory log4d.appender.<name>.filter1.minimum=warn # Maximum logging level to match on, Level, mandatory log4d.appender.<name>.filter1.maximum=error } TLogLevelRangeFilter = class(TLogCustomFilter) private FMaxLevel: TLogLevel; FMinLevel: TLogLevel; protected procedure SetOption(const Name, Value: string); override; public constructor Create(const MaxLevel, MinLevel: TLogLevel; const AcceptOnMatch: Boolean = True); reintroduce; property AcceptOnMatch; property MaxLevel: TLogLevel read FMaxLevel write FMaxLevel; property MinLevel: TLogLevel read FMinLevel write FMinLevel; function Decide(const Event: TLogEvent): TLogFilterDecision; override; end; { Filter by text within the message. Accepts the following options (as well as the standard acceptOnMatch one): # Class identification log4d.appender.<name>.filter1=TLogStringFilter # Text to match on anywhere in message, string, mandatory log4d.appender.<name>.filter1.match=xyz # Whether match is case-sensitive, Boolean, optional, defaults to false log4d.appender.<name>.filter1.ignoreCase=true } TLogStringFilter = class(TLogCustomFilter) private FIgnoreCase: Boolean; FMatch: string; protected procedure SetOption(const Name, Value: string); override; public constructor Create(const Match: string; const IgnoreCase: Boolean = False; const AcceptOnMatch: Boolean = True); reintroduce; property AcceptOnMatch; property IgnoreCase: Boolean read FIgnoreCase write FIgnoreCase; property Match: string read FMatch write FMatch; function Decide(const Event: TLogEvent): TLogFilterDecision; override; end; { Appenders -------------------------------------------------------------------} { Implement this interface for your own strategies for printing log statements. } ILogAppender = interface(ILogOptionHandler) ['{E1A06EA7-34CA-4DA4-9A8A-C76CF34257AC}'] procedure AddFilter(const Filter: ILogFilter); procedure Append(const Event: TLogEvent); procedure Close; function GetErrorHandler: ILogErrorHandler; function GetFilters: TInterfaceList; function GetLayout: ILogLayout; function GetName: string; procedure RemoveAllFilters; procedure RemoveFilter(const Filter: ILogFilter); function RequiresLayout: Boolean; procedure SetErrorHandler(const ErrorHandler: ILogErrorHandler); procedure SetLayout(const Layout: ILogLayout); procedure SetName(const Name: string); property ErrorHandler: ILogErrorHandler read GetErrorHandler write SetErrorHandler; property Filters: TInterfaceList read GetFilters; property Layout: ILogLayout read GetLayout write SetLayout; property Name: string read GetName write SetName; end; { Basic implementation of an appender for printing log statements. Subclasses should at least override DoAppend(string). } TLogCustomAppender = class(TLogOptionHandler, ILogDynamicCreate, ILogOptionHandler, ILogAppender) private FClosed: Boolean; FErrorHandler: ILogErrorHandler; FFilters: TInterfaceList; FLayout: ILogLayout; FName: string; FThreshold : TLogLevel; {$IFDEF UNICODE} FEncoding: TEncoding; {$ENDIF UNICODE} protected FCriticalAppender: TRTLCriticalSection; function GetErrorHandler: ILogErrorHandler; function GetFilters: TInterfaceList; function GetLayout: ILogLayout; function GetName: string; {$IFDEF UNICODE} function GetEncoding: TEncoding; procedure SetEncoding(const Value: TEncoding); {$ENDIF UNICODE} procedure SetErrorHandler(const ErrorHandler: ILogErrorHandler); procedure SetLayout(const Layout: ILogLayout); procedure SetName(const Name: string); function CheckEntryConditions: Boolean; virtual; function CheckFilters(const Event: TLogEvent): Boolean; virtual; procedure DoAppend(const Event: TLogEvent); overload; virtual; procedure DoAppend(const Message: string); overload; virtual; abstract; procedure WriteFooter; virtual; procedure WriteHeader; virtual; procedure SetOption(const Name, Value: string); override; function isAsSevereAsThreshold(level : TLogLevel) : boolean; public constructor Create(const Name: string; const Layout: ILogLayout = nil); reintroduce; virtual; destructor Destroy; override; property ErrorHandler: ILogErrorHandler read GetErrorHandler write SetErrorHandler; property Filters: TInterfaceList read GetFilters; property Layout: ILogLayout read GetLayout write SetLayout; property Name: string read GetName write SetName; procedure AddFilter(const Filter: ILogFilter); virtual; procedure Append(const Event: TLogEvent); virtual; procedure Close; virtual; procedure Init; override; procedure RemoveAllFilters; virtual; procedure RemoveFilter(const Filter: ILogFilter); virtual; function RequiresLayout: Boolean; virtual; {$IFDEF UNICODE} property Encoding: TEncoding read GetEncoding write SetEncoding; {$ENDIF UNICODE} end; { Discard log messages. } TLogNullAppender = class(TLogCustomAppender) protected procedure DoAppend(const Message: string); override; end; { Send log messages to debugging output. } TLogODSAppender = class(TLogCustomAppender) protected procedure DoAppend(const Message: string); override; end; { Send log messages to a stream. } TLogStreamAppender = class(TLogCustomAppender) private FStream: TStream; protected procedure DoAppend(const Message: string); override; public constructor Create(const Name: string; const Stream: TStream; const Layout: ILogLayout = nil); reintroduce; virtual; destructor Destroy; override; end; { Send log messages to a file. Accepts the following options: # Class identification log4d.appender.<name>=TLogFileAppender # Name of the file to write to, string, mandatory log4d.appender.<name>.fileName=C:\Logs\App.log # Whether to append to file, Boolean, optional, defaults to true log4d.appender.<name>.append=false } TLogFileAppender = class(TLogStreamAppender) private FAppend: Boolean; FFileName: TFileName; protected procedure SetOption(const Name, Value: string); override; procedure SetLogFile(const Name: string); virtual; procedure CloseLogFile; virtual; public constructor Create(const Name, FileName: string; const Layout: ILogLayout = nil; const Append: Boolean = True); reintroduce; virtual; property FileName: TFileName read FFileName; property OpenAppend: Boolean read FAppend; end; { Implement this interface for your own strategies for printing log statements. } ILogRollingFileAppender = interface(ILogAppender) ['{49981B61-840B-440F-A444-BF11A91D1876}'] procedure RollOver; end; { Send log messages to a file which uses logfile rotation Accepts the following options: # Class identification log4d.appender.<name>=TLogRollingFileAppender # Name of the file to write to, string, mandatory log4d.appender.<name>.fileName=C:\Logs\App.log # Whether to append to file, Boolean, optional, defaults to true log4d.appender.<name>.append=false # Max. file size accepts suffix "KB", "MB" and "GB", optional, default 10MB log4d.appender.<name>.maxFileSize=10MB # Max number of backup files, optional, default is 1 log4d.appender.<name>.maxBackupIndex=3 } TLogRollingFileAppender = class(TLogFileAppender, ILogRollingFileAppender) private FMaxFileSize : integer; FMaxBackupIndex : integer; FCurrentSize : integer; protected procedure SetOption(const Name, Value: string); override; procedure DoAppend(const msg: string); override; public procedure Init; override; procedure RollOver; virtual; // just in case someone wants to override it... property MaxFileSize : integer read FMaxFileSize; property MaxBackupIndex : integer read FMaxBackupIndex; end; { Configurators ---------------------------------------------------------------} { Use this class to quickly configure the package. } TLogBasicConfigurator = class(TObject) private FRegistry: TStringList; FLoggerFactory: ILogLoggerFactory; protected { Used by subclasses to add a renderer to the hierarchy passed as parameter. } procedure AddRenderer(const Hierarchy: TLogHierarchy; const RenderedName, RendererName: string); function AppenderGet(const Name: string): ILogAppender; procedure AppenderPut(const Appender: ILogAppender); procedure SetGlobalProps(const Hierarchy: TLogHierarchy; const FactoryClassName, Debug, Threshold: string); public constructor Create; destructor Destroy; override; { Add appender to the root logger. If no appender is provided, add a TLogODSAppender that uses TLogPatternLayout with the TTCCPattern and prints to debugging output for the root logger. } class procedure Configure(const Appender: ILogAppender = nil); { Reset the default hierarchy to its default. It is equivalent to calling Logger.GetDefaultHierarchy.ResetConfiguration. See TLogHierarchy.ResetConfiguration for more details. } class procedure ResetConfiguration; end; { Extends BasicConfigurator to provide configuration from an external file. See DoConfigure for the expected format. It is sometimes useful to see how Log4D is reading configuration files. You can enable Log4D internal logging by defining the log4d.debug variable. } TLogPropertyConfigurator = class(TLogBasicConfigurator) protected procedure ConfigureRootLogger(const Props: TStringList; const Hierarchy: TLogHierarchy); procedure ParseAdditivityForLogger(const Props: TStringList; const Logger: TLogLogger); function ParseAppender(const Props: TStringList; const AppenderName: string): ILogAppender; procedure ParseLoggersAndRenderers(const Props: TStringList; const Hierarchy: TLogHierarchy); procedure ParseLogger(const Props: TStringList; const Logger: TLogLogger; const Value: string); public class procedure Configure(const Filename: string); overload; class procedure Configure(const Props: TStringList); overload; procedure DoConfigure(const FileName: string; const Hierarchy: TLogHierarchy); overload; procedure DoConfigure(const Props: TStringList; const Hierarchy: TLogHierarchy); overload; end; { Register a new appender class. } procedure RegisterAppender(const Appender: TClass); { Find an appender based on its class name and create a new instance of it. } function FindAppender(const ClassName: string): ILogAppender; { Register a new logger factory class. } procedure RegisterLoggerFactory(const LoggerFactory: TClass); { Find a logger factory based on its class name and create a new instance of it. } function FindLoggerFactory(const ClassName: string): ILogLoggerFactory; { Register a new error handler class. } procedure RegisterErrorHandler(const ErrorHandler: TClass); { Find an error handler based on its class name and create a new instance of it. } function FindErrorHandler(const ClassName: string): ILogErrorHandler; { Register a new filter class. } procedure RegisterFilter(const Filter: TClass); { Find a filter based on its class name and create a new instance of it. } function FindFilter(const ClassName: string): ILogFilter; { Register a new layout class. } procedure RegisterLayout(const Layout: TClass); { Find a layout based on its class name and create a new instance of it. } function FindLayout(const ClassName: string): ILogLayout; { Register a new class that can be rendered. } procedure RegisterRendered(const Rendered: TClass); { Find a rendered class based on its class name and return its class. } function FindRendered(const ClassName: string): TClass; { Register a new object renderer class. } procedure RegisterRenderer(const Renderer: TClass); { Find an object renderer based on its class name and create a new instance of it. } function FindRenderer(const ClassName: string): ILogRenderer; { Convert string value to a Boolean, with default. } function StrToBool(Value: string; const Default: Boolean): Boolean; {$IFDEF UNICODE} { Convert string encoding value to a default TEncoding. } function FindEncodingFromName(const Name: string): TEncoding; {$ENDIF UNICODE} {$IFDEF LINUX} procedure EnterCriticalSection(var CS: TCriticalSection); procedure LeaveCriticalSection(var CS: TCriticalSection); procedure InitializeCriticalSection(var CS: TCriticalSection); procedure DeleteCriticalSection(var CS: TCriticalSection); function GetCurrentThreadID: Integer; procedure OutputDebugString(const S: PChar); {$ENDIF} var { Default implementation of ILogLoggerFactory } DefaultLoggerFactory: TLogDefaultLoggerFactory; { The logging hierarchy } DefaultHierarchy: TLogHierarchy; { Internal package logging. } LogLog: TLogLog; implementation {$IFDEF UNICODE} uses {$IFDEF VER210} Consts; {$ELSE} Vcl.Consts; {$ENDIF} {$ENDIF UNICODE} const CRLF = #13#10; MilliSecsPerDay = 24 * 60 * 60 * 1000; resourcestring AddingLoggerMsg = 'Adding logger "%s" in error handler'; AppenderDefinedMsg = 'Appender "%s" was already parsed'; BadConfigFileMsg = 'Couldn''t read configuration file "%s" - %s'; ClosedAppenderMsg = 'Not allowed to write to a closed appender'; ConvertErrorMsg = 'Could not convert "%s" to level'; EndAppenderMsg = 'Parsed "%s" options'; EndErrorHandlerMsg = 'End of parsing for "%s" error handler'; EndFiltersMsg = 'End of parsing for "%s" filter'; EndLayoutMsg = 'End of parsing for "%s" layout'; FallbackMsg = 'Fallback on error %s'; FallbackReplaceMsg = 'Fallback replacing "%s" with "%s" in logger "%s"'; FinishedConfigMsg = 'Finished configuring with %s'; HandlingAdditivityMsg = 'Handling %s="%s"'; IgnoreConfigMsg = 'Ignoring configuration file "%s"'; InterfaceNotImplMsg = '%s doesn''t implement %s'; LayoutRequiredMsg = 'Appender "%s" requires a layout'; LevelHdr = 'Level'; LevelTokenMsg = 'Level token is "%s"'; LoggerFactoryMsg = 'Setting logger factory to "%s"'; LoggerHdr = 'Logger'; MessageHdr = 'Message'; NDCHdr = 'NDC'; NilErrorHandlerMsg = 'An appender cannot have a nil error handler'; NilLevelMsg = 'The root can''t have a nil level'; NoAppendersMsg = 'No appenders could be found for logger "%s"'; NoAppenderCreatedMsg = 'Couldn''t create appender named "%s"'; NoClassMsg = 'Couldn''t find class %s'; NoLayoutMsg = 'No layout set for appender named "%s"'; NoRenderedCreatedMsg = 'Couldn''t find rendered class "%s"'; NoRendererMsg = 'No renderer found for class %s'; NoRendererCreatedMsg = 'Couldn''t create renderer "%s"'; NoRootLoggerMsg = 'Couldn''t find root logger information. Is this OK?'; ParsingAppenderMsg = 'Parsing appender named "%s"'; ParsingLoggerMsg = 'Parsing for logger "%s" with value="%s"'; ParsingErrorHandlerMsg = 'Parsing error handler options for "%s"'; ParsingFiltersMsg = 'Parsing filter options for "%s"'; ParsingLayoutMsg = 'Parsing layout options for "%s"'; PleaseInitMsg = 'Please initialise the Log4D system properly'; RendererMsg = 'Rendering class: "%s", Rendered class: "%s"'; SessionStartMsg = 'Log session start time'; SettingAdditivityMsg = 'Setting additivity for "%s" to "%s"'; SettingAppenderMsg = 'Setting appender "%s" in error handler'; SettingBackupMsg = 'Setting backup appender "%s" in error handler'; SettingLevelMsg = 'Logger "%s" set to level "%s"'; SettingLoggerMsg = 'Setting logger "%s" in error handler'; ThreadHdr = 'Thread'; TimeHdr = 'Time'; ValueUnknownMsg = 'Unknown'; var { Start time for the logging process - to compute elapsed time. } StartTime: TDateTime; { TLogOptionHandler -----------------------------------------------------------} constructor TLogOptionHandler.Create; begin inherited Create; Init; end; destructor TLogOptionHandler.Destroy; begin FOptions.Free; inherited Destroy; end; { Just return the saved option value. } function TLogOptionHandler.GetOption(const Name: string): string; begin Result := FOptions.Values[Name]; end; procedure TLogOptionHandler.Init; begin FOptions := TStringList.Create; end; { Just save the option value. } procedure TLogOptionHandler.SetOption(const Name, Value: string); begin FOptions.Values[Name] := Value; end; { TLogLevel -------------------------------------------------------------------} var Levels: TObjectList; { Accumulate a list (in descending order) of TLogLevel objects defined. } procedure RegisterLevel(Level: TLogLevel); var Index: Integer; begin if Levels.IndexOf(Level) > -1 then Exit; for Index := 0 to Levels.Count - 1 do if TLogLevel(Levels[Index]).Level < Level.Level then begin Levels.Insert(Index, Level); Exit; end else if TLogLevel(Levels[Index]).Level = Level.Level then begin {$IFDEF DELPHI4} TObject(Levels[Index]).Free; {$ELSE} Levels[Index].Free; {$ENDIF} Levels[Index] := Level; Exit; end; Levels.Add(Level); end; constructor TLogLevel.Create(Name: string; Level: Integer); begin inherited Create; FName := Name; FLevel := Level; RegisterLevel(Self); end; { Retrieve a level object given its level. } class function TLogLevel.GetLevel(LogLevel: Integer): TLogLevel; begin Result := GetLevel(LogLevel, Debug); end; { Retrieve a level object given its level, or default if not valid. } class function TLogLevel.GetLevel(LogLevel: Integer; DefaultLevel: TLogLevel): TLogLevel; var Index: Integer; begin Result := DefaultLevel; for Index := 0 to Levels.Count - 1 do if TLogLevel(Levels[Index]).Level = LogLevel then begin Result := TLogLevel(Levels[Index]); Break; end else if TLogLevel(Levels[Index]).Level < LogLevel then Break; end; { Retrieve a level object given its name. } class function TLogLevel.GetLevel(Name: string): TLogLevel; begin Result := GetLevel(Name, Debug); end; { Retrieve a level object given its name, or default if not valid. } class function TLogLevel.GetLevel(Name: string; DefaultLevel: TLogLevel): TLogLevel; var Index: Integer; begin Result := DefaultLevel; for Index := 0 to Levels.Count - 1 do if TLogLevel(Levels[Index]).Name = Name then begin Result := TLogLevel(Levels[Index]); Exit; end; end; { Returns True if this level has a higher or equal value than the level passed as argument, False otherwise. } function TLogLevel.IsGreaterOrEqual(LogLevel: TLogLevel): Boolean; begin Result := (Self.Level >= LogLevel.Level); end; { TLogNDC ---------------------------------------------------------------------} var { The nested diagnostic contexts (NDCs). This list has one entry for each thread. For each entry, the attached object is another string list containing the actual context strings. } NDC: TStringList; { The controller for synchronisation } CriticalNDC: TRTLCriticalSection; { Empty out the current NDC stack. } class procedure TLogNDC.Clear; var Index: Integer; begin EnterCriticalSection(CriticalNDC); try Index := GetNDCIndex; if Index > -1 then TStringList(NDC.Objects[Index]).Clear; finally LeaveCriticalSection(CriticalNDC); end; end; { Return a copy of the current NDC. } class procedure TLogNDC.CloneStack(const Context: TStringList); var Index: Integer; begin EnterCriticalSection(CriticalNDC); try Index := GetNDCIndex; if Index > -1 then Context.Assign(TStringList(NDC.Objects[Index])) else Context.Clear; finally LeaveCriticalSection(CriticalNDC); end; end; { Retrieve the depth for the current NDC. } class function TLogNDC.GetDepth: Integer; var Index: Integer; begin EnterCriticalSection(CriticalNDC); try Result := 0; Index := GetNDCIndex; if Index > -1 then Result := TStringList(NDC.Objects[Index]).Count; finally LeaveCriticalSection(CriticalNDC); end; end; { Find the index in the NDCs for the current thread. } class function TLogNDC.GetNDCIndex: Integer; begin Result := NDC.IndexOf(GetThreadId); end; { Return the current thread id as a string. } class function TLogNDC.GetThreadId: string; begin Result := IntToStr(GetCurrentThreadId); end; { Use the provided context for this NDC. } class procedure TLogNDC.Inherit(const Context: TStringList); var Index: Integer; begin if Context = nil then Exit; EnterCriticalSection(CriticalNDC); try Index := GetNDCIndex; if Index = -1 then Index := NDC.AddObject(GetThreadId, TStringList.Create); TStringList(NDC.Objects[Index]).Assign(Context) finally LeaveCriticalSection(CriticalNDC); end; end; { Retrieve the current NDC for display. } class function TLogNDC.Peek: string; var Index, Index2: Integer; begin EnterCriticalSection(CriticalNDC); try Result := ''; Index := GetNDCIndex; if Index = -1 then Exit; with TStringList(NDC.Objects[Index]) do for Index2 := 0 to Count - 1 do Result := Result + '|' + Strings[Index2]; Delete(Result, 1, 1); finally LeaveCriticalSection(CriticalNDC); end; end; { Remove the last context string added to the stack and return its value. } class function TLogNDC.Pop: string; var Index, Index2: Integer; begin EnterCriticalSection(CriticalNDC); try Result := ''; Index := GetNDCIndex; if Index = -1 then Exit; with TStringList(NDC.Objects[Index]) do begin for Index2 := 0 to Count - 1 do Result := Result + '|' + Strings[Index2]; if Count <= 1 then TLogNDC.Clear else if Count > 0 then Delete(Count - 1); end; finally LeaveCriticalSection(CriticalNDC); end; end; { Add a new context string to the stack. } class procedure TLogNDC.Push(const Context: string); var Index: Integer; begin EnterCriticalSection(CriticalNDC); try Index := GetNDCIndex; if Index = -1 then Index := NDC.AddObject(GetThreadId, TStringList.Create); with TStringList(NDC.Objects[Index]) do Add(Context); finally LeaveCriticalSection(CriticalNDC) end; end; { Remove the current NDC. } class procedure TLogNDC.Remove; var Index: Integer; begin EnterCriticalSection(CriticalNDC); try Index := GetNDCIndex; if Index > -1 then begin NDC.Objects[Index].Free; NDC.Delete(Index); end; finally LeaveCriticalSection(CriticalNDC); end; end; { Trim the current NDC back to a certain depth. } class procedure TLogNDC.SetMaxDepth(const MaxDepth: Integer); var Index: Integer; begin EnterCriticalSection(CriticalNDC); try Index := GetNDCIndex; if Index > -1 then with TStringList(NDC.Objects[Index]) do while Count > MaxDepth do Delete(Count - 1); finally LeaveCriticalSection(CriticalNDC); end; end; { TLogEvent -------------------------------------------------------------------} constructor TLogEvent.Create(const Logger: TLogLogger; const Level: TLogLevel; const Message: string; const Err: Exception; const TimeStamp: TDateTime); begin inherited Create; FLogger := Logger; FLevel := Level; FMessage := Message; FError := Err; if TimeStamp = 0 then FTimeStamp := Now else FTimeStamp := TimeStamp; end; { Immediately render an object into a text message. } constructor TLogEvent.Create(const Logger: TLogLogger; const Level: TLogLevel; const Message: TObject; const Err: Exception; const TimeStamp: TDateTime); var Renderer: ILogRenderer; begin Renderer := Logger.Hierarchy.GetRenderer(Message.ClassType); if Renderer = nil then begin LogLog.Error(Format(NoRendererMsg, [Message.ClassName])); Abort; end else Create(Logger, Level, Renderer.Render(Message), Err, Timestamp); end; { The elapsed time since package start up (in milliseconds). } function TLogEvent.GetElapsedTime: LongInt; begin Result := Round((TimeStamp - StartTime) * MilliSecsPerDay); end; { Return the embedded exception's class name (if there is one). } function TLogEvent.GetErrorClass: string; begin if Error <> nil then Result := Error.ClassName else Result := ''; end; { Return the embedded exception's message and classname (if there is one). } function TLogEvent.GetErrorMessage: string; begin if Error <> nil then Result := Error.Message + ' (' + Error.ClassName + ')' else Result := ''; end; { Return the name of the logger. } function TLogEvent.GetLoggerName: string; begin Result := FLogger.Name; end; { Return the nested diagnostic context. } function TLogEvent.GetNDC: string; begin Result := TLogNDC.Peek; end; { Return the current thread ID. } function TLogEvent.GetThreadId: LongInt; begin Result := GetCurrentThreadId; end; { TLogDefaultLoggerFactory ----------------------------------------------------} function TLogDefaultLoggerFactory.MakeNewLoggerInstance(const Name: string): TLogLogger; begin Result := TLogLogger.Create(Name); end; { TLogLogger ------------------------------------------------------------------} constructor TLogLogger.Create(const Name: string); begin inherited Create; InitializeCriticalSection(FCriticalLogger); FAdditive := True; FAppenders := TInterfaceList.Create; FName := Name; end; destructor TLogLogger.Destroy; begin FAppenders.Free; DeleteCriticalSection(FCriticalLogger); inherited Destroy; end; procedure TLogLogger.AddAppender(const Appender: ILogAppender); begin LockLogger; try if FAppenders.IndexOf(Appender) = -1 then begin FAppenders.Add(Appender); if FHierarchy <> nil then FHierarchy.FireAppenderEvent(True, Self, Appender); end; finally UnlockLogger; end; end; { Log a message if the assertion is false. } procedure TLogLogger.AssertLog(const Assertion: Boolean; const Message: string); begin if not Assertion then DoLog(Log4D.Error, Message); end; { Log a message if the assertion is false. } procedure TLogLogger.AssertLog(const Assertion: Boolean; const Message: TObject); begin if not Assertion then DoLog(Log4D.Error, Message); end; { Send event to each appender to be logged. If additive, also send to parent's appenders. } procedure TLogLogger.CallAppenders(const Event: TLogEvent); var Index: Integer; begin LockLogger; try if CountAppenders = 0 then begin LogLog.Error(Format(NoAppendersMsg, [Name])); LogLog.Error(PleaseInitMsg); Exit; end; for Index := 0 to FAppenders.Count - 1 do ILogAppender(FAppenders[Index]).Append(Event); if Additive and (Parent <> nil) then Parent.CallAppenders(Event); finally UnlockLogger; end; end; procedure TLogLogger.CloseAllAppenders; var Index: Integer; begin LockLogger; try for Index := 0 to FAppenders.Count - 1 do ILogAppender(FAppenders[Index]).Close; finally UnlockLogger; end; end; { Include parent's appenders in the count (if additive). } function TLogLogger.CountAppenders: Integer; begin Result := FAppenders.Count; if Additive and (Parent <> nil) then Result := Result + Parent.CountAppenders; end; procedure TLogLogger.Debug(const Message: string; const Err: Exception); begin Log(Log4D.Debug, Message, Err); end; procedure TLogLogger.Debug(const Message: TObject; const Err: Exception); begin Log(Log4D.Debug, Message, Err); end; { Create the logging event object and send it to the appenders. } procedure TLogLogger.DoLog(const LogLevel: TLogLevel; const Message: string; const Err: Exception); var Event: TLogEvent; begin Event := TLogEvent.Create(Self, LogLevel, Message, Err); try CallAppenders(Event); finally Event.Free; end; end; procedure TLogLogger.DoLog(const LogLevel: TLogLevel; const Message: TObject; const Err: Exception); var Event: TLogEvent; begin Event := TLogEvent.Create(Self, LogLevel, Message, Err); try CallAppenders(Event); finally Event.Free; end; end; procedure TLogLogger.Error(const Message: string; const Err: Exception); begin Log(Log4D.Error, Message, Err); end; procedure TLogLogger.Error(const Message: TObject; const Err: Exception); begin Log(Log4D.Error, Message, Err); end; procedure TLogLogger.Fatal(const Message: string; const Err: Exception); begin Log(Log4D.Fatal, Message, Err); end; procedure TLogLogger.Fatal(const Message: TObject; const Err: Exception); begin Log(Log4D.Fatal, Message, Err); end; { Find an appender by name. } function TLogLogger.GetAppender(const Name: string): ILogAppender; var Index: Integer; begin Result := nil; LockLogger; try for Index := 0 to FAppenders.Count - 1 do if ILogAppender(FAppenders[Index]).Name = Name then begin Result := ILogAppender(FAppenders[Index]); Exit; end; finally UnlockLogger; end; end; { Create new loggers via the logger class. } class function TLogLogger.GetLogger(const Clazz: TClass; const Factory: ILogLoggerFactory): TLogLogger; begin Result := GetLogger(Clazz.ClassName, Factory); end; { Create new loggers via the logger class. } class function TLogLogger.GetLogger(const Name: string; const Factory: ILogLoggerFactory): TLogLogger; begin Result := DefaultHierarchy.GetLogger(Name, Factory); end; { Retrieve the root logger. } class function TLogLogger.GetRootLogger: TLogLogger; begin Result := DefaultHierarchy.Root; end; { Return parent's level if not set in this logger. } function TLogLogger.GetLevel: TLogLevel; begin if FLevel <> nil then Result := FLevel else Result := Parent.Level; end; procedure TLogLogger.Info(const Message: string; const Err: Exception); begin Log(Log4D.Info, Message, Err); end; procedure TLogLogger.Info(const Message: TObject; const Err: Exception); begin Log(Log4D.Info, Message, Err); end; { Is a given appender in use. } function TLogLogger.IsAppender(const Appender: ILogAppender): Boolean; begin Result := (FAppenders.IndexOf(Appender) > -1); end; function TLogLogger.IsDebugEnabled: Boolean; begin Result := IsEnabledFor(Log4D.Debug); end; { Hierarchy can disable logging at a global level. } function TLogLogger.IsEnabledFor(const LogLevel: TLogLevel): Boolean; begin Result := not Hierarchy.IsDisabled(LogLevel.Level) and LogLevel.IsGreaterOrEqual(Level); end; function TLogLogger.IsErrorEnabled: Boolean; begin Result := IsEnabledFor(Log4D.Error); end; function TLogLogger.IsFatalEnabled: Boolean; begin Result := IsEnabledFor(Log4D.Fatal); end; function TLogLogger.IsInfoEnabled: Boolean; begin Result := IsEnabledFor(Log4D.Info); end; function TLogLogger.IsTraceEnabled: Boolean; begin Result := IsEnabledFor(Log4D.Trace); end; function TLogLogger.IsWarnEnabled: Boolean; begin Result := IsEnabledFor(Log4D.Warn); end; { Synchronise access to the logger. } procedure TLogLogger.LockLogger; begin EnterCriticalSection(FCriticalLogger); end; { Hierarchy can disable logging at a global level. } procedure TLogLogger.Log(const LogLevel: TLogLevel; const Message: string; const Err: Exception); begin if IsEnabledFor(LogLevel) then DoLog(LogLevel, Message, Err); end; procedure TLogLogger.Log(const LogLevel: TLogLevel; const Message: TObject; const Err: Exception); begin if IsEnabledFor(LogLevel) then DoLog(LogLevel, Message, Err); end; procedure TLogLogger.RemoveAllAppenders; begin LockLogger; try FAppenders.Clear; finally UnlockLogger; end; end; procedure TLogLogger.RemoveAppender(const Appender: ILogAppender); begin LockLogger; try FAppenders.Remove(Appender); if FHierarchy <> nil then FHierarchy.FireAppenderEvent(False, Self, Appender); finally UnlockLogger; end; end; procedure TLogLogger.RemoveAppender(const Name: string); var Appender: ILogAppender; begin LockLogger; try Appender := GetAppender(Name); if Appender <> nil then FAppenders.Remove(Appender); finally UnlockLogger; end; end; procedure TLogLogger.Trace(const Message: string; const Err: Exception); begin Log(Log4D.Trace, Message, Err); end; procedure TLogLogger.Trace(const Message: TObject; const Err: Exception); begin Log(Log4D.Trace, Message, Err); end; { Release synchronised access to the logger. } procedure TLogLogger.UnlockLogger; begin LeaveCriticalSection(FCriticalLogger); end; procedure TLogLogger.Warn(const Message: string; const Err: Exception); begin Log(Log4D.Warn, Message, Err); end; procedure TLogLogger.Warn(const Message: TObject; const Err: Exception); begin Log(Log4D.Warn, Message, Err); end; { TLogRoot --------------------------------------------------------------------} const InternalRootName = 'root'; constructor TLogRoot.Create(const Level: TLogLevel); begin inherited Create(InternalRootName); Self.Level := Level; end; { Root logger cannot have a nil level. } procedure TLogRoot.SetLevel(const Level: TLogLevel); begin if Level = nil then begin LogLog.Error(NilLevelMsg); inherited Level := Log4D.Debug; end else inherited Level := Level; end; { TLogLog ---------------------------------------------------------------------} { Initialise internal logging - send it to debugging output. } constructor TLogLog.Create; begin inherited Create(''); AddAppender(TLogODSAppender.Create('')); InternalDebugging := False; Level := Log4D.Debug; end; { Only log internal debugging messages when requested. } procedure TLogLog.DoLog(const LogLevel: TLogLevel; const Message: string; const Err: Exception); begin if (LogLevel <> Log4D.Debug) or InternalDebugging then inherited DoLog(LogLevel, Message, Err); end; procedure TLogLog.DoLog(const LogLevel: TLogLevel; const Message: TObject; const Err: Exception); begin if (LogLevel <> Log4D.Debug) or InternalDebugging then inherited DoLog(LogLevel, Message, Err); end; { TLogHierarchy ---------------------------------------------------------------} constructor TLogHierarchy.Create(Root: TLogLogger); begin inherited Create; InitializeCriticalSection(FCriticalHierarchy); FEmittedNoAppenderWarning := False; FListeners := TInterfaceList.Create; FLoggers := TStringList.Create; FRenderedClasses := TClassList.Create; FRenderers := TInterfaceList.Create; FRoot := Root; FRoot.Hierarchy := Self; FThreshold := All; end; destructor TLogHierarchy.Destroy; begin Shutdown; Clear; FListeners.Free; FLoggers.Free; if TLogLogger(FRoot).RefCount > 0 then TLogLogger(FRoot)._Release else FRoot.Free; FRenderedClasses.Free; FRenderers.Free; DeleteCriticalSection(FCriticalHierarchy); inherited Destroy; end; { Add a new listener for hierarchy events. } procedure TLogHierarchy.AddHierarchyEventListener( const Listener: ILogHierarchyEventListener); begin if FListeners.IndexOf(Listener) = -1 then FListeners.Add(Listener); end; { Add an object renderer for a specific class. } procedure TLogHierarchy.AddRenderer(RenderedClass: TClass; Renderer: ILogRenderer); var Index: Integer; begin Index := FRenderedClasses.IndexOf(RenderedClass); if Index = -1 then begin FRenderedClasses.Add(RenderedClass); FRenderers.Add(Renderer); end else FRenderers[Index] := Renderer; end; { This call will clear all logger definitions from the internal hashtable. Invoking this method will irrevocably mess up the logger hierarchy. You should really know what you are doing before invoking this method. } procedure TLogHierarchy.Clear; var Index: Integer; begin for Index := 0 to FLoggers.Count - 1 do if TLogLogger(FLoggers.Objects[Index]).RefCount > 0 then TLogLogger(FLoggers.Objects[Index])._Release else FLoggers.Objects[Index].Free; FLoggers.Clear; end; { Warn the user about no appenders for a logger, but only once. } procedure TLogHierarchy.EmitNoAppenderWarning(const Logger: TLogLogger); begin if not FEmittedNoAppenderWarning then begin LogLog.Warn(Format(NoAppendersMsg, [Logger.Name])); LogLog.Warn(PleaseInitMsg); FEmittedNoAppenderWarning := True; end; end; { Check if the named logger exists in the hirarchy. If so return its reference, otherwise return nil. } function TLogHierarchy.Exists(const Name: string): TLogLogger; var Index: Integer; begin Index := FLoggers.IndexOf(Name); if Index > -1 then Result := TLogLogger(FLoggers.Objects[Index]) else Result := nil; end; { Notify registered listeners of an event. } procedure TLogHierarchy.FireAppenderEvent(const Adding: Boolean; const Logger: TLogLogger; const Appender: ILogAppender); var Index: Integer; begin for Index := 0 to FListeners.Count - 1 do with ILogHierarchyEventListener(FListeners[Index]) do if Adding then AddAppenderEvent(Logger, Appender) else RemoveAppenderEvent(Logger, Appender); end; { Returns all the currently defined loggers in this hierarchy as a string list (excluding the root logger). } procedure TLogHierarchy.GetCurrentLoggers(const List: TStringList); var Index: Integer; begin for Index := 0 to FLoggers.Count - 1 do List.Add(FLoggers[Index]); end; { Return a new logger instance named as the first parameter using the specified factory. If no factory is provided, use the DefaultLoggerFactory. If a logger of that name already exists, then it will be returned. Otherwise, a new logger is instantiated by the factory parameter and linked with its existing ancestors as well as children. } function TLogHierarchy.GetLogger(const Name: string; const Factory: ILogLoggerFactory): TLogLogger; var LoggerFactory: ILogLoggerFactory; begin EnterCriticalSection(FCriticalHierarchy); try Result := Exists(Name); if Result = nil then begin if Factory <> nil then LoggerFactory := Factory else LoggerFactory := DefaultLoggerFactory; Result := LoggerFactory.MakeNewLoggerInstance(Name); Result.Hierarchy := Self; FLoggers.AddObject(Name, Result); UpdateParent(Result); end; finally LeaveCriticalSection(FCriticalHierarchy); end; end; { Return a renderer for the named class. } function TLogHierarchy.GetRenderer(const RenderedClass: TClass): ILogRenderer; var Index: Integer; Rendered: TClass; begin Result := nil; Rendered := RenderedClass; repeat Index := FRenderedClasses.IndexOf(Rendered); if Index > -1 then Result := ILogRenderer(FRenderers[Index]) else Rendered := Rendered.ClassParent; until (Result <> nil) or (Rendered.ClassName = 'TObject'); end; { Check for global disabling of levels. } function TLogHierarchy.IsDisabled(const LogLevel: Integer): Boolean; begin Result := (FThreshold.Level > LogLevel); end; { Remove a previously register event listener. } procedure TLogHierarchy.RemoveHierarchyEventListener( const Listener: ILogHierarchyEventListener); begin FListeners.Remove(Listener); end; { Reset all values contained in this hierarchy instance to their default. This removes all appenders from all loggers, sets the level of all non-root loggers to nil, sets their additivity flag to true and sets the level of the root logger to Debug. Moreover, message disabling is set its default 'off' value. Existing loggers are not removed. They are just reset. } procedure TLogHierarchy.ResetConfiguration; var Index: Integer; begin EnterCriticalSection(FCriticalHierarchy); try Root.Level := Debug; Threshold := All; Shutdown; { Nested locks are OK } for Index := 0 to FLoggers.Count - 1 do with TLogLogger(FLoggers.Objects[Index]) do begin Level := nil; Additive := True; end; FRenderedClasses.Clear; FRenderers.Clear; finally LeaveCriticalSection(FCriticalHierarchy); end; end; { Set the overall logging level. Cannot set a nil threshold. } procedure TLogHierarchy.SetThresholdProp(const Level: TLogLevel); begin if Level <> nil then FThreshold := Level; end; { Set the overall hierarchy logging level by name. } procedure TLogHierarchy.SetThreshold(const Name: string); var Level: TLogLevel; begin Level := TLogLevel.GetLevel(LowerCase(Name), nil); if Level = nil then LogLog.Warn(Format(ConvertErrorMsg, [Name])) else Threshold := Level; end; { Shutting down a hierarchy will safely close and remove all appenders in all loggers including the root logger. Some appenders need to be closed before the application exists, otherwise, pending logging events might be lost. } procedure TLogHierarchy.Shutdown; var Index: Integer; begin EnterCriticalSection(FCriticalHierarchy); try Root.CloseAllAppenders; Root.RemoveAllAppenders; for Index := 0 to FLoggers.Count - 1 do with TLogLogger(FLoggers.Objects[Index]) do begin CloseAllAppenders; RemoveAllAppenders; end; finally LeaveCriticalSection(FCriticalHierarchy); end; end; { Set the parent for the specified logger. The logger hierarchy is based on names separated by a dot (.). The root is the ultimate parent. Otherwise, we use GetLogger to return a reference to the immediate parent (and create it if necessary). } procedure TLogHierarchy.UpdateParent(const Logger: TLogLogger); var Index: Integer; { Return the index of the last dot (.) in the text, or zero if none. } function LastDot(Text: string): Integer; begin for Result := Length(Text) downto 1 do if Text[Result] = '.' then Exit; Result := 0; end; begin Index := LastDot(Logger.Name); if Index = 0 then Logger.FParent := Root else Logger.FParent := GetLogger(Copy(Logger.Name, 1, Index - 1)); end; { TLogCustomLayout ------------------------------------------------------------} { Returns the content type output by this layout. The base class returns 'text/plain'. } function TLogCustomLayout.GetContentType: string; begin Result := 'text/plain'; end; { Returns the footer for the layout format. The base class returns ''. } function TLogCustomLayout.GetFooter: string; begin Result := ''; end; { Returns the header for the layout format. The base class returns ''. } function TLogCustomLayout.GetHeader: string; begin Result := ''; end; { If the layout handles the Exception object contained within, then the layout should return False. Otherwise, if the layout ignores Exception object, then the layout should return True. The base class returns True. } function TLogCustomLayout.IgnoresException: Boolean; begin Result := True; end; { Initialisation - date format is a standard option. } procedure TLogCustomLayout.Init; var FormatSettings : TFormatSettings; begin inherited Init; SetOption(DateFormatOpt, {$IF CompilerVersion >= 20}FormatSettings.{$IFEND}ShortDateFormat); end; { Set a list of options for this layout. } procedure TLogCustomLayout.SetOption(const Name, Value: string); begin inherited SetOption(Name, Value); if (Name = DateFormatOpt) and (Value <> '') then DateFormat := Value; end; { TLogSimpleLayout ------------------------------------------------------------} { Show event level and message. } function TLogSimpleLayout.Format(const Event: TLogEvent): string; begin Result := Event.Level.Name + ' - ' + Event.Message + CRLF; end; { TLogHTMLLayout --------------------------------------------------------------} { Write a HTML table row for each event. } function TLogHTMLLayout.Format(const Event: TLogEvent): string; var ErrorMessage: string; begin Result := '<tr><td>' + IntToStr(Event.ElapsedTime) + '</td><td>' + IntToStr(Event.ThreadId) + '</td><td>'; if Event.Level = Debug then Result := Result + '<font color="#339933">' + Event.Level.Name + '</font>' else if Event.Level.IsGreaterOrEqual(Warn) then Result := Result + '<font color="#993300"><strong>' + Event.Level.Name + '</strong></font>' else Result := Result + Event.Level.Name; Result := Result + '</td><td>' + Event.LoggerName + '</td>' + '<td>' + Event.NDC + '</td><td>' + Event.Message + '</td></tr>' + CRLF; ErrorMessage := Event.ErrorMessage; if ErrorMessage <> '' then Result := Result + '<tr><td bgcolor="#993300" ' + 'style="color: White; font-size: xx-small;" colspan="6">' + ErrorMessage + '</td></tr>' + CRLF; end; { Returns the content type output by this layout, i.e 'text/html'. } function TLogHTMLLayout.GetContentType: string; begin Result := 'text/html'; end; { Returns appropriate HTML footers. } function TLogHTMLLayout.GetFooter: string; begin Result := '</table>' + CRLF + '</body>' + CRLF + '</html>' + CRLF; end; { Returns appropriate HTML headers. } function TLogHTMLLayout.GetHeader: string; begin Result := '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ' + '"http://www.w3.org/TR/html4/loose.dtd">' + CRLF + '<html>' + CRLF + '<head>' + CRLF + '<title>' + Title + '</title>' + CRLF + '<style type="text/css">' + CRLF + '<!--' + CRLF + 'body, table {font-family: arial,sans-serif; font-size: x-small;}' + CRLF + 'th {background: #336699; color: #FFFFFF; text-align: left;}' + CRLF + '-->' + CRLF + '</style>' + CRLF + '</head>' + CRLF + '<body bgcolor="#FFFFFF" topmargin="6" leftmargin="6">' + CRLF + '<hr size="1" noshade>' + CRLF + SessionStartMsg + ' ' + DateTimeToStr(Now) + '<br>' + CRLF + '<br>' + CRLF + '<table cellspacing="0" cellpadding="4" border="1" ' + 'bordercolor="#224466" width="100%">' + CRLF + '<tr><th>' + TimeHdr + '</th><th>' + ThreadHdr + '</th>' + '<th>' + LevelHdr + '</th><th>' + LoggerHdr + '</th>' + '<th>' + NDCHdr + '</th><th>' + MessageHdr + '</th></tr>' + CRLF; end; { The HTML layout handles the exception contained in logging events. Hence, this method return False. } function TLogHTMLLayout.IgnoresException: Boolean; begin Result := False; end; { Set the title for the HTML page. } procedure TLogHTMLLayout.SetOption(const Name, Value: string); begin inherited SetOption(Name, Value); if (Name = TitleOpt) and (Value <> '') then Title := Value; end; { TLogPatternLayout -----------------------------------------------------------} type TPatternPart = (ppText, ppLogger, ppClassName, ppDate, ppException, ppFileName, ppLocation, ppLine, ppMessage, ppMethod, ppNewLine, ppLevel, ppRuntime, ppThread, ppNDC, ppPercent); const { These characters identify the types above. } PatternChars = ' cCdeFlLmMnprtx%'; { These characters substitute for those above in the processed format. } PatternReplacements = ' ssssssdssssddss'; constructor TLogPatternLayout.Create(const Pattern: string); begin inherited Create; Self.Pattern := Pattern; end; destructor TLogPatternLayout.Destroy; begin FPatternParts.Free; inherited Destroy; end; { Compile the formatted string from the specified pattern and its parts. Pattern characters are as follows: c - Logger name, e.g. myapp.more C - Class name of caller - not implemented e - Message and class name from the exception associated with the event d - Current date and time, using date format set as option F - File name of calling class - not implemented l - Name and location within calling method - not implemented L - Line number within calling method - not implemented m - Message associated with event M - Method name within calling class - not implemented n - New line p - Level name r - Runtime in milliseconds since start t - Thread id x - Nested diagnostic context (NDC) % - The percent character Pattern characters are preceded by a percent sign (%) and may contain field formatting characters per Delphi's Format function, e.g. %-7p displays the event's level, left justified in a 7 character field. Other text is displayed as is. } function TLogPatternLayout.Format(const Event: TLogEvent): string; var Index: Integer; begin Result := ''; for Index := 0 to FPatternParts.Count - 1 do case TPatternPart(FPatternParts.Objects[Index]) of ppText: Result := Result + FPatternParts[Index]; ppLogger: Result := Result + SysUtils.Format(FPatternParts[Index], [Event.LoggerName]); ppClassName: Result := Result + SysUtils.Format(FPatternParts[Index], [ValueUnknownMsg]); ppDate: Result := Result + FormatDateTime(DateFormat, Now); ppException: Result := Result + SysUtils.Format(FPatternParts[Index], [Event.ErrorMessage]); ppFileName: Result := Result + SysUtils.Format(FPatternParts[Index], [ValueUnknownMsg]); ppLocation: Result := Result + SysUtils.Format(FPatternParts[Index], [ValueUnknownMsg]); ppLine: Result := Result + SysUtils.Format(FPatternParts[Index], [ValueUnknownMsg]); ppMessage: Result := Result + SysUtils.Format(FPatternParts[Index], [Event.Message]); ppMethod: Result := Result + SysUtils.Format(FPatternParts[Index], [ValueUnknownMsg]); ppNewLine: Result := Result + CRLF; ppLevel: Result := Result + SysUtils.Format(FPatternParts[Index], [Event.Level.Name]); ppRuntime: Result := Result + SysUtils.Format(FPatternParts[Index], [Event.ElapsedTime]); ppThread: Result := Result + SysUtils.Format(FPatternParts[Index], [Event.ThreadId]); ppNDC: Result := Result + SysUtils.Format(FPatternParts[Index], [Event.NDC]); ppPercent: Result := Result + '%'; end; end; procedure TLogPatternLayout.Init; begin inherited Init; FPatternParts := TStringList.Create; end; procedure TLogPatternLayout.SetOption(const Name, Value: string); begin inherited SetOption(Name, Value); if (Name = PatternOpt) and (Value <> '') then Pattern := Value; end; { Extract the portions of the pattern for easier processing later. } procedure TLogPatternLayout.SetPattern(const Pattern: string); var Index: Integer; Part: string; PartType: TPatternPart; begin FPattern := Pattern; FPatternParts.Clear; Part := ''; Index := 1; while Index <= Length(FPattern) do begin if FPattern[Index] = '%' then begin { Patterns are delimited by percents (%) and continue up to one of the special characters noted earlier. } repeat Part := Part + FPattern[Index]; Inc(Index); until (Index > Length(FPattern)) or (Pos(FPattern[Index], PatternChars) > 1); if Index > Length(FPattern) then Part := Part + 'm' else Part := Part + FPattern[Index]; PartType := TPatternPart(Pos(Part[Length(Part)], PatternChars) - 1); Part[Length(Part)] := PatternReplacements[Pos(FPattern[Index], PatternChars)]; FPatternParts.AddObject(Part, Pointer(Integer(PartType))); Part := ''; Inc(Index); end else begin { The rest is straight text - up to the next percent (%). } repeat Part := Part + FPattern[Index]; Inc(Index); until (Index > Length(FPattern)) or (FPattern[Index] = '%'); FPatternParts.AddObject(Part, Pointer(Integer(ppText))); Part := ''; end; end; end; { TLogCustomErrorHandler ------------------------------------------------------} procedure TLogCustomErrorHandler.SetAppender(const Appender: ILogAppender); begin FAppender := Appender; LogLog.Debug(Format(SettingAppenderMsg, [Appender.Name])); end; procedure TLogCustomErrorHandler.SetBackupAppender( const BackupAppender: ILogAppender); begin FBackupAppender := BackupAppender; LogLog.Debug(Format(SettingBackupMsg, [BackupAppender.Name])); end; procedure TLogCustomErrorHandler.SetLogger(const Logger: TLogLogger); begin FLogger := Logger; LogLog.Debug(Format(SettingLoggerMsg, [Logger.Name])); end; { TLogOnlyOnceErrorHandler ----------------------------------------------------} { Only first error sent here is reported. } procedure TLogOnlyOnceErrorHandler.Error(const Message: string); begin if not FSeenError then begin LogLog.Error(Message); FSeenError := True; end; end; procedure TLogOnlyOnceErrorHandler.Error(const Message: string; const Err: Exception; const ErrorCode: Integer; const Event: TLogEvent); begin if not FSeenError then Error(Format('%s - (%d) %s', [Message, Err.Message, ErrorCode])); end; { TLogFallbackErrorHandler ----------------------------------------------------} constructor TLogFallbackErrorHandler.Create; begin inherited Create; FLoggers := TObjectList.Create; {$IFDEF DELPHI5_UP} FLoggers.OwnsObjects := False; {$ENDIF} end; destructor TLogFallbackErrorHandler.Destroy; begin FLoggers.Free; inherited Destroy; end; { Fallback on an alternative appender if an error arises. } procedure TLogFallbackErrorHandler.Error(const Message: string); var Index: Integer; begin LogLog.Debug(Format(FallbackMsg, [Message])); for Index := 0 to FLoggers.Count - 1 do with TLogLogger(FLoggers[Index]) do begin LogLog.Debug(Format(FallbackReplaceMsg, [FAppender.Name, FBackupAppender.Name, Name])); RemoveAppender(FAppender); AddAppender(FBackupAppender); end; end; procedure TLogFallbackErrorHandler.Error(const Message: string; const Err: Exception; const ErrorCode: Integer; const Event: TLogEvent); begin Error(Format('%s - (%d) %s', [Message, Err.Message, ErrorCode])); end; { Add to the list of loggers to search for on failure. } procedure TLogFallbackErrorHandler.SetLogger(const Logger: TLogLogger); begin if FLoggers.IndexOf(Logger) = -1 then begin FLoggers.Add(Logger); LogLog.Debug(Format(AddingLoggerMsg, [Logger.Name])); end; end; { TLogCustomFilter ------------------------------------------------------------} const Acceptance: array [Boolean] of TLogFilterDecision = (fdDeny, fdAccept); { Initialisation. } constructor TLogCustomFilter.Create(const AcceptOnMatch: Boolean); begin inherited Create; Self.AcceptOnMatch := AcceptOnMatch; end; { Set common option. } procedure TLogCustomFilter.SetOption(const Name, Value: string); begin inherited SetOption(Name, Value); if Name = AcceptMatchOpt then FAcceptOnMatch := StrToBool(Value, True); end; { TLogDenyAllFilter -----------------------------------------------------------} { Deny all messages. } function TLogDenyAllFilter.Decide(const Event: TLogEvent): TLogFilterDecision; begin Result := fdDeny; end; { TLogLevelMatchFilter --------------------------------------------------------} { Initialisation. } constructor TLogLevelMatchFilter.Create(const MatchLevel: TLogLevel; const AcceptOnMatch: Boolean); begin inherited Create(AcceptOnMatch); Self.MatchLevel := MatchLevel; end; { Check for the matching level, then accept or deny based on the flag. } function TLogLevelMatchFilter.Decide(const Event: TLogEvent): TLogFilterDecision; begin if (MatchLevel <> nil) and (MatchLevel.Level = Event.Level.Level) then Result := Acceptance[AcceptOnMatch] else Result := fdNeutral; end; { Set matching level from options. } procedure TLogLevelMatchFilter.SetOption(const Name, Value: string); begin inherited SetOption(Name, Value); if Name = MatchOpt then FMatchLevel := TLogLevel.GetLevel(Value); end; { TLogLevelRangeFilter --------------------------------------------------------} { Initialisation. } constructor TLogLevelRangeFilter.Create(const MaxLevel, MinLevel: TLogLevel; const AcceptOnMatch: Boolean); begin inherited Create(AcceptOnMatch); Self.MaxLevel := MaxLevel; Self.MinLevel := MinLevel; end; { Check for the matching levels, then accept or deny based on the flag. } function TLogLevelRangeFilter.Decide(const Event: TLogEvent): TLogFilterDecision; begin if (MaxLevel <> nil) and (MaxLevel.Level >= Event.Level.Level) and (MinLevel <> nil) and (MinLevel.Level <= Event.Level.Level) then Result := Acceptance[AcceptOnMatch] else Result := fdNeutral; end; { Set matching levels from options. } procedure TLogLevelRangeFilter.SetOption(const Name, Value: string); begin inherited SetOption(Name, Value); if Name = MaxOpt then FMaxLevel := TLogLevel.GetLevel(Value) else if Name = MinOpt then FMinLevel := TLogLevel.GetLevel(Value); end; { TLogStringFilter ------------------------------------------------------------} { Initialisation. } constructor TLogStringFilter.Create(const Match: string; const IgnoreCase: Boolean; const AcceptOnMatch: Boolean); begin inherited Create(AcceptOnMatch); Self.Match := Match; Self.IgnoreCase := IgnoreCase; end; { Check for the matching string, then accept or deny based on the flag. } function TLogStringFilter.Decide(const Event: TLogEvent): TLogFilterDecision; var MatchOn, MatchWith: string; begin if IgnoreCase then begin MatchOn := LowerCase(Match); MatchWith := LowerCase(Event.Message); end else begin MatchOn := Match; MatchWith := Event.Message; end; if Pos(MatchOn, MatchWith) > 0 then Result := Acceptance[AcceptOnMatch] else Result := fdNeutral; end; { Set string value to match and case-sensitivity from options. } procedure TLogStringFilter.SetOption(const Name, Value: string); begin inherited SetOption(Name, Value); if Name = MatchOpt then FMatch := Value else if Name = IgnoreCaseOpt then FIgnoreCase := StrToBool(Value, FIgnoreCase); end; { TLogCustomAppender ----------------------------------------------------------} constructor TLogCustomAppender.Create(const Name: string; const Layout: ILogLayout); begin inherited Create; FName := Name; if Layout <> nil then FLayout := Layout else FLayout := TLogSimpleLayout.Create; end; destructor TLogCustomAppender.Destroy; begin Close; FFilters.Free; DeleteCriticalSection(FCriticalAppender); inherited Destroy; end; { Add a filter to the end of the filter list. } procedure TLogCustomAppender.AddFilter(const Filter: ILogFilter); begin if FFilters.IndexOf(Filter) = -1 then FFilters.Add(Filter); end; { Log in appender-specific way. } procedure TLogCustomAppender.Append(const Event: TLogEvent); begin EnterCriticalSection(FCriticalAppender); try if isAsSevereAsThreshold(Event.Level) then if CheckEntryConditions then if CheckFilters(Event) then DoAppend(Event); finally LeaveCriticalSection(FCriticalAppender); end; end; { Only log if not closed and a layout is available. } function TLogCustomAppender.CheckEntryConditions: Boolean; begin Result := False; if FClosed then begin LogLog.Warn(ClosedAppenderMsg); Exit; end; if (Layout = nil) and RequiresLayout then begin ErrorHandler.Error(Format(NoLayoutMsg, [Name])); Exit; end; Result := True; end; { Only log if any/all filters allow it. } function TLogCustomAppender.CheckFilters(const Event: TLogEvent): Boolean; var Index: Integer; begin for Index := 0 to FFilters.Count - 1 do case ILogFilter(FFilters[Index]).Decide(Event) of fdAccept: begin Result := True; Exit; end; fdDeny: begin Result := False; Exit; end; fdNeutral: { Try next one } end; Result := True; end; { Release any resources allocated within the appender such as file handles, network connections, etc. It is a programming error to append to a closed appender. } procedure TLogCustomAppender.Close; begin EnterCriticalSection(FCriticalAppender); try if FClosed then Exit; WriteFooter; FClosed := True; finally LeaveCriticalSection(FCriticalAppender); end; end; procedure TLogCustomAppender.DoAppend(const Event: TLogEvent); begin DoAppend(Layout.Format(Event)); end; { Returns the error handler for this appender. } function TLogCustomAppender.GetErrorHandler: ILogErrorHandler; begin Result := FErrorHandler; end; { Returns the filters for this appender. } function TLogCustomAppender.GetFilters: TInterfaceList; begin Result := FFilters; end; { Returns this appender's layout. } function TLogCustomAppender.GetLayout: ILogLayout; begin Result := FLayout; end; { Get the name of this appender. The name uniquely identifies the appender. } function TLogCustomAppender.GetName: string; begin Result := FName; end; { Initialisation. } procedure TLogCustomAppender.Init; begin inherited Init; InitializeCriticalSection(FCriticalAppender); FClosed := False; FErrorHandler := TLogOnlyOnceErrorHandler.Create; FFilters := TInterfaceList.Create; FThreshold := All; end; { Clear the list of filters by removing all the filters in it. } procedure TLogCustomAppender.RemoveAllFilters; begin FFilters.Clear; end; { Delete a filter from the appender's list. } procedure TLogCustomAppender.RemoveFilter(const Filter: ILogFilter); begin FFilters.Remove(Filter); end; { Configurators call this method to determine if the appender requires a layout. If this method returns True, meaning that a layout is required, then the configurator will configure a layout using the configuration information at its disposal. If this method returns False, meaning that a layout is not required, then layout configuration will be used if available. } function TLogCustomAppender.RequiresLayout: Boolean; begin Result := True; end; {$IFDEF UNICODE} function TLogCustomAppender.GetEncoding: TEncoding; begin if (FEncoding = nil) then Result := TEncoding.Default else Result := FEncoding; end; procedure TLogCustomAppender.SetEncoding(const Value: TEncoding); begin if (FEncoding <> nil) and not TEncoding.IsStandardEncoding(FEncoding) then FEncoding.Free; FEncoding := Value; end; {$ENDIF UNICODE} { Set the error handler for this appender - it cannot be nil. } procedure TLogCustomAppender.SetErrorHandler( const ErrorHandler: ILogErrorHandler); begin EnterCriticalSection(FCriticalAppender); try if ErrorHandler = nil then LogLog.Warn(NilErrorHandlerMsg) else FErrorHandler := ErrorHandler; finally LeaveCriticalSection(FCriticalAppender); end; end; { Set the layout for this appender. } procedure TLogCustomAppender.SetLayout(const Layout: ILogLayout); begin FLayout := Layout; end; { Set the name of this appender. The name is used by other components to identify this appender. } procedure TLogCustomAppender.SetName(const Name: string); begin FName := Name; end; procedure TLogCustomAppender.WriteFooter; begin if Layout <> nil then DoAppend(Layout.Footer); end; procedure TLogCustomAppender.WriteHeader; begin if Layout <> nil then DoAppend(Layout.Header); end; procedure TLogCustomAppender.SetOption(const Name, Value: string); begin inherited SetOption(Name, Value); if (Name = ThresholdOpt) and (Value <> '') then begin FThreshold := TLogLevel.GetLevel(Value, All); end {$IFDEF UNICODE} else if (Name = EncodingOpt) then begin Encoding := FindEncodingFromName(Value); end {$ENDIF} end; function TLogCustomAppender.isAsSevereAsThreshold(level: TLogLevel): boolean; begin Result := not ((FThreshold <> nil) and (level.Level < FThreshold.Level)); end; { TLogNullAppender ------------------------------------------------------------} { Do nothing. } procedure TLogNullAppender.DoAppend(const Message: string); begin end; { TLogODSAppender -------------------------------------------------------------} { Log to debugging output. } procedure TLogODSAppender.DoAppend(const Message: string); begin OutputDebugString(PChar(Message)); end; { TLogStreamAppender ----------------------------------------------------------} constructor TLogStreamAppender.Create(const Name: string; const Stream: TStream; const Layout: ILogLayout); begin inherited Create(Name, Layout); FStream := Stream; end; destructor TLogStreamAppender.Destroy; begin Close; FStream.Free; inherited Destroy; end; { Log to the attached stream. } procedure TLogStreamAppender.DoAppend(const Message: string); var StrStream: TStringStream; begin if FStream <> nil then begin {$IFDEF UNICODE} StrStream := TStringStream.Create(Message, Encoding, False); {$ELSE} StrStream := TStringStream.Create(Message); {$ENDIF} try FStream.CopyFrom(StrStream, 0); finally StrStream.Free; end; end; end; { TLogFileAppender ------------------------------------------------------------} { Create a file stream and delegate to the parent class. } constructor TLogFileAppender.Create(const Name, FileName: string; const Layout: ILogLayout; const Append: Boolean); begin inherited Create(Name, nil, Layout); FAppend := Append; SetOption(FileNameOpt, FileName); end; { create file stream } procedure TLogFileAppender.SetLogFile(const Name: string); var strPath: string; f : TextFile; begin CloseLogFile; FFileName := Name; if FAppend and FileExists(FFileName) then begin // append to existing file FStream := TFileStream.Create(FFileName, fmOpenReadWrite or fmShareDenyWrite); FStream.Seek(0, soFromEnd); end else begin // Check if directory exists strPath := ExtractFileDir(FFileName); if (strPath <> '') and not DirectoryExists(strPath) then ForceDirectories(strPath); //FIX 04.10.2006 MHoenemann: // SysUtils.FileCreate() ignores any sharing option (like our fmShareDenyWrite), // Creating new file AssignFile(f, FFileName); ReWrite(f); CloseFile(f); // now use this file FStream := TFileStream.Create(FFileName, fmOpenReadWrite or fmShareDenyWrite); end; WriteHeader; end; { close file stream } procedure TLogFileAppender.CloseLogFile; begin if FStream <> nil then FreeAndNil(FStream); end; procedure TLogFileAppender.SetOption(const Name, Value: string); begin inherited SetOption(Name, Value); EnterCriticalSection(FCriticalAppender); try if (Name = AppendOpt) and (Value <> '') then begin FAppend := StrToBool(Value, FAppend); end else if (Name = FileNameOpt) and (Value <> '') then begin SetLogFile(Value); // changed by adasen end; finally LeaveCriticalSection(FCriticalAppender); end; end; { TLogRollingFileAppender } procedure TLogRollingFileAppender.DoAppend(const msg: string); begin if assigned(FStream) and (FCurrentSize = 0) then FCurrentSize := FStream.Size; FCurrentSize := FCurrentSize + Length(msg); // should be faster than TFileStream.Size if (FStream <> nil) and (FCurrentSize > FMaxFileSize) then begin FCurrentSize := 0; RollOver; end; inherited; end; { set defaults } procedure TLogRollingFileAppender.Init; begin inherited; FMaxFileSize := DEFAULT_MAX_FILE_SIZE; FMaxBackupIndex := DEFAULT_MAX_BACKUP_INDEX; end; { log file rotation } procedure TLogRollingFileAppender.RollOver; var i : integer; filename : string; begin // If maxBackups <= 0, then there is no file renaming to be done. if FMaxBackupIndex > 0 then begin // Delete the oldest file, to keep Windows happy. DeleteFile(FFileName + '.' + IntToStr(FMaxBackupIndex)); // Map (maxBackupIndex - 1), ..., 2, 1 to maxBackupIndex, ..., 3, 2 for i := FMaxBackupIndex - 1 downto 1 do begin filename := FFileName + '.' + IntToStr(i); if FileExists(filename) then RenameFile(filename, FFileName + '.' + IntToStr(i+1)); end; // close file CloseLogFile; // Rename fileName to fileName.1 RenameFile(FFileName, FFileName + '.1'); // open new file SetLogFile(FFileName); end; end; procedure TLogRollingFileAppender.SetOption(const Name, Value: string); var suffix : string; begin inherited SetOption(Name, Value); EnterCriticalSection(FCriticalAppender); try if (Name = MaxFileSizeOpt) and (Value <> '') then begin // check suffix suffix := Copy(Value, Length(Value)-1, 2); if suffix = 'KB' then FMaxFileSize := StrToIntDef(Copy(Value, 1, Length(Value)-2), 0) * 1024 else if suffix = 'MB' then FMaxFileSize := StrToIntDef(Copy(Value, 1, Length(Value)-2), 0) * 1024 * 1024 else if suffix = 'GB' then FMaxFileSize := StrToIntDef(Copy(Value, 1, Length(Value)-2), 0) * 1024 * 1024 * 1024 else FMaxFileSize := StrToIntDef(Value, 0); if FMaxFileSize = 0 then FMaxFileSize := DEFAULT_MAX_FILE_SIZE; end else if (Name = MaxBackupIndexOpt) and (Value <> '') then begin FMaxBackupIndex := StrToIntDef(Value, DEFAULT_MAX_BACKUP_INDEX); end; finally LeaveCriticalSection(FCriticalAppender); end; end; { OptionConvertors ------------------------------------------------------------} { Convert string value to Boolean, with default. } function StrToBool(Value: string; const Default: Boolean): Boolean; begin Value := LowerCase(Value); if (Value = 'true') or (Value = 'yes') then Result := True else if (Value = 'false') or (Value = 'no') then Result := False else Result := Default; end; {$IFDEF UNICODE} function FindEncodingFromName(const Name: string): TEncoding; begin Result := nil; if SameText(Name, SANSIEncoding) then Result := TEncoding.Default else if SameText(Name, SASCIIEncoding) then Result := TEncoding.ASCII else if SameText(Name, SUnicodeEncoding) then Result := TEncoding.Unicode else if SameText(Name, SBigEndianEncoding) then Result := TEncoding.BigEndianUnicode else if SameText(Name, SUTF7Encoding) then Result := TEncoding.UTF7 else if SameText(Name, SUTF8Encoding) then Result := TEncoding.UTF8; end; {$ENDIF UNICODE} { TAppender -------------------------------------------------------------------} type { Holder for an appender reference. } TAppender = class(TObject) public Appender: ILogAppender; constructor Create(Appender: ILogAppender); end; constructor TAppender.Create(Appender: ILogAppender); begin inherited Create; Self.Appender := Appender; end; { TLogBasicConfigurator -------------------------------------------------------} constructor TLogBasicConfigurator.Create; begin inherited Create; FLoggerFactory := TLogDefaultLoggerFactory.Create; FRegistry := TStringList.Create; end; destructor TLogBasicConfigurator.Destroy; var Index: Integer; begin for Index := 0 to FRegistry.Count - 1 do FRegistry.Objects[Index].Free; FRegistry.Free; inherited Destroy; end; { Used by subclasses to add a renderer to the hierarchy passed as parameter. } procedure TLogBasicConfigurator.AddRenderer(const Hierarchy: TLogHierarchy; const RenderedName, RendererName: string); var Rendered: TClass; Renderer: ILogRenderer; begin LogLog.Debug(Format(RendererMsg, [RendererName, RenderedName])); Rendered := FindRendered(RenderedName); Renderer := FindRenderer(RendererName); if Rendered = nil then begin LogLog.Error(Format(NoRenderedCreatedMsg, [RenderedName])); Exit; end; if Renderer = nil then begin LogLog.Error(Format(NoRendererCreatedMsg, [RendererName])); Exit; end; Hierarchy.AddRenderer(Rendered, Renderer); end; { Return a reference to an already defined named appender, or nil if none. } function TLogBasicConfigurator.AppenderGet(const Name: string): ILogAppender; var Index: Integer; begin Index := FRegistry.IndexOf(Name); if Index = -1 then Result := nil else Result := TAppender(FRegistry.Objects[Index]).Appender; end; { Save reference to named appender. } procedure TLogBasicConfigurator.AppenderPut(const Appender: ILogAppender); begin FRegistry.AddObject(Appender.Name, TAppender.Create(Appender)); end; { Add appender to the root logger. If no appender is provided, add a TLogODSAppender that uses TLogPatternLayout with the TTCCPattern and prints to debugging output for the root logger. } class procedure TLogBasicConfigurator.Configure(const Appender: ILogAppender); var NewAppender: ILogAppender; begin if Appender = nil then NewAppender := TLogODSAppender.Create('ODS', TLogPatternLayout.Create(TTCCPattern)) else NewAppender := Appender; DefaultHierarchy.Root.AddAppender(NewAppender); end; { Reset the default hierarchy to its default. } class procedure TLogBasicConfigurator.ResetConfiguration; begin DefaultHierarchy.ResetConfiguration; end; { Initialise standard global settings. } procedure TLogBasicConfigurator.SetGlobalProps(const Hierarchy: TLogHierarchy; const FactoryClassName, Debug, Threshold: string); begin if FactoryClassName <> '' then begin FLoggerFactory := FindLoggerFactory(FactoryClassName); if FLoggerFactory <> nil then LogLog.Debug(Format(LoggerFactoryMsg, [FactoryClassName])) else FLoggerFactory := TLogDefaultLoggerFactory.Create; end; if Debug <> '' then LogLog.InternalDebugging := StrToBool(Debug, False); if Threshold <> '' then DefaultHierarchy.Threshold := TLogLevel.GetLevel(LowerCase(Threshold)); end; { TLogPropertyConfigurator ----------------------------------------------------} { Split the supplied value into tokens with specified delimiters. } procedure Tokenise(const Value: string; const Items: TStringList; const Delimiters: string); var Index: Integer; Item: string; begin Item := ''; for Index := 1 to Length(Value) do if Pos(Value[Index], Delimiters) > 0 then begin Items.Add(Item); Item := ''; end else Item := Item + Value[Index]; if Item <> '' then Items.Add(Item); end; { Extract properties with the given prefix from the supplied list and send them to the option handler. } procedure SetSubProps(const Prefix: string; const Props: TStringList; const Handler: ILogOptionHandler); var Index: Integer; begin for Index := 0 to Props.Count - 1 do if Pos(Prefix, Props.Names[Index]) = 1 then Handler.Options[Copy(Props.Names[Index], Length(Prefix) + 2, 255)] := Props.Values[Props.Names[Index]]; end; { Read configuration options from a file. See DoConfigure for the expected format. } class procedure TLogPropertyConfigurator.Configure(const Filename: string); var Config: TLogPropertyConfigurator; begin Config := TLogPropertyConfigurator.Create; try Config.DoConfigure(Filename, DefaultHierarchy); finally Config.Free; end; end; { Read configuration options from properties. See DoConfigure for the expected format. } class procedure TLogPropertyConfigurator.Configure(const Props: TStringList); var Config: TLogPropertyConfigurator; begin Config := TLogPropertyConfigurator.Create; try Config.DoConfigure(Props, DefaultHierarchy); finally Config.Free; end; end; procedure TLogPropertyConfigurator.ConfigureRootLogger(const Props: TStringList; const Hierarchy: TLogHierarchy); var Value: string; begin Value := Props.Values[RootLoggerKey]; if Value = '' then LogLog.Debug(NoRootLoggerMsg) else ParseLogger(Props, Hierarchy.Root, Value); end; { Read configuration options from a file. See DoConfigure below for the expected format. } procedure TLogPropertyConfigurator.DoConfigure(const FileName: string; const Hierarchy: TLogHierarchy); var Props: TStringList; begin Props := TStringList.Create; try try Props.LoadFromFile(FileName); DoConfigure(Props, Hierarchy); except on Ex: Exception do begin LogLog.Error(Format(BadConfigFileMsg, [FileName, Ex.Message])); LogLog.Error(Format(IgnoreConfigMsg, [FileName])); end; end; finally Props.Free; end; end; { Read configuration from properties. The existing configuration is not cleared nor reset. If you require a different behaviour, then call ResetConfiguration method before calling Configure. The configuration file consists of entries in the format key=value. Global Settings Where level is used below it indicates one of the following values: all|fatal|error|warn|info|debug|off|<custom level name> To set a global threshold for all loggers use the following syntax (defaults to all): log4d.threshold=level Logging of internal debugging events can be enabled with the following: log4d.configDebug=true Appender configuration Appender configuration syntax is: # For appender named appenderName, set its class. log4d.appender.appenderName=nameOfAppenderClass # Set appender specific options. log4d.appender.appenderName.option1=value1 : log4d.appender.appenderName.optionN=valueN For each named appender you can configure its ErrorHandler. The syntax for configuring an appender's error handler is: log4d.appender.appenderName.errorHandler=nameOfErrorHandlerClass For each named appender you can configure its Layout. The syntax for configuring an appender's layout and its options is: log4d.appender.appenderName.layout=nameOfLayoutClass log4d.appender.appenderName.layout.option1=value1 : log4d.appender.appenderName.layout.optionN=valueN For each named appender you can configure its Filters. The syntax for configuring an appender's filters is (where x is a sequential number): log4d.appender.appenderName.filterx=nameOfFilterClass log4d.appender.appenderName.filterx.option1=value1 : log4d.appender.appenderName.filterx.optionN=valueN Configuring loggers The syntax for configuring the root logger is: log4d.rootLogger=[level],appenderName[,appenderName]... This syntax means that one of the level values (e.g. error, info, or debug) can be supplied followed by appender name(s) separated by commas. If one of the optional level values is given, the root level is set to the corresponding level. If no level value is specified, then the root level remains untouched. The root logger can be assigned multiple appenders. Each appenderName (separated by commas) will be added to the root logger. The named appender is defined using the appender syntax defined above. For non-root loggers the syntax is almost the same: log4d.logger.loggerName=[inherited|level],appenderName[,appenderName]... Thus, one of the usual level values can be optionally specified. For any of these values the named logger is assigned the corresponding level. In addition however, the value "inherited" can be optionally specified which means that named logger should inherit its level from the logger hierarchy. If no level value is supplied, then the level of the named logger remains untouched. By default loggers inherit their level from the hierarchy. However, if you set the level of a logger and later decide that that logger should inherit its level, then you should specify "inherited" as the value for the level value. Similar to the root logger syntax, each appenderName (separated by commas) will be attached to the named logger. Logger additivity is set in the following fashion: log4d.additive.loggerName=true|false ObjectRenderers You can customise the way message objects of a given type are converted to a string before being logged. This is done by specifying an object renderer for the object type would like to customise. The syntax is: log4d.renderer.nameOfRenderedClass=nameOfRenderingClass As in, log4d.renderer.TFruit=TFruitRenderer Class Factories In case you are using your own sub-types of the TLogLogger class and wish to use configuration files, then you must set the LoggerFactory for the sub-type that you are using. The syntax is: log4d.loggerFactory=nameOfLoggerFactoryClass Example An example configuration is given below. # Set internal debugging log4d.configDebug=true # Global logging level - don't show debug events log4d.threshold=info # Set logger factory - this is the default anyway log4d.loggerFactory=TLogDefaultLoggerFactory # Set root level to log warnings and above - sending to appender ODS log4d.rootLogger=warn,ODS # Establish logger hierarchy # 'myapp' inherits its level from root log4d.logger.myapp=inherited,Mem1 # 'myapp.more' displays all messages (from debug up) log4d.logger.myapp.more=debug,Mem2 # 'myapp.other' doesn't display debug messages log4d.logger.myapp.other=info,Mem3 # 'alt' only displays error and fatal messages log4d.logger.alt=error,Mem4,Fil1 # 'myapp.other' logger doesn't log to its parents - others do log4d.additive.myapp.other=false # Create root appender - logging to debugging output log4d.appender.ODS=TLogODSAppender # Using the simple layout, i.e. message only log4d.appender.ODS.layout=TLogSimpleLayout # Create memo appenders, with layouts log4d.appender.Mem1=TMemoAppender # Specify the name of the memo component to attach to log4d.appender.Mem1.memo=memMyapp # Use a pattern layout log4d.appender.Mem1.layout=TLogPatternLayout # With the specified pattern: runtime (in field of 7 characters), # thread id (left justified in field of 8 characters), level, # logger, NDC, message, and a new line log4d.appender.Mem1.layout.pattern=%7r [%-8t] %p %c %x - %m%n # Add a string filter log4d.appender.Mem1.filter1=TLogStringFilter # That matches on 'x' log4d.appender.Mem1.filter1.match=x # And accepts all messages containing it log4d.appender.Mem1.filter1.acceptOnMatch=false # Add a second string filter log4d.appender.Mem1.filter2=TLogStringFilter # That matches on 'y' log4d.appender.Mem1.filter2.match=y # And discards all messages containing it # Note: messages with 'x' and 'y' will be logged as filter 1 is checked first log4d.appender.Mem1.filter2.acceptOnMatch=false log4d.appender.Mem2=TMemoAppender log4d.appender.Mem2.memo=memMyappMore log4d.appender.Mem2.layout=TLogSimpleLayout log4d.appender.Mem3=TMemoAppender log4d.appender.Mem3.memo=memMyappOther log4d.appender.Mem3.layout=TLogHTMLLayout log4d.appender.Mem4=TMemoAppender log4d.appender.Mem4.memo=memAlt log4d.appender.Mem4.layout=TLogPatternLayout log4d.appender.Mem4.layout.pattern=>%m<%n # Create a file appender log4d.appender.Fil1=TLogFileAppender log4d.appender.Fil1.filename=C:\Temp\Log4D.log log4d.appender.Fil1.errorHandler=TLogOnlyOnceErrorHandler log4d.appender.Fil1.layout=TLogPatternLayout log4d.appender.Fil1.layout.pattern=%r [%t] %p %c %x - %m%n # Nominate renderers - when objects of type TEdit are presented, # use TComponentRenderer to display them log4d.renderer.TEdit=TComponentRenderer Use the # character at the beginning of a line for comments. } procedure TLogPropertyConfigurator.DoConfigure(const Props: TStringList; const Hierarchy: TLogHierarchy); begin SetGlobalProps(Hierarchy, Props.Values[LoggerFactoryKey], Props.Values[DebugKey], Props.Values[ThresholdKey]); ConfigureRootLogger(Props, Hierarchy); ParseLoggersAndRenderers(Props, Hierarchy); LogLog.Debug(Format(FinishedConfigMsg, [ClassName])); end; const Bool: array [Boolean] of string = ('false', 'true'); { Parse the additivity option for a non-root logger. } procedure TLogPropertyConfigurator.ParseAdditivityForLogger( const Props: TStringList; const Logger: TLogLogger); var Value: string; begin Value := Props.Values[AdditiveKey + Logger.Name]; LogLog.Debug(Format(HandlingAdditivityMsg, [AdditiveKey + Logger.Name, Value])); { Touch additivity only if necessary } if Value <> '' then begin Logger.Additive := StrToBool(Value, True); LogLog.Debug(Format(SettingAdditivityMsg, [Logger.Name, Bool[Logger.Additive]])); end; end; { Parse entries for an appender and its constituents. } function TLogPropertyConfigurator.ParseAppender(const Props: TStringList; const AppenderName: string): ILogAppender; var Prefix, SubPrefix: string; ErrorHandler: ILogErrorHandler; Layout: ILogLayout; Filter: ILogFilter; Index: Integer; begin Result := AppenderGet(AppenderName); if Result <> nil then begin LogLog.Debug(Format(AppenderDefinedMsg, [AppenderName])); Exit; end; { Appender was not previously initialised. } Prefix := AppenderKey + AppenderName; Result := FindAppender(Props.Values[Prefix]); if Result = nil then begin LogLog.Error(Format(NoAppenderCreatedMsg, [AppenderName])); Exit; end; Result.Name := AppenderName; { Process any error handler entry. } SubPrefix := Prefix + ErrorHandlerKey; ErrorHandler := FindErrorHandler(Props.Values[SubPrefix]); if ErrorHandler <> nil then begin Result.ErrorHandler := ErrorHandler; LogLog.Debug(Format(ParsingErrorHandlerMsg, [AppenderName])); SetSubProps(SubPrefix, Props, ErrorHandler); LogLog.Debug(Format(EndErrorHandlerMsg, [AppenderName])); end; { Process any layout entry. } SubPrefix := Prefix + LayoutKey; Layout := FindLayout(Props.Values[SubPrefix]); if Layout <> nil then begin Result.Layout := Layout; LogLog.Debug(Format(ParsingLayoutMsg, [AppenderName])); SetSubProps(SubPrefix, Props, Layout); LogLog.Debug(Format(EndLayoutMsg, [AppenderName])); end; if Result.RequiresLayout and (Result.Layout = nil) then LogLog.Error(Format(LayoutRequiredMsg, [AppenderName])); { Process any filter entries. } SubPrefix := Prefix + FilterKey; for Index := 0 to Props.Count - 1 do if (Copy(Props.Names[Index], 1, Length(SubPrefix)) = SubPrefix) and (Pos('.', Copy(Props.Names[Index], Length(SubPrefix), 255)) = 0) then begin Filter := FindFilter(Props.Values[Props.Names[Index]]); if Filter = nil then Continue; Result.AddFilter(Filter); LogLog.Debug(Format(ParsingFiltersMsg, [AppenderName])); SetSubProps(Props.Names[Index], Props, Filter); LogLog.Debug(Format(EndFiltersMsg, [AppenderName])); end; { Set any options for the appender. } SetSubProps(Prefix, Props, Result); LogLog.Debug(Format(EndAppenderMsg, [AppenderName])); AppenderPut(Result); end; { Parse non-root elements, such as non-root loggers and renderers. } procedure TLogPropertyConfigurator.ParseLoggersAndRenderers( const Props: TStringList; const Hierarchy: TLogHierarchy); var Index: Integer; Key, Name: string; Logger: TLogLogger; begin for Index := 0 to Props.Count - 1 do begin Key := Props.Names[Index]; if Copy(Key, 1, Length(LoggerKey)) = LoggerKey then begin Name := Copy(Key, Length(LoggerKey) + 1, 255); Logger := Hierarchy.GetLogger(Name, FLoggerFactory); Logger.LockLogger; try ParseLogger(Props, Logger, Props.Values[Key]); ParseAdditivityForLogger(Props, Logger); finally Logger.UnlockLogger; end; end else if Copy(Key, 1, Length(RendererKey)) = RendererKey then AddRenderer(Hierarchy, Copy(Key, Length(RendererKey) + 1, 255), Props.Values[Key]); end; end; { This method must work for the root logger as well. } procedure TLogPropertyConfigurator.ParseLogger(const Props: TStringList; const Logger: TLogLogger; const Value: string); var Appender: ILogAppender; Index: Integer; Items: TStringList; begin LogLog.Debug(Format(ParsingLoggerMsg, [Logger.Name, Value])); Items := TStringList.Create; try { We must skip over ',' but not white space } Tokenise(Value, Items, ','); if Items.Count = 0 then Exit; { If value is not in the form ", appender.." or "", then we should set the level of the logger. } if Items[0] <> '' then begin LogLog.Debug(Format(LevelTokenMsg, [Items[0]])); { If the level value is inherited, set logger level value to nil. We also check that the user has not specified inherited for the root logger. } if (LowerCase(Items[0]) = InheritedLevel) and (Logger.Name <> InternalRootName) then Logger.Level := nil else Logger.Level := TLogLevel.GetLevel(LowerCase(Items[0])); LogLog.Debug(Format(SettingLevelMsg, [Logger.Name, Logger.Level.Name])); end; { Remove all existing appenders. They will be reconstructed below. } Logger.RemoveAllAppenders; for Index := 1 to Items.Count - 1 do begin if Items[Index] = '' then Continue; LogLog.Debug(Format(ParsingAppenderMsg, [Items[Index]])); Appender := ParseAppender(Props, Items[Index]); if Appender <> nil then Logger.AddAppender(Appender); end; finally Items.Free; end; end; { Registration ----------------------------------------------------------------} { Register a class as an implementor of a particular interface. } procedure RegisterClass(ClassType: TClass; InterfaceType: TGUID; InterfaceName: string; Names: TStringList; Classes: TClassList); var Index: Integer; begin if ClassType.GetInterfaceEntry(InterfaceType) = nil then raise ELogException.Create(Format(InterfaceNotImplMsg, [ClassType.ClassName, InterfaceName])); Index := Names.IndexOf(ClassType.ClassName); if Index = -1 then begin Names.Add(ClassType.ClassName); Classes.Add(ClassType); end else Classes[Index] := ClassType; end; { Create a new instance of a class implementing a particular interface. } function FindClass(ClassName: string; InterfaceType: TGUID; Names: TStringList; Classes: TClassList): IUnknown; var Index: Integer; Creator: ILogDynamicCreate; begin if ClassName = '' then Exit; Index := Names.IndexOf(ClassName); if Index = -1 then begin LogLog.Error(Format(NoClassMsg, [ClassName])); Result := nil; end else begin {$IFDEF DELPHI4} TClass(Classes[Index]).Create.GetInterface(InterfaceType, Result); {$ELSE} Classes[Index].Create.GetInterface(InterfaceType, Result); {$ENDIF} Result.QueryInterface(ILogDynamicCreate, Creator); if Creator <> nil then Creator.Init; end; end; var AppenderNames: TStringList; AppenderClasses: TClassList; procedure RegisterAppender(const Appender: TClass); begin RegisterClass(Appender, ILogAppender, 'ILogAppender', AppenderNames, AppenderClasses); end; function FindAppender(const ClassName: string): ILogAppender; begin Result := FindClass(ClassName, ILogAppender, AppenderNames, AppenderClasses) as ILogAppender; end; var LoggerFactoryNames: TStringList; LoggerFactoryClasses: TClassList; procedure RegisterLoggerFactory(const LoggerFactory: TClass); begin RegisterClass(LoggerFactory, ILogLoggerFactory, 'ILogLoggerFactory', LoggerFactoryNames, LoggerFactoryClasses); end; function FindLoggerFactory(const ClassName: string): ILogLoggerFactory; begin Result := FindClass(ClassName, ILogLoggerFactory, LoggerFactoryNames, LoggerFactoryClasses) as ILogLoggerFactory; end; var ErrorHandlerNames: TStringList; ErrorHandlerClasses: TClassList; procedure RegisterErrorHandler(const ErrorHandler: TClass); begin RegisterClass(ErrorHandler, ILogErrorHandler, 'ILogErrorHandler', ErrorHandlerNames, ErrorHandlerClasses); end; function FindErrorHandler(const ClassName: string): ILogErrorHandler; begin Result := FindClass(ClassName, ILogErrorHandler, ErrorHandlerNames, ErrorHandlerClasses) as ILogErrorHandler; end; var FilterNames: TStringList; FilterClasses: TClassList; procedure RegisterFilter(const Filter: TClass); begin RegisterClass(Filter, ILogFilter, 'ILogFilter', FilterNames, FilterClasses); end; function FindFilter(const ClassName: string): ILogFilter; begin Result := FindClass(ClassName, ILogFilter, FilterNames, FilterClasses) as ILogFilter; end; var LayoutNames: TStringList; LayoutClasses: TClassList; procedure RegisterLayout(const Layout: TClass); begin RegisterClass(Layout, ILogLayout, 'ILogLayout', LayoutNames, LayoutClasses); end; function FindLayout(const ClassName: string): ILogLayout; begin Result := FindClass(ClassName, ILogLayout, LayoutNames, LayoutClasses) as ILogLayout; end; var RenderedNames: TStringList; RenderedClasses: TClassList; { Register a class to be rendered. } procedure RegisterRendered(const Rendered: TClass); var Index: Integer; begin Index := RenderedNames.IndexOf(Rendered.ClassName); if Index = -1 then begin RenderedNames.Add(Rendered.ClassName); RenderedClasses.Add(Rendered); end else RenderedClasses[Index] := Rendered; end; { Return a reference to the named class. } function FindRendered(const ClassName: string): TClass; var Index: Integer; begin Index := RenderedNames.IndexOf(ClassName); if Index = -1 then begin LogLog.Error(Format(NoClassMsg, [ClassName])); Result := nil; end else {$IFDEF DELPHI4} Result := TClass(RenderedClasses[Index]); {$ELSE} Result := RenderedClasses[Index]; {$ENDIF} end; var RendererNames: TStringList; RendererClasses: TClassList; procedure RegisterRenderer(const Renderer: TClass); begin RegisterClass(Renderer, ILogRenderer, 'ILogRenderer', RendererNames, RendererClasses); end; function FindRenderer(const ClassName: string): ILogRenderer; begin Result := FindClass(ClassName, ILogRenderer, RendererNames, RendererClasses) as ILogRenderer; end; {$IFDEF LINUX} procedure EnterCriticalSection(var CS: TCriticalSection); begin CS.Enter; end; procedure LeaveCriticalSection(var CS: TCriticalSection); begin CS.Leave; end; procedure InitializeCriticalSection(var CS: TCriticalSection); begin CS := TCriticalSection.Create; end; procedure DeleteCriticalSection(var CS: TCriticalSection); begin CS.Free; end; function GetCurrentThreadID: Integer; begin Result := 0; end; procedure OutputDebugString(const S: PChar); begin WriteLn(Trim(string(S))); end; {$ENDIF} procedure LevelFree; var Index : Integer; begin for Index := 0 to Levels.Count - 1 do TObject(Levels[Index]).Free; end; procedure NDCFree; var Index : Integer; begin for Index := 0 to NDC.Count - 1 do NDC.Objects[Index].Free; NDC.Free; end; initialization { Timestamping. } StartTime := Now; { Synchronisation. } InitializeCriticalSection(CriticalNDC); { Standard levels. } Levels := TObjectList.Create; {$IFDEF DELPHI5_UP} Levels.OwnsObjects := True; {$ENDIF} All := TLogLevel.Create('all', AllValue); Trace := TLogLevel.Create('trace', TraceValue); Debug := TLogLevel.Create('debug', DebugValue); Info := TLogLevel.Create('info', InfoValue); Warn := TLogLevel.Create('warn', WarnValue); Error := TLogLevel.Create('error', ErrorValue); Fatal := TLogLevel.Create('fatal', FatalValue); Off := TLogLevel.Create('off', OffValue); { NDC stack. } NDC := TStringList.Create; NDC.Sorted := True; { Registration setup. } AppenderNames := TStringList.Create; AppenderClasses := TClassList.Create; ErrorHandlerNames := TStringList.Create; ErrorHandlerClasses := TClassList.Create; FilterNames := TStringList.Create; FilterClasses := TClassList.Create; LayoutNames := TStringList.Create; LayoutClasses := TClassList.Create; LoggerFactoryNames := TStringList.Create; LoggerFactoryClasses := TClassList.Create; RenderedNames := TStringList.Create; RenderedClasses := TClassList.Create; RendererNames := TStringList.Create; RendererClasses := TClassList.Create; { Registration of standard implementations. } RegisterLoggerFactory(TLogDefaultLoggerFactory); RegisterErrorHandler(TLogFallbackErrorHandler); RegisterErrorHandler(TLogOnlyOnceErrorHandler); RegisterLayout(TLogHTMLLayout); RegisterLayout(TLogPatternLayout); RegisterLayout(TLogSimpleLayout); RegisterFilter(TLogDenyAllFilter); RegisterFilter(TLogLevelMatchFilter); RegisterFilter(TLogLevelRangeFilter); RegisterFilter(TLogStringFilter); RegisterAppender(TLogFileAppender); RegisterAppender(TLogNullAppender); RegisterAppender(TLogODSAppender); RegisterAppender(TLogStreamAppender); RegisterAppender(TLogRollingFileAppender); { Standard logger factory and hierarchy. } DefaultLoggerFactory := TLogDefaultLOggerFactory.Create; DefaultLoggerFactory._AddRef; DefaultHierarchy := TLogHierarchy.Create(TLogRoot.Create(Error)); { Internal logging } LogLog := TLogLog.Create; LogLog.Hierarchy := DefaultHierarchy; finalization {$IFDEF DELPHI4} LevelFree; {$ENDIF} Levels.Free; DefaultLoggerFactory._Release; DefaultHierarchy.Free; { Registration cleanup. } AppenderNames.Free; AppenderClasses.Free; ErrorHandlerNames.Free; ErrorHandlerClasses.Free; FilterNames.Free; FilterClasses.Free; LayoutNames.Free; LayoutClasses.Free; LoggerFactoryNames.Free; LoggerFactoryClasses.Free; RenderedNames.Free; RenderedClasses.Free; RendererNames.Free; RendererClasses.Free; { NDC. } NDCFree; { Internal logging. } LogLog.Free; { Synchronisation. } DeleteCriticalSection(CriticalNDC); end.
30.69776
98
0.710619
47c24f345d558923f2584767d34e0c09f61c2eee
2,445
pas
Pascal
src/Horse.WebModule.pas
alantelles/horse
dd8a9eadf8222671bfa6537e52200358ed3b8261
[ "MIT" ]
633
2018-10-02T05:53:07.000Z
2022-03-31T11:32:47.000Z
src/Horse.WebModule.pas
alantelles/horse
dd8a9eadf8222671bfa6537e52200358ed3b8261
[ "MIT" ]
99
2018-10-02T18:46:30.000Z
2022-03-28T21:10:20.000Z
src/Horse.WebModule.pas
alantelles/horse
dd8a9eadf8222671bfa6537e52200358ed3b8261
[ "MIT" ]
191
2018-11-05T10:18:51.000Z
2022-03-31T11:34:47.000Z
unit Horse.WebModule; {$IF DEFINED(FPC)} {$MODE DELPHI}{$H+} {$ENDIF} interface uses {$IF DEFINED(FPC)} SysUtils, Classes, httpdefs, fpHTTP, fpWeb, {$ELSE} System.SysUtils, System.Classes, Web.HTTPApp, {$ENDIF} Horse.Core, Horse.Commons; type {$IF DEFINED(FPC)} THorseWebModule = class(TFPWebModule) procedure DoOnRequest(ARequest: TRequest; AResponse: TResponse; var AHandled: Boolean); override; {$ELSE} THorseWebModule = class(TWebModule) {$ENDIF} procedure HandlerAction(Sender: TObject; Request: {$IF DEFINED(FPC)}TRequest{$ELSE} TWebRequest {$ENDIF}; Response: {$IF DEFINED(FPC)}TResponse{$ELSE} TWebResponse {$ENDIF}; var Handled: Boolean); private FHorse: THorseCore; public property Horse: THorseCore read FHorse write FHorse; constructor Create(AOwner: TComponent); override; end; var {$IF DEFINED(FPC)} HorseWebModule: THorseWebModule; {$ELSE} WebModuleClass: TComponentClass = THorseWebModule; {$ENDIF} implementation uses Horse.HTTP, Horse.Exception; {%CLASSGROUP 'System.Classes.TPersistent'} {$IF DEFINED(FPC)} {$R Horse.WebModule.lfm} {$ELSE} {$R *.dfm} {$ENDIF} constructor THorseWebModule.Create(AOwner: TComponent); begin {$IF DEFINED(FPC)} inherited CreateNew(AOwner, 0); {$ELSE} inherited; {$ENDIF} FHorse := THorseCore.GetInstance; end; {$IF DEFINED(FPC)} procedure THorseWebModule.DoOnRequest(ARequest: {$IF DEFINED(FPC)}TRequest{$ELSE} TWebRequest {$ENDIF}; AResponse: {$IF DEFINED(FPC)}TResponse{$ELSE} TWebResponse {$ENDIF}; var AHandled: Boolean); begin HandlerAction(Self, ARequest, AResponse, AHandled); end; {$ENDIF} procedure THorseWebModule.HandlerAction(Sender: TObject; Request: {$IF DEFINED(FPC)}TRequest{$ELSE} TWebRequest {$ENDIF}; Response: {$IF DEFINED(FPC)}TResponse{$ELSE} TWebResponse {$ENDIF}; var Handled: Boolean); var LRequest: THorseRequest; LResponse: THorseResponse; begin Handled := true; LRequest := THorseRequest.Create(Request); LResponse := THorseResponse.Create(Response); try try FHorse.Routes.Execute(LRequest, LResponse) except on E: Exception do if not E.InheritsFrom(EHorseCallbackInterrupted) then raise; end; finally if LRequest.Body<TObject> = LResponse.Content then LResponse.Content(nil); LRequest.Free; LResponse.Free; end; end; {$IF DEFINED(FPC)} initialization RegisterHTTPModule(THorseWebModule); {$ENDIF} end.
24.94898
202
0.718609
61198ca5cced472487b4dbf5f0be6842e849ac18
4,137
dpr
Pascal
tutorial3/tutorial3.dpr
AntonAngeloff/DX11_Examples
ac0dec9a59ea276a7286a3a3dcf4a1b836025711
[ "MIT" ]
5
2016-08-03T05:39:27.000Z
2020-06-06T22:06:12.000Z
tutorial3/tutorial3.dpr
AntonAngeloff/DX11_Examples
ac0dec9a59ea276a7286a3a3dcf4a1b836025711
[ "MIT" ]
null
null
null
tutorial3/tutorial3.dpr
AntonAngeloff/DX11_Examples
ac0dec9a59ea276a7286a3a3dcf4a1b836025711
[ "MIT" ]
2
2017-04-25T13:06:06.000Z
2020-09-16T00:57:44.000Z
program tutorial3; { DirectX 11 - Tutorial #3 Added from previous tutorial: - We have created a model class to manage the lifecycle of the vertex and index buffer. - We created a constructor for the model class to generate a simple quad mesh. - We created a shader program for filling using a texture - We load 24bit bitmap from file, then convert it to 32bit and load it as a texture. TODO: - Nothing so far } {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} uses Windows, Messages, SysUtils, Renderer, Shader, model; const APP_NAME = 'Direct3D 11 - Tutorial #3'; APP_SCREEN_WIDTH = 800; APP_SCREEN_HEIGHT = 600; var app_hinstance, app_hwnd: HWND; screen_width, screen_height: Integer; Renderer: TDXRenderer; Function OnKeyDown(vkey: DWORD): LRESULT; Begin If vkey = VK_ESCAPE then Begin //Post WM_QUIT message PostMessage(app_hwnd, WM_QUIT, 0, 0); End; Result := 0; End; Function WndProc(window_handle:HWND; umessage:UINT; w_param:WPARAM; l_param:LPARAM): LRESULT; stdcall; Begin case umessage of //Check if window is destroyed WM_DESTROY: Begin PostQuitMessage(0); Exit(0); End; //Check if window is being closed WM_CLOSE: Begin PostQuitMessage(0); Exit(0); end; //Handle key down WM_KEYDOWN: Begin Result := OnKeyDown(w_param); Exit; End else Begin Result := DefWindowProc(window_handle, umessage, w_param, l_param); Exit; end; end; Result := E_FAIL; End; Function InitializeWindow: HRESULT; var wnd_class: TWNDClassEx; pos_x, pos_y: Integer; Begin //Get the instance of this application app_hinstance := GetModuleHandle(nil); //Setup the windows class with default settings. With wnd_class do Begin style := CS_HREDRAW or CS_VREDRAW or CS_OWNDC; lpfnWndProc := @WndProc; cbClsExtra := 0; cbWndExtra := 0; hInstance := app_hinstance; hIcon := LoadIcon(0, IDI_WINLOGO); hIconSm := wnd_class.hIcon; hCursor := LoadCursor(0, IDC_ARROW); hbrBackground := GetStockObject(BLACK_BRUSH); lpszMenuName := nil; lpszClassName := APP_NAME; cbSize := sizeof(WNDCLASSEX); end; //Register window class RegisterClassEx(wnd_class); //Decide window resolution screen_width := APP_SCREEN_WIDTH; screen_height := APP_SCREEN_HEIGHT; //Place window on center of the screen pos_x := (GetSystemMetrics(SM_CXSCREEN) - screen_width) div 2; pos_y := (GetSystemMetrics(SM_CYSCREEN) - screen_height) div 2; //Create window app_hwnd := CreateWindowEx( WS_EX_APPWINDOW, APP_NAME, APP_NAME, WS_CLIPSIBLINGS or WS_CLIPCHILDREN or WS_POPUP or WS_OVERLAPPED or WS_CAPTION or WS_SYSMENU, pos_x, pos_y, screen_width, screen_height, 0, 0, app_hinstance, nil ); //Show and set focus ShowWindow(app_hwnd, SW_SHOW); SetForegroundWindow(app_hwnd); SetFocus(app_hwnd); Result := S_OK; End; Function UninitializeWindow: HRESULT; Begin //Destroy window and unregister class DestroyWindow(app_hwnd); UnregisterClass(APP_NAME, app_hinstance); Result := S_OK; End; Procedure AppLoop; var msg: TMSG; Begin //Initialize message record {$HINTS off} FillChar(msg, SizeOf(msg), 0); {$HINTS on} While true do Begin //Handle message if PeekMessage(msg, 0, 0, 0, PM_REMOVE) then Begin TranslateMessage(msg); DispatchMessage(msg); end; //Terminate loop if we have received WM_QUIT if msg.message = WM_QUIT then Break; //Draw here Renderer.Clear(D3DColor4f(0.0, 0.15, 0.5, 1)); Renderer.Render; Renderer.Present; end; End; begin //Initialize window and acquire hWND InitializeWindow; //Create our renderer class, which will initialize Direct3D 11 Renderer := TDXRenderer.Create(app_hwnd, screen_width, screen_height); //Enter message handling loop AppLoop; //Destroy our renderer class (and thus uninitialize Direct3D 11) Renderer.Free; //Destroy window UninitializeWindow; end.
21.659686
102
0.678028
83d575592573fc6c6f36a81d4607db64b61150f9
735
pas
Pascal
Win11_Delphi11/VCLControlColorsB/VCLColorButtonsUnit1.pas
marcocantu/DelphiSessions
c3fe2ab2eb8619343179b8474ae728c8b0f305db
[ "MIT" ]
44
2017-05-30T20:54:06.000Z
2022-02-25T16:44:23.000Z
Win11_Delphi11/VCLControlColorsB/VCLColorButtonsUnit1.pas
marcocantu/DelphiSessions
c3fe2ab2eb8619343179b8474ae728c8b0f305db
[ "MIT" ]
null
null
null
Win11_Delphi11/VCLControlColorsB/VCLColorButtonsUnit1.pas
marcocantu/DelphiSessions
c3fe2ab2eb8619343179b8474ae728c8b0f305db
[ "MIT" ]
19
2017-07-25T10:03:13.000Z
2021-10-17T11:40:38.000Z
unit VCLColorButtonsUnit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.WinXCtrls, Vcl.StdCtrls, Vcl.Imaging.jpeg; type TForm1 = class(TForm) Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; Button5: TButton; Button6: TButton; Button7: TButton; Button8: TButton; RelativePanel1: TRelativePanel; Image1: TImage; Button9: TButton; Button10: TButton; Button11: TButton; Label1: TLabel; private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} end.
18.375
98
0.692517
47204c8dede062db676de446c34f74af3bea96f4
228
pas
Pascal
CAT/tests/09. exceptions/try_except_1.pas
SkliarOleksandr/NextPascal
4dc26abba6613f64c0e6b5864b3348711eb9617a
[ "Apache-2.0" ]
19
2018-10-22T23:45:31.000Z
2021-05-16T00:06:49.000Z
CAT/tests/09. exceptions/try_except_1.pas
SkliarOleksandr/NextPascal
4dc26abba6613f64c0e6b5864b3348711eb9617a
[ "Apache-2.0" ]
1
2019-06-01T06:17:08.000Z
2019-12-28T10:27:42.000Z
CAT/tests/09. exceptions/try_except_1.pas
SkliarOleksandr/NextPascal
4dc26abba6613f64c0e6b5864b3348711eb9617a
[ "Apache-2.0" ]
6
2018-08-30T05:16:21.000Z
2021-05-12T20:25:43.000Z
unit try_except_1; interface implementation uses System; var G: Int32; procedure Test; begin try //raise Exception.Create('test'); except G := 111; end; end; initialization Test(); finalization end.
9.12
39
0.666667
47a89b5177336f597f394447b65dfacfda435098
187
pas
Pascal
Test/DelegateLib/method delegate calling factory autofree.pas
synapsea/DW-Script
b36c2e57f0285c217f8f0cae8e4e158d21127163
[ "Condor-1.1" ]
1
2022-02-18T22:14:44.000Z
2022-02-18T22:14:44.000Z
Test/DelegateLib/method delegate calling factory autofree.pas
synapsea/DW-Script
b36c2e57f0285c217f8f0cae8e4e158d21127163
[ "Condor-1.1" ]
null
null
null
Test/DelegateLib/method delegate calling factory autofree.pas
synapsea/DW-Script
b36c2e57f0285c217f8f0cae8e4e158d21127163
[ "Condor-1.1" ]
null
null
null
uses Factory; procedure DoOnTest(Sender: TObject); begin Stuff.DoIt(Sender.ClassName); // PrintLn(Sender.ClassName); end; var Foo := TFoo.Create; Foo.OnTest := DoOnTest; Foo.Test;
14.384615
36
0.721925
f15f8a35957eaed27d927846b4529fa4f44ee27d
1,354
pas
Pascal
test/code/ooFS.Archive.InUse_test.pas
VencejoSoftware/ooFileSystem
fd1e8937326e648bfb371f7d9f13edcb0bad4ad6
[ "BSD-3-Clause" ]
null
null
null
test/code/ooFS.Archive.InUse_test.pas
VencejoSoftware/ooFileSystem
fd1e8937326e648bfb371f7d9f13edcb0bad4ad6
[ "BSD-3-Clause" ]
null
null
null
test/code/ooFS.Archive.InUse_test.pas
VencejoSoftware/ooFileSystem
fd1e8937326e648bfb371f7d9f13edcb0bad4ad6
[ "BSD-3-Clause" ]
2
2019-11-21T03:19:12.000Z
2021-01-26T04:52:12.000Z
{ Copyright (c) 2016, Vencejo Software Distributed under the terms of the Modified BSD License The full license is distributed with this software } unit ooFS.Archive.InUse_test; interface uses Classes, SysUtils, ooFS.Archive, ooFS.Archive.InUse, ooFSUtils, {$IFDEF FPC} fpcunit, testregistry {$ELSE} TestFramework {$ENDIF}; type TFSArchiveInUseTest = class sealed(TTestCase) private _Archive: IFSArchive; protected procedure SetUp; override; procedure TearDown; override; published procedure IsNotInUse; procedure IsInUse; end; implementation procedure TFSArchiveInUseTest.IsInUse; var NewTextFile: TextFile; begin AssignFile(NewTextFile, _Archive.Path); try Reset(NewTextFile); CheckTrue(TFSArchiveInUse.New(_Archive).Execute); finally CloseFile(NewTextFile); end; end; procedure TFSArchiveInUseTest.IsNotInUse; begin CheckFalse(TFSArchiveInUse.New(_Archive).Execute); end; procedure TFSArchiveInUseTest.SetUp; begin inherited; _Archive := TFSArchive.New(nil, IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'temp_file_to_Copy.txt'); CreateTempArchive(_Archive.Path); end; procedure TFSArchiveInUseTest.TearDown; begin inherited; DeleteArchive(_Archive.Path); end; initialization RegisterTest(TFSArchiveInUseTest {$IFNDEF FPC}.Suite {$ENDIF}); end.
19.342857
120
0.768095
f1e467561714e2581fa8c8654c50dfdf4ccc4f7a
79,915
pas
Pascal
reference-platform/r4/FHIRMetaModel.pas
novakjf2000/FHIRServer
a47873825e94cd6cdfa1a077f02e0960098bbefa
[ "BSD-3-Clause" ]
1
2018-01-08T06:40:02.000Z
2018-01-08T06:40:02.000Z
reference-platform/r4/FHIRMetaModel.pas
novakjf2000/FHIRServer
a47873825e94cd6cdfa1a077f02e0960098bbefa
[ "BSD-3-Clause" ]
null
null
null
reference-platform/r4/FHIRMetaModel.pas
novakjf2000/FHIRServer
a47873825e94cd6cdfa1a077f02e0960098bbefa
[ "BSD-3-Clause" ]
null
null
null
unit FHIRMetaModel; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) 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 HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } {$IFNDEF FHIR4} This is the dstu3 version of the FHIR code {$ENDIF} interface uses SysUtils, Classes, Variants, Math, AdvObjects, AdvGenerics, AdvStreams, AdvBuffers, AdvVclStreams, AdvMemories, ParserSupport, MXML, XmlBuilder, AdvXmlBuilders, AdvJson, DateSupport, TextUtilities, FHIRBase, FHIRTypes, FHIRResources, FHIRContext, FHIRUtilities, FHIRSupport, FHIRXHtml; type TFHIRMMSpecialElement = (fsecNil, fsecCONTAINED, fsecBUNDLE_ENTRY, fsecBUNDLE_OUTCOME, fsecPARAMETER); TFHIRMMProperty = class (TAdvObject) private FContext : TFHIRWorkerContext; FDefinition : TFHIRElementDefinition; FStructure : TFHIRStructureDefinition; FCanBePrimitive : integer; function GetName: string; public Constructor create(context : TFHIRWorkerContext; definition : TFHIRElementDefinition; structure : TFHIRStructureDefinition); Destructor Destroy; override; function link : TFHIRMMProperty; overload; property context : TFHIRWorkerContext read FContext; property definition : TFHIRElementDefinition read FDefinition; property structure : TFHIRStructureDefinition read FStructure; property name : string read GetName; function getType : string; overload; function typeCode : String; function getType(elementName : String) : string; overload; function hasType(elementName : String) : boolean; function isPrimitive(name : String) : boolean; function isResource : boolean; function isList : boolean; function getScopedPropertyName : String; function getNamespace : string; function IsLogicalAndHasPrimitiveValue(name : String) : boolean; function isChoice : boolean; function getChildProperties(elementName, statedType : String): TAdvList<TFHIRMMProperty>; overload; function getChildProperties(type_ : TFHIRTypeDetails) : TAdvList<TFHIRMMProperty>; overload; function getChild(elementName, childName : String) : TFHIRMMProperty; overload; function getChild(name : String; type_ : TFHIRTypeDetails) : TFHIRMMProperty; overload; function specialElementClass : TFHIRMMSpecialElement; end; TFHIRMMElement = class; TProfileUsage = class (TAdvObject) private FIsChecked: boolean; FDefn: TFHIRStructureDefinition; procedure SetDefn(const Value: TFHIRStructureDefinition); public destructor Destroy; override; function Link : TProfileUsage; overload; property checked : boolean read FIsChecked write FIsChecked; property defn : TFHIRStructureDefinition read FDefn write SetDefn; end; TProfileUsages = class (TAdvObject) private FEntries : TAdvList<TProfileUsage>; FIsProcessed: boolean; function GetIsEmpty: boolean; public constructor Create; override; destructor Destroy; override; procedure addProfile(sd : TFHIRStructureDefinition); property isProcessed : boolean read FisProcessed write FisProcessed; property isEmpty : boolean read GetIsEmpty; property entries : TAdvList<TProfileUsage> read FEntries; end; {* This class represents the reference model of FHIR * * A resource is nothing but a set of elements, where every element has a * name, maybe a stated type, maybe an id, and either a value or child elements * (one or the other, but not both or neither) *} TFHIRMMElement = class (TFHIRObject) private FComments : TStringList;// not relevant for production, but useful in documentation FName : String; FType : String; FValue : String; FIndex : integer; FChildren : TAdvList<TFHIRMMElement>; FProperty : TFHIRMMProperty; FElementProperty : TFHIRMMProperty; // this is used when special is set to true - it tracks the underlying element property which is used in a few places FlocStart: TSourceLocation; FlocEnd: TSourceLocation; FSpecial : TFHIRMMSpecialElement; FXhtml : TFhirXHtmlNode; // if this is populated, then value will also hold the string representation // validation support FProfiles : TProfileUsages; function GetType: String; function GetChildren: TAdvList<TFHIRMMElement>; function GetComments: TStringList; procedure SetXhtml(const Value: TFhirXHtmlNode); function GetProfiles: TProfileUsages; protected Procedure ListProperties(oList : TFHIRPropertyList; bInheritedProperties, bPrimitiveValues : Boolean); Override; public constructor Create(name : String); overload; constructor Create(name : String; prop : TFHIRMMProperty); overload; constructor Create(name : String; prop : TFHIRMMProperty; type_, value : String); overload; Destructor Destroy; override; function link : TFHIRMMElement; overload; procedure updateProperty(prop : TFHIRMMProperty; special : TFHIRMMSpecialElement; elementProp : TFHIRMMProperty); property name : String read FName; property type_ : String read GetType write FType; property value : String read FValue write FValue; property children : TAdvList<TFHIRMMElement> read GetChildren; property comments : TStringList read GetComments; property prop : TFHIRMMProperty read FProperty; property elementProp : TFHIRMMProperty read FElementProperty; property index : integer read FIndex write FIndex; property special : TFHIRMMSpecialElement read FSpecial; property LocStart : TSourceLocation read FLocStart; property LocEnd : TSourceLocation read FLocEnd; property xhtml : TFhirXHtmlNode read FXhtml write SetXhtml; property profiles : TProfileUsages read GetProfiles; function hasChildren : boolean; function hasComments : boolean; function hasValue : boolean; function hasIndex : boolean; procedure GetChildrenByName(name : String; children : TFHIRSelectionList); override; procedure getNamedChildrenWithWildcard(name : String; children : TAdvList<TFHIRMMElement>); function getNamedChild(name : String) : TFHIRMMElement; procedure getNamedChildren(name : String; list : TAdvList<TFHIRMMElement>); function getNamedChildValue(name : String) : string; procedure numberChildren; function getChildValue(name : String) : string; procedure SetChildValue(name, value : String); function hasType : boolean; function markLocation(start, end_ : TSourceLocation) : TFHIRMMElement; function isPrimitive : boolean; override; function isResource : boolean; function hasPrimitiveValue : boolean; override; function fhirType : String; override; function primitiveValue : String; override; procedure getProperty(name : String; checkValid : boolean; list : TAdvList<TFHIRObject>); override; procedure listChildren(list : TAdvList<TFHIRMMProperty>); function isEmpty : boolean; override; end; TFHIRValidationPolicy = (fvpNONE, fvpQUICK, fvpEVERYTHING); TFHIRMMParserBase = class (TAdvObject) protected FContext : TFHIRWorkerContext; FPolicy : TFHIRValidationPolicy; FErrors : TFhirOperationOutcomeIssueList; function getChildProperties(prop : TFHIRMMProperty; elementName, statedType : String) : TAdvList<TFHIRMMProperty>; function getDefinition(line, col : integer; ns, name : String) : TFHIRStructureDefinition; overload; function getDefinition(line, col : integer; name : String) : TFHIRStructureDefinition; overload; public constructor create(context : TFHIRWorkerContext); destructor Destroy; override; procedure setupValidation(policy : TFHIRValidationPolicy; errors : TFhirOperationOutcomeIssueList); procedure logError(line, col : integer; path : String; type_ : TFhirIssueTypeEnum; message : String; level : TFhirIssueSeverityEnum); function parse(stream : TStream) : TFHIRMMElement; overload; virtual; abstract; function parse(stream : TAdvStream) : TFHIRMMElement; overload; virtual; function parse(buffer : TAdvBuffer) : TFHIRMMElement; overload; virtual; procedure compose(e : TFHIRMMElement; stream : TStream; pretty : boolean; base : String); overload; virtual; abstract; end; TFHIRMMManager = class (TAdvObject) public class function parseFile(context : TFHIRWorkerContext; filename : string; inputFormat : TFhirFormat) : TFHIRMMElement; class function parse(context : TFHIRWorkerContext; source : TStream; inputFormat : TFhirFormat) : TFHIRMMElement; class procedure compose(context : TFHIRWorkerContext; e : TFHIRMMElement; destination : TStream; outputFormat : TFhirFormat; pretty : boolean; base : String = ''); class procedure composeFile(context : TFHIRWorkerContext; e : TFHIRMMElement; filename : String; outputFormat : TFhirFormat; pretty : boolean; base : String = ''); class function makeParser(context : TFHIRWorkerContext; format : TFhirFormat) : TFHIRMMParserBase; end; TFHIRMMXmlParser = class (TFHIRMMParserBase) private function line(node : TMXmlElement) : integer; function col(node : TMXmlElement) : integer; function start(node : TMXmlElement) : TSourceLocation; function end_(node : TMXmlElement) : TSourceLocation; function pathPrefix(ns : String) : String; procedure checkRootNode(document : TMXmlDocument); function empty(element : TMXmlElement) : boolean ; procedure checkElement(element : TMXmlElement; path : String; prop : TFHIRMMProperty); function convertForDateFormat(fmt, av : String) : String; procedure reapComments(element : TMXmlElement; context : TFHIRMMElement); function getElementProp(props : TAdvList<TFHIRMMProperty>; nodeName : String) : TFHIRMMProperty; function getAttrProp(props : TAdvList<TFHIRMMProperty>; nodeName : String) : TFHIRMMProperty; function getTextProp(props : TAdvList<TFHIRMMProperty>) : TFHIRMMProperty; function isAttr(prop : TFHIRMMProperty) : boolean; function isText(prop : TFHIRMMProperty) : boolean; procedure parseChildren(path : String; node : TMXmlElement; context : TFHIRMMElement); procedure parseResource(s : String; container : TMXmlElement; parent : TFHIRMMElement; elementProperty : TFHIRMMProperty); procedure composeElement(xml : TXmlBuilder; element : TFHIRMMElement; elementName : String); public destructor Destroy; override; function parse(stream : TStream) : TFHIRMMElement; overload; override; function parse(document : TMXmlDocument) : TFHIRMMElement; overload; function parse(element : TMXmlElement) : TFHIRMMElement; overload; function parse(element : TMXmlElement; sd : TFHIRStructureDefinition) : TFHIRMMElement; overload; procedure compose(e : TFHIRMMElement; stream : TStream; pretty : boolean; base : String); override; end; TFHIRMMJsonParser = class (TFHIRMMParserBase) private json : TJSONWriter; procedure checkObject(obj : TJsonObject; path : String); procedure reapComments(obj : TJsonObject; context : TFHIRMMElement); procedure parseChildren(path : String; obj : TJsonObject; context : TFHIRMMElement; hasResourceType : boolean); procedure parseChildComplex(path : String; obj: TJsonObject; context : TFHIRMMElement; processed : TAdvStringSet; prop : TFHIRMMProperty; name : String); procedure parseChildComplexInstance(path : String; obj: TJsonObject; context : TFHIRMMElement; prop : TFHIRMMProperty; name : String; e : TJsonNode); procedure parseChildPrimitive(path : String; obj: TJsonObject; context : TFHIRMMElement; processed : TAdvStringSet; prop : TFHIRMMProperty; name : String); procedure parseChildPrimitiveInstance(npath : String; obj: TJsonObject; context : TFHIRMMElement; processed : TAdvStringSet; prop : TFHIRMMProperty; name : String; main, fork : TJsonNode); procedure parseResource(path : String; obj: TJsonObject; parent : TFHIRMMElement; elementProperty : TFHIRMMProperty); procedure composeElement(e : TFHIRMMElement); overload; procedure composeElement(path : String; e : TFHIRMMElement; done : TAdvStringSet; child : TFHIRMMElement); overload; procedure composeList(path : String; list : TFHIRSelectionList); procedure primitiveValue(name : String; item : TFHIRMMElement); procedure composeElement(path : String; element : TFHIRMMElement); overload; public function parse(stream : TStream) : TFHIRMMElement; overload; override; function parse(obj : TJsonObject) : TFHIRMMElement; overload; procedure compose(e : TFHIRMMElement; stream : TStream; pretty : boolean; base : String); overload; override; procedure compose(e : TFHIRMMElement; stream : TAdvStream; pretty : boolean; base : String); overload; end; TFHIRMMResourceLoader = class (TFHIRMMParserBase) private procedure parseChildren(path : String; obj : TFHIRObject; context : TFHIRMMElement); public function parse(r : TFHIRResource) : TFHIRMMElement; overload; function parse(r : TFHIRObject) : TFHIRMMElement; overload; procedure compose(e : TFHIRMMElement; stream : TStream; pretty : boolean; base : String); overload; override; end; TFHIRCustomResource = class (TFHIRResource) private FRoot: TFHIRMMElement; procedure SetRoot(const Value: TFHIRMMElement); protected Procedure GetChildrenByName(child_name : string; list : TFHIRSelectionList); override; Procedure ListProperties(oList : TFHIRPropertyList; bInheritedProperties, bPrimitiveValues : Boolean); Override; function GetResourceType : TFhirResourceType; override; public constructor Create(root : TFHIRMMElement); Destructor Destroy; override; function isMetaDataBased : boolean; override; class function CreateFromBase(context : TFHIRWorkerContext; base : TFHIRObject) : TFHIRCustomResource; property Root : TFHIRMMElement read FRoot write SetRoot; procedure Assign(oSource : TAdvObject); override; function Link : TFHIRCustomResource; overload; function Clone : TFHIRCustomResource; overload; procedure setProperty(propName : string; propValue : TFHIRObject); override; function createPropertyValue(propName : string) : TFHIRObject; override; function fhirType : string; override; function equalsDeep(other : TFHIRObject) : boolean; override; function equalsShallow(other : TFHIRObject) : boolean; override; procedure getProperty(name : String; checkValid : boolean; list : TAdvList<TFHIRObject>); override; end; implementation uses StringSupport, FHIRConstants, FHIRProfileUtilities; function tail(path : String) : string; begin if path.contains('.') then result := path.substring(path.lastIndexOf('.')+1) else result := path; end; function lowFirst(t: String): String; begin result := t.ToLower.substring(0, 1)+t.substring(1); end; { TFHIRMMProperty } constructor TFHIRMMProperty.create(context : TFHIRWorkerContext; definition: TFHIRElementDefinition; structure: TFHIRStructureDefinition); begin inherited create; FContext := context; FDefinition := definition; FStructure := structure; end; destructor TFHIRMMProperty.Destroy; begin FContext.Free; FDefinition.Free; FStructure.Free; inherited; end; function TFHIRMMProperty.link: TFHIRMMProperty; begin result := TFHIRMMProperty(inherited link); end; function TFHIRMMProperty.specialElementClass: TFHIRMMSpecialElement; begin if (structure.id = 'Parameters') then result := fsecPARAMETER else if (structure.id = 'Bundle') and (getName() = 'resource') then result := fsecBUNDLE_ENTRY else if (structure.id = 'Bundle') and (getName() = 'outcome') then result := fsecBUNDLE_OUTCOME else if (getName() = 'contained') then result := fsecCONTAINED else raise DefinitionException.create('Unknown resource containing a native resource: '+definition.Id); end; function TFHIRMMProperty.typeCode: String; var tr : TFHIRElementDefinitionType; begin result := ''; for tr in definition.type_List do begin if result <> '' then result := result + '|'; result := result + tr.code; end; end; function TFHIRMMProperty.GetName: string; begin result := definition.Path.substring(definition.Path.lastIndexOf('.')+1); end; function TFHIRMMProperty.getType: string; var i : integer; begin if (definition.Type_List.count() = 0) then result := '' else if (definition.type_List.count() > 1) then begin result := definition.type_List[0].Code; for i := 1 to definition.type_List.count - 1 do if (result <> definition.type_List[i].Code) then raise Exception.create('logic error, gettype when types > 1'); end else result := definition.type_List[0].Code; end; function TFHIRMMProperty.getType(elementName: String): string; var t, name, tail, s : String; all : boolean; tr : TFhirElementDefinitionType; ed, d : TFhirElementDefinition; begin if (not definition.path.contains('.')) then exit(definition.path); ed := definition; if (definition.ContentReference <> '') then begin if (not definition.contentReference.startsWith('#')) then raise Exception.create('not handled yet'); ed := nil; s := definition.ContentReference.substring(1); for d in structure.snapshot.elementList do begin if (d.Id <> '') and (d.Id = s) then ed := d; end; if (ed = nil) then raise Exception.create('Unable to resolve '+definition.contentReference+' at '+definition.path+' on '+structure.Url); end; if (definition.type_List.count() = 0) then result := '' else if (definition.type_list.count() > 1) then begin t := definition.type_list[0].Code; all := true; for tr in definition.type_list do begin if (t <> tr.Code) then all := false; end; if (all) then result := t else begin tail := definition.Path.substring(definition.Path.lastIndexOf('.')+1); if (tail.endsWith('[x]') and elementName.startsWith(tail.substring(0, tail.length-3))) then begin name := elementName.substring(tail.length-3); if isPrimitiveType(lowFirst(name)) then result := lowFirst(name) else result := name; end else raise Exception.create('logic error, gettype when types > 1, name mismatch'); end; end else result := definition.type_list[0].Code; end; function TFHIRMMProperty.hasType(elementName: String): boolean; var t, tail : String; all : boolean; tr : TFhirElementDefinitionType; begin if (definition.Type_list.count = 0) then result := false else if (definition.Type_list.count > 1) then begin t := definition.Type_list[0].Code; all := true; for tr in definition.type_List do begin if (t <> tr.Code) then all := false; end; if (all) then result := true else begin tail := definition.Path.substring(definition.Path.lastIndexOf('.')+1); if (tail.endsWith('[x]') and elementName.startsWith(tail.substring(0, tail.length-3))) then begin // name := elementName.substring(tail.length-3); result := true; end else result := false; end; end else result := true; end; function TFHIRMMProperty.isPrimitive(name : String): boolean; var sd : TFHIRStructureDefinition; begin sd := TFHIRStructureDefinition(context.fetchResource(frtStructureDefinition, 'http://hl7.org/fhir/StructureDefinition/'+name)); try result := (sd <> nil) and (sd.Kind = StructureDefinitionKindPRIMITIVETYPE); finally sd.free; end; end; function TFHIRMMProperty.isResource: boolean; begin if (definition.type_List.count > 0) then result := (definition.type_list.count = 1) and (('Resource' = definition.Type_List[0].Code) or ('DomainResource' = definition.Type_list[0].Code)) else result := not definition.Path.contains('.') and (structure.Kind = StructureDefinitionKindRESOURCE); end; function TFHIRMMProperty.isList: boolean; begin result := definition.Max <> '1' end; function TFHIRMMProperty.IsLogicalAndHasPrimitiveValue(name: String): boolean; var sd : TFhirStructureDefinition; ed : TFhirElementDefinition; begin // if (FcanBePrimitive <> 0) then // result := FcanBePrimitive > 0; FcanBePrimitive := -1; if (structure.Kind <> StructureDefinitionKindLOGICAL) then exit(false); if (not hasType(name)) then exit(false); sd := context.getStructure(structure.Url.substring(0, structure.Url.lastIndexOf('/')+1)+getType(name)); try if (sd <> nil) and (sd.Kind = StructureDefinitionKindPRIMITIVETYPE) then exit(true); if (sd = nil) or (sd.Kind <> StructureDefinitionKindLOGICAL) then exit(false); for ed in sd.Snapshot.elementList do if (ed.Path = sd.Id+'.value') and (ed.type_List.count = 1) and isPrimitive(ed.type_List[0].Code) then begin FcanBePrimitive := 1; exit(true); end; result := false; finally sd.free; end; end; function TFHIRMMProperty.getScopedPropertyName: String; begin result := definition.Base.Path; end; function TFHIRMMProperty.getNamespace: string; begin if definition.hasExtension('http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace') then result := definition.getExtensionString('http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace') else if structure.hasExtension('http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace') then result := definition.getExtensionString('http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace') else result := FHIR_NS; end; function TFHIRMMProperty.isChoice: boolean; var tn : String; tr : TFhirElementDefinitionType; begin result := false; if (definition.type_List.count > 1) then begin tn := definition.type_List[0].Code; for tr in definition.type_List do if (tr.Code <> tn) then exit(true); end; end; function TFHIRMMProperty.getChildProperties(elementName, statedType : String): TAdvList<TFHIRMMProperty>; var ed, child : TFHIRElementDefinition; sd : TFHIRStructureDefinition; children : TFHIRElementDefinitionList; t : String; all, ok : boolean; tr : TFhirElementDefinitionType; begin ed := definition; sd := structure; children := getChildMap(sd, ed); try if (children.isEmpty()) then begin // ok, find the right definitions t := ''; if (ed.Type_List.count = 1) then t := ed.type_list[0].Code else if (ed.type_list.count = 0) then raise DefinitionException.create('types == 0, and no children found') else begin t := ed.type_list[0].code; all := true; for tr in ed.type_list do begin if (tr.Code <> t) then begin all := false; break; end; end; if (not all) then begin // ok, it's polymorphic if (PropertyRepresentationTYPEATTR in ed.Representation) then begin t := statedType; if (t = '') and ed.hasExtension('http://hl7.org/fhir/StructureDefinition/elementdefinition-defaulttype') then t := ed.getExtensionString('http://hl7.org/fhir/StructureDefinition/elementdefinition-defaulttype'); ok := false; for tr in ed.type_list do if (tr.Code = t) then ok := true; if (not ok) then raise DefinitionException.create('Type "'+t+'" is not an acceptable type for "'+elementName+'" on property '+definition.path); end else begin t := elementName.substring(tail(ed.path).length - 3); if (isPrimitive(lowFirst(t))) then t := lowFirst(t); end; end; end; if ('xhtml' <> t) then begin sd := TFHIRStructureDefinition(context.fetchResource(frtStructureDefinition, 'http://hl7.org/fhir/StructureDefinition/'+t)); try if (sd = nil) then raise DefinitionException.create('Unable to find class "'+t+'" for name "'+elementName+'" on property '+definition.path); children.free; children := getChildMap(sd, sd.snapshot.elementList[0]); finally sd.free; end; end; end; result := TAdvList<TFHIRMMProperty>.create; for child in children do result.add(TFHIRMMProperty.create(context.Link, child.Link, sd.Link)); finally children.free; end; end; function TFHIRMMProperty.getChildProperties(type_ : TFHIRTypeDetails) : TAdvList<TFHIRMMProperty>; var ed, child : TFHIRElementDefinition; children : TFHIRElementDefinitionList; sd : TFHIRStructureDefinition; t : string; all : boolean; tr : TFhirElementDefinitionType; begin all := false; ed := definition; sd := structure; children := getChildMap(sd, ed); try if (children.isEmpty()) then begin // ok, find the right definitions t := ''; if (ed.Type_List.count = 1) then t := ed.type_list[0].Code else if (ed.type_list.count = 0) then raise DefinitionException.create('types == 0, and no children found') else begin t := ed.type_list[0].code; all := true; for tr in ed.type_list do begin if (tr.Code <> t) then begin all := false; break; end; end; end; if (not all) then t := type_.type_; end; if ('xhtml' <> t) then begin sd := TFHIRStructureDefinition(context.fetchResource(frtStructureDefinition, 'http://hl7.org/fhir/StructureDefinition/'+t)); if (sd = nil) then raise DefinitionException.create('Unable to find class "'+t+'" for name "'+ed.path+'" on property '+definition.path); children := getChildMap(sd, sd.snapshot.elementList[0]); end; result := TAdvList<TFHIRMMProperty>.create; for child in children do result.add(TFHIRMMProperty.create(context.Link, child.Link, sd.Link)); finally children.free; end; end; function TFHIRMMProperty.getChild(elementName, childName : String) : TFHIRMMProperty; var p : TFHIRMMProperty; begin result := nil; for p in getChildProperties(elementName, null) do if p.name = childName then exit(p); end; function TFHIRMMProperty.getChild(name : String; type_ : TFHIRTypeDetails) : TFHIRMMProperty; var p : TFHIRMMProperty; begin result := nil; for p in getChildProperties(name, null) do if (p.Name = name) or (p.Name = name+'[x]') then exit(p); end; { TFHIRMMElement } constructor TFHIRMMElement.Create(name: String); begin inherited Create; self.Fname := name; FIndex := -1; end; constructor TFHIRMMElement.Create(name: String; prop: TFHIRMMProperty); begin inherited Create; self.Fname := name; self.fproperty := prop; FIndex := -1; end; constructor TFHIRMMElement.Create(name: String; prop: TFHIRMMProperty; type_, value: String); begin inherited Create; self.Fname := name; self.fproperty := prop; self.Ftype := type_; self.Fvalue := value; FIndex := -1; end; destructor TFHIRMMElement.Destroy; begin FComments.Free; FChildren.Free; FProperty.Free; FElementProperty.Free; FXhtml.Free; FProfiles.Free; inherited; end; procedure TFHIRMMElement.updateProperty(prop: TFHIRMMProperty; special: TFHIRMMSpecialElement; elementProp : TFHIRMMProperty); begin FProperty.Free; FProperty := prop; FElementProperty.Free; FElementProperty := elementProp; FSpecial := special; end; function TFHIRMMElement.GetType: String; begin if (Ftype = '') then result := FProperty.getType(name) else result := Ftype; end; function TFHIRMMElement.hasChildren: boolean; begin result := (FChildren <> nil) and (FChildren.count > 0); end; function TFHIRMMElement.GetComments: TStringList; begin if FComments = nil then FComments := TStringList.Create; result := FComments; end; function TFHIRMMElement.hasValue: boolean; begin result := FValue <> ''; end; procedure TFHIRMMElement.getChildrenByName(name: String; children: TFHIRSelectionList); var child : TFHIRMMElement; begin if (hasChildren()) then begin for child in self.Fchildren do if (name = child.Name) then children.add(child.link); end; end; procedure TFHIRMMElement.numberChildren; var last : string; index : integer; child : TFHIRMMElement; begin if (haschildren) then begin last := ''; index := 0; for child in self.Fchildren do begin if (child.prop.isList) then begin if (last = child.Name) then inc(index) else begin last := child.Name; index := 0; end; child.index := index; end else child.index := -1; child.numberChildren(); end; end; end; function TFHIRMMElement.hasIndex: boolean; begin result := FIndex > -1; end; function TFHIRMMElement.getChildValue(name: String): string; var child : TFHIRMMElement; begin result := ''; if (hasChildren()) then begin for child in self.Fchildren do if (name = child.Name) then result := child.Value; end; end; function TFHIRMMElement.GetChildren: TAdvList<TFHIRMMElement>; begin if FChildren = nil then FChildren := TAdvList<TFHIRMMElement>.create; result := FChildren; end; function TFHIRMMElement.hasType: boolean; begin if (Ftype = '') then result := FProperty.hasType(name) else result := true; end; function TFHIRMMElement.fhirType: String; begin result := GetType; end; procedure TFHIRMMElement.getProperty(name: String; checkValid: boolean; list: TAdvList<TFHIRObject>); var child : TFHIRMMElement; tn : String; begin if isPrimitive and (name = 'value') and (value <> '') then begin tn := getType(); raise DefinitionException.create('not done yet'); end; if FChildren <> nil then begin for child in Fchildren do begin if (child.Name = name) then list.add(child); if (child.Name.startsWith(name) and child.Prop.isChoice and (child.Prop.Name = name+'[x]')) then list.add(child.link); end; end; end; function TFHIRMMElement.isEmpty: boolean; var next : TFHIRMMElement; begin if (value <> '') then exit(false); for next in getChildren() do if (not next.isEmpty()) then exit(false); result := true; end; function TFHIRMMElement.isPrimitive: boolean; begin if (Ftype <> '') then result := isPrimitiveType(Ftype) else result := prop.isPrimitive(prop.getType(name)); end; function TFHIRMMElement.isResource: boolean; begin result := Prop.isResource; end; function TFHIRMMElement.hasPrimitiveValue: boolean; begin result := prop.isPrimitive(prop.getType(name)) or prop.IsLogicalAndHasPrimitiveValue(name); end; function TFHIRMMElement.primitiveValue: String; var c : TFHIRMMElement; begin result := ''; if (isPrimitive()) then result := value else if (hasPrimitiveValue() and hasChildren) then for c in Fchildren do if (c.Name = 'value') then exit(c.primitiveValue()); end; function TFHIRMMElement.markLocation(start, end_: TSourceLocation): TFHIRMMElement; begin FLocStart := start; FLocEnd := end_; result := self; end; function TFHIRMMElement.getNamedChild(name: String): TFHIRMMElement; var c : TFHIRMMElement; begin result := nil; if (Fchildren <> nil) then begin for c in Fchildren do if (c.Name = name) or (name.endsWith('[x]') and (c.name.startsWith(name.substring(0, name.length-3)))) then if (result = nil) then result := c else raise Exception.create('Attempt to read a single element when there is more than one present ('+name+')'); end; end; procedure TFHIRMMElement.getNamedChildren(name: String; list: TAdvList<TFHIRMMElement>); var c : TFHIRMMElement; begin if (Fchildren <> nil) then for c in Fchildren do if (c.Name = name) then list.add(c.link); end; procedure TFHIRMMElement.getNamedChildrenWithWildcard(name: String; children: TAdvList<TFHIRMMElement>); var start : String; child : TFHIRMMElement; begin start := name.substring(0, name.length - 3); if (children <> nil) then for child in children do if (child.Name.startsWith(start)) then children.add(child); end; function TFHIRMMElement.getNamedChildValue(name: String): string; var child : TFHIRMMElement; begin child := getNamedChild(name); if (child = nil) then result := '' else result := child.value; end; function TFHIRMMElement.GetProfiles: TProfileUsages; begin if FProfiles = nil then FProfiles := TProfileUsages.Create; result := FProfiles; end; function TFHIRMMElement.hasComments: boolean; begin result := (FComments <> nil) and (FComments.count > 0); end; function TFHIRMMElement.link: TFHIRMMElement; begin result := TFHIRMMElement(inherited Link); end; procedure TFHIRMMElement.listChildren(list: TAdvList<TFHIRMMProperty>); begin end; procedure TFHIRMMElement.ListProperties(oList: TFHIRPropertyList; bInheritedProperties, bPrimitiveValues: Boolean); var props : TAdvList<TFHIRMMProperty>; p : TFHIRMMProperty; list : TFHIRObjectList; child : TFHIRMMElement; begin inherited; props := FProperty.getChildProperties(Name, GetType); try for p in props do if p.isList then begin list := TFHIRObjectList.create; try if (children <> nil) then for child in children do if (child.Name = p.name) then list.add(child.Link); oList.add(TFHIRProperty.create(self, p.name, p.typeCode, p.isList, nil, list.link)); finally list.free; end; end else if p.isPrimitive(GetType) then oList.add(TFHIRProperty.create(self, p.name, p.typeCode, p.isList, nil, value)) else oList.add(TFHIRProperty.create(self, p.name, p.typeCode, p.isList, nil, getNamedChild(p.name).Link)); finally props.free; end; end; procedure TFHIRMMElement.SetChildValue(name, value: String); var child : TFHIRMMElement; begin for child in getchildren do if (name = child.Name) then begin if (not child.isPrimitive()) then raise DefinitionException('Cannot set a value of a non-primitive type ('+name+' on '+self.name+')'); child.Value := value; end; raise DefinitionException.create('not done yet'); end; procedure TFHIRMMElement.SetXhtml(const Value: TFhirXHtmlNode); begin FXhtml.Free; FXhtml := Value; end; { TFHIRMMParserBase } constructor TFHIRMMParserBase.create(context: TFHIRWorkerContext); begin inherited create; self.FContext := context; end; destructor TFHIRMMParserBase.Destroy; begin FContext.Free; FErrors.Free; inherited; end; procedure TFHIRMMParserBase.setupValidation(policy: TFHIRValidationPolicy; errors: TFhirOperationOutcomeIssueList); begin FPolicy := policy; FErrors.Free; FErrors := errors; end; procedure TFHIRMMParserBase.logError(line, col: integer; path: String; type_: TFhirIssueTypeEnum; message: String; level: TFhirIssueSeverityEnum); var err : TFhirOperationOutcomeIssue; begin if (Fpolicy = fvpEVERYTHING) then begin err := Ferrors.Append; err.locationList.add(path); err.code := type_; err.severity := level; err.details := TFhirCodeableConcept.Create; err.details.text := message+Stringformat(' at line %d col %d', [line, col]); end else if (level = IssueSeverityFatal) or ((level = IssueSeverityERROR) and (Fpolicy = fvpQUICK)) then raise Exception.create(message+Stringformat(' at line %d col %d', [line, col])); end; function TFHIRMMParserBase.parse(stream: TAdvStream): TFHIRMMElement; var vcl : TVCLStream; begin vcl := TVCLStream.create; try vcl.Stream := stream.link; result := parse(vcl); finally vcl.Free; end; end; function TFHIRMMParserBase.parse(buffer: TAdvBuffer): TFHIRMMElement; var mem : TAdvMemoryStream; begin mem := TAdvMemoryStream.Create; try mem.Buffer := buffer.Link; result := parse(mem); finally mem.Free; end; end; function TFHIRMMParserBase.getDefinition(line, col: integer; ns, name: String): TFHIRStructureDefinition; begin result := nil; if (ns = '') then begin logError(line, col, name, IssueTypeSTRUCTURE, 'This cannot be parsed as a FHIR object (no namespace)', IssueSeverityFATAL); exit(nil); end; if (name = '') then begin logError(line, col, name, IssueTypeSTRUCTURE, 'This cannot be parsed as a FHIR object (no name)', IssueSeverityFATAL); exit(nil); end; result := FContext.getStructure(ns, name).Link; if result = nil then logError(line, col, name, IssueTypeSTRUCTURE, 'This does not appear to be a FHIR resource (unknown namespace/name "'+ns+'::'+name+'")', IssueSeverityFATAL); end; function TFHIRMMParserBase.getDefinition(line, col: integer; name: String): TFHIRStructureDefinition; var sd : TFHIRStructureDefinition; begin result := nil; if (name = '') then begin logError(line, col, name, IssueTypeSTRUCTURE, 'This cannot be parsed as a FHIR object (no name)', IssueSeverityFATAL); exit(nil); end; for sd in Fcontext.allStructures do if (name = sd.Id) then exit(sd.Link); logError(line, col, name, IssueTypeSTRUCTURE, 'This does not appear to be a FHIR resource (unknown name "'+name+'")', IssueSeverityFATAL); result := nil; end; function TFHIRMMParserBase.getChildProperties(prop: TFHIRMMProperty; elementName, statedType: String): TAdvList<TFHIRMMProperty>; var ed : TFhirElementDefinition; sd : TFhirStructureDefinition; children : TFhirElementDefinitionList; child : TFhirElementDefinition; tr : TFhirElementDefinitionType; t : String; all, ok : boolean; begin if (prop.isResource) and (statedType <> '') then begin sd := FContext.getStructure('http://hl7.org/fhir/StructureDefinition/'+statedType); ed := sd.snapshot.elementList[0]; end else begin ed := prop.Definition; sd := prop.Structure.Link; end; children := FContext.getChildMap(sd, ed); try if (children.isEmpty()) then begin // ok, find the right definitions t := ''; if (ed.type_list.count() = 1) then t := ed.type_list[0].Code else if (ed.type_list.count() = 0) then raise Exception.create('types = 0, and no children found') else begin t := ed.type_list[0].Code; all := true; for tr in ed.type_list do if (tr.Code <> t) then all := false; if (not all) then begin // ok, it's polymorphic if (PropertyRepresentationTYPEATTR in ed.Representation) then begin t := statedType; if (t = '') and ed.hasExtension('http://hl7.org/fhir/StructureDefinition/elementdefinition-defaultype') then t := ed.GetExtensionString('http://hl7.org/fhir/StructureDefinition/elementdefinition-defaultype'); ok := false; for tr in ed.type_List do if (tr.code = t) then ok := true; if (not ok) then raise Exception.create('Type "'+t+'" is not an acceptable type for "'+elementName+'" on property '+prop.Definition.Path); end else begin t := elementName.substring(tail(ed.Path).length - 3); if (isPrimitiveType(lowFirst(t))) then t := lowFirst(t); end; end; end; if (t <> 'xhtml') then begin sd.Free; sd := FContext.getStructure('http://hl7.org/fhir/StructureDefinition/'+t); if (sd = nil) then raise Exception.create('Unable to find class "'+t+'" for name "'+elementName+'" on property '+prop.Definition.Path); children.Free; children := FContext.getChildMap(sd, sd.snapshot.elementList[0]); end; end; result := TAdvList<TFHIRMMProperty>.create; for child in children do result.add(TFHIRMMProperty.create(FContext.link, child.link, sd.link)); finally children.Free; sd.Free; end; end; { TFHIRMMManager } class procedure TFHIRMMManager.composeFile(context: TFHIRWorkerContext; e: TFHIRMMElement; filename: String; outputFormat: TFhirFormat; pretty: boolean; base: String); var f : TFileStream; begin f := TFileStream.create(filename, fmCreate); try compose(context, e, f, outputFormat, pretty, base); finally f.free; end; end; class function TFHIRMMManager.makeParser(context: TFHIRWorkerContext; format: TFhirFormat): TFHIRMMParserBase; begin case format of ffXML : result := TFHIRMMXmlParser.create(context.Link); ffJSON : result := TFHIRMMJsonParser.create(context.Link); // fmfTURTLE : result := TFHIRMMTurtleParser.create(context); // fmfJSONLD : result := TFHIRMMJsonLDParser.create(context); else result := nil; end; end; class procedure TFHIRMMManager.compose(context: TFHIRWorkerContext; e: TFHIRMMElement; destination: TStream; outputFormat: TFhirFormat; pretty: boolean; base: String); var p : TFHIRMMParserBase; begin p := makeParser(context, outputFormat); try p.compose(e, destination, pretty, base); finally p.Free; end; end; class function TFHIRMMManager.parse(context: TFHIRWorkerContext; source: TStream; inputFormat: TFhirFormat): TFHIRMMElement; var p : TFHIRMMParserBase; begin p := makeParser(context, inputFormat); try result := p.parse(source); finally p.Free; end; end; class function TFHIRMMManager.parseFile(context: TFHIRWorkerContext; filename: string; inputFormat: TFhirFormat): TFHIRMMElement; var f : TFileStream; begin f := TFileStream.create(filename, fmOpenread + fmShareDenywrite); try result := parse(context, f, inputFormat); finally f.free; end; end; { TFHIRMMXmlParser } destructor TFHIRMMXmlParser.Destroy; begin inherited; end; function TFHIRMMXmlParser.parse(stream: TStream): TFHIRMMElement; var doc : TMXmlDocument; begin doc := nil; try try doc := TMXmlParser.Parse(stream, [xpResolveNamespaces]); except on e : Exception do begin logError(0, 0, '(syntax)', IssueTypeINVALID, e.Message, IssueSeverityFATAL); exit(nil); end; end; result := parse(doc.document); finally doc.Free; end; end; procedure TFHIRMMXmlParser.checkRootNode(document : TMXmlDocument); var node : TMXmlElement; begin if (FPolicy = fvpEVERYTHING) then begin node := document.First; while (node <> nil) do begin if (node.NodeType = ntProcessingInstruction) then logError(line(document), col(document), '(document)', IssueTypeINVALID, 'No processing instructions allowed in resources', IssueSeverityERROR); if (node.NodeType = ntDocumentDeclaration) then logError(line(document), col(document), '(document)', IssueTypeINVALID, 'No document type declarations allowed in resources', IssueSeverityERROR); node := node.Next; end; end; end; function TFHIRMMXmlParser.line(node : TMXmlElement) : integer; begin result := node.Start.line; end; function TFHIRMMXmlParser.col(node : TMXmlElement) : integer; begin result := node.Start.col; end; function TFHIRMMXmlParser.parse(document : TMXmlDocument) : TFHIRMMElement; var element : TMXmlElement; begin checkRootNode(document); element := document.Document; result := parse(element); end; function TFHIRMMXmlParser.parse(element : TMXmlElement) : TFHIRMMElement; var ns, name, path : String; sd : TFhirStructureDefinition; begin ns := element.NamespaceURI; name := element.localName; path := '/'+pathPrefix(ns)+name; sd := getDefinition(line(element), col(element), ns, name); try if (sd = nil) then exit(nil); result := nil; result := TFHIRMMElement.create(element.localName, TFHIRMMProperty.create(Fcontext.link, sd.Snapshot.ElementList[0].Link, sd.Link)); checkElement(element, path, result.Prop); result.markLocation(start(element), end_(element)); result.type_ := element.localName; parseChildren(path, element, result); result.numberChildren(); finally sd.free; end; end; function TFHIRMMXmlParser.parse(element : TMXmlElement; sd : TFhirStructureDefinition) : TFHIRMMElement; begin result := TFHIRMMElement.create(element.localName, TFHIRMMProperty.create(Fcontext.link, sd.Snapshot.ElementList[0].Link, sd.Link)); checkElement(element, sd.id, result.Prop); result.markLocation(start(element), end_(element)); result.type_ := element.localName; parseChildren(sd.id, element, result); result.numberChildren(); end; function TFHIRMMXmlParser.pathPrefix(ns : String) : String; begin if (ns = '') then exit(''); if (ns = FHIR_NS) then exit('f:'); if (ns = XHTML_NS) then exit('h:'); if (ns = 'urn:hl7-org:v3') then exit('v3:'); exit('?:'); end; function TFHIRMMXmlParser.empty(element : TMXmlElement) : boolean ; var n : String; node : TMXmlElement; begin for n in element.attributes.keys do begin if (n <> 'xmlns') and not n.startsWith('xmlns:') then exit(false); end; if ('' <> trim(element.text)) then exit(false); node := element.First; while (node <> nil) do begin if (node.NodeType = ntElement) then exit(false); node := node.Next; end; exit(true); end; function TFHIRMMXmlParser.end_(node: TMXmlElement): TSourceLocation; begin result := node.Stop; end; procedure TFHIRMMXmlParser.checkElement(element : TMXmlElement; path : String; prop : TFHIRMMProperty); var ns : String; begin if (FPolicy = fvpEVERYTHING) then begin if (empty(element)) then logError(line(element), col(element), path, IssueTypeINVALID, 'Element must have some content', IssueSeverityERROR); ns := FHIR_NS; if (prop.Definition.hasExtension('http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace')) then ns := prop.Definition.getExtensionString('http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace') else if (prop.Structure.hasExtension('http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace')) then ns := prop.Structure.getExtensionString('http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace'); if (element.NamespaceURI <> ns) then logError(line(element), col(element), path, IssueTypeINVALID, 'Wrong namespace - expected "'+ns+'"', IssueSeverityERROR); end; end; function getXsiType(node : TMXmlElement) : String; begin result := node.attributeNS['http://www.w3.org/2001/XMLSchema-instance', 'type']; if (result.contains(':')) then result := result.substring(result.indexOf(';')+1); end; procedure TFHIRMMXmlParser.parseChildren(path : String; node : TMXmlElement; context : TFHIRMMElement); var properties : TAdvList<TFHIRMMProperty>; prop : TFHIRMMProperty; s, text : String; attr : TMXmlAttribute; child : TMXmlElement; e : TMXmlElement; av: String; xhtml: TFhirXHtmlNode; n : TFHIRMMElement; npath, xsiType : String; ok : boolean; begin // this parsing routine retains the original order in a the XML file, to support validation reapComments(node, context); properties := getChildProperties(context.Prop, context.Name, getXsiType(node)); try text := node.allText.trim(); if ('' <> text) then begin prop := getTextProp(properties); if (prop <> nil) then begin context.getChildren().add(TFHIRMMElement.create(prop.Name, prop.Link, prop.getType(), text).markLocation(start(node), end_(node))); end else begin logError(line(node), col(node), path, IssueTypeSTRUCTURE, 'Text should not be present', IssueSeverityERROR); end; end; for s in node.Attributes.Keys do begin attr := node.Attributes[s]; if not ((s = 'xmlns') or StringStartsWith(s, 'xmlns:')) then begin prop := getAttrProp(properties, s); if (prop <> nil) then begin av := attr.Value; if (prop.Definition.hasExtension('http://www.healthintersections.com.au/fhir/StructureDefinition/elementdefinition-dateformat')) then av := convertForDateFormat(prop.Definition.getExtensionString('http://www.healthintersections.com.au/fhir/StructureDefinition/elementdefinition-dateformat'), av); if (prop.Name = 'value') and context.isPrimitive() then context.Value := av else context.getChildren().add(TFHIRMMElement.create(prop.Name, prop.Link, prop.getType(), av).markLocation(start(node), end_(node))); end else logError(line(node), col(node), path, IssueTypeSTRUCTURE, 'Undefined attribute "@'+s+'"', IssueSeverityERROR); end; end; child := node.First; while (child <> nil) do begin if (child.NodeType = ntElement) then begin e := child as TMXmlElement; prop := getElementProp(properties, e.localName); if (prop <> nil) then begin if (not prop.isChoice()) and ('xhtml' = prop.getType()) then begin xhtml := TFHIRXhtmlParser.parse('en', xppReject, [xopValidatorMode], e, path, FHIR_NS); n := TFHIRMMElement.create('div', prop.link, 'xhtml', TFHIRXhtmlParser.compose(xhtml)); context.getChildren().add(n); n.Xhtml := xhtml; n.markLocation(start(e), end_(e)); end else begin npath := path+'/'+pathPrefix(e.NamespaceURI)+e.localName; n := TFHIRMMElement.create(e.localName, prop.Link); context.getChildren().add(n); n.markLocation(start(e), end_(e)); checkElement(e as TMXmlElement, npath, n.Prop); ok := true; if (prop.isChoice()) then begin if (PropertyRepresentationTYPEATTR in prop.Definition.Representation) then begin xsiType := getXsiType(e); if (xsiType = '') then begin logError(line(e), col(e), path, IssueTypeSTRUCTURE, 'No type found on "'+e.localName+'"', IssueSeverityERROR); ok := false; end else begin if (xsiType.contains(':')) then xsiType := xsiType.substring(xsiType.indexOf(':')+1); n.Type_ := xsiType; end; end else n.Type_ := n.getType(); end; if (ok) then begin if (prop.isResource()) then parseResource(npath, e, n, prop) else parseChildren(npath, e, n); end; end; end else logError(line(e), col(e), path, IssueTypeSTRUCTURE, 'Undefined element "'+e.localName+'"', IssueSeverityERROR); end else if (child.NodeType = ntCData) then logError(line(child), col(child), path, IssueTypeSTRUCTURE, 'CDATA is not allowed', IssueSeverityERROR) else if not (child.NodeType in [ntText, ntComment]) then logError(line(child), col(child), path, IssueTypeSTRUCTURE, 'Node type '+CODES_TMXmlElementType[child.NodeType]+' is not allowed', IssueSeverityERROR); child := child.Next; end; finally properties.free; end; end; function TFHIRMMXmlParser.getElementProp(props : TAdvList<TFHIRMMProperty>; nodeName : String) : TFHIRMMProperty; var p : TFHIRMMProperty; begin for p in props do if not (PropertyRepresentationXMLATTR in p.Definition.Representation) and not (PropertyRepresentationXMLTEXT in p.Definition.Representation) then begin if (p.Name = nodeName) then exit(p); if (p.Name.endsWith('[x]')) and (nodeName.length > p.Name.length-3) and (p.Name.substring(0, p.Name.length-3) = nodeName.substring(0, p.Name.length-3)) then exit(p); end; exit(nil); end; function TFHIRMMXmlParser.getAttrProp(props : TAdvList<TFHIRMMProperty>; nodeName : String) : TFHIRMMProperty; var p : TFHIRMMProperty; begin for p in props do if (p.Name = nodeName) and (PropertyRepresentationXMLATTR in p.Definition.Representation) then exit(p); exit(nil); end; function TFHIRMMXmlParser.getTextProp(props : TAdvList<TFHIRMMProperty>) : TFHIRMMProperty; var p : TFHIRMMProperty; begin for p in props do if (PropertyRepresentationXMLTEXT in p.Definition.Representation) then exit(p); exit(nil); end; function TFHIRMMXmlParser.convertForDateFormat(fmt, av : String) : String; begin if ('v3' = fmt) then result := TDateTimeEx.fromHL7(av).ToXML else raise Exception.create('Unknown Data format "'+fmt+'"'); end; procedure TFHIRMMXmlParser.parseResource(s : String; container : TMXmlElement; parent : TFHIRMMElement; elementProperty : TFHIRMMProperty); var res : TMXmlElement; name : String; sd : TFHIRStructureDefinition; begin res := container.firstElement; name := res.localName; sd := Fcontext.getStructure('http://hl7.org/fhir/StructureDefinition/'+name); try if (sd = nil) then raise Exception.create('Contained resource does not appear to be a FHIR resource (unknown name "'+res.localName+'")'); parent.updateProperty(TFHIRMMProperty.create(Fcontext.Link, sd.Snapshot.ElementList[0].Link, sd.Link), parent.prop.specialElementClass, elementProperty.Link); parent.Type_ := name; parseChildren(res.localName, res, parent); finally sd.free; end; end; procedure TFHIRMMXmlParser.reapComments(element : TMXmlElement; context : TFHIRMMElement); var node : TMXmlElement; begin node := element.previous; while (node <> nil) and (node.NodeType <> ntElement) do begin if (node.NodeType = ntComment) then context.getComments().insert(0, node.Text); node := node.previous; end; node := element.last; while (node <> nil) and (node.NodeType <> ntElement) do begin node := node.previous; end; while (node <> nil) do begin if (node.NodeType = ntComment) then context.getComments().add(node.Text); node := node.Next; end; end; function TFHIRMMXmlParser.start(node: TMXmlElement): TSourceLocation; begin result := node.Start; end; function TFHIRMMXmlParser.isAttr(prop : TFHIRMMProperty) : boolean; begin result := PropertyRepresentationXMLATTR in prop.Definition.Representation; end; function TFHIRMMXmlParser.isText(prop : TFHIRMMProperty) : boolean; begin result := PropertyRepresentationXMLTEXT in prop.Definition.Representation; end; procedure TFHIRMMXmlParser.compose(e : TFHIRMMElement; stream : TStream; pretty : boolean; base : String); var xml : TXmlBuilder; begin xml := TAdvXmlBuilder.Create; try xml.IsPretty := pretty; xml.NoHeader := true; xml.CurrentNamespaces.DefaultNS := e.Prop.getNamespace(); xml.Start; composeElement(xml, e, e.getType()); xml.Finish; xml.Build(stream); finally xml.Free; end; end; procedure TFHIRMMXmlParser.composeElement(xml : TXmlBuilder; element : TFHIRMMElement; elementName : String); var s : String; child : TFHIRMMElement; begin for s in element.Comments do xml.comment(s); if (isText(element.Prop)) then begin xml.Open(elementName); xml.text(element.Value); xml.close(elementName); end else if element.isPrimitive() or (element.hasType() and isPrimitiveType(element.getType())) then begin if (element.getType() = 'xhtml') then begin xml.inject(TEncoding.UTF8.getBytes(element.Value)); end else if (isText(element.Prop)) then begin xml.text(element.Value); end else begin if element.value <> '' then xml.AddAttribute('value', element.Value); if element.hasChildren then begin xml.open(elementName); for child in element.Children do composeElement(xml, child, child.Name); xml.close(elementName); end else xml.Tag(elementName); end; end else begin for child in element.Children do begin if (isAttr(child.Prop)) then xml.AddAttribute(child.Name, child.Value); end; xml.open(elementName); if element.special <> fsecNil then xml.open(element.type_); for child in element.Children do begin if (isText(child.Prop)) then xml.text(child.Value) else if (not isAttr(child.prop)) then composeElement(xml, child, child.Name); end; if element.special <> fsecNil then xml.close(element.type_); xml.close(elementName); end; end; { TFHIRMMJsonParser } function TFHIRMMJsonParser.parse(stream: TStream): TFHIRMMElement; var obj : TJsonObject; begin try obj := TJSONParser.parse(stream); except on e : Exception do begin logError(0, 0, '(syntax)', IssueTypeINVALID, e.Message, IssueSeverityFATAL); exit(nil); end; end; try result := parse(obj); finally obj.free; end; end; function TFHIRMMJsonParser.parse(obj: TJsonObject): TFHIRMMElement; var name, path : String; sd : TFHIRStructureDefinition; begin if not obj.has('resourceType') then begin logError(obj.LocationStart.Line, obj.LocationStart.Col, '$', IssueTypeINVALID, 'Unable to find resourceType property', IssueSeverityFATAL); exit(nil); end; name := obj.str['resourceType']; path := '/'+name; sd := getDefinition(obj.LocationStart.Line, obj.LocationStart.Col, name); try if (sd = nil) then exit(nil); result := TFHIRMMElement.create(name, TFHIRMMProperty.create(FContext.link, sd.Snapshot.ElementList[0].Link, sd.Link)); try checkObject(obj, path); result.markLocation(obj.LocationStart, obj.LocationEnd); result.Type_ := name; parseChildren(path, obj, result, true); result.numberChildren(); result.link; finally result.free; end; finally sd.free; end; end; procedure TFHIRMMJsonParser.checkObject(obj: TJsonObject; path : String); begin if (FPolicy = fvpEVERYTHING) and (obj.properties.count = 0) then logError(obj.LocationStart.Line, obj.LocationStart.Col, path, IssueTypeINVALID, 'Object must have some content', IssueSeverityERROR); end; procedure TFHIRMMJsonParser.parseChildren(path : String; obj: TJsonObject; context : TFHIRMMElement; hasResourceType : boolean); var properties : TAdvList<TFHIRMMProperty>; prop : TFHIRMMProperty; processed : TAdvStringSet; tr : TFHIRElementDefinitionType; ename, name : String; begin reapComments(obj, context); properties := getChildProperties(context.Prop, context.Name, ''); processed := TAdvStringSet.create; try if (hasResourceType) then processed.add('resourceType'); processed.add('fhir_comments'); // note that we do not trouble ourselves to maintain the wire format order here - we don"t even know what it was anyway // first pass: process the properties for prop in properties do begin if (prop.isChoice()) then begin for tr in prop.Definition.Type_List do begin eName := prop.Name.substring(0, prop.Name.length-3) + capitalize(tr.Code); if (not isPrimitiveType(tr.Code) and obj.has(eName)) then begin parseChildComplex(path, obj, context, processed, prop, eName); break; end else if (isPrimitiveType(tr.Code) and (obj.has(eName) or obj.has('_'+eName))) then begin parseChildPrimitive(path, obj, context, processed, prop, eName); break; end; end; end else if (prop.isPrimitive(prop.getType(''))) then begin parseChildPrimitive(path, obj, context, processed, prop, prop.Name); end else if (obj.has(prop.Name)) then begin parseChildComplex(path, obj, context, processed, prop, prop.Name); end; end; // second pass: check for things not processed if (FPolicy <> fvpNONE) then begin for name in obj.properties.keys do begin if (not processed.contains(name)) then logError(obj.properties[name].locationStart.line, obj.properties[name].locationStart.col, path, IssueTypeSTRUCTURE, 'Unrecognised prop "'+name+'"', IssueSeverityERROR); end; end; finally properties.Free; processed.Free; end; end; procedure TFHIRMMJsonParser.parseChildComplex(path : String; obj: TJsonObject; context : TFHIRMMElement; processed : TAdvStringSet; prop : TFHIRMMProperty; name : String); var npath : String; e : TJsonNode; arr : TJsonArray; am : TJsonNode; begin processed.add(name); npath := path+'/'+prop.Name; e := obj.properties[name]; if (prop.isList() and (e is TJsonArray)) then begin arr := e as TjsonArray; for am in arr do parseChildComplexInstance(npath, obj, context, prop, name, am); end else parseChildComplexInstance(npath, obj, context, prop, name, e); end; procedure TFHIRMMJsonParser.parseChildComplexInstance(path : String; obj: TJsonObject; context : TFHIRMMElement; prop : TFHIRMMProperty; name : String; e : TJsonNode); var child : TJsonObject; n : TFHIRMMElement; begin if (e is TJsonObject) then begin child := e as TJsonObject; n := TFHIRMMElement.create(name, prop.Link).markLocation(child.LocationStart, child.LocationEnd); checkObject(child, path); context.getChildren().add(n); if (prop.isResource()) then parseResource(path, child, n, prop) else parseChildren(path, child, n, false); end else if prop.isList then logError(e.LocationStart.Line, e.LocationStart.Col, path, IssueTypeINVALID, 'This prop must be an Array not a '+e.ClassName, IssueSeverityERROR) else logError(e.LocationStart.Line, e.LocationStart.Col, path, IssueTypeINVALID, 'This prop must be an object, not a '+e.className, IssueSeverityERROR); end; function arrC(arr : TJsonArray) : integer; begin if (arr = nil) then result := 0 else result := arr.Count; end; function arrI(arr : TJsonArray; i : integer) : TJsonNode; begin if (arr = nil) or (i >= arr.count) then result := nil else if arr.item[i] is TJsonNull then result := nil else result := arr.item[i]; end; procedure TFHIRMMJsonParser.parseChildPrimitive(path : String; obj: TJsonObject; context : TFHIRMMElement; processed : TAdvStringSet; prop : TFHIRMMProperty; name : String); var npath : String; main, fork : TJsonNode; arr1, arr2 : TJsonArray; m, f : TJsonNode; i : integer; begin npath := path+'/'+prop.Name; processed.add(name); processed.add('_'+name); if (obj.has(name)) then main := obj.properties[name] else main := nil; if (obj.has('_'+name)) then fork := obj.properties['_'+name] else fork := nil; if (main <> nil) or (fork <> nil) then begin if (prop.isList() and ((main = nil) or (main is TJsonArray)) and ((fork = nil) or (fork is TJsonArray)) ) then begin arr1 := main as TjsonArray; arr2 := fork as TjsonArray; for i := 0 to max(arrC(arr1), arrC(arr2)) - 1 do begin m := arrI(arr1, i); f := arrI(arr2, i); parseChildPrimitiveInstance(npath, obj, context, processed, prop, name, m, f); end; end else parseChildPrimitiveInstance(npath, obj, context, processed, prop, name, main, fork); end; end; procedure TFHIRMMJsonParser.parseChildPrimitiveInstance(npath : String; obj: TJsonObject; context : TFHIRMMElement; processed : TAdvStringSet; prop : TFHIRMMProperty; name : String; main, fork : TJsonNode); var n : TFHIRMMElement; child : TJsonObject; begin if (main <> nil) and not ((main is TJsonString) or (main is TJsonBoolean) or (main is TJsonNull) or (main is TJsonNumber)) then logError(main.LocationStart.Line, main.LocationStart.Col, npath, IssueTypeINVALID, 'This prop must be an simple value, not a '+main.className, IssueSeverityERROR) else if (fork <> nil) and (not (fork is TJsonObject)) then logError(fork.LocationStart.Line, fork.LocationStart.Col, npath, IssueTypeINVALID, 'This prop must be an obj, not a '+fork.className, IssueSeverityERROR) else begin n := TFHIRMMElement.create(name, prop.link); context.Children.add(n); if (main <> nil) then n.markLocation(main.LocationStart, main.LocationEnd) else n.markLocation(fork.LocationStart, fork.LocationEnd); if (main <> nil) then begin if (main is TJsonString) then n.value := (main as TJsonString).Value else if (main is TJsonNumber) then n.value := (main as TJsonNumber).Value else if (main is TJsonBoolean) then if (main as TJsonBoolean).Value then n.value := 'true' else n.value := 'false'; if ( not n.Prop.isChoice()) and (n.Type_ = 'xhtml') then begin try n.Xhtml := TFHIRXhtmlParser.parse('en', xppAllow, [xopValidatorMode], n.value); Except on e : Exception do logError(main.LocationStart.Line, main.LocationStart.Col, npath, IssueTypeINVALID, 'Error parsing XHTML: '+e.Message, IssueSeverityERROR); end; end; if (FPolicy = fvpEVERYTHING) then begin // now we cross-check the primitive format against the stated type if (n.Type_ = 'boolean') then begin if not (main is TJsonBoolean) then logError(main.LocationStart.Line, main.LocationStart.Col, npath, IssueTypeINVALID, 'Error parsing JSON: the primitive value must be a boolean', IssueSeverityERROR); end else if (StringArrayExistsSensitive(['integer', 'unsignedInt', 'positiveInt', 'decimal'], n.Type_)) then begin if not (main is TJsonNumber) then logError(main.LocationStart.Line, main.LocationStart.Col, npath, IssueTypeINVALID, 'Error parsing JSON: the primitive value must be a number', IssueSeverityERROR); end else if not (main is TJsonString) then logError(main.LocationStart.Line, main.LocationStart.Col, npath, IssueTypeINVALID, 'Error parsing JSON: the primitive value must be a string', IssueSeverityERROR); end; end; if (fork <> nil) then begin child := fork as TJsonObject; checkObject(child, npath); parseChildren(npath, child, n, false); end; end; end; procedure TFHIRMMJsonParser.parseResource(path : String; obj: TJsonObject; parent : TFHIRMMElement; elementProperty : TFHIRMMProperty); var name : String; sd : TFHIRStructureDefinition; begin if not obj.has('resourceType') then begin logError(obj.LocationStart.Line, obj.LocationStart.Col, '$', IssueTypeINVALID, 'Unable to find resourceType property', IssueSeverityFATAL); exit; end; name := obj.str['resourceType']; sd := getDefinition(obj.LocationStart.Line, obj.LocationStart.Col, name); try if (sd <> nil) then begin parent.updateProperty(TFHIRMMProperty.create(Fcontext.Link, sd.Snapshot.ElementList[0].Link, sd.Link), parent.prop.specialElementClass, elementProperty.Link); parent.Type_ := name; parseChildren(path, obj, parent, true); end; finally sd.free; end; end; procedure TFHIRMMJsonParser.reapComments(obj : TJsonObject; context : TFHIRMMElement); var arr : TJsonArray; i : integer; begin if (obj.has('fhir_comments')) then begin arr := obj.Arr['fhir_comments']; for i := 0 to arr.count - 1 do context.getComments().add((arr.Item[i] as TJsonString).value); end; end; procedure TFHIRMMJsonParser.compose(e : TFHIRMMElement; stream : TStream; pretty : boolean; base : String); var oStream : TAdvVCLStream; begin oStream := TAdvVCLStream.Create; try oStream.Stream := stream; compose(e, oStream, pretty, base); finally oStream.free; end; end; procedure TFHIRMMJsonParser.compose(e : TFHIRMMElement; stream : TAdvStream; pretty : boolean; base : String); begin json := TJSONWriter.Create; try json.Stream := stream.Link; json.Start; json.HasWhitespace := pretty; composeElement(e); json.Finish; finally json.free; end; end; procedure TFHIRMMJsonParser.composeElement(e : TFHIRMMElement); var done : TAdvStringSet; child : TFHIRMMElement; begin json.value('resourceType', e.type_); done := TAdvStringSet.create; try {no-comments composeComments(e); } for child in e.Children do composeElement(e.Name, e, done, child); finally done.free; end; end; procedure TFHIRMMJsonParser.composeElement(path : String; e : TFHIRMMElement; done : TAdvStringSet; child : TFHIRMMElement); var list : TFHIRSelectionList; islist: boolean; begin if child.elementProp <> nil then isList := child.elementProp.isList() else isList := child.prop.isList(); if not islist then // for specials, ignore the cardinality of the stated type composeElement(path, child) else if not (done.contains(child.Name)) then begin done.add(child.Name); list := TFHIRSelectionList.create; try e.getChildrenByName(child.Name, list); composeList(path, list); finally list.free; end; end; end; procedure TFHIRMMJsonParser.composeList(path : String; list : TFHIRSelectionList); var item, child : TFHIRMMElement; name : String; complex, prim : boolean; o : TFHIRSelection; done : TAdvStringSet; begin item := list[0].value as TFHIRMMElement; // there will be at least one element name := item.Name; complex := true; if (item.isPrimitive()) then begin prim := false; complex := false; for o in list do begin item := o.value as TFHIRMMElement; if (item.hasValue()) then prim := true; if (item.hasChildren()) {no-comments or (item.hasComments())} then complex := true; end; if (prim) then begin json.ValueArray(name); for o in list do begin item := o.value as TFHIRMMElement; if (item.hasValue()) then primitiveValue('', item) else json.ValueNullInArray; end; json.FinishArray(); end; name := '_'+name; end; if (complex) then begin json.ValueArray(name); for o in list do begin item := o.value as TFHIRMMElement; if (item.hasChildren()) then begin json.ValueObject; {no-comments composeComments(item);} if (item.Prop.isResource()) then begin json.value('resourceType', item.type_); end; done := TAdvStringSet.create; try for child in item.Children do composeElement(path+'.'+name+'[]', item, done, child); finally done.free; end; json.FinishObject; end else json.ValueNullInArray(); end; json.FinishArray(); end; end; procedure TFHIRMMJsonParser.primitiveValue(name : String; item : TFHIRMMElement); begin if (item.type_ = 'boolean') then json.value(name, item.Value.Trim = 'true') else if (StringArrayExists(['decimal', 'integer', 'unsignedInt', 'positiveInt'], item.type_)) then json.ValueNumber(name, item.Value) else json.value(name, item.Value); end; procedure TFHIRMMJsonParser.composeElement(path : String; element : TFHIRMMElement); var name : string; done : TAdvStringSet; child : TFHIRMMElement; begin name := element.Name; if (element.isPrimitive()) or (isPrimitiveType(element.type_)) then begin if (element.hasValue()) then primitiveValue(name, element); name := '_'+name; end; if (element.hasChildren()) then begin json.ValueObject(name); if (element.isResource()) then json.value('resourceType', element.Type_); done := TAdvStringSet.create; try for child in element.Children do composeElement(path+'.'+element.Name, element, done, child); finally done.free; end; json.finishObject; end; end; { TFHIRMMResourceLoader } function TFHIRMMResourceLoader.parse(r: TFHIRResource): TFHIRMMElement; var name, path : String; sd : TFHIRStructureDefinition; begin name := CODES_TFHIRResourceType[r.resourceType]; path := name; sd := getDefinition(-1, -1, name); if (sd = nil) then raise Exception.create('Unable to find definition for '+name); try result := TFHIRMMElement.create(name, TFHIRMMProperty.create(FContext.link, sd.Snapshot.ElementList[0].Link, sd.Link)); try result.Type_ := name; parseChildren(path, r, result); result.numberChildren(); result.link; finally result.free; end; finally sd.free; end; end; procedure TFHIRMMResourceLoader.compose(e: TFHIRMMElement; stream: TStream; pretty: boolean; base: String); begin raise Exception.create('not implemented'); end; function TFHIRMMResourceLoader.parse(r: TFHIRObject): TFHIRMMElement; var name, path : String; sd : TFHIRStructureDefinition; begin name := r.fhirType; path := name; sd := getDefinition(-1, -1, name); try if (sd = nil) then raise Exception.create('Unable to find definition for '+name); result := TFHIRMMElement.create(name, TFHIRMMProperty.create(FContext.link, sd.Snapshot.ElementList[0].Link, sd.Link)); try result.Type_ := name; parseChildren(path, r, result); result.numberChildren(); result.link; finally result.free; end; finally sd.free; end; end; procedure TFHIRMMResourceLoader.parseChildren(path: String; obj: TFHIRObject; context: TFHIRMMElement); var properties : TAdvList<TFHIRMMProperty>; prop : TFHIRMMProperty; name : String; list : TFHIRSelectionList; o : TFHIRSelection; n : TFHIRMMElement; begin properties := getChildProperties(context.Prop, context.Name, context.Type_); try for prop in properties do begin list := TFHIRSelectionList.create; try obj.ListChildrenByName(prop.name, list); for o in list do begin if (o.value <> nil) then begin if o.value is TFHIRObjectText then context.value := TFHIRObjectText(o.value).value else if o.value is TFhirXHtmlNode then begin n := TFHIRMMElement.create(prop.name, prop.Link); n.Xhtml := TFhirXHtmlNode(o.value).link; n.value := TFHIRXhtmlParser.compose(TFhirXHtmlNode(o.value)); context.getChildren().add(n); end else if o.value is TFHIRObject then begin name := prop.name; if name.endsWith('[x]') then name := name.substring(0, name.length - 3)+capitalize(TFHIRObject(o.value).fhirType); n := TFHIRMMElement.create(name, prop.Link); context.getChildren().add(n); // is this a resource boundary? if prop.isResource then n.type_ := TFHIRObject(o.value).fhirType; parseChildren(path+'.'+name, o.value as TFHIRObject, n); end; end; end; finally list.free; end; end; finally properties.Free; end; end; { TFHIRCustomResource } constructor TFHIRCustomResource.Create(root: TFHIRMMElement); begin inherited Create; FRoot := root; end; class function TFHIRCustomResource.CreateFromBase(context : TFHIRWorkerContext; base: TFHIRObject): TFHIRCustomResource; var e : TFHIRMMElement; l : TFHIRMMResourceLoader; begin l := TFHIRMMResourceLoader.create(context.link); try e := l.parse(base); try result := TFHIRCustomResource.create(e.link); finally e.free; end; finally l.free; end; end; destructor TFHIRCustomResource.Destroy; begin FRoot.Free; inherited; end; procedure TFHIRCustomResource.SetRoot(const Value: TFHIRMMElement); begin FRoot.Free; FRoot := Value; end; function TFHIRCustomResource.Link: TFHIRCustomResource; begin result := TFHIRCustomResource(inherited Link); end; procedure TFHIRCustomResource.Assign(oSource: TAdvObject); begin raise Exception.Create('Not done yet: TFHIRCustomResource.Assign'); end; function TFHIRCustomResource.Clone: TFHIRCustomResource; begin raise Exception.Create('Not done yet: TFHIRCustomResource.Clone:'); end; function TFHIRCustomResource.equalsDeep(other: TFHIRObject): boolean; begin raise Exception.Create('Not done yet: TFHIRCustomResource.equalsDeep'); end; function TFHIRCustomResource.equalsShallow(other: TFHIRObject): boolean; begin raise Exception.Create('Not done yet: TFHIRCustomResource.equalsShallow'); end; function TFHIRCustomResource.FhirType: string; begin result := FRoot.fhirType; end; procedure TFHIRCustomResource.GetChildrenByName(child_name: string; list: TFHIRSelectionList); begin FRoot.GetChildrenByName(child_name, list); end; procedure TFHIRCustomResource.getProperty(name: String; checkValid: boolean; list: TAdvList<TFHIRObject>); begin raise Exception.Create('Not done yet: TFHIRCustomResource.getProperty'); end; function TFHIRCustomResource.GetResourceType: TFhirResourceType; begin result := frtCustom; end; function TFHIRCustomResource.isMetaDataBased: boolean; begin raise Exception.Create('Not done yet: TFHIRCustomResource.isMetaDataBased:'); end; procedure TFHIRCustomResource.ListProperties(oList: TFHIRPropertyList; bInheritedProperties, bPrimitiveValues: Boolean); begin raise Exception.Create('Not done yet: TFHIRCustomResource.ListProperties'); end; function TFHIRCustomResource.createPropertyValue(propName: string): TFHIRObject; begin raise Exception.Create('Not done yet: TFHIRCustomResource.makeProperty'); end; procedure TFHIRCustomResource.setProperty(propName: string; propValue: TFHIRObject); begin raise Exception.Create('Not done yet: TFHIRCustomResource.setProperty'); end; { TProfileUsages } constructor TProfileUsages.create; begin inherited; FEntries := TAdvList<TProfileUsage>.create; end; destructor TProfileUsages.destroy; begin FEntries.Free; inherited; end; procedure TProfileUsages.addProfile(sd: TFHIRStructureDefinition); var pu : TProfileUsage; begin for pu in FEntries do if pu.defn = sd then exit; pu := TProfileUsage.create; try pu.defn := sd.link; FEntries.add(pu.link); finally pu.free; end; end; function TProfileUsages.GetIsEmpty: boolean; begin result := FEntries.Count = 0; end; { TProfileUsage } destructor TProfileUsage.Destroy; begin FDefn.free; inherited; end; function TProfileUsage.Link: TProfileUsage; begin result := TProfileUsage(Inherited link); end; procedure TProfileUsage.SetDefn(const Value: TFHIRStructureDefinition); begin FDefn.free; FDefn := Value; end; end.
30.843304
206
0.69131
4702197645f93d9d1a6a640b4ac49c50b4adce7b
222
lpr
Pascal
Src/Graphics32/Examples/Drawing/AntiAliasing/AntiAliasing.lpr
ryujt/ryulib-delphi
a59d308d6535de6a2fdb1ac49ded981849031c60
[ "MIT" ]
12
2019-11-09T11:44:47.000Z
2022-03-01T23:38:30.000Z
Src/Graphics32/Examples/Drawing/AntiAliasing/AntiAliasing.lpr
ryujt/ryulib-delphi
a59d308d6535de6a2fdb1ac49ded981849031c60
[ "MIT" ]
1
2019-11-08T08:27:34.000Z
2019-11-08T08:43:51.000Z
Src/Graphics32/Examples/Drawing/AntiAliasing/AntiAliasing.lpr
ryujt/ryulib-delphi
a59d308d6535de6a2fdb1ac49ded981849031c60
[ "MIT" ]
15
2019-10-15T12:34:29.000Z
2021-02-23T08:25:48.000Z
program AntiAliasing; {$R Media.rc} uses Interfaces, Forms, MainUnit in 'MainUnit.pas'; begin Application.Initialize; Application.CreateForm(TFrmAntiAliasingTest, FrmAntiAliasingTest); Application.Run; end.
14.8
68
0.765766
4732e9776589c04ed8e2acb4f2f472aad4b9dd9f
55,645
pas
Pascal
Source/Services/SimpleEmail/Base/AWS.SES.pas
herux/aws-sdk-delphi
4ef36e5bfc536b1d9426f78095d8fda887f390b5
[ "Apache-2.0" ]
67
2021-07-28T23:47:09.000Z
2022-03-15T11:48:35.000Z
Source/Services/SimpleEmail/Base/AWS.SES.pas
gabrielbaltazar/aws-sdk-delphi
ea1713b227a49cbbc5a2e1bf04cbf2de1f9b611a
[ "Apache-2.0" ]
5
2021-09-01T09:31:16.000Z
2022-03-16T18:19:21.000Z
Source/Services/SimpleEmail/Base/AWS.SES.pas
gabrielbaltazar/aws-sdk-delphi
ea1713b227a49cbbc5a2e1bf04cbf2de1f9b611a
[ "Apache-2.0" ]
13
2021-07-29T02:41:16.000Z
2022-03-16T10:22:38.000Z
unit AWS.SES; interface uses AWS.SES.Client, AWS.SES.ClientIntf, AWS.SES.Config, AWS.SES.Enums, AWS.SES.Exception, AWS.SES.Metadata, AWS.SES.Model.AccountSendingPausedException, AWS.SES.Model.AddHeaderAction, AWS.SES.Model.AlreadyExistsException, AWS.SES.Model.Body, AWS.SES.Model.BounceAction, AWS.SES.Model.BouncedRecipientInfo, AWS.SES.Model.BulkEmailDestination, AWS.SES.Model.BulkEmailDestinationStatus, AWS.SES.Model.CannotDeleteException, AWS.SES.Model.CloneReceiptRuleSetRequest, AWS.SES.Model.CloneReceiptRuleSetResponse, AWS.SES.Model.CloudWatchDestination, AWS.SES.Model.CloudWatchDimensionConfiguration, AWS.SES.Model.ConfigurationSet, AWS.SES.Model.ConfigurationSetAlreadyExistsException, AWS.SES.Model.ConfigurationSetDoesNotExistException, AWS.SES.Model.ConfigurationSetSendingPausedException, AWS.SES.Model.Content, AWS.SES.Model.CreateConfigurationSetEventDestinationRequest, AWS.SES.Model.CreateConfigurationSetEventDestinationResponse, AWS.SES.Model.CreateConfigurationSetRequest, AWS.SES.Model.CreateConfigurationSetResponse, AWS.SES.Model.CreateConfigurationSetTrackingOptionsRequest, AWS.SES.Model.CreateConfigurationSetTrackingOptionsResponse, AWS.SES.Model.CreateCustomVerificationEmailTemplateRequest, AWS.SES.Model.CreateCustomVerificationEmailTemplateResponse, AWS.SES.Model.CreateReceiptFilterRequest, AWS.SES.Model.CreateReceiptFilterResponse, AWS.SES.Model.CreateReceiptRuleRequest, AWS.SES.Model.CreateReceiptRuleResponse, AWS.SES.Model.CreateReceiptRuleSetRequest, AWS.SES.Model.CreateReceiptRuleSetResponse, AWS.SES.Model.CreateTemplateRequest, AWS.SES.Model.CreateTemplateResponse, AWS.SES.Model.CustomVerificationEmailInvalidContentException, AWS.SES.Model.CustomVerificationEmailTemplate, AWS.SES.Model.CustomVerificationEmailTemplateAlreadyExistsException, AWS.SES.Model.CustomVerificationEmailTemplateDoesNotExistException, AWS.SES.Model.DeleteConfigurationSetEventDestinationRequest, AWS.SES.Model.DeleteConfigurationSetEventDestinationResponse, AWS.SES.Model.DeleteConfigurationSetRequest, AWS.SES.Model.DeleteConfigurationSetResponse, AWS.SES.Model.DeleteConfigurationSetTrackingOptionsRequest, AWS.SES.Model.DeleteConfigurationSetTrackingOptionsResponse, AWS.SES.Model.DeleteCustomVerificationEmailTemplateRequest, AWS.SES.Model.DeleteCustomVerificationEmailTemplateResponse, AWS.SES.Model.DeleteIdentityPolicyRequest, AWS.SES.Model.DeleteIdentityPolicyResponse, AWS.SES.Model.DeleteIdentityRequest, AWS.SES.Model.DeleteIdentityResponse, AWS.SES.Model.DeleteReceiptFilterRequest, AWS.SES.Model.DeleteReceiptFilterResponse, AWS.SES.Model.DeleteReceiptRuleRequest, AWS.SES.Model.DeleteReceiptRuleResponse, AWS.SES.Model.DeleteReceiptRuleSetRequest, AWS.SES.Model.DeleteReceiptRuleSetResponse, AWS.SES.Model.DeleteTemplateRequest, AWS.SES.Model.DeleteTemplateResponse, AWS.SES.Model.DeleteVerifiedEmailAddressRequest, AWS.SES.Model.DeleteVerifiedEmailAddressResponse, AWS.SES.Model.DeliveryOptions, AWS.SES.Model.DescribeActiveReceiptRuleSetRequest, AWS.SES.Model.DescribeActiveReceiptRuleSetResponse, AWS.SES.Model.DescribeConfigurationSetRequest, AWS.SES.Model.DescribeConfigurationSetResponse, AWS.SES.Model.DescribeReceiptRuleRequest, AWS.SES.Model.DescribeReceiptRuleResponse, AWS.SES.Model.DescribeReceiptRuleSetRequest, AWS.SES.Model.DescribeReceiptRuleSetResponse, AWS.SES.Model.Destination, AWS.SES.Model.EventDestination, AWS.SES.Model.EventDestinationAlreadyExistsException, AWS.SES.Model.EventDestinationDoesNotExistException, AWS.SES.Model.ExtensionField, AWS.SES.Model.FromEmailAddressNotVerifiedException, AWS.SES.Model.GetAccountSendingEnabledRequest, AWS.SES.Model.GetAccountSendingEnabledResponse, AWS.SES.Model.GetCustomVerificationEmailTemplateRequest, AWS.SES.Model.GetCustomVerificationEmailTemplateResponse, AWS.SES.Model.GetIdentityDkimAttributesRequest, AWS.SES.Model.GetIdentityDkimAttributesResponse, AWS.SES.Model.GetIdentityMailFromDomainAttributesRequest, AWS.SES.Model.GetIdentityMailFromDomainAttributesResponse, AWS.SES.Model.GetIdentityNotificationAttributesRequest, AWS.SES.Model.GetIdentityNotificationAttributesResponse, AWS.SES.Model.GetIdentityPoliciesRequest, AWS.SES.Model.GetIdentityPoliciesResponse, AWS.SES.Model.GetIdentityVerificationAttributesRequest, AWS.SES.Model.GetIdentityVerificationAttributesResponse, AWS.SES.Model.GetSendQuotaRequest, AWS.SES.Model.GetSendQuotaResponse, AWS.SES.Model.GetSendStatisticsRequest, AWS.SES.Model.GetSendStatisticsResponse, AWS.SES.Model.GetTemplateRequest, AWS.SES.Model.GetTemplateResponse, AWS.SES.Model.IdentityDkimAttributes, AWS.SES.Model.IdentityMailFromDomainAttributes, AWS.SES.Model.IdentityNotificationAttributes, AWS.SES.Model.IdentityVerificationAttributes, AWS.SES.Model.InvalidCloudWatchDestinationException, AWS.SES.Model.InvalidConfigurationSetException, AWS.SES.Model.InvalidDeliveryOptionsException, AWS.SES.Model.InvalidFirehoseDestinationException, AWS.SES.Model.InvalidLambdaFunctionException, AWS.SES.Model.InvalidPolicyException, AWS.SES.Model.InvalidRenderingParameterException, AWS.SES.Model.InvalidS3ConfigurationException, AWS.SES.Model.InvalidSNSDestinationException, AWS.SES.Model.InvalidSnsTopicException, AWS.SES.Model.InvalidTemplateException, AWS.SES.Model.InvalidTrackingOptionsException, AWS.SES.Model.KinesisFirehoseDestination, AWS.SES.Model.LambdaAction, AWS.SES.Model.LimitExceededException, AWS.SES.Model.ListConfigurationSetsRequest, AWS.SES.Model.ListConfigurationSetsResponse, AWS.SES.Model.ListCustomVerificationEmailTemplatesRequest, AWS.SES.Model.ListCustomVerificationEmailTemplatesResponse, AWS.SES.Model.ListIdentitiesRequest, AWS.SES.Model.ListIdentitiesResponse, AWS.SES.Model.ListIdentityPoliciesRequest, AWS.SES.Model.ListIdentityPoliciesResponse, AWS.SES.Model.ListReceiptFiltersRequest, AWS.SES.Model.ListReceiptFiltersResponse, AWS.SES.Model.ListReceiptRuleSetsRequest, AWS.SES.Model.ListReceiptRuleSetsResponse, AWS.SES.Model.ListTemplatesRequest, AWS.SES.Model.ListTemplatesResponse, AWS.SES.Model.ListVerifiedEmailAddressesRequest, AWS.SES.Model.ListVerifiedEmailAddressesResponse, AWS.SES.Model.MailFromDomainNotVerifiedException, AWS.SES.Model.Message, AWS.SES.Model.MessageDsn, AWS.SES.Model.MessageRejectedException, AWS.SES.Model.MessageTag, AWS.SES.Model.MissingRenderingAttributeException, AWS.SES.Model.ProductionAccessNotGrantedException, AWS.SES.Model.PutConfigurationSetDeliveryOptionsRequest, AWS.SES.Model.PutConfigurationSetDeliveryOptionsResponse, AWS.SES.Model.PutIdentityPolicyRequest, AWS.SES.Model.PutIdentityPolicyResponse, AWS.SES.Model.RawMessage, AWS.SES.Model.ReceiptAction, AWS.SES.Model.ReceiptFilter, AWS.SES.Model.ReceiptIpFilter, AWS.SES.Model.ReceiptRule, AWS.SES.Model.ReceiptRuleSetMetadata, AWS.SES.Model.RecipientDsnFields, AWS.SES.Model.ReorderReceiptRuleSetRequest, AWS.SES.Model.ReorderReceiptRuleSetResponse, AWS.SES.Model.ReputationOptions, AWS.SES.Model.Request, AWS.SES.Model.RuleDoesNotExistException, AWS.SES.Model.RuleSetDoesNotExistException, AWS.SES.Model.S3Action, AWS.SES.Model.SendBounceRequest, AWS.SES.Model.SendBounceResponse, AWS.SES.Model.SendBulkTemplatedEmailRequest, AWS.SES.Model.SendBulkTemplatedEmailResponse, AWS.SES.Model.SendCustomVerificationEmailRequest, AWS.SES.Model.SendCustomVerificationEmailResponse, AWS.SES.Model.SendDataPoint, AWS.SES.Model.SendEmailRequest, AWS.SES.Model.SendEmailResponse, AWS.SES.Model.SendRawEmailRequest, AWS.SES.Model.SendRawEmailResponse, AWS.SES.Model.SendTemplatedEmailRequest, AWS.SES.Model.SendTemplatedEmailResponse, AWS.SES.Model.SetActiveReceiptRuleSetRequest, AWS.SES.Model.SetActiveReceiptRuleSetResponse, AWS.SES.Model.SetIdentityDkimEnabledRequest, AWS.SES.Model.SetIdentityDkimEnabledResponse, AWS.SES.Model.SetIdentityFeedbackForwardingEnabledRequest, AWS.SES.Model.SetIdentityFeedbackForwardingEnabledResponse, AWS.SES.Model.SetIdentityHeadersInNotificationsEnabledRequest, AWS.SES.Model.SetIdentityHeadersInNotificationsEnabledResponse, AWS.SES.Model.SetIdentityMailFromDomainRequest, AWS.SES.Model.SetIdentityMailFromDomainResponse, AWS.SES.Model.SetIdentityNotificationTopicRequest, AWS.SES.Model.SetIdentityNotificationTopicResponse, AWS.SES.Model.SetReceiptRulePositionRequest, AWS.SES.Model.SetReceiptRulePositionResponse, AWS.SES.Model.SNSAction, AWS.SES.Model.SNSDestination, AWS.SES.Model.StopAction, AWS.SES.Model.Template, AWS.SES.Model.TemplateDoesNotExistException, AWS.SES.Model.TemplateMetadata, AWS.SES.Model.TestRenderTemplateRequest, AWS.SES.Model.TestRenderTemplateResponse, AWS.SES.Model.TrackingOptions, AWS.SES.Model.TrackingOptionsAlreadyExistsException, AWS.SES.Model.TrackingOptionsDoesNotExistException, AWS.SES.Model.UpdateAccountSendingEnabledRequest, AWS.SES.Model.UpdateAccountSendingEnabledResponse, AWS.SES.Model.UpdateConfigurationSetEventDestinationRequest, AWS.SES.Model.UpdateConfigurationSetEventDestinationResponse, AWS.SES.Model.UpdateConfigurationSetReputationMetricsEnabledRequest, AWS.SES.Model.UpdateConfigurationSetReputationMetricsEnabledResponse, AWS.SES.Model.UpdateConfigurationSetSendingEnabledRequest, AWS.SES.Model.UpdateConfigurationSetSendingEnabledResponse, AWS.SES.Model.UpdateConfigurationSetTrackingOptionsRequest, AWS.SES.Model.UpdateConfigurationSetTrackingOptionsResponse, AWS.SES.Model.UpdateCustomVerificationEmailTemplateRequest, AWS.SES.Model.UpdateCustomVerificationEmailTemplateResponse, AWS.SES.Model.UpdateReceiptRuleRequest, AWS.SES.Model.UpdateReceiptRuleResponse, AWS.SES.Model.UpdateTemplateRequest, AWS.SES.Model.UpdateTemplateResponse, AWS.SES.Model.VerifyDomainDkimRequest, AWS.SES.Model.VerifyDomainDkimResponse, AWS.SES.Model.VerifyDomainIdentityRequest, AWS.SES.Model.VerifyDomainIdentityResponse, AWS.SES.Model.VerifyEmailAddressRequest, AWS.SES.Model.VerifyEmailAddressResponse, AWS.SES.Model.VerifyEmailIdentityRequest, AWS.SES.Model.VerifyEmailIdentityResponse, AWS.SES.Model.WorkmailAction; type EAccountSendingPausedException = AWS.SES.Model.AccountSendingPausedException.EAccountSendingPausedException; EAlreadyExistsException = AWS.SES.Model.AlreadyExistsException.EAlreadyExistsException; EAmazonSimpleEmailServiceException = AWS.SES.Exception.EAmazonSimpleEmailServiceException; ECannotDeleteException = AWS.SES.Model.CannotDeleteException.ECannotDeleteException; EConfigurationSetAlreadyExistsException = AWS.SES.Model.ConfigurationSetAlreadyExistsException.EConfigurationSetAlreadyExistsException; EConfigurationSetDoesNotExistException = AWS.SES.Model.ConfigurationSetDoesNotExistException.EConfigurationSetDoesNotExistException; EConfigurationSetSendingPausedException = AWS.SES.Model.ConfigurationSetSendingPausedException.EConfigurationSetSendingPausedException; ECustomVerificationEmailInvalidContentException = AWS.SES.Model.CustomVerificationEmailInvalidContentException.ECustomVerificationEmailInvalidContentException; ECustomVerificationEmailTemplateAlreadyExistsException = AWS.SES.Model.CustomVerificationEmailTemplateAlreadyExistsException.ECustomVerificationEmailTemplateAlreadyExistsException; ECustomVerificationEmailTemplateDoesNotExistException = AWS.SES.Model.CustomVerificationEmailTemplateDoesNotExistException.ECustomVerificationEmailTemplateDoesNotExistException; EEventDestinationAlreadyExistsException = AWS.SES.Model.EventDestinationAlreadyExistsException.EEventDestinationAlreadyExistsException; EEventDestinationDoesNotExistException = AWS.SES.Model.EventDestinationDoesNotExistException.EEventDestinationDoesNotExistException; EFromEmailAddressNotVerifiedException = AWS.SES.Model.FromEmailAddressNotVerifiedException.EFromEmailAddressNotVerifiedException; EInvalidCloudWatchDestinationException = AWS.SES.Model.InvalidCloudWatchDestinationException.EInvalidCloudWatchDestinationException; EInvalidConfigurationSetException = AWS.SES.Model.InvalidConfigurationSetException.EInvalidConfigurationSetException; EInvalidDeliveryOptionsException = AWS.SES.Model.InvalidDeliveryOptionsException.EInvalidDeliveryOptionsException; EInvalidFirehoseDestinationException = AWS.SES.Model.InvalidFirehoseDestinationException.EInvalidFirehoseDestinationException; EInvalidLambdaFunctionException = AWS.SES.Model.InvalidLambdaFunctionException.EInvalidLambdaFunctionException; EInvalidPolicyException = AWS.SES.Model.InvalidPolicyException.EInvalidPolicyException; EInvalidRenderingParameterException = AWS.SES.Model.InvalidRenderingParameterException.EInvalidRenderingParameterException; EInvalidS3ConfigurationException = AWS.SES.Model.InvalidS3ConfigurationException.EInvalidS3ConfigurationException; EInvalidSNSDestinationException = AWS.SES.Model.InvalidSNSDestinationException.EInvalidSNSDestinationException; EInvalidSnsTopicException = AWS.SES.Model.InvalidSnsTopicException.EInvalidSnsTopicException; EInvalidTemplateException = AWS.SES.Model.InvalidTemplateException.EInvalidTemplateException; EInvalidTrackingOptionsException = AWS.SES.Model.InvalidTrackingOptionsException.EInvalidTrackingOptionsException; ELimitExceededException = AWS.SES.Model.LimitExceededException.ELimitExceededException; EMailFromDomainNotVerifiedException = AWS.SES.Model.MailFromDomainNotVerifiedException.EMailFromDomainNotVerifiedException; EMessageRejectedException = AWS.SES.Model.MessageRejectedException.EMessageRejectedException; EMissingRenderingAttributeException = AWS.SES.Model.MissingRenderingAttributeException.EMissingRenderingAttributeException; EProductionAccessNotGrantedException = AWS.SES.Model.ProductionAccessNotGrantedException.EProductionAccessNotGrantedException; ERuleDoesNotExistException = AWS.SES.Model.RuleDoesNotExistException.ERuleDoesNotExistException; ERuleSetDoesNotExistException = AWS.SES.Model.RuleSetDoesNotExistException.ERuleSetDoesNotExistException; ETemplateDoesNotExistException = AWS.SES.Model.TemplateDoesNotExistException.ETemplateDoesNotExistException; ETrackingOptionsAlreadyExistsException = AWS.SES.Model.TrackingOptionsAlreadyExistsException.ETrackingOptionsAlreadyExistsException; ETrackingOptionsDoesNotExistException = AWS.SES.Model.TrackingOptionsDoesNotExistException.ETrackingOptionsDoesNotExistException; IAddHeaderAction = AWS.SES.Model.AddHeaderAction.IAddHeaderAction; IAmazonSimpleEmailService = AWS.SES.ClientIntf.IAmazonSimpleEmailService; IBody = AWS.SES.Model.Body.IBody; IBounceAction = AWS.SES.Model.BounceAction.IBounceAction; IBouncedRecipientInfo = AWS.SES.Model.BouncedRecipientInfo.IBouncedRecipientInfo; IBulkEmailDestination = AWS.SES.Model.BulkEmailDestination.IBulkEmailDestination; IBulkEmailDestinationStatus = AWS.SES.Model.BulkEmailDestinationStatus.IBulkEmailDestinationStatus; ICloneReceiptRuleSetRequest = AWS.SES.Model.CloneReceiptRuleSetRequest.ICloneReceiptRuleSetRequest; ICloneReceiptRuleSetResponse = AWS.SES.Model.CloneReceiptRuleSetResponse.ICloneReceiptRuleSetResponse; ICloudWatchDestination = AWS.SES.Model.CloudWatchDestination.ICloudWatchDestination; ICloudWatchDimensionConfiguration = AWS.SES.Model.CloudWatchDimensionConfiguration.ICloudWatchDimensionConfiguration; IConfigurationSet = AWS.SES.Model.ConfigurationSet.IConfigurationSet; IContent = AWS.SES.Model.Content.IContent; ICreateConfigurationSetEventDestinationRequest = AWS.SES.Model.CreateConfigurationSetEventDestinationRequest.ICreateConfigurationSetEventDestinationRequest; ICreateConfigurationSetEventDestinationResponse = AWS.SES.Model.CreateConfigurationSetEventDestinationResponse.ICreateConfigurationSetEventDestinationResponse; ICreateConfigurationSetRequest = AWS.SES.Model.CreateConfigurationSetRequest.ICreateConfigurationSetRequest; ICreateConfigurationSetResponse = AWS.SES.Model.CreateConfigurationSetResponse.ICreateConfigurationSetResponse; ICreateConfigurationSetTrackingOptionsRequest = AWS.SES.Model.CreateConfigurationSetTrackingOptionsRequest.ICreateConfigurationSetTrackingOptionsRequest; ICreateConfigurationSetTrackingOptionsResponse = AWS.SES.Model.CreateConfigurationSetTrackingOptionsResponse.ICreateConfigurationSetTrackingOptionsResponse; ICreateCustomVerificationEmailTemplateRequest = AWS.SES.Model.CreateCustomVerificationEmailTemplateRequest.ICreateCustomVerificationEmailTemplateRequest; ICreateCustomVerificationEmailTemplateResponse = AWS.SES.Model.CreateCustomVerificationEmailTemplateResponse.ICreateCustomVerificationEmailTemplateResponse; ICreateReceiptFilterRequest = AWS.SES.Model.CreateReceiptFilterRequest.ICreateReceiptFilterRequest; ICreateReceiptFilterResponse = AWS.SES.Model.CreateReceiptFilterResponse.ICreateReceiptFilterResponse; ICreateReceiptRuleRequest = AWS.SES.Model.CreateReceiptRuleRequest.ICreateReceiptRuleRequest; ICreateReceiptRuleResponse = AWS.SES.Model.CreateReceiptRuleResponse.ICreateReceiptRuleResponse; ICreateReceiptRuleSetRequest = AWS.SES.Model.CreateReceiptRuleSetRequest.ICreateReceiptRuleSetRequest; ICreateReceiptRuleSetResponse = AWS.SES.Model.CreateReceiptRuleSetResponse.ICreateReceiptRuleSetResponse; ICreateTemplateRequest = AWS.SES.Model.CreateTemplateRequest.ICreateTemplateRequest; ICreateTemplateResponse = AWS.SES.Model.CreateTemplateResponse.ICreateTemplateResponse; ICustomVerificationEmailTemplate = AWS.SES.Model.CustomVerificationEmailTemplate.ICustomVerificationEmailTemplate; IDeleteConfigurationSetEventDestinationRequest = AWS.SES.Model.DeleteConfigurationSetEventDestinationRequest.IDeleteConfigurationSetEventDestinationRequest; IDeleteConfigurationSetEventDestinationResponse = AWS.SES.Model.DeleteConfigurationSetEventDestinationResponse.IDeleteConfigurationSetEventDestinationResponse; IDeleteConfigurationSetRequest = AWS.SES.Model.DeleteConfigurationSetRequest.IDeleteConfigurationSetRequest; IDeleteConfigurationSetResponse = AWS.SES.Model.DeleteConfigurationSetResponse.IDeleteConfigurationSetResponse; IDeleteConfigurationSetTrackingOptionsRequest = AWS.SES.Model.DeleteConfigurationSetTrackingOptionsRequest.IDeleteConfigurationSetTrackingOptionsRequest; IDeleteConfigurationSetTrackingOptionsResponse = AWS.SES.Model.DeleteConfigurationSetTrackingOptionsResponse.IDeleteConfigurationSetTrackingOptionsResponse; IDeleteCustomVerificationEmailTemplateRequest = AWS.SES.Model.DeleteCustomVerificationEmailTemplateRequest.IDeleteCustomVerificationEmailTemplateRequest; IDeleteCustomVerificationEmailTemplateResponse = AWS.SES.Model.DeleteCustomVerificationEmailTemplateResponse.IDeleteCustomVerificationEmailTemplateResponse; IDeleteIdentityPolicyRequest = AWS.SES.Model.DeleteIdentityPolicyRequest.IDeleteIdentityPolicyRequest; IDeleteIdentityPolicyResponse = AWS.SES.Model.DeleteIdentityPolicyResponse.IDeleteIdentityPolicyResponse; IDeleteIdentityRequest = AWS.SES.Model.DeleteIdentityRequest.IDeleteIdentityRequest; IDeleteIdentityResponse = AWS.SES.Model.DeleteIdentityResponse.IDeleteIdentityResponse; IDeleteReceiptFilterRequest = AWS.SES.Model.DeleteReceiptFilterRequest.IDeleteReceiptFilterRequest; IDeleteReceiptFilterResponse = AWS.SES.Model.DeleteReceiptFilterResponse.IDeleteReceiptFilterResponse; IDeleteReceiptRuleRequest = AWS.SES.Model.DeleteReceiptRuleRequest.IDeleteReceiptRuleRequest; IDeleteReceiptRuleResponse = AWS.SES.Model.DeleteReceiptRuleResponse.IDeleteReceiptRuleResponse; IDeleteReceiptRuleSetRequest = AWS.SES.Model.DeleteReceiptRuleSetRequest.IDeleteReceiptRuleSetRequest; IDeleteReceiptRuleSetResponse = AWS.SES.Model.DeleteReceiptRuleSetResponse.IDeleteReceiptRuleSetResponse; IDeleteTemplateRequest = AWS.SES.Model.DeleteTemplateRequest.IDeleteTemplateRequest; IDeleteTemplateResponse = AWS.SES.Model.DeleteTemplateResponse.IDeleteTemplateResponse; IDeleteVerifiedEmailAddressRequest = AWS.SES.Model.DeleteVerifiedEmailAddressRequest.IDeleteVerifiedEmailAddressRequest; IDeleteVerifiedEmailAddressResponse = AWS.SES.Model.DeleteVerifiedEmailAddressResponse.IDeleteVerifiedEmailAddressResponse; IDeliveryOptions = AWS.SES.Model.DeliveryOptions.IDeliveryOptions; IDescribeActiveReceiptRuleSetRequest = AWS.SES.Model.DescribeActiveReceiptRuleSetRequest.IDescribeActiveReceiptRuleSetRequest; IDescribeActiveReceiptRuleSetResponse = AWS.SES.Model.DescribeActiveReceiptRuleSetResponse.IDescribeActiveReceiptRuleSetResponse; IDescribeConfigurationSetRequest = AWS.SES.Model.DescribeConfigurationSetRequest.IDescribeConfigurationSetRequest; IDescribeConfigurationSetResponse = AWS.SES.Model.DescribeConfigurationSetResponse.IDescribeConfigurationSetResponse; IDescribeReceiptRuleRequest = AWS.SES.Model.DescribeReceiptRuleRequest.IDescribeReceiptRuleRequest; IDescribeReceiptRuleResponse = AWS.SES.Model.DescribeReceiptRuleResponse.IDescribeReceiptRuleResponse; IDescribeReceiptRuleSetRequest = AWS.SES.Model.DescribeReceiptRuleSetRequest.IDescribeReceiptRuleSetRequest; IDescribeReceiptRuleSetResponse = AWS.SES.Model.DescribeReceiptRuleSetResponse.IDescribeReceiptRuleSetResponse; IDestination = AWS.SES.Model.Destination.IDestination; IEventDestination = AWS.SES.Model.EventDestination.IEventDestination; IExtensionField = AWS.SES.Model.ExtensionField.IExtensionField; IGetAccountSendingEnabledRequest = AWS.SES.Model.GetAccountSendingEnabledRequest.IGetAccountSendingEnabledRequest; IGetAccountSendingEnabledResponse = AWS.SES.Model.GetAccountSendingEnabledResponse.IGetAccountSendingEnabledResponse; IGetCustomVerificationEmailTemplateRequest = AWS.SES.Model.GetCustomVerificationEmailTemplateRequest.IGetCustomVerificationEmailTemplateRequest; IGetCustomVerificationEmailTemplateResponse = AWS.SES.Model.GetCustomVerificationEmailTemplateResponse.IGetCustomVerificationEmailTemplateResponse; IGetIdentityDkimAttributesRequest = AWS.SES.Model.GetIdentityDkimAttributesRequest.IGetIdentityDkimAttributesRequest; IGetIdentityDkimAttributesResponse = AWS.SES.Model.GetIdentityDkimAttributesResponse.IGetIdentityDkimAttributesResponse; IGetIdentityMailFromDomainAttributesRequest = AWS.SES.Model.GetIdentityMailFromDomainAttributesRequest.IGetIdentityMailFromDomainAttributesRequest; IGetIdentityMailFromDomainAttributesResponse = AWS.SES.Model.GetIdentityMailFromDomainAttributesResponse.IGetIdentityMailFromDomainAttributesResponse; IGetIdentityNotificationAttributesRequest = AWS.SES.Model.GetIdentityNotificationAttributesRequest.IGetIdentityNotificationAttributesRequest; IGetIdentityNotificationAttributesResponse = AWS.SES.Model.GetIdentityNotificationAttributesResponse.IGetIdentityNotificationAttributesResponse; IGetIdentityPoliciesRequest = AWS.SES.Model.GetIdentityPoliciesRequest.IGetIdentityPoliciesRequest; IGetIdentityPoliciesResponse = AWS.SES.Model.GetIdentityPoliciesResponse.IGetIdentityPoliciesResponse; IGetIdentityVerificationAttributesRequest = AWS.SES.Model.GetIdentityVerificationAttributesRequest.IGetIdentityVerificationAttributesRequest; IGetIdentityVerificationAttributesResponse = AWS.SES.Model.GetIdentityVerificationAttributesResponse.IGetIdentityVerificationAttributesResponse; IGetSendQuotaRequest = AWS.SES.Model.GetSendQuotaRequest.IGetSendQuotaRequest; IGetSendQuotaResponse = AWS.SES.Model.GetSendQuotaResponse.IGetSendQuotaResponse; IGetSendStatisticsRequest = AWS.SES.Model.GetSendStatisticsRequest.IGetSendStatisticsRequest; IGetSendStatisticsResponse = AWS.SES.Model.GetSendStatisticsResponse.IGetSendStatisticsResponse; IGetTemplateRequest = AWS.SES.Model.GetTemplateRequest.IGetTemplateRequest; IGetTemplateResponse = AWS.SES.Model.GetTemplateResponse.IGetTemplateResponse; IIdentityDkimAttributes = AWS.SES.Model.IdentityDkimAttributes.IIdentityDkimAttributes; IIdentityMailFromDomainAttributes = AWS.SES.Model.IdentityMailFromDomainAttributes.IIdentityMailFromDomainAttributes; IIdentityNotificationAttributes = AWS.SES.Model.IdentityNotificationAttributes.IIdentityNotificationAttributes; IIdentityVerificationAttributes = AWS.SES.Model.IdentityVerificationAttributes.IIdentityVerificationAttributes; IKinesisFirehoseDestination = AWS.SES.Model.KinesisFirehoseDestination.IKinesisFirehoseDestination; ILambdaAction = AWS.SES.Model.LambdaAction.ILambdaAction; IListConfigurationSetsRequest = AWS.SES.Model.ListConfigurationSetsRequest.IListConfigurationSetsRequest; IListConfigurationSetsResponse = AWS.SES.Model.ListConfigurationSetsResponse.IListConfigurationSetsResponse; IListCustomVerificationEmailTemplatesRequest = AWS.SES.Model.ListCustomVerificationEmailTemplatesRequest.IListCustomVerificationEmailTemplatesRequest; IListCustomVerificationEmailTemplatesResponse = AWS.SES.Model.ListCustomVerificationEmailTemplatesResponse.IListCustomVerificationEmailTemplatesResponse; IListIdentitiesRequest = AWS.SES.Model.ListIdentitiesRequest.IListIdentitiesRequest; IListIdentitiesResponse = AWS.SES.Model.ListIdentitiesResponse.IListIdentitiesResponse; IListIdentityPoliciesRequest = AWS.SES.Model.ListIdentityPoliciesRequest.IListIdentityPoliciesRequest; IListIdentityPoliciesResponse = AWS.SES.Model.ListIdentityPoliciesResponse.IListIdentityPoliciesResponse; IListReceiptFiltersRequest = AWS.SES.Model.ListReceiptFiltersRequest.IListReceiptFiltersRequest; IListReceiptFiltersResponse = AWS.SES.Model.ListReceiptFiltersResponse.IListReceiptFiltersResponse; IListReceiptRuleSetsRequest = AWS.SES.Model.ListReceiptRuleSetsRequest.IListReceiptRuleSetsRequest; IListReceiptRuleSetsResponse = AWS.SES.Model.ListReceiptRuleSetsResponse.IListReceiptRuleSetsResponse; IListTemplatesRequest = AWS.SES.Model.ListTemplatesRequest.IListTemplatesRequest; IListTemplatesResponse = AWS.SES.Model.ListTemplatesResponse.IListTemplatesResponse; IListVerifiedEmailAddressesRequest = AWS.SES.Model.ListVerifiedEmailAddressesRequest.IListVerifiedEmailAddressesRequest; IListVerifiedEmailAddressesResponse = AWS.SES.Model.ListVerifiedEmailAddressesResponse.IListVerifiedEmailAddressesResponse; IMessage = AWS.SES.Model.Message.IMessage; IMessageDsn = AWS.SES.Model.MessageDsn.IMessageDsn; IMessageTag = AWS.SES.Model.MessageTag.IMessageTag; IPutConfigurationSetDeliveryOptionsRequest = AWS.SES.Model.PutConfigurationSetDeliveryOptionsRequest.IPutConfigurationSetDeliveryOptionsRequest; IPutConfigurationSetDeliveryOptionsResponse = AWS.SES.Model.PutConfigurationSetDeliveryOptionsResponse.IPutConfigurationSetDeliveryOptionsResponse; IPutIdentityPolicyRequest = AWS.SES.Model.PutIdentityPolicyRequest.IPutIdentityPolicyRequest; IPutIdentityPolicyResponse = AWS.SES.Model.PutIdentityPolicyResponse.IPutIdentityPolicyResponse; IRawMessage = AWS.SES.Model.RawMessage.IRawMessage; IReceiptAction = AWS.SES.Model.ReceiptAction.IReceiptAction; IReceiptFilter = AWS.SES.Model.ReceiptFilter.IReceiptFilter; IReceiptIpFilter = AWS.SES.Model.ReceiptIpFilter.IReceiptIpFilter; IReceiptRule = AWS.SES.Model.ReceiptRule.IReceiptRule; IReceiptRuleSetMetadata = AWS.SES.Model.ReceiptRuleSetMetadata.IReceiptRuleSetMetadata; IRecipientDsnFields = AWS.SES.Model.RecipientDsnFields.IRecipientDsnFields; IReorderReceiptRuleSetRequest = AWS.SES.Model.ReorderReceiptRuleSetRequest.IReorderReceiptRuleSetRequest; IReorderReceiptRuleSetResponse = AWS.SES.Model.ReorderReceiptRuleSetResponse.IReorderReceiptRuleSetResponse; IReputationOptions = AWS.SES.Model.ReputationOptions.IReputationOptions; IS3Action = AWS.SES.Model.S3Action.IS3Action; ISendBounceRequest = AWS.SES.Model.SendBounceRequest.ISendBounceRequest; ISendBounceResponse = AWS.SES.Model.SendBounceResponse.ISendBounceResponse; ISendBulkTemplatedEmailRequest = AWS.SES.Model.SendBulkTemplatedEmailRequest.ISendBulkTemplatedEmailRequest; ISendBulkTemplatedEmailResponse = AWS.SES.Model.SendBulkTemplatedEmailResponse.ISendBulkTemplatedEmailResponse; ISendCustomVerificationEmailRequest = AWS.SES.Model.SendCustomVerificationEmailRequest.ISendCustomVerificationEmailRequest; ISendCustomVerificationEmailResponse = AWS.SES.Model.SendCustomVerificationEmailResponse.ISendCustomVerificationEmailResponse; ISendDataPoint = AWS.SES.Model.SendDataPoint.ISendDataPoint; ISendEmailRequest = AWS.SES.Model.SendEmailRequest.ISendEmailRequest; ISendEmailResponse = AWS.SES.Model.SendEmailResponse.ISendEmailResponse; ISendRawEmailRequest = AWS.SES.Model.SendRawEmailRequest.ISendRawEmailRequest; ISendRawEmailResponse = AWS.SES.Model.SendRawEmailResponse.ISendRawEmailResponse; ISendTemplatedEmailRequest = AWS.SES.Model.SendTemplatedEmailRequest.ISendTemplatedEmailRequest; ISendTemplatedEmailResponse = AWS.SES.Model.SendTemplatedEmailResponse.ISendTemplatedEmailResponse; ISetActiveReceiptRuleSetRequest = AWS.SES.Model.SetActiveReceiptRuleSetRequest.ISetActiveReceiptRuleSetRequest; ISetActiveReceiptRuleSetResponse = AWS.SES.Model.SetActiveReceiptRuleSetResponse.ISetActiveReceiptRuleSetResponse; ISetIdentityDkimEnabledRequest = AWS.SES.Model.SetIdentityDkimEnabledRequest.ISetIdentityDkimEnabledRequest; ISetIdentityDkimEnabledResponse = AWS.SES.Model.SetIdentityDkimEnabledResponse.ISetIdentityDkimEnabledResponse; ISetIdentityFeedbackForwardingEnabledRequest = AWS.SES.Model.SetIdentityFeedbackForwardingEnabledRequest.ISetIdentityFeedbackForwardingEnabledRequest; ISetIdentityFeedbackForwardingEnabledResponse = AWS.SES.Model.SetIdentityFeedbackForwardingEnabledResponse.ISetIdentityFeedbackForwardingEnabledResponse; ISetIdentityHeadersInNotificationsEnabledRequest = AWS.SES.Model.SetIdentityHeadersInNotificationsEnabledRequest.ISetIdentityHeadersInNotificationsEnabledRequest; ISetIdentityHeadersInNotificationsEnabledResponse = AWS.SES.Model.SetIdentityHeadersInNotificationsEnabledResponse.ISetIdentityHeadersInNotificationsEnabledResponse; ISetIdentityMailFromDomainRequest = AWS.SES.Model.SetIdentityMailFromDomainRequest.ISetIdentityMailFromDomainRequest; ISetIdentityMailFromDomainResponse = AWS.SES.Model.SetIdentityMailFromDomainResponse.ISetIdentityMailFromDomainResponse; ISetIdentityNotificationTopicRequest = AWS.SES.Model.SetIdentityNotificationTopicRequest.ISetIdentityNotificationTopicRequest; ISetIdentityNotificationTopicResponse = AWS.SES.Model.SetIdentityNotificationTopicResponse.ISetIdentityNotificationTopicResponse; ISetReceiptRulePositionRequest = AWS.SES.Model.SetReceiptRulePositionRequest.ISetReceiptRulePositionRequest; ISetReceiptRulePositionResponse = AWS.SES.Model.SetReceiptRulePositionResponse.ISetReceiptRulePositionResponse; ISNSAction = AWS.SES.Model.SNSAction.ISNSAction; ISNSDestination = AWS.SES.Model.SNSDestination.ISNSDestination; IStopAction = AWS.SES.Model.StopAction.IStopAction; ITemplate = AWS.SES.Model.Template.ITemplate; ITemplateMetadata = AWS.SES.Model.TemplateMetadata.ITemplateMetadata; ITestRenderTemplateRequest = AWS.SES.Model.TestRenderTemplateRequest.ITestRenderTemplateRequest; ITestRenderTemplateResponse = AWS.SES.Model.TestRenderTemplateResponse.ITestRenderTemplateResponse; ITrackingOptions = AWS.SES.Model.TrackingOptions.ITrackingOptions; IUpdateAccountSendingEnabledRequest = AWS.SES.Model.UpdateAccountSendingEnabledRequest.IUpdateAccountSendingEnabledRequest; IUpdateAccountSendingEnabledResponse = AWS.SES.Model.UpdateAccountSendingEnabledResponse.IUpdateAccountSendingEnabledResponse; IUpdateConfigurationSetEventDestinationRequest = AWS.SES.Model.UpdateConfigurationSetEventDestinationRequest.IUpdateConfigurationSetEventDestinationRequest; IUpdateConfigurationSetEventDestinationResponse = AWS.SES.Model.UpdateConfigurationSetEventDestinationResponse.IUpdateConfigurationSetEventDestinationResponse; IUpdateConfigurationSetReputationMetricsEnabledRequest = AWS.SES.Model.UpdateConfigurationSetReputationMetricsEnabledRequest.IUpdateConfigurationSetReputationMetricsEnabledRequest; IUpdateConfigurationSetReputationMetricsEnabledResponse = AWS.SES.Model.UpdateConfigurationSetReputationMetricsEnabledResponse.IUpdateConfigurationSetReputationMetricsEnabledResponse; IUpdateConfigurationSetSendingEnabledRequest = AWS.SES.Model.UpdateConfigurationSetSendingEnabledRequest.IUpdateConfigurationSetSendingEnabledRequest; IUpdateConfigurationSetSendingEnabledResponse = AWS.SES.Model.UpdateConfigurationSetSendingEnabledResponse.IUpdateConfigurationSetSendingEnabledResponse; IUpdateConfigurationSetTrackingOptionsRequest = AWS.SES.Model.UpdateConfigurationSetTrackingOptionsRequest.IUpdateConfigurationSetTrackingOptionsRequest; IUpdateConfigurationSetTrackingOptionsResponse = AWS.SES.Model.UpdateConfigurationSetTrackingOptionsResponse.IUpdateConfigurationSetTrackingOptionsResponse; IUpdateCustomVerificationEmailTemplateRequest = AWS.SES.Model.UpdateCustomVerificationEmailTemplateRequest.IUpdateCustomVerificationEmailTemplateRequest; IUpdateCustomVerificationEmailTemplateResponse = AWS.SES.Model.UpdateCustomVerificationEmailTemplateResponse.IUpdateCustomVerificationEmailTemplateResponse; IUpdateReceiptRuleRequest = AWS.SES.Model.UpdateReceiptRuleRequest.IUpdateReceiptRuleRequest; IUpdateReceiptRuleResponse = AWS.SES.Model.UpdateReceiptRuleResponse.IUpdateReceiptRuleResponse; IUpdateTemplateRequest = AWS.SES.Model.UpdateTemplateRequest.IUpdateTemplateRequest; IUpdateTemplateResponse = AWS.SES.Model.UpdateTemplateResponse.IUpdateTemplateResponse; IVerifyDomainDkimRequest = AWS.SES.Model.VerifyDomainDkimRequest.IVerifyDomainDkimRequest; IVerifyDomainDkimResponse = AWS.SES.Model.VerifyDomainDkimResponse.IVerifyDomainDkimResponse; IVerifyDomainIdentityRequest = AWS.SES.Model.VerifyDomainIdentityRequest.IVerifyDomainIdentityRequest; IVerifyDomainIdentityResponse = AWS.SES.Model.VerifyDomainIdentityResponse.IVerifyDomainIdentityResponse; IVerifyEmailAddressRequest = AWS.SES.Model.VerifyEmailAddressRequest.IVerifyEmailAddressRequest; IVerifyEmailAddressResponse = AWS.SES.Model.VerifyEmailAddressResponse.IVerifyEmailAddressResponse; IVerifyEmailIdentityRequest = AWS.SES.Model.VerifyEmailIdentityRequest.IVerifyEmailIdentityRequest; IVerifyEmailIdentityResponse = AWS.SES.Model.VerifyEmailIdentityResponse.IVerifyEmailIdentityResponse; IWorkmailAction = AWS.SES.Model.WorkmailAction.IWorkmailAction; TAddHeaderAction = AWS.SES.Model.AddHeaderAction.TAddHeaderAction; TAmazonSimpleEmailServiceClient = AWS.SES.Client.TAmazonSimpleEmailServiceClient; TAmazonSimpleEmailServiceConfig = AWS.SES.Config.TAmazonSimpleEmailServiceConfig; TAmazonSimpleEmailServiceMetadata = AWS.SES.Metadata.TAmazonSimpleEmailServiceMetadata; TAmazonSimpleEmailServiceRequest = AWS.SES.Model.Request.TAmazonSimpleEmailServiceRequest; TBehaviorOnMXFailure = AWS.SES.Enums.TBehaviorOnMXFailure; TBody = AWS.SES.Model.Body.TBody; TBounceAction = AWS.SES.Model.BounceAction.TBounceAction; TBouncedRecipientInfo = AWS.SES.Model.BouncedRecipientInfo.TBouncedRecipientInfo; TBounceType = AWS.SES.Enums.TBounceType; TBulkEmailDestination = AWS.SES.Model.BulkEmailDestination.TBulkEmailDestination; TBulkEmailDestinationStatus = AWS.SES.Model.BulkEmailDestinationStatus.TBulkEmailDestinationStatus; TBulkEmailStatus = AWS.SES.Enums.TBulkEmailStatus; TCloneReceiptRuleSetRequest = AWS.SES.Model.CloneReceiptRuleSetRequest.TCloneReceiptRuleSetRequest; TCloneReceiptRuleSetResponse = AWS.SES.Model.CloneReceiptRuleSetResponse.TCloneReceiptRuleSetResponse; TCloudWatchDestination = AWS.SES.Model.CloudWatchDestination.TCloudWatchDestination; TCloudWatchDimensionConfiguration = AWS.SES.Model.CloudWatchDimensionConfiguration.TCloudWatchDimensionConfiguration; TConfigurationSet = AWS.SES.Model.ConfigurationSet.TConfigurationSet; TConfigurationSetAttribute = AWS.SES.Enums.TConfigurationSetAttribute; TContent = AWS.SES.Model.Content.TContent; TCreateConfigurationSetEventDestinationRequest = AWS.SES.Model.CreateConfigurationSetEventDestinationRequest.TCreateConfigurationSetEventDestinationRequest; TCreateConfigurationSetEventDestinationResponse = AWS.SES.Model.CreateConfigurationSetEventDestinationResponse.TCreateConfigurationSetEventDestinationResponse; TCreateConfigurationSetRequest = AWS.SES.Model.CreateConfigurationSetRequest.TCreateConfigurationSetRequest; TCreateConfigurationSetResponse = AWS.SES.Model.CreateConfigurationSetResponse.TCreateConfigurationSetResponse; TCreateConfigurationSetTrackingOptionsRequest = AWS.SES.Model.CreateConfigurationSetTrackingOptionsRequest.TCreateConfigurationSetTrackingOptionsRequest; TCreateConfigurationSetTrackingOptionsResponse = AWS.SES.Model.CreateConfigurationSetTrackingOptionsResponse.TCreateConfigurationSetTrackingOptionsResponse; TCreateCustomVerificationEmailTemplateRequest = AWS.SES.Model.CreateCustomVerificationEmailTemplateRequest.TCreateCustomVerificationEmailTemplateRequest; TCreateCustomVerificationEmailTemplateResponse = AWS.SES.Model.CreateCustomVerificationEmailTemplateResponse.TCreateCustomVerificationEmailTemplateResponse; TCreateReceiptFilterRequest = AWS.SES.Model.CreateReceiptFilterRequest.TCreateReceiptFilterRequest; TCreateReceiptFilterResponse = AWS.SES.Model.CreateReceiptFilterResponse.TCreateReceiptFilterResponse; TCreateReceiptRuleRequest = AWS.SES.Model.CreateReceiptRuleRequest.TCreateReceiptRuleRequest; TCreateReceiptRuleResponse = AWS.SES.Model.CreateReceiptRuleResponse.TCreateReceiptRuleResponse; TCreateReceiptRuleSetRequest = AWS.SES.Model.CreateReceiptRuleSetRequest.TCreateReceiptRuleSetRequest; TCreateReceiptRuleSetResponse = AWS.SES.Model.CreateReceiptRuleSetResponse.TCreateReceiptRuleSetResponse; TCreateTemplateRequest = AWS.SES.Model.CreateTemplateRequest.TCreateTemplateRequest; TCreateTemplateResponse = AWS.SES.Model.CreateTemplateResponse.TCreateTemplateResponse; TCustomMailFromStatus = AWS.SES.Enums.TCustomMailFromStatus; TCustomVerificationEmailTemplate = AWS.SES.Model.CustomVerificationEmailTemplate.TCustomVerificationEmailTemplate; TDeleteConfigurationSetEventDestinationRequest = AWS.SES.Model.DeleteConfigurationSetEventDestinationRequest.TDeleteConfigurationSetEventDestinationRequest; TDeleteConfigurationSetEventDestinationResponse = AWS.SES.Model.DeleteConfigurationSetEventDestinationResponse.TDeleteConfigurationSetEventDestinationResponse; TDeleteConfigurationSetRequest = AWS.SES.Model.DeleteConfigurationSetRequest.TDeleteConfigurationSetRequest; TDeleteConfigurationSetResponse = AWS.SES.Model.DeleteConfigurationSetResponse.TDeleteConfigurationSetResponse; TDeleteConfigurationSetTrackingOptionsRequest = AWS.SES.Model.DeleteConfigurationSetTrackingOptionsRequest.TDeleteConfigurationSetTrackingOptionsRequest; TDeleteConfigurationSetTrackingOptionsResponse = AWS.SES.Model.DeleteConfigurationSetTrackingOptionsResponse.TDeleteConfigurationSetTrackingOptionsResponse; TDeleteCustomVerificationEmailTemplateRequest = AWS.SES.Model.DeleteCustomVerificationEmailTemplateRequest.TDeleteCustomVerificationEmailTemplateRequest; TDeleteCustomVerificationEmailTemplateResponse = AWS.SES.Model.DeleteCustomVerificationEmailTemplateResponse.TDeleteCustomVerificationEmailTemplateResponse; TDeleteIdentityPolicyRequest = AWS.SES.Model.DeleteIdentityPolicyRequest.TDeleteIdentityPolicyRequest; TDeleteIdentityPolicyResponse = AWS.SES.Model.DeleteIdentityPolicyResponse.TDeleteIdentityPolicyResponse; TDeleteIdentityRequest = AWS.SES.Model.DeleteIdentityRequest.TDeleteIdentityRequest; TDeleteIdentityResponse = AWS.SES.Model.DeleteIdentityResponse.TDeleteIdentityResponse; TDeleteReceiptFilterRequest = AWS.SES.Model.DeleteReceiptFilterRequest.TDeleteReceiptFilterRequest; TDeleteReceiptFilterResponse = AWS.SES.Model.DeleteReceiptFilterResponse.TDeleteReceiptFilterResponse; TDeleteReceiptRuleRequest = AWS.SES.Model.DeleteReceiptRuleRequest.TDeleteReceiptRuleRequest; TDeleteReceiptRuleResponse = AWS.SES.Model.DeleteReceiptRuleResponse.TDeleteReceiptRuleResponse; TDeleteReceiptRuleSetRequest = AWS.SES.Model.DeleteReceiptRuleSetRequest.TDeleteReceiptRuleSetRequest; TDeleteReceiptRuleSetResponse = AWS.SES.Model.DeleteReceiptRuleSetResponse.TDeleteReceiptRuleSetResponse; TDeleteTemplateRequest = AWS.SES.Model.DeleteTemplateRequest.TDeleteTemplateRequest; TDeleteTemplateResponse = AWS.SES.Model.DeleteTemplateResponse.TDeleteTemplateResponse; TDeleteVerifiedEmailAddressRequest = AWS.SES.Model.DeleteVerifiedEmailAddressRequest.TDeleteVerifiedEmailAddressRequest; TDeleteVerifiedEmailAddressResponse = AWS.SES.Model.DeleteVerifiedEmailAddressResponse.TDeleteVerifiedEmailAddressResponse; TDeliveryOptions = AWS.SES.Model.DeliveryOptions.TDeliveryOptions; TDescribeActiveReceiptRuleSetRequest = AWS.SES.Model.DescribeActiveReceiptRuleSetRequest.TDescribeActiveReceiptRuleSetRequest; TDescribeActiveReceiptRuleSetResponse = AWS.SES.Model.DescribeActiveReceiptRuleSetResponse.TDescribeActiveReceiptRuleSetResponse; TDescribeConfigurationSetRequest = AWS.SES.Model.DescribeConfigurationSetRequest.TDescribeConfigurationSetRequest; TDescribeConfigurationSetResponse = AWS.SES.Model.DescribeConfigurationSetResponse.TDescribeConfigurationSetResponse; TDescribeReceiptRuleRequest = AWS.SES.Model.DescribeReceiptRuleRequest.TDescribeReceiptRuleRequest; TDescribeReceiptRuleResponse = AWS.SES.Model.DescribeReceiptRuleResponse.TDescribeReceiptRuleResponse; TDescribeReceiptRuleSetRequest = AWS.SES.Model.DescribeReceiptRuleSetRequest.TDescribeReceiptRuleSetRequest; TDescribeReceiptRuleSetResponse = AWS.SES.Model.DescribeReceiptRuleSetResponse.TDescribeReceiptRuleSetResponse; TDestination = AWS.SES.Model.Destination.TDestination; TDimensionValueSource = AWS.SES.Enums.TDimensionValueSource; TDsnAction = AWS.SES.Enums.TDsnAction; TEventDestination = AWS.SES.Model.EventDestination.TEventDestination; TEventType = AWS.SES.Enums.TEventType; TExtensionField = AWS.SES.Model.ExtensionField.TExtensionField; TGetAccountSendingEnabledRequest = AWS.SES.Model.GetAccountSendingEnabledRequest.TGetAccountSendingEnabledRequest; TGetAccountSendingEnabledResponse = AWS.SES.Model.GetAccountSendingEnabledResponse.TGetAccountSendingEnabledResponse; TGetCustomVerificationEmailTemplateRequest = AWS.SES.Model.GetCustomVerificationEmailTemplateRequest.TGetCustomVerificationEmailTemplateRequest; TGetCustomVerificationEmailTemplateResponse = AWS.SES.Model.GetCustomVerificationEmailTemplateResponse.TGetCustomVerificationEmailTemplateResponse; TGetIdentityDkimAttributesRequest = AWS.SES.Model.GetIdentityDkimAttributesRequest.TGetIdentityDkimAttributesRequest; TGetIdentityDkimAttributesResponse = AWS.SES.Model.GetIdentityDkimAttributesResponse.TGetIdentityDkimAttributesResponse; TGetIdentityMailFromDomainAttributesRequest = AWS.SES.Model.GetIdentityMailFromDomainAttributesRequest.TGetIdentityMailFromDomainAttributesRequest; TGetIdentityMailFromDomainAttributesResponse = AWS.SES.Model.GetIdentityMailFromDomainAttributesResponse.TGetIdentityMailFromDomainAttributesResponse; TGetIdentityNotificationAttributesRequest = AWS.SES.Model.GetIdentityNotificationAttributesRequest.TGetIdentityNotificationAttributesRequest; TGetIdentityNotificationAttributesResponse = AWS.SES.Model.GetIdentityNotificationAttributesResponse.TGetIdentityNotificationAttributesResponse; TGetIdentityPoliciesRequest = AWS.SES.Model.GetIdentityPoliciesRequest.TGetIdentityPoliciesRequest; TGetIdentityPoliciesResponse = AWS.SES.Model.GetIdentityPoliciesResponse.TGetIdentityPoliciesResponse; TGetIdentityVerificationAttributesRequest = AWS.SES.Model.GetIdentityVerificationAttributesRequest.TGetIdentityVerificationAttributesRequest; TGetIdentityVerificationAttributesResponse = AWS.SES.Model.GetIdentityVerificationAttributesResponse.TGetIdentityVerificationAttributesResponse; TGetSendQuotaRequest = AWS.SES.Model.GetSendQuotaRequest.TGetSendQuotaRequest; TGetSendQuotaResponse = AWS.SES.Model.GetSendQuotaResponse.TGetSendQuotaResponse; TGetSendStatisticsRequest = AWS.SES.Model.GetSendStatisticsRequest.TGetSendStatisticsRequest; TGetSendStatisticsResponse = AWS.SES.Model.GetSendStatisticsResponse.TGetSendStatisticsResponse; TGetTemplateRequest = AWS.SES.Model.GetTemplateRequest.TGetTemplateRequest; TGetTemplateResponse = AWS.SES.Model.GetTemplateResponse.TGetTemplateResponse; TIdentityDkimAttributes = AWS.SES.Model.IdentityDkimAttributes.TIdentityDkimAttributes; TIdentityMailFromDomainAttributes = AWS.SES.Model.IdentityMailFromDomainAttributes.TIdentityMailFromDomainAttributes; TIdentityNotificationAttributes = AWS.SES.Model.IdentityNotificationAttributes.TIdentityNotificationAttributes; TIdentityType = AWS.SES.Enums.TIdentityType; TIdentityVerificationAttributes = AWS.SES.Model.IdentityVerificationAttributes.TIdentityVerificationAttributes; TInvocationType = AWS.SES.Enums.TInvocationType; TKinesisFirehoseDestination = AWS.SES.Model.KinesisFirehoseDestination.TKinesisFirehoseDestination; TLambdaAction = AWS.SES.Model.LambdaAction.TLambdaAction; TListConfigurationSetsRequest = AWS.SES.Model.ListConfigurationSetsRequest.TListConfigurationSetsRequest; TListConfigurationSetsResponse = AWS.SES.Model.ListConfigurationSetsResponse.TListConfigurationSetsResponse; TListCustomVerificationEmailTemplatesRequest = AWS.SES.Model.ListCustomVerificationEmailTemplatesRequest.TListCustomVerificationEmailTemplatesRequest; TListCustomVerificationEmailTemplatesResponse = AWS.SES.Model.ListCustomVerificationEmailTemplatesResponse.TListCustomVerificationEmailTemplatesResponse; TListIdentitiesRequest = AWS.SES.Model.ListIdentitiesRequest.TListIdentitiesRequest; TListIdentitiesResponse = AWS.SES.Model.ListIdentitiesResponse.TListIdentitiesResponse; TListIdentityPoliciesRequest = AWS.SES.Model.ListIdentityPoliciesRequest.TListIdentityPoliciesRequest; TListIdentityPoliciesResponse = AWS.SES.Model.ListIdentityPoliciesResponse.TListIdentityPoliciesResponse; TListReceiptFiltersRequest = AWS.SES.Model.ListReceiptFiltersRequest.TListReceiptFiltersRequest; TListReceiptFiltersResponse = AWS.SES.Model.ListReceiptFiltersResponse.TListReceiptFiltersResponse; TListReceiptRuleSetsRequest = AWS.SES.Model.ListReceiptRuleSetsRequest.TListReceiptRuleSetsRequest; TListReceiptRuleSetsResponse = AWS.SES.Model.ListReceiptRuleSetsResponse.TListReceiptRuleSetsResponse; TListTemplatesRequest = AWS.SES.Model.ListTemplatesRequest.TListTemplatesRequest; TListTemplatesResponse = AWS.SES.Model.ListTemplatesResponse.TListTemplatesResponse; TListVerifiedEmailAddressesRequest = AWS.SES.Model.ListVerifiedEmailAddressesRequest.TListVerifiedEmailAddressesRequest; TListVerifiedEmailAddressesResponse = AWS.SES.Model.ListVerifiedEmailAddressesResponse.TListVerifiedEmailAddressesResponse; TMessage = AWS.SES.Model.Message.TMessage; TMessageDsn = AWS.SES.Model.MessageDsn.TMessageDsn; TMessageTag = AWS.SES.Model.MessageTag.TMessageTag; TNotificationType = AWS.SES.Enums.TNotificationType; TPutConfigurationSetDeliveryOptionsRequest = AWS.SES.Model.PutConfigurationSetDeliveryOptionsRequest.TPutConfigurationSetDeliveryOptionsRequest; TPutConfigurationSetDeliveryOptionsResponse = AWS.SES.Model.PutConfigurationSetDeliveryOptionsResponse.TPutConfigurationSetDeliveryOptionsResponse; TPutIdentityPolicyRequest = AWS.SES.Model.PutIdentityPolicyRequest.TPutIdentityPolicyRequest; TPutIdentityPolicyResponse = AWS.SES.Model.PutIdentityPolicyResponse.TPutIdentityPolicyResponse; TRawMessage = AWS.SES.Model.RawMessage.TRawMessage; TReceiptAction = AWS.SES.Model.ReceiptAction.TReceiptAction; TReceiptFilter = AWS.SES.Model.ReceiptFilter.TReceiptFilter; TReceiptFilterPolicy = AWS.SES.Enums.TReceiptFilterPolicy; TReceiptIpFilter = AWS.SES.Model.ReceiptIpFilter.TReceiptIpFilter; TReceiptRule = AWS.SES.Model.ReceiptRule.TReceiptRule; TReceiptRuleSetMetadata = AWS.SES.Model.ReceiptRuleSetMetadata.TReceiptRuleSetMetadata; TRecipientDsnFields = AWS.SES.Model.RecipientDsnFields.TRecipientDsnFields; TReorderReceiptRuleSetRequest = AWS.SES.Model.ReorderReceiptRuleSetRequest.TReorderReceiptRuleSetRequest; TReorderReceiptRuleSetResponse = AWS.SES.Model.ReorderReceiptRuleSetResponse.TReorderReceiptRuleSetResponse; TReputationOptions = AWS.SES.Model.ReputationOptions.TReputationOptions; TS3Action = AWS.SES.Model.S3Action.TS3Action; TSendBounceRequest = AWS.SES.Model.SendBounceRequest.TSendBounceRequest; TSendBounceResponse = AWS.SES.Model.SendBounceResponse.TSendBounceResponse; TSendBulkTemplatedEmailRequest = AWS.SES.Model.SendBulkTemplatedEmailRequest.TSendBulkTemplatedEmailRequest; TSendBulkTemplatedEmailResponse = AWS.SES.Model.SendBulkTemplatedEmailResponse.TSendBulkTemplatedEmailResponse; TSendCustomVerificationEmailRequest = AWS.SES.Model.SendCustomVerificationEmailRequest.TSendCustomVerificationEmailRequest; TSendCustomVerificationEmailResponse = AWS.SES.Model.SendCustomVerificationEmailResponse.TSendCustomVerificationEmailResponse; TSendDataPoint = AWS.SES.Model.SendDataPoint.TSendDataPoint; TSendEmailRequest = AWS.SES.Model.SendEmailRequest.TSendEmailRequest; TSendEmailResponse = AWS.SES.Model.SendEmailResponse.TSendEmailResponse; TSendRawEmailRequest = AWS.SES.Model.SendRawEmailRequest.TSendRawEmailRequest; TSendRawEmailResponse = AWS.SES.Model.SendRawEmailResponse.TSendRawEmailResponse; TSendTemplatedEmailRequest = AWS.SES.Model.SendTemplatedEmailRequest.TSendTemplatedEmailRequest; TSendTemplatedEmailResponse = AWS.SES.Model.SendTemplatedEmailResponse.TSendTemplatedEmailResponse; TSetActiveReceiptRuleSetRequest = AWS.SES.Model.SetActiveReceiptRuleSetRequest.TSetActiveReceiptRuleSetRequest; TSetActiveReceiptRuleSetResponse = AWS.SES.Model.SetActiveReceiptRuleSetResponse.TSetActiveReceiptRuleSetResponse; TSetIdentityDkimEnabledRequest = AWS.SES.Model.SetIdentityDkimEnabledRequest.TSetIdentityDkimEnabledRequest; TSetIdentityDkimEnabledResponse = AWS.SES.Model.SetIdentityDkimEnabledResponse.TSetIdentityDkimEnabledResponse; TSetIdentityFeedbackForwardingEnabledRequest = AWS.SES.Model.SetIdentityFeedbackForwardingEnabledRequest.TSetIdentityFeedbackForwardingEnabledRequest; TSetIdentityFeedbackForwardingEnabledResponse = AWS.SES.Model.SetIdentityFeedbackForwardingEnabledResponse.TSetIdentityFeedbackForwardingEnabledResponse; TSetIdentityHeadersInNotificationsEnabledRequest = AWS.SES.Model.SetIdentityHeadersInNotificationsEnabledRequest.TSetIdentityHeadersInNotificationsEnabledRequest; TSetIdentityHeadersInNotificationsEnabledResponse = AWS.SES.Model.SetIdentityHeadersInNotificationsEnabledResponse.TSetIdentityHeadersInNotificationsEnabledResponse; TSetIdentityMailFromDomainRequest = AWS.SES.Model.SetIdentityMailFromDomainRequest.TSetIdentityMailFromDomainRequest; TSetIdentityMailFromDomainResponse = AWS.SES.Model.SetIdentityMailFromDomainResponse.TSetIdentityMailFromDomainResponse; TSetIdentityNotificationTopicRequest = AWS.SES.Model.SetIdentityNotificationTopicRequest.TSetIdentityNotificationTopicRequest; TSetIdentityNotificationTopicResponse = AWS.SES.Model.SetIdentityNotificationTopicResponse.TSetIdentityNotificationTopicResponse; TSetReceiptRulePositionRequest = AWS.SES.Model.SetReceiptRulePositionRequest.TSetReceiptRulePositionRequest; TSetReceiptRulePositionResponse = AWS.SES.Model.SetReceiptRulePositionResponse.TSetReceiptRulePositionResponse; TSNSAction = AWS.SES.Model.SNSAction.TSNSAction; TSNSActionEncoding = AWS.SES.Enums.TSNSActionEncoding; TSNSDestination = AWS.SES.Model.SNSDestination.TSNSDestination; TStopAction = AWS.SES.Model.StopAction.TStopAction; TStopScope = AWS.SES.Enums.TStopScope; TTemplate = AWS.SES.Model.Template.TTemplate; TTemplateMetadata = AWS.SES.Model.TemplateMetadata.TTemplateMetadata; TTestRenderTemplateRequest = AWS.SES.Model.TestRenderTemplateRequest.TTestRenderTemplateRequest; TTestRenderTemplateResponse = AWS.SES.Model.TestRenderTemplateResponse.TTestRenderTemplateResponse; TTlsPolicy = AWS.SES.Enums.TTlsPolicy; TTrackingOptions = AWS.SES.Model.TrackingOptions.TTrackingOptions; TUpdateAccountSendingEnabledRequest = AWS.SES.Model.UpdateAccountSendingEnabledRequest.TUpdateAccountSendingEnabledRequest; TUpdateAccountSendingEnabledResponse = AWS.SES.Model.UpdateAccountSendingEnabledResponse.TUpdateAccountSendingEnabledResponse; TUpdateConfigurationSetEventDestinationRequest = AWS.SES.Model.UpdateConfigurationSetEventDestinationRequest.TUpdateConfigurationSetEventDestinationRequest; TUpdateConfigurationSetEventDestinationResponse = AWS.SES.Model.UpdateConfigurationSetEventDestinationResponse.TUpdateConfigurationSetEventDestinationResponse; TUpdateConfigurationSetReputationMetricsEnabledRequest = AWS.SES.Model.UpdateConfigurationSetReputationMetricsEnabledRequest.TUpdateConfigurationSetReputationMetricsEnabledRequest; TUpdateConfigurationSetReputationMetricsEnabledResponse = AWS.SES.Model.UpdateConfigurationSetReputationMetricsEnabledResponse.TUpdateConfigurationSetReputationMetricsEnabledResponse; TUpdateConfigurationSetSendingEnabledRequest = AWS.SES.Model.UpdateConfigurationSetSendingEnabledRequest.TUpdateConfigurationSetSendingEnabledRequest; TUpdateConfigurationSetSendingEnabledResponse = AWS.SES.Model.UpdateConfigurationSetSendingEnabledResponse.TUpdateConfigurationSetSendingEnabledResponse; TUpdateConfigurationSetTrackingOptionsRequest = AWS.SES.Model.UpdateConfigurationSetTrackingOptionsRequest.TUpdateConfigurationSetTrackingOptionsRequest; TUpdateConfigurationSetTrackingOptionsResponse = AWS.SES.Model.UpdateConfigurationSetTrackingOptionsResponse.TUpdateConfigurationSetTrackingOptionsResponse; TUpdateCustomVerificationEmailTemplateRequest = AWS.SES.Model.UpdateCustomVerificationEmailTemplateRequest.TUpdateCustomVerificationEmailTemplateRequest; TUpdateCustomVerificationEmailTemplateResponse = AWS.SES.Model.UpdateCustomVerificationEmailTemplateResponse.TUpdateCustomVerificationEmailTemplateResponse; TUpdateReceiptRuleRequest = AWS.SES.Model.UpdateReceiptRuleRequest.TUpdateReceiptRuleRequest; TUpdateReceiptRuleResponse = AWS.SES.Model.UpdateReceiptRuleResponse.TUpdateReceiptRuleResponse; TUpdateTemplateRequest = AWS.SES.Model.UpdateTemplateRequest.TUpdateTemplateRequest; TUpdateTemplateResponse = AWS.SES.Model.UpdateTemplateResponse.TUpdateTemplateResponse; TVerificationStatus = AWS.SES.Enums.TVerificationStatus; TVerifyDomainDkimRequest = AWS.SES.Model.VerifyDomainDkimRequest.TVerifyDomainDkimRequest; TVerifyDomainDkimResponse = AWS.SES.Model.VerifyDomainDkimResponse.TVerifyDomainDkimResponse; TVerifyDomainIdentityRequest = AWS.SES.Model.VerifyDomainIdentityRequest.TVerifyDomainIdentityRequest; TVerifyDomainIdentityResponse = AWS.SES.Model.VerifyDomainIdentityResponse.TVerifyDomainIdentityResponse; TVerifyEmailAddressRequest = AWS.SES.Model.VerifyEmailAddressRequest.TVerifyEmailAddressRequest; TVerifyEmailAddressResponse = AWS.SES.Model.VerifyEmailAddressResponse.TVerifyEmailAddressResponse; TVerifyEmailIdentityRequest = AWS.SES.Model.VerifyEmailIdentityRequest.TVerifyEmailIdentityRequest; TVerifyEmailIdentityResponse = AWS.SES.Model.VerifyEmailIdentityResponse.TVerifyEmailIdentityResponse; TWorkmailAction = AWS.SES.Model.WorkmailAction.TWorkmailAction; implementation end.
84.566869
185
0.884572
472ba977a1ce5bf6c51053711f8d1f64750334fa
248
dpr
Pascal
Bass/Reverse/prjRev.dpr
liborm85/qip-plugin-fmtune
b2ecd3b7aaaa378f6e729ca7cbd039db9c79dab9
[ "MIT" ]
8
2019-07-02T15:59:30.000Z
2021-07-13T05:13:43.000Z
Bass/Reverse/prjRev.dpr
liborm85/qip-plugin-fmtune
b2ecd3b7aaaa378f6e729ca7cbd039db9c79dab9
[ "MIT" ]
null
null
null
Bass/Reverse/prjRev.dpr
liborm85/qip-plugin-fmtune
b2ecd3b7aaaa378f6e729ca7cbd039db9c79dab9
[ "MIT" ]
1
2019-07-02T15:59:31.000Z
2019-07-02T15:59:31.000Z
program prjRev; uses Forms, reverse in 'reverse.pas' {frmReverse}, BASS_FX in '..\bass_fx.pas', BASS in '..\bass.pas'; {$R *.RES} begin Application.Initialize; Application.CreateForm(TfrmReverse, frmReverse); Application.Run; end.
15.5
50
0.693548
f18ef7c89f8403d19e8a23f105be16ab4862eb3d
3,914
pas
Pascal
Apps/WindmillPP/output/Output.Treeview.pas
GDKsoftware/OpenTestGrip
a06f7840aea852c9d84ea2178e792d93866bf797
[ "MIT" ]
5
2017-11-08T22:44:16.000Z
2019-08-16T10:02:39.000Z
Apps/WindmillPP/output/Output.Treeview.pas
GDKsoftware/OpenTestGrip
a06f7840aea852c9d84ea2178e792d93866bf797
[ "MIT" ]
18
2016-05-18T10:33:07.000Z
2019-04-10T13:50:33.000Z
Apps/WindmillPP/output/Output.Treeview.pas
GDKsoftware/OpenTestGrip
a06f7840aea852c9d84ea2178e792d93866bf797
[ "MIT" ]
2
2016-04-30T11:25:35.000Z
2018-03-02T06:58:37.000Z
unit Output.Treeview; interface uses Output.Interfaces, Vcl.ComCtrls; type TOutputTreeview = class(TInterfacedObject, IOutput) private FTreeview: TTreeView; FErrorCount: Integer; FWarningCount: Integer; FInfoCount: Integer; function CreateFilenode(const Filepath: string): TTreeNode; function FindFilenode(const Filepath: string): TTreeNode; function FindOrCreateFilenode(const Filepath: string): TTreeNode; public constructor Create(const Tree: TTreeView); procedure SetWarningAsError(const Yes: Boolean); procedure Warning(const Filepath: string; const Linenumber: Integer; const Warning: string); procedure Error(const Filepath: string; const Linenumber: Integer; const Error: string); procedure Info(const Info: string); function WarningCount: Integer; function ErrorCount: Integer; function InfoCount: Integer; end; TOutputInfo = class public Text: string; end; TOutputSourcefile = class(TOutputInfo) public Filepath: string; end; TOutputMessage = class(TOutputInfo) public Linenumber: Integer; end; TOutputWarning = class(TOutputMessage); TOutputError = class(TOutputMessage); implementation uses System.SysUtils; constructor TOutputTreeview.Create(const Tree: TTreeView); begin inherited Create; FTreeview := Tree; end; function TOutputTreeview.FindFilenode(const Filepath: string): TTreeNode; var IdxNode: Integer; Node: TTreeNode; Data: TOutputInfo; begin Result := nil; for IdxNode := 0 to FTreeview.Items.Count - 1 do begin Node := FTreeview.Items[IdxNode]; Data := TOutputInfo(Node.Data); if Data is TOutputSourcefile then begin if SameText(TOutputSourcefile(Data).Filepath, Filepath) then begin Result := Node; Exit; end; end; end; end; function TOutputTreeview.CreateFilenode(const Filepath: string): TTreeNode; var Data: TOutputSourcefile; begin Inc(FErrorCount); Data := TOutputSourcefile.Create; Data.Text := ExtractFileName(Filepath); Data.Filepath := Filepath; Result := FTreeview.Items.AddChild(nil, ExtractFileName(Filepath)); Result.Data := Data; end; function TOutputTreeview.FindOrCreateFilenode(const Filepath: string): TTreeNode; begin Result := FindFilenode(Filepath); if not Assigned(Result) then begin Result := CreateFilenode(Filepath); end; end; procedure TOutputTreeview.SetWarningAsError(const Yes: Boolean); begin end; procedure TOutputTreeview.Warning(const Filepath: string; const Linenumber: Integer; const Warning: string); var Data: TOutputWarning; Node: TTreeNode; Filenode: TTreeNode; begin Inc(FWarningCount); Data := TOutputWarning.Create; Data.Text := Warning; Data.Linenumber := Linenumber; Filenode := FindOrCreateFilenode(Filepath); Node := FTreeview.Items.AddChild(Filenode, '[Warning] ' + Linenumber.ToString + ': ' + Warning); Node.Data := Data; end; procedure TOutputTreeview.Error(const Filepath: string; const Linenumber: Integer; const Error: string); var Data: TOutputError; Node: TTreeNode; Filenode: TTreeNode; begin Inc(FErrorCount); Data := TOutputError.Create; Data.Text := Error; Data.Linenumber := Linenumber; Filenode := FindOrCreateFilenode(Filepath); Node := FTreeview.Items.AddChild(Filenode, '[Error] ' + Linenumber.ToString + ': ' + Error); Node.Data := Data; end; procedure TOutputTreeview.Info(const Info: string); var Data: TOutputInfo; Node: TTreeNode; begin Inc(FInfoCount); Data := TOutputInfo.Create; Data.Text := Info; Node := FTreeview.Items.AddChild(nil, Info); Node.Data := Data; end; function TOutputTreeview.WarningCount: Integer; begin Result := FWarningCount; end; function TOutputTreeview.ErrorCount: Integer; begin Result := FErrorCount; end; function TOutputTreeview.InfoCount: Integer; begin Result := FInfoCount; end; end.
21.744444
108
0.729688
6a43cadd7dfaf822c60daf9695b5b0179ff43e6f
1,966
pas
Pascal
IntXLib.Tests/Delphi.Tests/src/LessOpTest.pas
jomael/IntXLib4Pascal
2ff77c8d82b66cef7148d32e2b1cf52a83096d2c
[ "MIT" ]
31
2017-07-17T09:55:13.000Z
2022-02-14T04:09:39.000Z
IntXLib.Tests/Delphi.Tests/src/LessOpTest.pas
jomael/IntXLib4Pascal
2ff77c8d82b66cef7148d32e2b1cf52a83096d2c
[ "MIT" ]
1
2015-09-14T06:46:54.000Z
2015-09-16T17:18:54.000Z
IntXLib.Tests/Delphi.Tests/src/LessOpTest.pas
Xor-el/DelphiIntXLib
0e3e9f204e13cb5e3b9f9b5e3975532712d32e86
[ "MIT" ]
16
2017-03-30T19:01:25.000Z
2021-12-26T07:06:26.000Z
unit LessOpTest; interface uses DUnitX.TestFramework, uIntXLibTypes, uIntX; type [TestFixture] TLessOpTest = class(TObject) public [Test] procedure Simple(); [Test] procedure SimpleFail(); [Test] procedure Big(); [Test] procedure BigFail(); [Test] procedure EqualValues(); [Test] procedure Neg(); end; implementation [Test] procedure TLessOpTest.Simple(); var int1, int2: TIntX; begin int1 := TIntX.Create(7); int2 := TIntX.Create(8); Assert.IsTrue(int1 < int2); end; [Test] procedure TLessOpTest.SimpleFail(); var int1: TIntX; begin int1 := TIntX.Create(8); Assert.IsFalse(int1 < 7); end; [Test] procedure TLessOpTest.Big(); var temp1, temp2: TIntXLibUInt32Array; int1, int2: TIntX; begin SetLength(temp1, 2); temp1[0] := 1; temp1[1] := 2; SetLength(temp2, 3); temp2[0] := 1; temp2[1] := 2; temp2[2] := 3; int1 := TIntX.Create(temp1, False); int2 := TIntX.Create(temp2, True); Assert.IsTrue(int2 < int1); end; [Test] procedure TLessOpTest.BigFail(); var temp1, temp2: TIntXLibUInt32Array; int1, int2: TIntX; begin SetLength(temp1, 2); temp1[0] := 1; temp1[1] := 2; SetLength(temp2, 3); temp2[0] := 1; temp2[1] := 2; temp2[2] := 3; int1 := TIntX.Create(temp1, False); int2 := TIntX.Create(temp2, True); Assert.IsFalse(int1 < int2); end; [Test] procedure TLessOpTest.EqualValues(); var temp1, temp2: TIntXLibUInt32Array; int1, int2: TIntX; begin SetLength(temp1, 3); temp1[0] := 1; temp1[1] := 2; temp1[2] := 3; SetLength(temp2, 3); temp2[0] := 1; temp2[1] := 2; temp2[2] := 3; int1 := TIntX.Create(temp1, True); int2 := TIntX.Create(temp2, True); Assert.IsFalse(int1 < int2); end; [Test] procedure TLessOpTest.Neg(); var int1, int2: TIntX; begin int1 := TIntX.Create(-10); int2 := TIntX.Create(-2); Assert.IsTrue(int1 < int2); end; initialization TDUnitX.RegisterTestFixture(TLessOpTest); end.
16.383333
41
0.639369
6afa13b88a98336672365b15aa763b14894eadc6
23,464
pas
Pascal
references/UIB/misc/AppServer/src/PDGUtils.pas
zekiguven/alcinoe
e55c5368ee8bfe7cd6d92424c29ab07d8a3e844c
[ "Apache-2.0" ]
851
2018-02-05T09:54:56.000Z
2022-03-24T23:13:10.000Z
references/UIB/misc/AppServer/src/PDGUtils.pas
zekiguven/alcinoe
e55c5368ee8bfe7cd6d92424c29ab07d8a3e844c
[ "Apache-2.0" ]
200
2018-02-06T18:52:39.000Z
2022-03-24T19:59:14.000Z
references/UIB/misc/AppServer/src/PDGUtils.pas
zekiguven/alcinoe
e55c5368ee8bfe7cd6d92424c29ab07d8a3e844c
[ "Apache-2.0" ]
197
2018-03-20T20:49:55.000Z
2022-03-21T17:38:14.000Z
(* "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 Initial Developer of the Original Code is Henri Gourvest <hgourvest@progdigy.com>. *) unit PDGUtils; {$IFDEF FPC} {$mode objfpc}{$H+} {$ENDIF} {$I PDGAppServer.inc} interface uses Classes, SysUtils {$IFDEF MSWINDOWS} , windows {$ENDIF} {$IFDEF FPC} , sockets , paszlib {$ELSE} , WinSock , PDGZLib {$ENDIF} ; {$IFDEF Darwin} const ThreadIdNull = nil; {$ELSE} const ThreadIdNull = 1; {$ENDIF} type {$IFNDEF FPC} PtrInt = Longint; TThreadID = LongWord; {$ENDIF} {$IFNDEF UNICODE} UnicodeString = WideString; RawByteString = AnsiString; {$ENDIF} ERemoteError = class(Exception) end; TPooledMemoryStream = class(TStream) private FPageSize: integer; FList: TList; FSize: Integer; FPosition: Integer; protected procedure SetSize(NewSize: Longint); override; public procedure Clear; function Seek(Offset: Longint; Origin: Word): Longint; override; function Read(var Buffer; Count: Longint): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; procedure WriteString(const str: string; writesize: boolean; cp: Integer = 0); procedure WriteInteger(const V: Integer); function ReadString: string; procedure SaveToStream(Stream: TStream); procedure SaveToFile(const FileName: string); function SaveToSocket(socket: longint; writesize: boolean = true): boolean; procedure LoadFromStream(Stream: TStream); procedure LoadFromFile(const FileName: string); function LoadFromSocket(socket: longint; readsize: boolean = true): boolean; constructor Create(PageSize: integer = 1024); virtual; destructor Destroy; override; end; function CompressStream(inStream, outStream: TStream; level: Integer = Z_DEFAULT_COMPRESSION): boolean; overload; function DecompressStream(inStream, outStream: TStream): boolean; overload; function CompressStream(inStream: TStream; outSocket: longint; level: Integer = Z_DEFAULT_COMPRESSION): boolean; overload; function DecompressStream(inSocket: longint; outStream: TStream): boolean; overload; function receive(s: longint; var Buf; len, flags: Integer): Integer; // Base64 functions from <dirk.claessens.dc@belgium.agfa.com> (modified) function StrTobase64(Buf: string): string; function Base64ToStr(const B64: string): string; procedure StreamToBase64(const StreamIn, StreamOut: TStream); procedure Base64ToStream(const data: string; stream: TStream); function FileToString(const FileName: string): string; function StreamToStr(stream: TStream): string; {$IFDEF UNIX} function GetTickCount: Cardinal; {$ENDIF} implementation uses uiblib, PDGOpenSSL; const Base64Code: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; Base64Map: array[#0..#127] of Integer = ( Byte('='), 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, 64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64, 64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64); {$IFDEF UNIX} function GetTickCount: Cardinal; var h, m, s, s1000: word; begin decodetime(time, h, m, s, s1000); Result := Cardinal(h * 3600000 + m * 60000 + s * 1000 + s1000); end; {$ENDIF} function StrTobase64(Buf: string): string; var i: integer; x1, x2, x3, x4: byte; PadCount: integer; begin PadCount := 0; // we need at least 3 input bytes... while length(Buf) < 3 do begin Buf := Buf + #0; inc(PadCount); end; // ...and all input must be an even multiple of 3 while (length(Buf) mod 3) <> 0 do begin Buf := Buf + #0; // if not, zero padding is added inc(PadCount); end; Result := ''; i := 1; // process 3-byte blocks or 24 bits while i <= length(Buf) - 2 do begin // each 3 input bytes are transformed into 4 index values // in the range of 0..63, by taking 6 bits each step // 6 high bytes of first char x1 := (Ord(Buf[i]) shr 2) and $3F; // 2 low bytes of first char + 4 high bytes of second char x2 := ((Ord(Buf[i]) shl 4) and $3F) or Ord(Buf[i + 1]) shr 4; // 4 low bytes of second char + 2 high bytes of third char x3 := ((Ord(Buf[i + 1]) shl 2) and $3F) or Ord(Buf[i + 2]) shr 6; // 6 low bytes of third char x4 := Ord(Buf[i + 2]) and $3F; // the index values point into the code array Result := Result + Base64Code[x1 + 1] + Base64Code[x2 + 1] + Base64Code[x3 + 1] + Base64Code[x4 + 1]; inc(i, 3); end; // if needed, finish by forcing padding chars ('=') // at end of string if PadCount > 0 then for i := Length(Result) downto 1 do begin Result[i] := '='; dec(PadCount); if PadCount = 0 then Break; end; end; function Base64ToStr(const B64: string): string; var i, PadCount: integer; x1, x2, x3: byte; begin Result := ''; // input _must_ be at least 4 chars long, // or multiple of 4 chars if (Length(B64) < 4) or (Length(B64) mod 4 <> 0) then Exit; PadCount := 0; i := Length(B64); // count padding chars, if any while (B64[i] = '=') and (i > 0) do begin inc(PadCount); dec(i); end; // Result := ''; i := 1; while i <= Length(B64) - 3 do begin // reverse process of above x1 := (Base64Map[B64[i]] shl 2) or (Base64Map[B64[i + 1]] shr 4); Result := Result + Char(x1); x2 := (Base64Map[B64[i + 1]] shl 4) or (Base64Map[B64[i + 2]] shr 2); Result := Result + Char(x2); x3 := (Base64Map[B64[i + 2]] shl 6) or (Base64Map[B64[i + 3]]); Result := Result + Char(x3); inc(i, 4); end; // delete padding, if any while PadCount > 0 do begin Delete(Result, Length(Result), 1); dec(PadCount); end; end; procedure StreamToBase64(const StreamIn, StreamOut: TStream); const Base64Code: PChar = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; EQ2: PChar = '=='; EQ4: PChar = 'A==='; var V: array[0..2] of byte; C: array[0..3] of Char; begin StreamIn.Seek(0, soFromBeginning); while true do case StreamIn.Read(V, 3) of 3: begin C[0] := Base64Code[(V[0] shr 2) and $3F]; C[1] := Base64Code[((V[0] shl 4) and $3F) or V[1] shr 4]; C[2] := Base64Code[((V[1] shl 2) and $3F) or V[2] shr 6]; C[3] := Base64Code[V[2] and $3F]; StreamOut.Write(C, 4*SizeOf(Char)); end; 2: begin C[0] := Base64Code[(V[0] shr 2) and $3F]; C[1] := Base64Code[((V[0] shl 4) and $3F) or V[1] shr 4]; C[2] := Base64Code[((V[1] shl 2) and $3F) or 0 shr 6]; StreamOut.Write(C, 3*SizeOf(Char)); StreamOut.Write(EQ2^, 1*SizeOf(Char)); Break; end; 1: begin C[0] := Base64Code[(V[0] shr 2) and $3F]; C[1] := Base64Code[((V[0] shl 4) and $3F) or 0 shr 4]; StreamOut.Write(C, 2*SizeOf(Char)); StreamOut.Write(EQ2^, 2*SizeOf(Char)); Break; end; 0: begin if StreamIn.Position = 0 then StreamOut.Write(EQ4^, 4*SizeOf(Char)); Break; end; end; end; procedure Base64ToStream(const data: string; stream: TStream); var i, PadCount: integer; buf: array[0..2] of byte; begin if (Length(data) < 4) or (Length(data) mod 4 <> 0) then Exit; PadCount := 0; i := Length(data); while (data[i] = '=') and (i > 0) do begin inc(PadCount); dec(i); end; i := 1; while i <= Length(data) - 3 do begin // reverse process of above buf[0] := (Base64Map[data[i]] shl byte(2)) or (Base64Map[data[i + 1]] shr byte(4)); buf[1] := (Base64Map[data[i + 1]] shl 4) or (Base64Map[data[i + 2]] shr 2); buf[2] := (Base64Map[data[i + 2]] shl 6) or (Base64Map[data[i + 3]]); stream.Write(buf, sizeof(buf)); inc(i, 4); end; // delete padding, if any if PadCount > 0 then stream.Position := stream.Position - PadCount; end; {$IF not declared(InterLockedCompareExchange)} {$IFDEF MSWINDOWS} function InterlockedCompareExchange(var Destination: longint; Exchange: longint; Comperand: longint): longint stdcall; external 'kernel32' name 'InterlockedCompareExchange'; {$ENDIF} {$ifend} const bufferSize = 32768; function receive(s: longint; var Buf; len, flags: Integer): Integer; var p: PChar; r, l: integer; begin Result := 0; p := @Buf; l := len; {$IFDEF FPC} r := fprecv(s, p, l, flags); {$ELSE} r := recv(s, p^, l, flags); {$ENDIF} while (r > 0) and (r < l) do begin inc(Result, r); dec(l, r); inc(p, r); {$IFDEF FPC} r := fprecv(s, p, l, flags); {$ELSE} r := recv(s, p^, l, flags); {$ENDIF} end; inc(Result, r); end; function CompressStream(inStream, outStream: TStream; level: Integer): boolean; var zstream: TZStream; zresult: Integer; inBuffer: array[0..bufferSize - 1] of byte; outBuffer: array[0..bufferSize - 1] of byte; inSize: Integer; outSize: Integer; label error; begin inStream.Seek(0, soFromBeginning); Result := False; FillChar(zstream, SizeOf(zstream), 0); if DeflateInit(zstream, level) < Z_OK then exit; inSize := inStream.Read(inBuffer, bufferSize); while inSize > 0 do begin zstream.next_in := @inBuffer; zstream.avail_in := inSize; repeat zstream.next_out := @outBuffer; zstream.avail_out := bufferSize; if deflate(zstream, Z_NO_FLUSH) < Z_OK then goto error; outSize := bufferSize - zstream.avail_out; outStream.Write(outBuffer, outSize); until (zstream.avail_in = 0) and (zstream.avail_out > 0); inSize := inStream.Read(inBuffer, bufferSize); end; repeat zstream.next_out := @outBuffer; zstream.avail_out := bufferSize; zresult := deflate(zstream, Z_FINISH); if zresult < Z_OK then goto error; outSize := bufferSize - zstream.avail_out; outStream.Write(outBuffer, outSize); until (zresult = Z_STREAM_END) and (zstream.avail_out > 0); Result := deflateEnd(zstream) >= Z_OK; exit; error: deflateEnd(zstream); end; function DecompressStream(inStream, outStream: TStream): boolean; var zstream: TZStream; zresult: Integer; inBuffer: array[0..bufferSize - 1] of byte; outBuffer: array[0..bufferSize - 1] of byte; inSize: Integer; outSize: Integer; label error; begin Result := False; inStream.Seek(0, soFromBeginning); FillChar(zstream, SizeOf(zstream), 0); if InflateInit(zstream) < Z_OK then exit; inSize := inStream.Read(inBuffer, bufferSize); while inSize > 0 do begin zstream.next_in := @inBuffer; zstream.avail_in := inSize; repeat zstream.next_out := @outBuffer; zstream.avail_out := bufferSize; if inflate(zstream, Z_NO_FLUSH) < Z_OK then goto error; outSize := bufferSize - zstream.avail_out; outStream.Write(outBuffer, outSize); until (zstream.avail_in = 0) and (zstream.avail_out > 0); inSize := inStream.Read(inBuffer, bufferSize); end; repeat zstream.next_out := @outBuffer; zstream.avail_out := bufferSize; zresult := inflate(zstream, Z_FINISH); if zresult < Z_OK then goto error; outSize := bufferSize - zstream.avail_out; outStream.Write(outBuffer, outSize); until (zresult = Z_STREAM_END) and (zstream.avail_out > 0); Result := inflateEnd(zstream) >= Z_OK; exit; error: inflateEnd(zstream); end; function CompressStream(inStream: TStream; outSocket: longint; level: Integer): boolean; var zstream: TZStream; zresult: Integer; inBuffer: array[0..bufferSize - 1] of byte; outBuffer: array[0..bufferSize - 1] of byte; inSize: Integer; outSize: Integer; label error; begin inStream.Seek(0, soFromBeginning); Result := False; FillChar(zstream, SizeOf(zstream), 0); if DeflateInit(zstream, level) < Z_OK then Exit; inSize := inStream.Read(inBuffer, bufferSize); while inSize > 0 do begin zstream.next_in := @inBuffer; zstream.avail_in := inSize; repeat zstream.next_out := @outBuffer; zstream.avail_out := bufferSize; if deflate(zstream, Z_NO_FLUSH) < Z_OK then goto error; outSize := bufferSize - zstream.avail_out; if outSize > 0 then begin {$IFDEF FPC} if fpsend(outSocket, @outSize, sizeof(outSize), 0) <> sizeof(outSize) then goto error; if fpsend(outSocket, @outBuffer, outSize, 0) <> outSize then goto error; {$ELSE} if send(outSocket, outSize, sizeof(outSize), 0) <> sizeof(outSize) then goto error; if send(outSocket, outBuffer, outSize, 0) <> outSize then goto error; {$ENDIF} end; until (zstream.avail_in = 0) and (zstream.avail_out > 0); inSize := inStream.Read(inBuffer, bufferSize); end; repeat zstream.next_out := @outBuffer; zstream.avail_out := bufferSize; zresult := deflate(zstream, Z_FINISH); if zresult < Z_OK then goto error; outSize := bufferSize - zstream.avail_out; if outSize > 0 then begin {$IFDEF FPC} if fpsend(outSocket, @outSize, sizeof(outSize), 0) <> sizeof(outSize) then goto error; if fpsend(outSocket, @outBuffer, outSize, 0) <> outSize then goto error; {$ELSE} if send(outSocket, outSize, sizeof(outSize), 0) <> sizeof(outSize) then goto error; if send(outSocket, outBuffer, outSize, 0) <> outSize then goto error; {$ENDIF} end; until (zresult = Z_STREAM_END) and (zstream.avail_out > 0); outsize := 0; {$IFDEF FPC} if fpsend(outSocket, @outSize, sizeof(outSize), 0) <> sizeof(outSize) then goto error; {$ELSE} if send(outSocket, outSize, sizeof(outSize), 0) <> sizeof(outSize) then goto error; {$ENDIF} Result := deflateEnd(zstream) >= Z_OK; Exit; error: deflateEnd(zstream); end; function DecompressStream(inSocket: longint; outStream: TStream): boolean; var zstream: TZStream; zresult: Integer; inBuffer: array[0..bufferSize - 1] of byte; outBuffer: array[0..bufferSize - 1] of byte; inSize: Integer; outSize: Integer; label error; begin Result := False; FillChar(zstream, SizeOf(zstream), 0); if InflateInit(zstream) < Z_OK then exit; if receive(inSocket, insize, sizeof(insize), 0) <> sizeof(insize) then goto error; if insize > 0 then if receive(inSocket, inBuffer, insize, 0) <> insize then goto error; while inSize > 0 do begin zstream.next_in := @inBuffer; zstream.avail_in := inSize; repeat zstream.next_out := @outBuffer; zstream.avail_out := bufferSize; if inflate(zstream, Z_NO_FLUSH) < Z_OK then goto error; outSize := bufferSize - zstream.avail_out; if outSize > 0 then outStream.Write(outBuffer, outSize); until (zstream.avail_in = 0) and (zstream.avail_out > 0); if receive(inSocket, insize, sizeof(insize), 0) <> sizeof(insize) then goto error; if insize > 0 then begin if receive(inSocket, inBuffer, insize, 0) <> insize then goto error; end; end; repeat zstream.next_out := @outBuffer; zstream.avail_out := bufferSize; zresult := inflate(zstream, Z_FINISH); if zresult < Z_OK then goto error; outSize := bufferSize - zstream.avail_out; outStream.Write(outBuffer, outSize); until (zresult = Z_STREAM_END) and (zstream.avail_out > 0); Result := inflateEnd(zstream) >= Z_OK; exit; error: inflateEnd(zstream); end; function StreamToStr(stream: TStream): string; begin stream.Seek(0, soFromBeginning); SetLength(Result, stream.Size div SizeOf(Char)); stream.Read(PChar(Result)^, stream.Size); end; function FileToString(const FileName: string): string; var strm: TFileStream; begin strm := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try Result := StreamToStr(strm); finally strm.Free; end; end; { TPooledMemoryStream } procedure TPooledMemoryStream.Clear; var i: integer; begin for i := 0 to FList.Count - 1 do FreeMem(FList[i]); FList.Clear; FSize := 0; FPosition := 0; end; constructor TPooledMemoryStream.Create(PageSize: integer); begin Assert(PageSize > 0); FPageSize := PageSize; FList := TList.Create; FSize := 0; FPosition := 0; end; destructor TPooledMemoryStream.Destroy; begin Clear; FList.Free; inherited; end; procedure TPooledMemoryStream.LoadFromFile(const FileName: string); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try LoadFromStream(Stream); finally Stream.Free; end; end; function TPooledMemoryStream.LoadFromSocket(socket: longint; readsize: boolean = true): boolean; var count, i, j: integer; p: PByte; begin Result := False; if readsize then begin if receive(socket, count, sizeof(count), 0) <> sizeof(count) then Exit; SetSize(count); end else count := Size; for i := 0 to FList.Count - 1 do begin p := FList[i]; for j := 0 to FPageSize - 1 do begin if count > 0 then begin if receive(socket, p^, 1, 0) <> 1 then exit; dec(count); end else Break; inc(p); end; end; Result := true; end; procedure TPooledMemoryStream.LoadFromStream(Stream: TStream); var s, count, i: integer; begin Stream.Position := 0; SetSize(Stream.Size); count := FSize; i := 0; while count > 0 do begin if count > FPageSize then s := FPageSize else s := count; stream.ReadBuffer(FList[i]^, s); dec(count, s); inc(i); end; end; function TPooledMemoryStream.Read(var Buffer; Count: Integer): Longint; var Pos, n: Integer; p, c: Pointer; begin if (FPosition >= 0) and (Count >= 0) then begin Pos := FPosition + Count; if Pos > 0 then begin if Pos > FSize then count := FSize - FPosition; Result := Count; c := @buffer; n := FPageSize - (FPosition mod FPageSize); if n > count then n := count; while n > 0 do begin p := Pointer(PtrInt(FList[FPosition div FPageSize]) + (FPosition mod FPageSize)); Move(p^, c^, n); dec(count, n); inc(PtrInt(c), n); inc(FPosition, n); if count >= FPageSize then n := FPageSize else n := count; end; Exit; end; end; Result := 0; end; function TPooledMemoryStream.ReadString: string; var s: Integer; begin Result := ''; Read(s, sizeof(s)); if s > 0 then begin SetLength(Result, s); Read(Result[1], s); end; end; procedure TPooledMemoryStream.SaveToFile(const FileName: string); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmCreate); try SaveToStream(Stream); finally Stream.Free; end; end; function TPooledMemoryStream.SaveToSocket(socket: longint; writesize: boolean): boolean; var s, count, i: integer; begin Result := False; count := FSize; if writesize then {$IFDEF FPC} if fpsend(socket, @count, sizeof(count), 0) <> sizeof(count) then Exit; {$ELSE} if send(socket, count, sizeof(count), 0) <> sizeof(count) then Exit; {$ENDIF} i := 0; while count > 0 do begin if count >= FPageSize then s := FPageSize else s := count; {$IFDEF FPC} if fpsend(socket, FList[i], s, 0) <> s then Exit; {$ELSE} if send(socket, FList[i]^, s, 0) <> s then Exit; {$ENDIF} dec(count, s); inc(i); end; Result := True; end; procedure TPooledMemoryStream.SaveToStream(Stream: TStream); var s, count, i: integer; begin count := FSize; i := 0; while count > 0 do begin if count >= FPageSize then s := FPageSize else s := count; stream.WriteBuffer(FList[i]^, s); dec(count, s); inc(i); end; end; function TPooledMemoryStream.Seek(Offset: Integer; Origin: Word): Longint; begin case Origin of soFromBeginning: FPosition := Offset; soFromCurrent: Inc(FPosition, Offset); soFromEnd: FPosition := FSize + Offset; end; Result := FPosition; end; procedure TPooledMemoryStream.SetSize(NewSize: Integer); var count, i: integer; p: Pointer; begin if (NewSize mod FPageSize) > 0 then count := (NewSize div FPageSize) + 1 else count := (NewSize div FPageSize); if (count > FList.Count) then begin for i := FList.Count to count - 1 do begin GetMem(p, FPageSize); FList.Add(p); end; end else if (count < FList.Count) then begin for i := FList.Count - 1 downto Count do begin FreeMem(FList[i]); FList.Delete(i); end; end; FSize := NewSize; if FPosition > FSize then Seek(0, soFromEnd); end; function TPooledMemoryStream.Write(const Buffer; Count: Integer): Longint; var Pos, n: Integer; p, c: Pointer; begin if (FPosition >= 0) and (Count >= 0) then begin Pos := FPosition + Count; if Pos > 0 then begin Result := Count; if Pos > FSize then SetSize(Pos); c := @buffer; n := FPageSize - (FPosition mod FPageSize); if n > count then n := count; while n > 0 do begin p := Pointer(PtrInt(FList[FPosition div FPageSize]) + (FPosition mod FPageSize)); Move(c^, p^, n); dec(count, n); inc(PtrInt(c), n); inc(FPosition, n); if count >= FPageSize then n := FPageSize else n := count; end; Exit; end; end; Result := 0; end; procedure TPooledMemoryStream.WriteInteger(const V: Integer); begin Write(v, sizeof(v)); end; procedure TPooledMemoryStream.WriteString(const str: string; writesize: boolean; cp: Integer); var s: Integer; data: RawByteString; begin data := MBUEncode(str, cp); s := Length(data); if writesize then Write(s, sizeof(s)); if s > 0 then Write(data[1], s * SizeOf(AnsiChar)) end; end.
26.603175
174
0.611362
4722e9c71c5d47a14693cb5662e372d275692b53
51
pas
Pascal
Test/FailureScripts/enums5.pas
skolkman/dwscript
b9f99d4b8187defac3f3713e2ae0f7b83b63d516
[ "Condor-1.1" ]
79
2015-03-18T10:46:13.000Z
2022-03-17T18:05:11.000Z
Test/FailureScripts/enums5.pas
skolkman/dwscript
b9f99d4b8187defac3f3713e2ae0f7b83b63d516
[ "Condor-1.1" ]
6
2016-03-29T14:39:00.000Z
2020-09-14T10:04:14.000Z
Test/FailureScripts/enums5.pas
skolkman/dwscript
b9f99d4b8187defac3f3713e2ae0f7b83b63d516
[ "Condor-1.1" ]
25
2016-05-04T13:11:38.000Z
2021-09-29T13:34:31.000Z
Type TEnum = (name); var i : TEnum; i := TEnum;
12.75
21
0.54902
cdb532983912892ad87e5cd2bd480bb98bfcdac7
2,943
pas
Pascal
source/ALAndroidAppsFlyerApi.pas
juliomar/alcinoe
4e59270f6a9258beed02676c698829e83e636b51
[ "Apache-2.0" ]
851
2018-02-05T09:54:56.000Z
2022-03-24T23:13:10.000Z
source/ALAndroidAppsFlyerApi.pas
juliomar/alcinoe
4e59270f6a9258beed02676c698829e83e636b51
[ "Apache-2.0" ]
200
2018-02-06T18:52:39.000Z
2022-03-24T19:59:14.000Z
source/ALAndroidAppsFlyerApi.pas
juliomar/alcinoe
4e59270f6a9258beed02676c698829e83e636b51
[ "Apache-2.0" ]
197
2018-03-20T20:49:55.000Z
2022-03-21T17:38:14.000Z
unit ALAndroidAppsFlyerApi; interface uses Androidapi.JNIBridge, Androidapi.JNI.App, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.JavaTypes; type {***************************************} JAppsFlyerConversionListener = interface; JALAppsFlyerLib = interface; {*******************************************************} JAppsFlyerConversionListenerClass = interface(IJavaClass) ['{E7C1E146-2E55-478F-9218-C1DAA89DA964}'] end; {**********************************************************} [JavaSignature('com/appsflyer/AppsFlyerConversionListener')] JAppsFlyerConversionListener = interface(IJavaInstance) ['{ACE202A5-AD33-4D2D-876B-296874928AA4}'] procedure onAppOpenAttribution(conversionData: JMap); cdecl; procedure onAttributionFailure(errorMessage: JString); cdecl; procedure onInstallConversionDataLoaded(conversionData: JMap); cdecl; procedure onInstallConversionFailure(errorMessage: JString); cdecl; end; TJAppsFlyerConversionListener = class(TJavaGenericImport<JAppsFlyerConversionListenerClass, JAppsFlyerConversionListener>) end; {*******************************} //this class because of this bug: //https://stackoverflow.com/questions/53141813/delphi-android-java-class-init-function JALAppsFlyerLibClass = interface(JObjectClass) ['{48A22162-044E-48B1-BBA0-C8D02162A522}'] {class} procedure initialize(key: JString; conversionListener: JAppsFlyerConversionListener; context: JContext); cdecl; {class} procedure sendDeepLinkData(activity: JActivity); cdecl; {class} procedure startTracking(application: JApplication); cdecl; {class} procedure trackEvent(context: JContext; eventName: JString; eventValues: JHashMap); cdecl; overload; {class} procedure trackEvent(context: JContext; eventName: JString); cdecl; overload; {class} procedure unregisterConversionListener; cdecl; {class} procedure setAndroidIdData(androidIdData: JString); cdecl; {class} procedure enableUninstallTracking(senderId: JString); cdecl; {class} procedure updateServerUninstallToken(context: JContext; refreshedToken: JString); cdecl; {class} procedure setCustomerUserId(id: JString); cdecl; end; {**************************************************} [JavaSignature('com/alcinoe/appsflyer/ALAppsFlyer')] JALAppsFlyerLib = interface(JObject) ['{6145C2CE-433B-4F69-B996-614EA0C015A5}'] end; TJALAppsFlyerLib = class(TJavaGenericImport<JALAppsFlyerLibClass, JALAppsFlyerLib>) end; implementation {**********************} procedure RegisterTypes; begin TRegTypes.RegisterType('ALAndroidAppsFlyerApi.JAppsFlyerConversionListener', TypeInfo(ALAndroidAppsFlyerApi.JAppsFlyerConversionListener)); TRegTypes.RegisterType('ALAndroidAppsFlyerApi.JALAppsFlyerLib', TypeInfo(ALAndroidAppsFlyerApi.JALAppsFlyerLib)); end; initialization RegisterTypes; end.
42.042857
142
0.703024
f1a1222588fa83f43f8d11560473fa5afba4a336
301
dpr
Pascal
mpeg_player/Player.dpr
trejder/delphi-solutions
e2434df83037b6c6d19abad42c08f7e69044be91
[ "MIT" ]
7
2017-01-15T02:58:37.000Z
2021-02-18T15:44:04.000Z
mpeg_player/Player.dpr
trejder/delphi-solutions
e2434df83037b6c6d19abad42c08f7e69044be91
[ "MIT" ]
null
null
null
mpeg_player/Player.dpr
trejder/delphi-solutions
e2434df83037b6c6d19abad42c08f7e69044be91
[ "MIT" ]
4
2016-06-01T13:12:38.000Z
2020-10-26T11:06:54.000Z
(* Adam Boduch@poland.com *) program Player; uses Forms, MainFrmU in 'MainFrmU.pas' {MainFrm}, BigFrmU in 'BigFrmU.pas' {FullForm}; {$R *.RES} begin Application.Initialize; Application.CreateForm(TMainFrm, MainFrm); Application.CreateForm(TFullForm, FullForm); Application.Run; end.
16.722222
46
0.72093
473242735bbf0720b414623edc36a7896e2952fa
11,926
pas
Pascal
uMainForm.pas
KoRiF/Delphi-JsonToDelphiClass
095797b16e314edea2d8f930466e543f3a608995
[ "MIT" ]
205
2015-01-03T21:36:05.000Z
2022-02-24T13:12:58.000Z
uMainForm.pas
KoRiF/Delphi-JsonToDelphiClass
095797b16e314edea2d8f930466e543f3a608995
[ "MIT" ]
17
2016-01-27T04:27:17.000Z
2021-12-17T05:36:55.000Z
uMainForm.pas
KoRiF/Delphi-JsonToDelphiClass
095797b16e314edea2d8f930466e543f3a608995
[ "MIT" ]
90
2015-01-04T07:09:50.000Z
2022-02-22T13:04:55.000Z
unit uMainForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Layouts, FMX.Memo, System.Json, Rest.Json, FMX.TreeView, TypInfo, RTTI, regularexpressions, generics.collections, Pkg.Json.Mapper, NetEncoding, FMX.Menus, FMX.Controls.Presentation, FMX.Edit, FMX.ConstrainedForm, REST.Client, uUpdate, System.Threading, uGitHub, FMX.Objects, uUpdateForm, SyncObjs, FMX.ScrollBox; const JsonValidatorUrl = 'http://jsonlint.com'; type TMainForm = class(TConstrainedForm) Memo1: TMemo; tv: TTreeView; StyleBook1: TStyleBook; StatusBar1: TStatusBar; Label1: TLabel; MainPopupMenu: TPopupMenu; MenuItem1: TMenuItem; MenuItem2: TMenuItem; MenuItem3: TMenuItem; Panel1: TPanel; Panel2: TPanel; Splitter1: TSplitter; Panel3: TPanel; btnVisualize: TButton; btnOnlineJsonValidator: TButton; btnExit: TButton; Label3: TLabel; Label4: TLabel; Edit2: TEdit; Label5: TLabel; MemoPopupMenu: TPopupMenu; MenuItem4: TMenuItem; MenuItem5: TMenuItem; MenuItem6: TMenuItem; MenuItem7: TMenuItem; Panel4: TPanel; MenuItem8: TMenuItem; btnGenerateUnit: TButton; procedure btnVisualizeClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure PreviewUnitClick(Sender: TObject); procedure btnExitClick(Sender: TObject); procedure MainPopupMenuPopup(Sender: TObject); procedure tvDblClick(Sender: TObject); procedure Memo1DblClick(Sender: TObject); procedure MenuItem3Click(Sender: TObject); procedure MenuItem5Click(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure Label1Click(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure tvKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure Panel1Resize(Sender: TObject); procedure MenuItem8Click(Sender: TObject); procedure btnOnlineJsonValidatorClick(Sender: TObject); private { Private declarations } procedure DisableMenuItems; procedure VisualizeClass; procedure PrepareMenu; procedure DisableGuiElements; public { Public declarations } jm: TPkgJsonMapper; FCheckVersionResponse: TObject; FChanged: boolean; // 0: Active // 1: Terminating // >=2: Terminated FApplicationStatus: integer; FUpdateCheckEvent: TEvent; end; var MainForm: TMainForm; implementation {$R *.fmx} uses uSaveUnitForm, {$IFDEF MSWINDOWS} Winapi.ShellAPI, Winapi.Windows; {$ENDIF MSWINDOWS} {$IFDEF POSIX} Posix.Stdlib; {$ENDIF POSIX} procedure TMainForm.btnOnlineJsonValidatorClick(Sender: TObject); begin MenuItem8Click(nil); end; procedure TMainForm.btnVisualizeClick(Sender: TObject); begin if FChanged then MessageDlg('You made changes to the structure. Do you want to load original class?', TMsgDlgType.mtWarning, [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], 0, procedure(const AResult: TModalResult) begin if AResult = mrYes then VisualizeClass; end ) else VisualizeClass; end; procedure TMainForm.DisableGuiElements; begin edit2.Enabled := false; Memo1.Enabled := false; tv.Enabled := false; tv.PopupMenu := nil; btnExit.Enabled := false; btnVisualize.Enabled := false; btnGenerateUnit.Enabled := false; end; procedure TMainForm.DisableMenuItems; var k: integer; begin for k := 0 to MainPopupMenu.ItemsCount - 1 do begin MainPopupMenu.Items[k].Enabled := false; end; end; procedure TMainForm.PreviewUnitClick(Sender: TObject); begin if tv.Count = 0 then btnVisualizeClick(self); jm.DestinationUnitName := edit2.Text; SaveUnitForm.sd.FileName := jm.DestinationUnitName + '.pas'; SaveUnitForm.Memo1.DeleteSelection; SaveUnitForm.Memo1.Text := jm.GenerateUnit; SaveUnitForm.Caption := 'Preview Delphi Unit - ' + SaveUnitForm.sd.FileName; // ShowModal bug - QC129552 // The same is declared in the SaveUnitForm's OnShow event SaveUnitForm.width := MainForm.Width - 50; SaveUnitForm.height := MainForm.Height - 50; SaveUnitForm.left := MainForm.Left + 25; SaveUnitForm.top := MainForm.Top + 25; SaveUnitForm.ShowModal; end; procedure TMainForm.btnExitClick(Sender: TObject); begin Close; end; procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if FUpdateCheckEvent.WaitFor(0) = wrSignaled then CanClose := true else begin CanClose := false; case FApplicationStatus of 0: begin TInterlocked.Increment(FApplicationStatus); DisableGuiElements; label1.Text := 'Terminating application, please wait...'; // We start a termination task. // This way the main thread will not freeze TTask.Run( procedure begin FUpdateCheckEvent.WaitFor(); // Indicate next stage TInterlocked.Increment(FApplicationStatus); // We enqueue the handler TThread.Queue(nil, procedure begin Close; end ); end ); end; 1: ; else CanClose := true; end; end; end; procedure TMainForm.FormCreate(Sender: TObject); begin FApplicationStatus := 0; FUpdateCheckEvent := TEvent.Create(nil, true, false, ''); self.Constraints.MinWidth := 1024; self.Constraints.MinHeight := 560; Caption := 'JsonToDelphiClass - ' + FloatToStr(ProgramVersion, PointDsFormatSettings) + ' | By Petar Georgiev'; jm := TPkgJsonMapper.Create(tv); label1.Text := 'Checking for update...'; NewCheckForUpdateTask( procedure(ARelease: TObject) begin FCheckVersionResponse := ARelease; if FCheckVersionResponse is TReleaseClass then begin label1.StyleLookup := 'LabelLinkStyle'; label1.Text := 'Version ' + (FCheckVersionResponse as TReleaseClass).tag_name + ' is available! Click here to download!'; (label1.FindStyleResource('text') as TText).OnClick := label1Click; label1.HitTest := true; end else if FCheckVersionResponse is TErrorClass then begin label1.StyleLookup := 'LabelErrorStyle'; label1.Text := 'Error checking for new version: ' + (FCheckVersionResponse as TErrorClass).message; end else begin label1.StyleLookup := 'LabelGreenStyle'; label1.Text := 'Your version ' + FloatToStr(uUpdate.ProgramVersion, PointDsFormatSettings) + ' is up to date! For more information about JsonToDelphiClass click here!'; (label1.FindStyleResource('text') as TText).OnClick := label1Click; end; FUpdateCheckEvent.SetEvent; end ); end; procedure TMainForm.FormDestroy(Sender: TObject); begin FreeAndNil(FUpdateCheckEvent); FreeAndNil(jm); FreeAndNil(FCheckVersionResponse); end; procedure TMainForm.FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if Key = 27 then close; end; procedure TMainForm.Label1Click(Sender: TObject); begin if FCheckVersionResponse <> nil then begin UpdateForm.FRelease := FCheckVersionResponse as TReleaseClass; UpdateForm.ShowModal; end else begin {$IFDEF MSWINDOWS} ShellExecute(0, 'OPEN', PChar(ProgramUrl), '', '', SW_SHOWNORMAL); {$ENDIF MSWINDOWS} {$IFDEF POSIX} _system(PAnsiChar('open ' + AnsiString(ProgramUrl))); {$ENDIF POSIX} end; end; procedure TMainForm.Memo1DblClick(Sender: TObject); var LTsl: TStringList; LJsonValue: TJSONValue; begin LTsl := TStringList.Create; try LJsonValue := TJSONObject.ParseJSONValue(memo1.Text); try if LJsonValue <> nil then PrettyPrintJSON(LJsonValue, LTsl); finally LJsonValue.Free; end; memo1.Text := LTsl.Text; finally LTsl.Free; end; end; procedure TMainForm.MenuItem3Click(Sender: TObject); var LString: string; LField: TStubField; begin LField := (Sender as TFmxObject).TagObject as TStubField; LString := InputBox('Rename Property ' + LField.Name, 'Enter new Property name', LField.Name); if (LString <> '') AND (LString.ToLower <> LField.Name.ToLower) then begin FChanged := true; LField.Name := LString; jm.Visualize(tv, 'TreeViewItem1Style1'); end; end; procedure TMainForm.MenuItem5Click(Sender: TObject); var LString: string; LClass: TStubClass; begin LClass := (Sender as TFmxObject).TagObject as TStubClass; LString := InputBox('Rename Class ' + LClass.Name, 'Enter new Class name', LClass.PureClassName); if (LString <> '') AND (LString.ToLower <> LClass.PureClassName.ToLower) then begin FChanged := true; LClass.Name := LString; jm.Visualize(tv, 'TreeViewItem1Style1'); end; end; procedure TMainForm.MenuItem8Click(Sender: TObject); begin {$IFDEF MSWINDOWS} ShellExecute(0, 'OPEN', PChar(JsonValidatorUrl), '', '', SW_SHOWNORMAL); {$ENDIF MSWINDOWS} {$IFDEF POSIX} _system(PAnsiChar('open ' + AnsiString(JsonValidatorUrl))); {$ENDIF POSIX} end; procedure TMainForm.Panel1Resize(Sender: TObject); begin if Panel1.Width < 200 then Panel1.Width := 200 else if Panel1.Width > (MainForm.Width - 20) div 2 then Panel1.Width := (MainForm.Width - 20) div 2; end; procedure TMainForm.MainPopupMenuPopup(Sender: TObject); var LItem: TTreeViewItem; LPoint: TPointF; begin DisableMenuItems; MainPopupMenu.Items[0].Text := '---'; LPoint := tv.AbsoluteToLocal(ScreenToClient(MainPopupMenu.PopupPoint)); LItem := tv.ItemByPoint(LPoint.X, LPoint.Y); if LItem <> nil then LItem.Select; PrepareMenu; end; procedure TMainForm.PrepareMenu; var LField: TStubField; begin if tv.Selected <> nil then begin MainPopupMenu.Items[0].Text := tv.Selected.Text; if tv.Selected <> tv.Items[0] then begin LField := tv.Selected.TagObject as TStubField; MainPopupMenu.Items[2].Enabled := true; MainPopupMenu.Items[2].TagObject := LField; if (LField is TStubContainerField) AND ((LField as TStubContainerField).ContainedType = TJsonType.jtObject) then begin MainPopupMenu.Items[3].Enabled := true; MainPopupMenu.Items[3].TagObject := (LField as TStubContainerField).FieldClass; end; end else begin MainPopupMenu.Items[3].Enabled := true; MainPopupMenu.Items[3].TagObject := tv.Selected.TagObject; end; end; end; procedure TMainForm.tvDblClick(Sender: TObject); begin if tv.Selected <> nil then tv.Selected.IsExpanded := not tv.Selected.IsExpanded; end; procedure TMainForm.tvKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if ((KeyChar = #0) AND (Key = 113)) AND (tv.Selected <> nil) then begin PrepareMenu; if tv.Selected = tv.Items[0] then MenuItem5Click(MenuItem5) else MenuItem3Click(MenuItem3); end; end; procedure TMainForm.VisualizeClass; begin FChanged := false; jm.Parse(memo1.Text, 'Root'); jm.Visualize(tv, 'TreeViewItem1Style1'); // Workarround for QC129540 Panel1.Width := Panel1.Width + 1; Panel1.Width := Panel1.Width - 1; end; end.
27.606481
179
0.665269
47c9ca7b6a49b176477a65b66559e015312f44f7
1,423
pas
Pascal
samples/a8/demoeffects/dli_scroll.pas
zbyti/Mad-Pascal
546cae9724828f93047080109488be7d0d07d47e
[ "MIT" ]
1
2021-12-15T23:47:19.000Z
2021-12-15T23:47:19.000Z
samples/a8/demoeffects/dli_scroll.pas
michalkolodziejski/Mad-Pascal
0a7a1e2f379e50b0a23878b0d881ff3407269ed6
[ "MIT" ]
null
null
null
samples/a8/demoeffects/dli_scroll.pas
michalkolodziejski/Mad-Pascal
0a7a1e2f379e50b0a23878b0d881ff3407269ed6
[ "MIT" ]
null
null
null
// DLI Scroll by Greblus uses crt; const dl: array [0..32] of byte = ( 112, 112, 112, 66, 0, 64, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 130, 86, 36, 67, 65, lo(word(@dl)), hi(word(@dl)) ); var col0: byte absolute 708; col1: byte absolute 709; savmsc: word absolute 88; nmien: byte absolute $d40e; pc: ^byte; tmp: word; hscrol: byte absolute 54276; vcount: byte absolute $d40b; colt: byte absolute $d017; wsync: byte absolute $d40a; dlist: word absolute 560; i,j,k,l,indx: byte; old_dli, old_vbl: pointer; procedure dli; interrupt; begin asm { phr }; inc(indx); for i:=0 to 7 do begin wsync:=1; if indx>30 then indx:=0; colt:=vcount+indx; end; asm { plr }; end; // mad pascal add RTI procedure scroll; interrupt; begin hscrol:=j; inc(j); if j=17 then begin j:=0; dec(pc^,2); inc(k); if k=14 then begin k:=0; pc^:=tmp; end end; asm { jmp $E462 }; end; begin i:=0; j:=0; k:=0; indx:=0; dlist:=word(@dl); GetIntVec(iVBL, old_vbl); GetIntVec(iDLI, old_dli); SetIntVec(iVBL, @scroll); SetIntVec(iDLI, @dli); nmien:=$c0; pc := @dl; inc(pc, 28); tmp := pc^+6; col0 := 14; col1 := 14; savmsc := $4000; for l:=1 to 22 do writeln(' mp rulez! '); repeat until keypressed; SetIntVec(iVBL, old_vbl); SetIntVec(iDLI, old_dli); end.
16.546512
55
0.563598
f129b9df1b5517f047b082010eee55fdcfb77be3
13,909
pas
Pascal
s6/olymp/testlib.pas
lisiynos/lisiynos.github.io
5900ee6ab0055a8047dd2b54b8667d05f3a145c2
[ "MIT" ]
1
2019-03-02T17:20:25.000Z
2019-03-02T17:20:25.000Z
s6/olymp/testlib.pas
lisiynos/lisiynos.github.io
5900ee6ab0055a8047dd2b54b8667d05f3a145c2
[ "MIT" ]
null
null
null
s6/olymp/testlib.pas
lisiynos/lisiynos.github.io
5900ee6ab0055a8047dd2b54b8667d05f3a145c2
[ "MIT" ]
null
null
null
{ Copyright(c) SPb-IFMO CTD Developers, 2000 } { Copyright(c) Anton Sukhanov, 1996 } { $Id: testlib.pas,v 1.9 2004/06/30 08:55:35 jury Exp $ } { Evaluating programs support stuff } {$ifdef VER70} {$A-,B-,D+,E+,F+,G+,I-,L+,N+,O-,P+,Q-,R+,S+,T-,V+,X+,Y+} {$M 65520, 0, 0} {$endif} (* Program, using testlib running format: CHECK <Input_File> <Output_File> <Answer_File> [<Result_File> [-xml]], If result file is specified it will contain results. *) { Modifications log: dd.mm.yyyy modified by modification log 17.09.2000 Andrew Stankevich XML correct comments 01.08.2000 Andrew Stankevich Messages translated to English APPES support added FAIL name changed 07.02.1998 Roman Elizarov Correct EOF processing 12.02.1998 Roman Elizarov SeekEoln corrected eoln added nextLine added nextChar is now function } unit TESTLIB; (* ================================================================= *) interface (* ================================================================= *) const eofChar = #$1A; eofRemap = ' '; NumberBefore = [#10,#13,' ',#09]; NumberAfter = [#10,#13,' ',#09,eofChar]; lineAfter = [#10,#13,eofChar]; Blanks = [#10,#13,' ',#09]; eolnChar = [#10,#13,eofChar]; type REAL = EXTENDED; {!!!!!!!!} type CharSet = set of char; TMode = (_Input, _Output, _Answer); TResult = (_OK, _WA, _PE, _Fail, _PC, _Dirt); {_OK - accepted, _WA - wrong answer, _PE - output format mismatch, _Fail - when everything fucks up } { _Dirt - for inner using} InStream = object cur: char; { current char, =EofChar, if eof } f: TEXT; { file } name: string; { file name } mode: TMode; opened: boolean; { for internal usage } constructor init (fname: string; m: TMode); function CurChar: char; { returns cur } function nextChar: char; { moves to next char } function seekeof: boolean; function eof : boolean; { == cur = EofChar } function eoln: boolean; function seekEoln: boolean; procedure nextLine; { skips current line } { Skips chars from given set } { Does not generate errors } procedure skip (setof: CharSet); { Read word. Skip before all chars from `before` and after all chars from `after`. If eof or word is empty or it contains more than 255 chars, generates _pe } function ReadWord (Before, After: CharSet): string; { reads integer } { _pe if error } { USE readlongint! } function ReadInteger: integer; { reads longint } { _pe if error } function ReadLongint: longint; { reads real } { _pe if error } function ReadReal: real; procedure Reset; { same as readword([], [#13 #10]) } function ReadString: string; { for internal usage } procedure QUIT (res: TResult; msg: string); procedure close; end; procedure Quit(res: TResult; msg: string); overload; procedure QuitWithPC(msg : string; pctype : integer); procedure SetCustomAttribute(name : string; value : string); overload; procedure SetCustomAttribute(name : string; value : integer); overload; procedure SetCustomAttribute(name : string; value : real); overload; var inf, ouf, ans: InStream; ResultName: string; { result file name } AppesMode: boolean; (* ================================================================= *) implementation (* ================================================================= *) {$ifdef VER70} uses crt; {$else} uses windows, sysutils; {$endif} {$ifndef VER70} const LightGray = $07; LightRed = $0c; LightCyan = $0b; LightGreen = $0a; Yellow = $0e; MAX_CUSTOM_ATTR = 256; type TCustomAttr = record name, value : string; end; var nCustomAttr : integer = 0; customAttr : array[1..MAX_CUSTOM_ATTR] of TCustomAttr; procedure SetCustomAttribute(name : string; value : string); overload; var i : integer; begin for i := 1 to nCustomAttr do if customAttr[i].name = name then begin customAttr[i].value := value; exit; end; inc(nCustomAttr); assert(nCustomAttr <= MAX_CUSTOM_ATTR); customAttr[nCustomAttr].name := name; customAttr[nCustomAttr].value := value; end; procedure SetCustomAttribute(name : string; value : integer); overload; begin SetCustomAttribute(name, inttostr(value)); end; procedure SetCustomAttribute(name : string; value : real); overload; begin SetCustomAttribute(name, floattostr(value)); end; procedure textcolor(x: word); var h: thandle; begin h := getstdhandle(std_output_handle); setconsoletextattribute(h, x); end; {$endif} {$ifdef ver70} procedure beep(freq, duration: integer); begin sound(freq); delay(duration); nosound; end; {$endif} const outcomes: array[0..8] of string = ( 'accepted', 'wrong-answer', 'presentation-error', 'fail', 'partially-correct', 'run-time-error', 'time-limit-exceeded', 'compilation-error', 'security-violation' ); procedure safewrite(var t: text; s: string); var i: longint; begin for i := 1 to length(s) do begin case s[i] of '&': write(t, '&amp;'); '<': write(t, '&lt;'); '"': write(t, '&quot;'); else if s[i] < ' ' then write(t, '?') else write(t, s[i]); end; { case } end; end; procedure quit (res: TResult; msg: string; pctype : integer); overload; forward; procedure quit (res: TResult; msg: string); overload; begin assert(res <> _PC); quit(res, msg, 0); end; procedure quitwithpc(msg : string; pctype : integer); begin quit(_PC, msg, pctype); end; procedure quit (res: TResult; msg: string; pctype : integer); var ResFile: text; ErrorName: string; i : integer; procedure scr (color: word; msg: string); begin if ResultName = '' then { if no result file } begin TextColor (color); write (msg); TextColor (LightGray); end; end; begin if (res = _OK) then begin ouf.skip (Blanks); if not ouf.eof then QUIT (_Dirt, 'Extra information in Output'); end; case res of _Fail: begin ErrorName := 'FAIL '; Scr (LightRed, ErrorName); end; _Dirt: begin ErrorName := 'wrong output format '; Scr (LightCyan, ErrorName); res := _PE; msg := 'Extra information in output file'; end; _PE: begin ErrorName := 'wrong output format '; Scr (LightRed, ErrorName); end; _OK: begin ErrorName := 'ok '; Scr (LightGreen, ErrorName); end; _PC: begin ErrorName := 'pc' + inttostr(pctype) + ' '; Scr (Yellow, ErrorName); end; _WA: begin ErrorName := 'wrong answer '; TextColor (LightRed); scr (LightRed, ErrorName); end; else QUIT (_Fail, 'What is the code ??? '); end; if ResultName <> '' then begin assign (RESFILE, ResultName); { Create file with result of evaluation } rewrite (ResFile); if IORESULT <> 0 then QUIT (_Fail, 'Can not write to Result file'); if AppesMode then begin writeln(ResFile, '<?xml version = "1.0" encoding = "windows-1251"?>'); writeln(ResFile, '<result'); writeln(ResFile, ' outcome = "', outcomes[ord(res)], '"'); write(ResFile, ' comment = "'); SafeWrite(ResFile, msg); writeln(ResFile, '" '); if res = _PC then writeln(ResFile, ' pc-type = "', pctype, '"'); for i := 1 to nCustomAttr do begin write(ResFile, ' ', customAttr[i].name, ' = "'); SafeWrite(ResFile, customAttr[i].value); writeln(ResFile, '"'); end; writeln(ResFile, '>'); SafeWrite(ResFile, msg); writeln(ResFile, '</result>'); end else begin writeln(resfile, msg); end; close (ResFile); if IORESULT <> 0 then QUIT (_Fail, 'Can not write to Result file'); end; Scr (LightGray, msg + ' '); writeln; if Res = _Fail then HALT (ord (res)); {$i-}close (inf.f); close (ouf.f); close (ans.f);{$i+} if ioresult<>0 then; TextColor (LightGray); if (res = _OK) or (appesmode) then HALT (0) else HALT (ord (res)); end; constructor Instream.init (fname: string; m: TMode); begin name := fname; mode := m; assign (f, fname); {$I-} system.reset (f); if IORESULT <> 0 then begin if mode = _Output then QUIT (_PE, 'File not found ' + fname); cur := EofChar; end else if system.eof (f) then cur := EofChar else begin cur := ' '; nextchar end; opened := true; end; function InStream.curchar: char; begin curchar := cur end; function InStream.nextChar: char; begin nextChar:= curChar; if cur = EofChar then { do nothing } else if system.eof (f) then cur := EofChar else begin {$I-} read (f, cur); if IORESULT <> 0 then Quit (_Fail, 'Read error' + name); if cur = eofChar then cur:= eofRemap; end; end; procedure InStream.QUIT (res: TResult; msg: string); begin if mode = _Output then TESTLIB.QUIT (res, msg) { if can't read input or answer - fail } else TESTLIB.QUIT (_Fail, msg + ' (' + name + ')'); end; function InStream.ReadWord (Before, After: CharSet): string; var {$ifdef ver70} i: integer; {$endif} res: string; begin while cur in Before do nextchar; if (cur = EofChar) and not (cur in after) then QUIT (_PE, 'Unexpected end-of-file'); {$ifdef ver70} i := 0; {$endif} res := ''; while not ((cur IN AFTER) or (cur = EofChar)) do begin {$ifdef ver70} inc (i); if i > 255 then QUIT (_PE, 'Line too long'); {$endif} res := res + cur; nextchar; end; ReadWord := res; end; function InStream.ReadInteger: integer; begin readinteger := readlongint; end; function InStream.ReadReal: real; var help: string; res: real; code: integer; begin help := ReadWord (NumberBefore, NumberAfter); val (help, res, code); if code <> 0 then QUIT (_PE, 'Expected real instead of "' + help + '"'); ReadReal := res end; function InStream.ReadLongint: longint; var help: string; res: longint; code: integer; begin help := ReadWord (NumberBefore, NumberAfter); val (help, res, code); if code <> 0 then QUIT (_PE, 'Expected longint instead of "' + help + '"'); ReadLongint := res end; procedure InStream.skip (setof: CharSet); begin while (cur in setof) and (cur <> eofchar) do nextchar; end; function InStream.eof: boolean; begin eof := cur = eofChar; end; function InStream.seekEof: boolean; begin while (cur in Blanks) do nextchar; seekeof := cur = EofChar; end; function InStream.eoln: boolean; begin eoln:= cur in eolnChar; end; function InStream.seekEoln: boolean; begin skip ( [' ', #9] ); seekEoln:= eoln; end; procedure InStream.nextLine; begin while not (cur in eolnChar) do nextchar; if cur = #13 then nextchar; if cur = #10 then nextchar; end; function InStream.ReadString: string; begin readstring:= ReadWord ([], lineAfter); nextLine; end; procedure InStream.Reset; begin {$I-} system.reset (f); if IORESULT <> 0 then begin cur := EofChar; { allow for other files } end else if system.eof (f) then cur := EofChar else begin cur := ' '; nextchar end; opened := true; end; procedure InStream.close; begin if opened then system.close(f); opened := false; end; function upper(s: string): string; var i: longint; begin for i := 1 to length(s) do s[i] := upcase(s[i]); upper := s; end; BEGIN { a.k.a. initialization } if (ParamCount < 3) or (ParamCount > 5) then quit(_fail, 'Program must be run with the following arguments: ' + '<INPUT-FILE> <OUTPUT-FILE> <ANSWER-FILE> [<Result_File> [-xml]]'); case ParamCount of 3: begin ResultName := ''; AppesMode := false; end; 4: begin ResultName := ParamStr(4); AppesMode := false; end; 5: begin if (upper(ParamStr(5)) <> '-XML') and (upper(paramstr(5)) <> '-APPES') then quit(_fail, 'Program must be run with the following arguments: ' + '<INPUT-FILE> <OUTPUT-FILE> <ANSWER-FILE> [<Result_File> [-xml]]'); ResultName := ParamStr(4); AppesMode := true; end; end; { case } inf.opened := false; ouf.opened := false; ans.opened := false; inf.init (ParamStr (1), _Input); ouf.init (ParamStr (2), _Output); ans.init (ParamStr (3), _Answer); END.
25.757407
85
0.540585
f1df430b59cb4c0495a0f1c83ae00168e07c46c9
34,858
pas
Pascal
SimpleClassifier/NeuralNetwork.pas
azrael11/mrai
b080d0c8c01f1286d1eaabd146b82d58f9fce53f
[ "Apache-2.0" ]
1
2020-07-20T11:27:27.000Z
2020-07-20T11:27:27.000Z
SimpleClassifier/NeuralNetwork.pas
azrael11/mrai
b080d0c8c01f1286d1eaabd146b82d58f9fce53f
[ "Apache-2.0" ]
null
null
null
SimpleClassifier/NeuralNetwork.pas
azrael11/mrai
b080d0c8c01f1286d1eaabd146b82d58f9fce53f
[ "Apache-2.0" ]
1
2020-07-20T11:27:29.000Z
2020-07-20T11:27:29.000Z
// ################################################################### // #### This file is part of the artificial intelligence project, and is // #### offered under the licence agreement described on // #### http://www.mrsoft.org/ // #### // #### Copyright:(c) 2016, Michael R. . All rights reserved. // #### // #### 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 NeuralNetwork; // ########################################### // #### Artificial Feed Forward Neural Networks // #### -> first version includes a very base // #### backpropagation learning algorithm following the // #### proposed algorithm from the neural network lecture of H. Bishof // ########################################### // -> the input neurons are normed suched that the maximum input // values are around the input examples mean and scaled. interface uses Types, BaseClassifier, BaseMathPersistence; // base simple neuron type TNeuronType = (ntLinear, ntExpSigmoid, ntTanSigmoid, ntExpSigFast); type TNeuron = class(TBaseMathPersistence) private fBeta : double; fNeuralType : TNeuronType; fWeights : TDoubleDynArray; // additional data only used in the learning step: fDeltaWM1 : TDoubleDynArray; // wheights update in the learning step before // helper functions for learning function Derrive(const outputVal : double) : double; procedure RandomInit(const RangeMin : double = -1; const RangeMax : double = 1); public function Feed(const Input : TDoubleDynArray) : double; procedure DefineProps; override; function PropTypeOfName(const Name : string) : TPropType; override; procedure OnLoadDoubleProperty(const Name : String; const Value : double); override; procedure OnLoadIntProperty(const Name : String; Value : integer); override; procedure OnLoadDoubleArr(const Name : String; const Value : TDoubleDynArray); override; constructor Create(NumInputs : integer; nnType : TNeuronType); end; // one layer -> collection of neurons type TNeuralLayer = class(TBaseMathPersistence) private fNeurons : Array of TNeuron; fType : TNeuronType; fLoadIdx : integer; public function Feed(const Input : TDoubleDynArray) : TDoubleDynArray; procedure DefineProps; override; function PropTypeOfName(const Name : string) : TPropType; override; procedure OnLoadBeginList(const Name : String; count : integer); override; function OnLoadObject(Obj : TBaseMathPersistence) : boolean; override; procedure OnLoadEndList; override; procedure OnLoadIntProperty(const Name : String; Value : integer); override; constructor Create(NumInputs, NumNeurons : integer; NeuronType : TNeuronType); destructor Destroy; override; end; // a complete feed forward net type TNeuralLayerRec = record NumNeurons : integer; NeuronType : TNeuronType; end; TNeuralLayerRecArr = Array of TNeuralLayerRec; TNeuralMinMax = packed Array[0..1] of double; //0..min, 1..max TNeuralMinMaxArr = Array of TNeuralMinMax; TFeedForwardNeuralNet = class(TBaseMathPersistence) private fLayer : Array of TNeuralLayer; fInputMinMax : TNeuralMinMaxArr; fInputMeanVar : TNeuralMinMaxArr; fOutputMinMax : TNeuralMinMax; fLoadIdx : integer; public function Feed(const Input : TDoubleDynArray) : TDoubleDynArray; procedure DefineProps; override; function PropTypeOfName(const Name : string) : TPropType; override; procedure OnLoadBeginList(const Name : String; count : integer); override; function OnLoadObject(Obj : TBaseMathPersistence) : boolean; override; procedure OnLoadEndList; override; procedure OnLoadBinaryProperty(const Name : String; const Value; size : integer); override; constructor Create(NumInputs : integer; const layers : TNeuralLayerRecArr; const InputMinMax, InputMeanVar : TNeuralMinMaxArr); destructor Destroy; override; end; type TNeuralNetLearnAlg = (nnBackprop, nnBackpropMomentum); TNeuralNetProps = record learnAlgorithm : TNeuralNetLearnAlg; layers : TNeuralLayerRecArr; // without the output layer! outputLayer : TNeuronType; // output neuron type. (number of output neurons is the number of classes eta : double; // learning rate alpha : double; // used in the momentum algorithm as multiplier of the second term learning rate cf : double; // flat spot elimination constant (used in momentum backprop) l1Normalization : double; // normalization factor used in the weight update proc maxNumIter : integer; // maximum number of batch iterations minNumIter : integer; // minimum number of batch iterations (despite the error change) stopOnMinDeltaErr : double; // when training error change is lower than this delta then stop training validationDataSetSize : double; // percentage (0-1) to be used as validation data set. if set to 0 the training // set is used for validation. numMinDeltaErr : integer; // number of batch iterations that needs to be lower than stopOnMinDeltaErr normMeanVar : boolean; // the input is normaized to (x - mean_i)/var_i where mean_i is the mean of that feature and var_i is it's variance end; // ########################################### // #### Feed forward neural net classifier type TNeuralNet = class(TCustomClassifier) private fNet : TFeedForwardNeuralNet; fClasses : TIntegerDynArray; public function Classify(Example : TCustomExample; var confidence : double) : integer; overload; override; function OnLoadObject(const Name : String; Obj : TBaseMathPersistence) : boolean; overload; override; procedure OnLoadIntArr(const Name : String; const Value : TIntegerDynArray); override; procedure DefineProps; override; function PropTypeOfName(const Name : string) : TPropType; override; constructor Create(aNet : TFeedForwardNeuralNet; aClassList : TIntegerDynArray); destructor Destroy; override; end; // ########################################### // #### Simple feed forward neural net learning class type TNeuralNetLearner = class(TCustomWeightedLearner) private fProps : TNeuralNetProps; fOk : Array of TDoubleDynArray; fnumFeatures : integer; fdeltaK, fdeltaI : TDoubleDynArray; fnumCl : integer; fclassLabels : TIntegerDynArray; foutputExpAct : TDoubleDynArray; fMaxNumNeurons : integer; fCurExampleWeight : double; fWeights : TDoubleDynArray; function DataSetMinMax : TNeuralMinMaxArr; function DataSetMeanVar : TNeuralMinMaxArr; procedure UpdateWeights(deltaK : double; outputs : TDoubleDynArray; neuron : TNeuron); procedure UpdateWeightsByLearnRate(deltaK : double; outputs : TDoubleDynArray; neuron : TNeuron); procedure UpdateWeightsMomentum(deltaK : double; outputs : TDoubleDynArray; neuron : TNeuron); procedure BackProp(net : TFeedForwardNeuralNet; randSet: TCustomLearnerExampleList; idx : TIntegerDynArray); protected function DoLearn(const weights : Array of double) : TCustomClassifier; override; public procedure SetProps(const Props : TNeuralNetProps); class function CanLearnClassifier(Classifier : TCustomClassifierClass) : boolean; override; end; implementation uses Math, SysUtils, BaseMatrixExamples, Matrix; // ################################################ // ##### persistence // ################################################ const cClassLabels = 'labels'; cNeuralNet = 'feedforwardnet'; cNetLayers = 'layers'; cInputMinMax = 'inputMinMax'; cOutputMinMax = 'outputMinMax'; cInputMeanVar = 'inputMeanVar'; cNeuronType = 'neuronType'; cNeuronList = 'neurons'; cNeuronThresh = 'neuronThresh'; cNeuronWeights = 'neuronWeights'; cNeuronBeta = 'neuronBeta'; { TNeuron } constructor TNeuron.Create(NumInputs: integer; nnType: TNeuronType); begin inherited Create; fNeuralType := nnType; fBeta := 1; SetLength(fWeights, NumInputs + 1); end; function TNeuron.Feed(const Input : TDoubleDynArray): double; var i : integer; absRes : double; invBeta : double; sign : double; const cD1 : double = (0.8808 - 0.5)/2; // slope between -2:2 cD2 : double = (1 - 0.8808)/3; // slope between 2:5 begin assert(Length(input) + 1 = length(fWeights), 'Error input does not match learned weights'); Result := fWeights[0]; for i := 0 to Length(Input) - 1 do Result := Result + Input[i]*fWeights[i + 1]; case fNeuralType of //ntPerceptron: Result := ifthen(Result < fThresh, 0, 1); ntLinear: Result := Result; ntExpSigmoid: Result := 1/(1 + exp(-fBeta*(Result))); ntTanSigmoid: Result := tanh(fBeta*(Result)); ntExpSigFast: begin absRes := abs(Result); invBeta := 1/fBeta; sign := 1; if Result < 0 then sign := -1; if absRes <= 2*invBeta then Result := 0.5 + fBeta*cD1*Result else if sign < 0 then Result := (1 - 0.8808) + sign*(absRes - 2)*cD2*fBeta else Result := 0.8808 + sign*(absRes - 2)*cD2*fBeta; Result := Max(0, Min(1, Result)); end; end; end; procedure TNeuron.RandomInit(const RangeMin : double = -1; const RangeMax: double = 1); var i : Integer; begin for i := 0 to Length(fWeights) - 1 do fWeights[i] := Random*(rangeMax - rangeMin) + RangeMin; end; function TNeuron.Derrive(const outputVal: double): double; begin case fNeuralType of ntLinear: Result := fBeta; ntExpSigmoid, ntExpSigFast: Result := fBeta*(outputVal*(1 - outputVal)); ntTanSigmoid: Result := fBeta*(1 - sqr(outputVal)); else Result := 0; end; end; procedure TNeuron.DefineProps; begin inherited; AddDoubleProperty(cNeuronBeta, fBeta); AddIntProperty(cNeuronType, Integer(fNeuralType)); AddDoubleArr(cNeuronWeights, fWeights); end; function TNeuron.PropTypeOfName(const Name: string): TPropType; begin if (CompareText(Name, cNeuronBeta) = 0) or (CompareText(Name, cNeuronWeights) = 0) then Result := ptDouble else if CompareText(Name, cNeuronType) = 0 then Result := ptInteger else Result := inherited PropTypeOfName(Name); end; procedure TNeuron.OnLoadIntProperty(const Name: String; Value: integer); begin if SameText(Name, cNeuronType) then fNeuralType := TNeuronType(Value) else inherited; end; procedure TNeuron.OnLoadDoubleProperty(const Name: String; const Value: double); begin if SameText(Name, cNeuronBeta) then fBeta := Value else inherited; end; procedure TNeuron.OnLoadDoubleArr(const Name: String; const Value: TDoubleDynArray); begin if SameText(Name, cNeuronWeights) then fWeights := Value else inherited; end; { TNeuralLayer } constructor TNeuralLayer.Create(NumInputs, NumNeurons: integer; NeuronType: TNeuronType); var i : integer; mult : double; begin inherited Create; fType := NeuronType; SetLength(fNeurons, NumNeurons); mult := 1/sqrt(NumInputs); for i := 0 to Length(fNeurons) - 1 do begin fNeurons[i] := TNeuron.Create(NumInputs, NeuronType); fNeurons[i].RandomInit(-1*mult, 1*mult); end; end; function TNeuralLayer.Feed(const Input: TDoubleDynArray): TDoubleDynArray; var i : integer; begin SetLength(Result, Length(fNeurons)); for i := 0 to Length(fNeurons) - 1 do Result[i] := fNeurons[i].Feed(Input); end; destructor TNeuralLayer.Destroy; var counter: Integer; begin for counter := 0 to Length(fNeurons) - 1 do fNeurons[counter].Free; inherited; end; procedure TNeuralLayer.DefineProps; var counter : integer; begin inherited; AddIntProperty(cNeuronType, Integer(fType)); BeginList(cNeuronList, Length(fNeurons)); for counter := 0 to Length(fNeurons) - 1 do AddObject(fNeurons[counter]); EndList; end; function TNeuralLayer.PropTypeOfName(const Name: string): TPropType; begin if CompareText(Name, cNeuronType) = 0 then Result := ptInteger else if CompareText(Name, cNeuronList) = 0 then Result := ptObject else Result := inherited PropTypeOfName(Name); end; procedure TNeuralLayer.OnLoadIntProperty(const Name: String; Value: integer); begin if SameText(Name, cNeuronType) then fType := TNeuronType(Value) else inherited; end; procedure TNeuralLayer.OnLoadBeginList(const Name: String; count: integer); begin fLoadIdx := -1; if SameText(Name, cNeuronList) then begin SetLength(fNeurons, count); fLoadIdx := 0; end else inherited; end; function TNeuralLayer.OnLoadObject(Obj: TBaseMathPersistence): boolean; begin Result := True; if fLoadIdx >= 0 then begin fNeurons[fLoadIdx] := obj as TNeuron; inc(fLoadIdx); end else Result := inherited OnLoadObject(obj); end; procedure TNeuralLayer.OnLoadEndList; begin if fLoadIdx >= 0 then fLoadIdx := -1 else inherited; end; { TFeedForwardNeuralNet } constructor TFeedForwardNeuralNet.Create(NumInputs: integer; const layers: TNeuralLayerRecArr; const InputMinMax, InputMeanVar : TNeuralMinMaxArr); var i : integer; lastNumInputs : integer; minVal, maxVal : double; procedure SetBetaAndThreshFirstLayer(aBeta : double; layer : TNeuralLayer); var counter : integer; begin for counter := 0 to Length(layer.fNeurons) - 1 do begin layer.fNeurons[counter].fWeights[0] := 0; //InputMinMax[counter][0] + InputMinMax[counter][1])/2; layer.fNeurons[counter].fBeta := aBeta; end; end; procedure SetBetaAndThresh(aBeta, aThresh : double; layer : TNeuralLayer); var counter : integer; begin for counter := 0 to Length(layer.fNeurons) - 1 do begin layer.fNeurons[counter].fWeights[0]:= -aThresh; layer.fNeurons[counter].fBeta := aBeta; end; end; begin SetLength(fLayer, Length(layers)); fInputMinMax := InputMinMax; fInputMeanVar := InputMeanVar; fOutputMinMax[1] := 1; case layers[High(layers)].NeuronType of ntLinear, ntTanSigmoid : fOutputMinMax[0] := -1; ntExpSigmoid, ntExpSigFast : fOutputMinMax[0] := 0; end; lastNumInputs := NumInputs; for i := 0 to Length(fLayer) - 1 do begin fLayer[i] := TNeuralLayer.Create(lastNumInputs, layers[i].NumNeurons, layers[i].NeuronType); lastNumInputs := layers[i].NumNeurons; end; minVal := MaxDouble; maxVal := -MaxDouble; for i := 0 to Length(fInputMinMax) - 1 do begin minVal := Min(minVal, fInputMinMax[i][0]); maxVal := Max(maxVal, fInputMinMax[i][1]) end; // adjust the input activation by the min max values and according to the input neuron type case fLayer[0].fType of ntLinear: SetBetaAndThreshFirstLayer( 1, fLayer[0]); ntExpSigmoid, ntExpSigFast: SetBetaAndThreshFirstLayer(10/(maxVal - minVal), fLayer[0]); ntTanSigmoid: SetBetaAndThreshFirstLayer(2*pi/(maxVal - minVal), fLayer[0]); end; for i := 1 to Length(fLayer) - 1 do begin if not (fLayer[i - 1].fType in [ntExpSigmoid, ntExpSigFast]) then SetBetaAndThresh(1, 0, fLayer[i]) else SetBetaAndThresh(1, 0.5, fLayer[i]); end; end; destructor TFeedForwardNeuralNet.Destroy; var i : integer; begin for i := 0 to Length(fLayer) - 1 do fLayer[i].Free; inherited; end; function TFeedForwardNeuralNet.Feed(const Input: TDoubleDynArray): TDoubleDynArray; var i : integer; begin SetLength(Result, Length(input)); Result := Input; // normalize by mean and var for i := 0 to Length(input) - 1 do Result[i] := (Result[i] - fInputMeanVar[i][0])/fInputMeanVar[i][1]; for i := 0 to Length(fLayer) - 1 do Result := fLayer[i].Feed(Result); end; procedure TFeedForwardNeuralNet.DefineProps; var counter: Integer; begin inherited; BeginList(cNetLayers, Length(fLayer)); for counter := 0 to Length(fLayer) - 1 do AddObject(fLayer[counter]); EndList; AddBinaryProperty(cInputMinMax, fInputMinMax, sizeof(TNeuralMinMax)*Length(fInputMinMax)); AddBinaryProperty(cOutputMinMax, fOutputMinMax, sizeof(fOutputMinMax)); AddBinaryProperty(cInputMeanVar, fInputMeanVar, sizeof(TNeuralMinMax)*Length(fInputMeanVar)); end; function TFeedForwardNeuralNet.PropTypeOfName(const Name: string): TPropType; begin if CompareText(Name, cNetLayers) = 0 then Result := ptObject else if (CompareText(Name, cInputMinMax) = 0) or (CompareText(Name, cOutputMinMax) = 0) or (CompareText(Name, cInputMeanVar) = 0) then Result := ptBinary else Result := inherited PropTypeOfName(Name); end; procedure TFeedForwardNeuralNet.OnLoadBinaryProperty(const Name: String; const Value; size: integer); begin if SameText(Name, cInputMinMax) then begin assert(Size mod sizeof(TNeuralMinMax) = 0, 'Error persistent size of Input Min Max differs'); SetLength(fInputMinMax, Size div sizeof(TNeuralMinMax)); Move(Value, fInputMinMax[0], Size); end else if SameText(Name, cOutputMinMax) then begin assert(Size = sizeof(fInputMinMax), 'Error persistent size of Input Min Max differs'); Move(Value, fOutputMinMax, Size); end else if SameText(Name, cInputMeanVar) then begin assert(Size mod sizeof(TNeuralMinMax) = 0, 'Error persistent size of Input Min Max differs'); SetLength(fInputMeanVar, Size div sizeof(TNeuralMinMax)); Move(Value, fInputMeanVar[0], Size); end; inherited; end; procedure TFeedForwardNeuralNet.OnLoadBeginList(const Name: String; count: integer); begin fLoadIdx := -1; if SameText(Name, cNetLayers) then begin SetLength(fLayer, count); fLoadIdx := 0; end else inherited; end; procedure TFeedForwardNeuralNet.OnLoadEndList; begin if fLoadIdx <> -1 then fLoadIdx := -1 else inherited; end; function TFeedForwardNeuralNet.OnLoadObject(Obj: TBaseMathPersistence): boolean; begin Result := True; if fLoadIdx >= 0 then begin fLayer[fLoadIdx] := obj as TNeuralLayer; inc(fLoadIdx); end else Result := inherited OnLoadObject(Obj); end; { TNeuralNetLearner } procedure TNeuralNetLearner.BackProp(net : TFeedForwardNeuralNet; randSet : TCustomLearnerExampleList; idx : TIntegerDynArray); var exmplCnt : integer; counter : integer; actIdx : integer; layerCnt : integer; lastClass : integer; neuronCnt : integer; tmp : TDoubleDynArray; begin // init section if fOk = nil then begin SetLength(fOk, 2 + Length(fProps.layers)); SetLength(fOk[0], fnumFeatures); SetLength(foutputExpAct, fnumCl); SetLength(fdeltak, fMaxNumNeurons); SetLength(fdeltaI, fMaxNumNeurons); end; if fProps.learnAlgorithm <> nnBackpropMomentum then fProps.cf := 0; lastClass := MaxInt; // ############################################### // #### Performs one batch backpropagations step on the given randomized data set // it reuses some global object variables for exmplCnt := 0 to randSet.Count - 1 do begin fCurExampleWeight := fWeights[idx[exmplCnt]]; // define wanted output activation for the current example if randSet.Example[idx[exmplCnt]].ClassVal <> lastClass then begin actIdx := -1; for counter := 0 to fNumCl - 1 do begin if fClassLabels[counter] = randSet.Example[idx[exmplCnt]].ClassVal then begin actIdx := counter; break; end; end; for counter := 0 to fnumCl - 1 do foutputExpAct[counter] := net.fOutputMinMax[IfThen(counter = actIdx, 1, 0) ]; end; for counter := 0 to fNumFeatures - 1 do fOk[0][counter] := randSet[idx[exmplCnt]].FeatureVec[counter]; // first layer -> normalize input by mean var of the complete input for counter := 0 to fnumFeatures - 1 do fOk[0][counter] := (fOk[0][counter] - net.fInputMeanVar[counter][0])/net.fInputMeanVar[counter][1]; // calculate activation (o_k) for all layers for layerCnt := 0 to Length(net.fLayer) - 1 do fOk[layerCnt + 1] := net.fLayer[layerCnt].Feed(fOk[layerCnt]); // output layer -> activation error is calculatead against the expected output for neuronCnt := 0 to Length(fok[length(fok) - 1]) - 1 do begin fdeltak[neuronCnt] := (foutputExpAct[neuronCnt] - fok[Length(fok) - 1][neuronCnt])* (fProps.cf + net.fLayer[Length(net.fLayer) - 1].fNeurons[neuronCnt].Derrive(fok[Length(fok) - 1][neuronCnt]) ); // update weights of the final neuron UpdateWeights(fdeltaK[neuronCnt], fok[Length(fok) - 2], net.fLayer[Length(net.fLayer) - 1].fNeurons[neuronCnt]); end; // propagate error through the layers and update weights for layerCnt := Length(fProps.layers) - 1 downto 0 do begin // switch deltai and deltak (faster reallocation ;) ) tmp := fdeltaK; fdeltaK := fdeltaI; fdeltaI := tmp; // ############################################# // #### backpropagation step for neuronCnt := 0 to fProps.layers[layerCnt].NumNeurons - 1 do begin fdeltaK[neuronCnt] := 0; for counter := 0 to Length(net.fLayer[layerCnt + 1].fNeurons) - 1 do fdeltaK[neuronCnt] := fdeltaK[neuronCnt] + fdeltaI[counter]* (fProps.cf + net.fLayer[layerCnt + 1].fNeurons[counter].fWeights[neuronCnt]); fdeltaK[neuronCnt] := fdeltaK[neuronCnt]*net.fLayer[layerCnt].fNeurons[neuronCnt].Derrive(fOk[layerCnt + 1][neuronCnt]); // update weights of the current neuron UpdateWeights(fdeltaK[neuronCnt], fOk[layerCnt], net.fLayer[layercnt].fNeurons[neuronCnt]); end; end; end; end; function TNeuralNetLearner.DoLearn(const weights : Array of double) : TCustomClassifier; var net : TFeedForwardNeuralNet; layers : TNeuralLayerRecArr; counter: Integer; learnCnt : integer; lastErr, curErr : double; numSmallErrChange : integer; errCnt : integer; inputMinMax, inputMeanVar : TNeuralMinMaxArr; randSet : TCustomLearnerExampleList; validationSet : TCustomLearnerExampleList; maxVal : double; shuffIdx : TIntegerDynArray; begin SetLength(fWeights, Length(weights)); // idea to use weights: multiply the weight update by the example weight. // normalize weights to 1 maxVal := MaxValue(weights); for counter := 0 to Length(weights) - 1 do fWeights[counter] := weights[counter]/maxVal; fclassLabels := Classes; fnumCl := Length(fclassLabels); fnumFeatures := DataSet.Example[0].FeatureVec.FeatureVecLen; fMaxNumNeurons := Max(fNumCl, fnumFeatures); for counter := 0 to Length(fProps.layers) - 1 do fMaxNumNeurons := Max(fMaxNumNeurons, fProps.layers[counter].NumNeurons); SetLength(layers, Length(fProps.layers) + 1); layers[Length(layers) - 1].NeuronType := fProps.outputLayer; layers[Length(layers) - 1].NumNeurons := fnumCl; inputMinMax := DataSetMinMax; inputMeanVar := DataSetMeanVar; if not fProps.normMeanVar then begin for counter := 0 to Length(inputMeanVar) - 1 do begin inputMeanVar[counter][0] := 0; inputMeanVar[counter][1] := 1; end; end; if Length(fProps.layers) > 0 then Move(fProps.layers[0], layers[0], Length(fProps.layers)*sizeof(fProps.layers[0])); net := TFeedForwardNeuralNet.Create(fnumFeatures, layers, inputMinMax, inputMeanVar); lastErr := 1; numSmallErrChange := 0; // ########################################### // #### create classifier Result := TNeuralNet.Create(net, Classes); // ########################################### // #### create Traingin sets Dataset.CreateTrainAndValidationSet(Round(100*fProps.validationDataSetSize), randSet, validationSet); // ######################################################### // ##### batch error evaluation for learnCnt := 0 to fProps.maxNumIter - 1 do begin // ########################################################## // #### One batch learn iteration (randomized data set) shuffIdx := randSet.Shuffle; Backprop(net, randSet, shuffIdx); // ################################################## // #### test learning error curErr := 0; for errCnt := 0 to validationSet.Count - 1 do begin if Result.Classify(validationSet.Example[errCnt]) <> validationSet.Example[errCnt].ClassVal then curErr := curErr + 1; end; curErr := curErr/validationSet.Count; if (learnCnt >= fProps.minNumIter) and (lastErr - curErr < fProps.stopOnMinDeltaErr) then begin inc(numSmallErrChange); if numSmallErrChange >= fProps.numMinDeltaErr then break; end else begin lastErr := curErr; numSmallErrChange := 0; end; end; randSet.Free; validationSet.Free; end; procedure TNeuralNetLearner.UpdateWeights(deltaK: double; outputs: TDoubleDynArray; neuron: TNeuron); begin case fProps.learnAlgorithm of nnBackprop: UpdateWeightsByLearnRate(deltaK, outputs, neuron); nnBackpropMomentum: UpdateWeightsMomentum(deltaK, outputs, neuron); end; end; procedure TNeuralNetLearner.SetProps(const Props: TNeuralNetProps); begin fProps := Props; end; function TNeuralNetLearner.DataSetMinMax: TNeuralMinMaxArr; var counter : integer; featureCnt : integer; begin SetLength(Result, DataSet[0].FeatureVec.FeatureVecLen); for featureCnt := 0 to DataSet[0].FeatureVec.FeatureVecLen - 1 do begin Result[0][0] := DataSet[0].FeatureVec[0]; Result[0][1] := DataSet[0].FeatureVec[0]; end; for counter := 1 to DataSet.Count - 1 do begin for featureCnt := 0 to DataSet[0].FeatureVec.FeatureVecLen - 1 do begin Result[featureCnt][0] := Min(Result[featureCnt][0], DataSet[counter].FeatureVec[featureCnt]); Result[featureCnt][1] := Max(Result[featureCnt][1], DataSet[counter].FeatureVec[featureCnt]); end; end; end; class function TNeuralNetLearner.CanLearnClassifier( Classifier: TCustomClassifierClass): boolean; begin Result := Classifier = TNeuralNet; end; procedure TNeuralNetLearner.UpdateWeightsByLearnRate(deltaK: double; outputs: TDoubleDynArray; neuron: TNeuron); var counter : integer; begin // very simple update rule (simple gradient decent with learning factor eta) neuron.fWeights[0] := neuron.fWeights[0] + fProps.eta*deltaK*1; if fProps.l1Normalization > 0 then begin for counter := 1 to Length(neuron.fWeights) - 1 do begin neuron.fWeights[counter] := neuron.fWeights[counter] + Sign(neuron.fWeights[counter])*fProps.l1Normalization; neuron.fWeights[counter] := neuron.fWeights[counter] + fCurExampleWeight*fProps.eta*deltaK*outputs[counter - 1]; end; end else begin for counter := 1 to Length(neuron.fWeights) - 1 do neuron.fWeights[counter] := neuron.fWeights[counter] + fCurExampleWeight*fProps.eta*deltaK*outputs[counter - 1]; end; end; procedure TNeuralNetLearner.UpdateWeightsMomentum(deltaK: double; outputs: TDoubleDynArray; neuron: TNeuron); var counter : integer; weightUpdate : TDoubleDynArray; begin SetLength(weightUpdate, Length(neuron.fWeights)); if neuron.fDeltaWM1 = nil then neuron.fDeltaWM1 := weightUpdate; // momentum: take the previous weight update into account weightUpdate[0] := fProps.eta*deltaK*1 + fProps.alpha*neuron.fDeltaWM1[0]; for counter := 1 to Length(neuron.fWeights) - 1 do weightUpdate[counter] := fProps.eta*deltaK*outputs[counter - 1] + fProps.alpha*neuron.fDeltaWM1[counter]; for counter := 0 to Length(neuron.fWeights) - 1 do neuron.fWeights[counter] := neuron.fWeights[counter] + fCurExampleWeight*weightUpdate[counter]; neuron.fDeltaWM1 := weightUpdate; end; function TNeuralNetLearner.DataSetMeanVar: TNeuralMinMaxArr; var counter : integer; featureCnt : integer; data : TDoubleDynArray; aMean, aVar : Extended; aMeanVarMtx : IMatrix; begin SetLength(Result, DataSet[0].FeatureVec.FeatureVecLen); SetLength(data, DataSet.Count); if DataSet is TMatrixLearnerExampleList then begin aMeanVarMtx := (DataSet as TMatrixLearnerExampleList).Matrix.MeanVariance(True); for featureCnt := 0 to aMeanVarMtx.Height - 1 do begin Result[featureCnt][0] := aMeanVarMtx[0, featureCnt]; Result[featureCnt][1] := sqrt( aMeanVarMtx[1, featureCnt] ); end; end else begin SetLength(data, DataSet.Count); for featureCnt := 0 to Length(Result) - 1 do begin for counter := 0 to DataSet.Count - 1 do data[counter] := DataSet[counter].FeatureVec[featureCnt]; MeanAndStdDev(data, aMean, aVar); Result[featureCnt][0] := aMean; Result[featureCnt][1] := aVar; end; end; end; { TNeuralNet } function TNeuralNet.Classify(Example: TCustomExample; var confidence: double): integer; var ok : TDoubleDynArray; counter: Integer; maxIdx : integer; begin confidence := 0; SetLength(ok, Example.FeatureVec.FeatureVecLen); // ########################################### // #### Restrict input to defined min max for counter := 0 to Example.FeatureVec.FeatureVecLen - 1 do ok[counter] := Max(Min(Example.FeatureVec[counter], fNet.fInputMinMax[counter][1]), fNet.fInputMinMax[counter][0]); ok := fNet.Feed(ok); //for layerCnt := 0 to Length(fNet.fLayer) - 1 do //s ok := fNet.fLayer[layerCnt].Feed(ok); // maximum wins maxIdx := 0; confidence := ok[0]; for counter := 0 to Length(ok) - 1 do if ok[maxIdx] < ok[counter] then begin maxIdx := counter; confidence := Max(0, ok[counter]); end; confidence := max(0, Min(1, confidence)); Result := fClasses[maxIdx]; end; constructor TNeuralNet.Create(aNet: TFeedForwardNeuralNet; aClassList : TIntegerDynArray); begin fNet := aNet; fClasses := aClassList; inherited Create; end; destructor TNeuralNet.Destroy; begin fNet.Free; inherited; end; function TNeuralNet.OnLoadObject(const Name: String; Obj: TBaseMathPersistence): boolean; begin Result := True; if SameText(Name, cNeuralNet) then fNet := Obj as TFeedForwardNeuralNet else Result := inherited OnLoadObject(Name, obj); end; procedure TNeuralNet.OnLoadIntArr(const Name: String; const Value: TIntegerDynArray); begin if SameText(Name, cClassLabels) then fClasses := Value else inherited; end; procedure TNeuralNet.DefineProps; begin inherited; AddIntArr(cClassLabels, fClasses); AddObject(cNeuralNet, fNet); end; function TNeuralNet.PropTypeOfName(const Name: string): TPropType; begin if CompareText(Name, cClassLabels) = 0 then Result := ptInteger else if CompareText(Name, cNeuralNet) = 0 then Result := ptObject else Result := inherited PropTypeOfName(Name); end; initialization RegisterMathIO(TNeuralNet); RegisterMathIO(TFeedForwardNeuralNet); RegisterMathIO(TNeuralLayer); RegisterMathIO(TNeuron); end.
33.581888
150
0.609358
f1c6c8107c3ccc33f37922d9d3fe03c7663c0825
2,670
dfm
Pascal
Samples/ARTCCM-TNIR-sample_EN_ver.1.3.1.3c/Sample/Win32/Delphi2006/Sample_Delphi_2006_2Cam/Unit1.dfm
PalavaNet/ARTCAM-SWIR-Matlab-Interface
b21f8c3ba26a001db57d6c77c3696c0092f5c68a
[ "MIT-0" ]
null
null
null
Samples/ARTCCM-TNIR-sample_EN_ver.1.3.1.3c/Sample/Win32/Delphi2006/Sample_Delphi_2006_2Cam/Unit1.dfm
PalavaNet/ARTCAM-SWIR-Matlab-Interface
b21f8c3ba26a001db57d6c77c3696c0092f5c68a
[ "MIT-0" ]
null
null
null
Samples/ARTCCM-TNIR-sample_EN_ver.1.3.1.3c/Sample/Win32/Delphi2006/Sample_Delphi_2006_2Cam/Unit1.dfm
PalavaNet/ARTCAM-SWIR-Matlab-Interface
b21f8c3ba26a001db57d6c77c3696c0092f5c68a
[ "MIT-0" ]
null
null
null
object Form1: TForm1 Left = 236 Top = 149 Caption = 'Sample' ClientHeight = 697 ClientWidth = 930 Color = clBtnFace Font.Charset = SHIFTJIS_CHARSET Font.Color = clWindowText Font.Height = -12 Font.Name = 'MS UI Gothic' Font.Style = [] Menu = MainMenu1 OldCreateOrder = False OnCreate = FormCreate OnDestroy = FormDestroy OnResize = FormResize PixelsPerInch = 96 TextHeight = 12 object Image1: TImage Left = 0 Top = 0 Width = 449 Height = 577 end object Image2: TImage Left = 464 Top = 0 Width = 441 Height = 577 end object MainMenu1: TMainMenu object PopupFile: TMenuItem Caption = 'File(&F)' object FileSave: TMenuItem Caption = 'Save(&S)' OnClick = SaveClick end object FileExit: TMenuItem Caption = 'End(&X)' OnClick = ExitClick end end object PopupShow: TMenuItem Caption = 'View(&V)' object ShowPreview: TMenuItem Caption = 'Preview(&P)' OnClick = PreviewClick end object ShowCallBack: TMenuItem Caption = 'Callback(&B)' OnClick = CallBackClick end object ShowSnapShot: TMenuItem Caption = 'Snapshot(&S)' OnClick = SnapShotClick end object ShowCapture: TMenuItem Caption = 'Capture(&C)' OnClick = CaptureClick end object ShowTrigger: TMenuItem Caption = 'Trigger(&T)' OnClick = TriggerClick end end object PopupSet: TMenuItem Caption = 'Settings(&S)' object SetCamera1: TMenuItem Caption = 'Camera settings1(&C)' OnClick = SetCameraClick1 end object SetCamera2: TMenuItem Caption = 'Camera settings2(&C)' OnClick = SetCameraClick2 end object SetFilter1: TMenuItem Caption = 'Filter settings1(&F)' OnClick = SetFilterClick1 end object SetFilter2: TMenuItem Caption = 'Filter settings2(&F)' OnClick = SetFilterClick2 end object SetAnalog1: TMenuItem Caption = 'Analog settings1(&A)' OnClick = SetAnalogClick1 end object SetAnalog2: TMenuItem Caption = 'Analog settings2(&A)' OnClick = SetAnalogClick2 end end object PopupDll: TMenuItem AutoHotkeys = maManual AutoLineReduction = maManual Caption = 'DLL(&L)' object Reload: TMenuItem AutoHotkeys = maManual AutoLineReduction = maManual Caption = 'Reload' OnClick = ReloadClick end end end object Timer1: TTimer OnTimer = Timer1Timer Top = 32 end end
24.054054
40
0.60824
8397bbe0d099b91de7bb05d8cea3d7b2a4316f5d
5,912
dfm
Pascal
mobaxterm/UnitDownloadBloquant.dfm
tangjie1992/MobaXterm
1f1a5e3d3004934536bce4d87e648ea659488bd6
[ "Apache-2.0" ]
1
2021-04-03T00:00:39.000Z
2021-04-03T00:00:39.000Z
mobaxterm/UnitDownloadBloquant.dfm
tangjie1992/MobaXterm
1f1a5e3d3004934536bce4d87e648ea659488bd6
[ "Apache-2.0" ]
null
null
null
mobaxterm/UnitDownloadBloquant.dfm
tangjie1992/MobaXterm
1f1a5e3d3004934536bce4d87e648ea659488bd6
[ "Apache-2.0" ]
null
null
null
object FormDownloadBloquant: TFormDownloadBloquant Left = 337 Top = 309 BorderStyle = bsDialog Caption = 'MobaXterm' ClientHeight = 135 ClientWidth = 298 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Arial' Font.Style = [] FormStyle = fsStayOnTop KeyPreview = True OldCreateOrder = False Position = poScreenCenter Scaled = False ScreenSnap = True OnCreate = FormCreate OnDestroy = FormDestroy OnKeyDown = FormKeyDown PixelsPerInch = 96 TextHeight = 14 object sGauge1: TsGauge Left = 18 Top = 38 Width = 183 Height = 23 Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -12 Font.Name = 'Arial' Font.Style = [] ParentFont = False ParentShowHint = False ShowHint = False SkinData.SkinSection = 'GAUGE' ForeColor = 16755336 Progress = 0 Suffix = '%' end object sLabel2: TsLabel Left = 17 Top = 63 Width = 183 Height = 13 Alignment = taCenter AutoSize = False Caption = '0 kb/s' ParentFont = False ParentShowHint = False ShowHint = False Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Arial' Font.Style = [] end object sLabel1: TsLabel Left = 16 Top = 15 Width = 181 Height = 16 Alignment = taCenter Caption = 'Please wait while opening file...' ParentFont = False ParentShowHint = False ShowHint = False Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Arial' Font.Style = [] end object DownloadImage: TsSpeedButton Left = 208 Top = 0 Width = 81 Height = 113 Enabled = False Flat = True SkinData.SkinSection = 'TOOLBUTTON' DisabledGlyphKind = [] DisabledKind = [] ImageIndex = 12 Images = Form1.Im64 Reflected = True ShowCaption = False DrawOverBorder = False end object FichierOuDossier: TListBox Left = 272 Top = 120 Width = 121 Height = 97 ItemHeight = 14 TabOrder = 0 Visible = False end object Destination: TListBox Left = 272 Top = 128 Width = 121 Height = 97 ItemHeight = 14 TabOrder = 1 Visible = False end object UploadFiles: TListBox Left = 264 Top = 120 Width = 121 Height = 97 ItemHeight = 14 TabOrder = 2 Visible = False end object sBitBtn1: TsBitBtn Left = 90 Top = 90 Width = 86 Height = 29 Hint = 'Abort file transfer' Caption = 'Cancel' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -12 Font.Name = 'Arial' Font.Style = [] ParentFont = False ParentShowHint = False ShowHint = True TabOrder = 3 TabStop = False OnClick = sBitBtn1Click SkinData.SkinSection = 'BUTTON' ImageIndex = 236 Images = Form1.Im16 end object sSkinProvider1: TsSkinProvider AddedTitle.Font.Charset = DEFAULT_CHARSET AddedTitle.Font.Color = clNone AddedTitle.Font.Height = -11 AddedTitle.Font.Name = 'Arial' AddedTitle.Font.Style = [] SkinData.SkinSection = 'FORM' ShowAppIcon = False TitleButtons = <> Left = 256 Top = 144 end object Timer1: TTimer Interval = 600 OnTimer = Timer1Timer Left = 8 Top = 72 end object JvTimer1: TTimer Interval = 1600 OnTimer = JvTimer1Timer Left = 40 Top = 72 end object SSHcli: TElSSHClient SoftwareName = 'SecureBlackbox.9' ForceCompression = False CompressionLevel = 6 AuthenticationTypes = 22 CloseIfNoActiveTunnels = False NoCharacterEncoding = False ObfuscateHandshake = False OnSend = SSHcliSend OnReceive = SSHcliReceive OnOpenConnection = SSHcliOpenConnection OnCloseConnection = SSHcliCloseConnection OnError = SSHcliError SSHAuthOrder = aoDefault Versions = [sbSSH1, sbSSH2] DefaultWindowSize = 2048000 MinWindowSize = 2048 MaxSSHPacketSize = 262144 TunnelList = ElTunnelList1 OnKeyValidate = SSHcliKeyValidate OnAuthenticationKeyboard = SSHcliAuthenticationKeyboard OnAuthenticationStart = SSHcliAuthenticationStart ThreadSafe = True AutoAdjustCiphers = True RequestPasswordChange = False Left = 196 Top = 65535 end object ElTunnelList1: TElSSHTunnelList Left = 220 Top = 65535 end object ElSubsystem1: TElSubsystemSSHTunnel AutoOpen = True TunnelList = ElTunnelList1 Subsystem = 'sftp' Left = 244 Top = 65535 end object SFTPcli: TElSftpClient SynchronousMode = False Tunnel = ElSubsystem1 SftpBufferSize = 131072 UseUTF8OnV3 = True Versions = [sbSFTP2, sbSFTP3, sbSFTP4, sbSFTP5, sbSFTP6] UploadBlockSize = 32768 DownloadBlockSize = 8192 PipelineLength = 32 AutoAdjustTransferBlock = True OperationErrorHandling = oehTryAllItems OnOpenConnection = SFTPcliOpenConnection OnCloseConnection = SFTPcliCloseConnection OnOpenFile = SFTPcliOpenFile OnError = SFTPcliError OnSuccess = SFTPcliSuccess OnFileAttributes = SFTPcliFileAttributes OnData = SFTPcliData OnBlockTransferPrepared = SFTPcliBlockTransferPrepared Left = 268 Top = 65535 end object JvThread1: TJvThread Exclusive = True MaxCount = 0 RunOnCreate = True FreeOnTerminate = True OnExecute = JvThread1Execute Left = 80 Top = 400 end object TimDisconnectSSH: TTimer Enabled = False Interval = 36 OnTimer = TimDisconnectSSHTimer Left = 8 Top = 104 end end
24.329218
61
0.639716
f1221f3646ba435a578e4ec4e74910c1819e4d5f
11,807
pas
Pascal
Foundation/PascalCoin.RPC.Operation.pas
KoRiF/PascalCoin-Framework
fd73ecb93f2b3f9b10adce12dc2cf796e8372d39
[ "MIT" ]
1
2022-02-06T13:50:39.000Z
2022-02-06T13:50:39.000Z
Foundation/PascalCoin.RPC.Operation.pas
KoRiF/PascalCoin-Framework
fd73ecb93f2b3f9b10adce12dc2cf796e8372d39
[ "MIT" ]
null
null
null
Foundation/PascalCoin.RPC.Operation.pas
KoRiF/PascalCoin-Framework
fd73ecb93f2b3f9b10adce12dc2cf796e8372d39
[ "MIT" ]
2
2021-11-16T14:35:13.000Z
2022-01-25T12:45:32.000Z
Unit PascalCoin.RPC.Operation; Interface Uses System.Generics.Collections, PascalCoin.RPC.Interfaces, System.JSON; Type TPascalCoinSender = Class(TInterfacedObject, IPascalCoinSender) Private FAccount: Cardinal; FN_Operation: Integer; FAmount: Currency; FAmount_s: String; FPayload: HexaStr; FPayloadType: integer; Protected Function GetAccount: Cardinal; Function GetN_operation: Integer; Function GetAmount: Currency; Function GetAmount_s: String; Function GetPayload: HexaStr; Function GetPayloadType: Integer; Public End; TPascalCoinReceiver = Class(TInterfacedObject, IPascalCoinReceiver) Private FAccount: Cardinal; FAmount: Currency; FAmount_s: String; FPayload: HexaStr; FPayloadType: integer; Protected Function GetAccount: Cardinal; Function GetAmount: Currency; Function GetAmount_s: String; Function GetPayload: HexaStr; Function GetPayloadType: Integer; Public End; TPascalCoinChanger = Class(TInterfacedObject, IPascalCoinChanger) Private FAccount: Cardinal; FN_Operation: Integer; FNew_enc_pubkey: HexaStr; FNew_Type: String; FSeller_account: Cardinal; FAccount_price: Currency; FLocked_until_block: UInt64; FFee: Currency; Protected Function GetAccount: Cardinal; Function GetN_operation: Integer; Function GetNew_enc_pubkey: String; Function GetNew_Type: String; Function GetSeller_account: Cardinal; Function GetAccount_price: Currency; Function GetLocked_until_block: UInt64; Function GetFee: Currency; Public End; TPascalCoinOperation = Class(TInterfacedObject, IPascalCoinOperation) Private FValid: Boolean; FErrors: String; FBlock: UInt64; FTime: Integer; FOpBlock: UInt64; FMaturation: Integer; FOpType: Integer; FOpTxt: String; FAccount: Cardinal; FAmount: Currency; FAmount_s: String; FFee: Currency; FFee_s: String; FBalance: Currency; FSender_Account: Cardinal; FDest_Account: Cardinal; FEnc_Pubkey: HexaStr; FOpHash: HexaStr; FOld_Ophash: HexaStr; FSubType: String; FSigner_account: Cardinal; FN_Operation: Integer; FPayload: HexaStr; FSenders: TArray<IPascalCoinSender>; FReceivers: TArray<IPascalCoinReceiver>; FChangers: TArray<IPascalCoinChanger>; Protected Function GetValid: Boolean; Function GetErrors: String; Function GetBlock: UInt64; Function GetTime: Integer; Function GetOpblock: Integer; Function GetMaturation: Integer; Function GetOptype: Integer; Function GetOperationType: TOperationType; Function GetOptxt: String; Function GetAccount: Cardinal; Function GetAmount: Currency; Function GetAmount_s: String; Function GetFee: Currency; Function GetFee_s: String; Function GetBalance: Currency; Function GetSender_account: Cardinal; Function GetDest_account: Cardinal; Function GetEnc_pubkey: HexaStr; Function GetOphash: HexaStr; Function GetOld_ophash: HexaStr; Function GetSubtype: String; Function GetSigner_account: Cardinal; Function GetN_operation: Integer; Function GetPayload: HexaStr; Function SendersCount: Integer; Function ReceiversCount: Integer; Function ChangersCount: Integer; Function GetSender(const index: integer): IPascalCoinSender; Function GetReceiver(const index: integer): IPascalCoinReceiver; Function GetChanger(const index: integer): IPascalCoinChanger; Public class function FromJSONValue(Value: TJSONValue): TPascalCoinOperation; End; TPascalCoinOperations = class(TInterfacedObject, IPascalCoinOperations) Private FOperations: TArray<TPascalCoinOperation>; protected Function GetOperation(const index: integer): IPascalCoinOperation; Function Count: Integer; public class function FromJsonValue(AOps: TJSONArray): TPascalCoinOperations; end; Implementation { TPascalCoinOperation } Uses REST.JSON; function TPascalCoinOperation.ChangersCount: Integer; begin Result := Length(FChangers) end; class function TPascalCoinOperation.FromJSONValue(Value: TJSONValue): TPascalCoinOperation; Var lObj: TJSONObject; lArr: TJSONArray; I: Integer; CD: Cardinal; S: String; C: Currency; Begin lObj := Value As TJSONObject; result := TPascalCoinOperation.Create; If lObj.TryGetValue<String>('valid', S) Then result.FValid := (S <> 'false') Else result.FValid := True; result.FBlock := lObj.Values['block'].AsType<UInt64>; // 279915 result.FTime := lObj.Values['time'].AsType<Integer>; // 0, result.FOpBlock := lObj.Values['opblock'].AsType<UInt64>; // 1, lObj.Values['maturation'].TryGetValue<Integer>(result.FMaturation); // null, result.FOpType := lObj.Values['optype'].AsType<Integer>; // 1, { TODO : should be Int? } result.FSubType := lObj.Values['subtype'].AsType<String>; // 12, result.FAccount := lObj.Values['account'].AsType<Cardinal>; // 865822, result.FSigner_account := lObj.Values['signer_account'].AsType<Cardinal>; // 865851, result.FN_Operation := lObj.Values['n_operation'].AsType<Integer>; result.FOpTxt := lObj.Values['optxt'].AsType<String>; // "Tx-In 16.0000 PASC from 865851-95 to 865822-14", result.FFee := lObj.Values['fee'].AsType<Currency>; // 0.0000, result.FFee_s := lObj.Values['fee_s'].AsType<String>; result.FAmount := lObj.Values['amount'].AsType<Currency>; // 16.0000, result.FAmount_s := lObj.Values['amount_s'].AsType<String>; result.FPayload := lObj.Values['payload'].AsType<HexaStr>; // "7A6962626564656520646F6F646168", if lObj.TryGetValue<Currency>('balance', C) then result.FBalance := C; // 19.1528, if lObj.TryGetValue<Cardinal>('sender_account', CD) then result.FSender_Account := CD; if lObj.TryGetValue<Cardinal>('dest_account', CD) then result.FDest_Account := CD; // 865822, result.FOpHash := lObj.Values['ophash'].AsType<HexaStr>; lArr := lObj.Values['senders'] As TJSONArray; SetLength(result.FSenders, lArr.Count); For I := 0 to lArr.Count - 1 Do Begin result.FSenders[I] := TJSON.JsonToObject<TPascalCoinSender>(lArr[I] As TJSONObject); End; lArr := lObj.Values['receivers'] As TJSONArray; SetLength(result.FReceivers, lArr.Count); For I := 0 to lArr.Count -1 Do Begin result.FReceivers[I] := TJSON.JsonToObject<TPascalCoinReceiver>(lArr[I] As TJSONObject); End; lArr := lObj.Values['changers'] As TJSONArray; SetLength(result.FChangers, lArr.Count); For I := 0 to lArr.Count - 1 do Begin result.FChangers[I] := TJSON.JsonToObject<TPascalCoinChanger>(lArr[I] As TJSONObject); End; end; Function TPascalCoinOperation.GetAccount: Cardinal; Begin result := FAccount; End; Function TPascalCoinOperation.GetAmount: Currency; Begin result := FAmount; End; function TPascalCoinOperation.GetAmount_s: String; begin Result := FAmount_s; end; Function TPascalCoinOperation.GetBalance: Currency; Begin result := FBalance; End; Function TPascalCoinOperation.GetBlock: UInt64; Begin result := FBlock; End; function TPascalCoinOperation.GetChanger(const index: integer): IPascalCoinChanger; begin Result := FChangers[index] as IPascalCoinChanger; end; Function TPascalCoinOperation.GetDest_account: Cardinal; Begin result := FDest_Account; End; Function TPascalCoinOperation.GetEnc_pubkey: HexaStr; Begin result := FEnc_Pubkey; End; Function TPascalCoinOperation.GetErrors: String; Begin result := FErrors; End; Function TPascalCoinOperation.GetFee: Currency; Begin result := FFee; End; function TPascalCoinOperation.GetFee_s: String; begin Result := FFee_s; end; Function TPascalCoinOperation.GetMaturation: Integer; Begin result := FMaturation; End; Function TPascalCoinOperation.GetN_operation: Integer; Begin result := FN_Operation; End; Function TPascalCoinOperation.GetOld_ophash: HexaStr; Begin result := FOld_Ophash; End; Function TPascalCoinOperation.GetOpblock: Integer; Begin result := FOpBlock; End; Function TPascalCoinOperation.GetOperationType: TOperationType; Begin result := TOperationType(FOpType); End; Function TPascalCoinOperation.GetOphash: HexaStr; Begin result := FOpHash; End; Function TPascalCoinOperation.GetOptxt: String; Begin result := FOpTxt; End; Function TPascalCoinOperation.GetOptype: Integer; Begin result := FOpType; End; Function TPascalCoinOperation.GetPayload: HexaStr; Begin result := FPayload; End; function TPascalCoinOperation.GetReceiver(const index: integer): IPascalCoinReceiver; begin Result := FReceivers[index] as IPascalCoinReceiver; end; function TPascalCoinOperation.GetSender(const index: integer): IPascalCoinSender; begin Result := FSenders[index] as IPascalCoinSender; end; Function TPascalCoinOperation.GetSender_account: Cardinal; Begin result := FSender_Account; End; Function TPascalCoinOperation.GetSigner_account: Cardinal; Begin result := FSigner_account; End; Function TPascalCoinOperation.GetSubtype: String; Begin result := FSubType; End; Function TPascalCoinOperation.GetTime: Integer; Begin result := FTime; End; Function TPascalCoinOperation.GetValid: Boolean; Begin result := FValid; End; function TPascalCoinOperation.ReceiversCount: Integer; begin Result := Length(FReceivers); end; function TPascalCoinOperation.SendersCount: Integer; begin Result := Length(FSenders); end; { TPascalCoinSender } Function TPascalCoinSender.GetAccount: Cardinal; Begin result := FAccount; End; Function TPascalCoinSender.GetAmount: Currency; Begin result := FAmount; End; function TPascalCoinSender.GetAmount_s: String; begin result := FAmount_s; end; Function TPascalCoinSender.GetN_operation: Integer; Begin Result := FN_Operation; End; Function TPascalCoinSender.GetPayload: HexaStr; Begin Result := FPayload; End; function TPascalCoinSender.GetPayloadType: Integer; begin Result := FPayloadType; end; { TPascalCoinReceiver } Function TPascalCoinReceiver.GetAccount: Cardinal; Begin Result := FAccount; End; Function TPascalCoinReceiver.GetAmount: Currency; Begin Result := FAmount; End; function TPascalCoinReceiver.GetAmount_s: String; begin Result := FAmount_s; end; Function TPascalCoinReceiver.GetPayload: HexaStr; Begin Result := FPayload; End; function TPascalCoinReceiver.GetPayloadType: Integer; begin Result := FPayloadType; end; { TPascalCoinChanger } Function TPascalCoinChanger.GetAccount: Cardinal; Begin Result := FAccount; End; Function TPascalCoinChanger.GetAccount_price: Currency; Begin Result := FAccount_Price; End; Function TPascalCoinChanger.GetFee: Currency; Begin Result := FFee; End; Function TPascalCoinChanger.GetLocked_until_block: UInt64; Begin Result := FLocked_until_block; End; Function TPascalCoinChanger.GetNew_enc_pubkey: String; Begin Result := FNew_enc_pubkey; End; Function TPascalCoinChanger.GetNew_Type: String; Begin Result := FNew_Type; End; Function TPascalCoinChanger.GetN_operation: Integer; Begin Result := FN_operation; End; Function TPascalCoinChanger.GetSeller_account: Cardinal; Begin Result := FSeller_account; End; { TPascalCoinOperations } function TPascalCoinOperations.Count: Integer; begin Result := Length(FOperations); end; class function TPascalCoinOperations.FromJsonValue(AOps: TJSONArray): TPascalCoinOperations; var I: Integer; begin Result := TPascalCoinOperations.Create; SetLength(Result.FOperations, AOps.Count); for I := 0 to AOps.Count - 1 do begin Result.FOperations[I] := TPascalCoinOperation.FromJSONValue(AOps[I]); end; end; function TPascalCoinOperations.GetOperation(const index: integer): IPascalCoinOperation; begin Result := FOperations[index] as IPascalCoinOperation; end; End.
23.661323
92
0.753367
4766cab7a884624e9a76ff2be514c11cd5edfc88
95,178
dfm
Pascal
Unit3.dfm
Corbolan/hefesto
4f0aabfac63da1c2cdfdd0644f3137845469b040
[ "MIT" ]
null
null
null
Unit3.dfm
Corbolan/hefesto
4f0aabfac63da1c2cdfdd0644f3137845469b040
[ "MIT" ]
null
null
null
Unit3.dfm
Corbolan/hefesto
4f0aabfac63da1c2cdfdd0644f3137845469b040
[ "MIT" ]
null
null
null
object frm_agenda: Tfrm_agenda Left = 0 Top = 0 BorderStyle = bsDialog Caption = 'Agenda de Compromissos' ClientHeight = 504 ClientWidth = 1000 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False Position = poDesktopCenter PixelsPerInch = 96 TextHeight = 13 object Label1: TLabel Left = 162 Top = 11 Width = 47 Height = 19 Caption = 'Nome' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -16 Font.Name = 'Tahoma' Font.Style = [fsBold] ParentFont = False end object Label2: TLabel Left = 360 Top = 13 Width = 39 Height = 19 Caption = 'Data' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -16 Font.Name = 'Tahoma' Font.Style = [fsBold] ParentFont = False end object Label3: TLabel Left = 520 Top = 13 Width = 39 Height = 19 Caption = 'Hora' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -16 Font.Name = 'Tahoma' Font.Style = [fsBold] ParentFont = False end object Label4: TLabel Left = 32 Top = 82 Width = 78 Height = 19 Caption = 'Descri'#231#227'o' FocusControl = memDescricao Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -16 Font.Name = 'Tahoma' Font.Style = [fsBold] ParentFont = False end object Label5: TLabel Left = 360 Top = 85 Width = 75 Height = 19 Caption = 'Endere'#231'o' FocusControl = memEndereco Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -16 Font.Name = 'Tahoma' Font.Style = [fsBold] ParentFont = False end object Label6: TLabel Left = 668 Top = 11 Width = 56 Height = 19 Caption = 'Cidade' FocusControl = memDescricao Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -16 Font.Name = 'Tahoma' Font.Style = [fsBold] ParentFont = False end object Label7: TLabel Left = 660 Top = 84 Width = 21 Height = 19 Caption = 'UF' FocusControl = memEndereco Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -16 Font.Name = 'Tahoma' Font.Style = [fsBold] ParentFont = False end object Label8: TLabel Left = 32 Top = 200 Width = 70 Height = 19 Caption = 'Situa'#231#227'o' FocusControl = memEndereco Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -16 Font.Name = 'Tahoma' Font.Style = [fsBold] ParentFont = False end object Label9: TLabel Left = 208 Top = 200 Width = 72 Height = 19 Caption = 'Urg'#234'ncia' FocusControl = memEndereco Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -16 Font.Name = 'Tahoma' Font.Style = [fsBold] ParentFont = False end object sbPrimeiro: TSpeedButton Left = 25 Top = 256 Width = 89 Height = 30 Glyph.Data = { 36080000424D3608000000000000360400002800000020000000200000000100 08000000000000040000120B0000120B0000000100000E00000000990000EFF9 EF007FCC7F002FAC2F00BFE5BF004FB94F008FD28F00FFFFFF000F9F0F00CFEC CF003FB23F005FBF5F009FD99F00000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707070707070707070701070707070707070707070707070707070707 0707070101070707070707070B04070707070707070707070707070707070707 07070705040707070707070C0004070707070707070707070707070707070707 07070B0004070707070704000004070707070707070707070707070707070707 070B000004070707070908000004070707070707070707070707070707070707 06000000040707070103000000030A0A0A0A0A0A0A0A0C07070707070707070C 00000000040707070A0000000000000000000000000002070707070707070C00 000000000407070B000000000000000000000000000002070707070707090800 0000000004070C00000000000000000000000000000002070707070709080000 0000000004040000000000000000000000000000000002070707070709080000 0000000004040000000000000000000000000000000002070707070707090800 0000000004070C00000000000000000000000000000002070707070707070C00 000000000407070B00000000000000000000000000000207070707070707070C 00000000040707070A0000000000000000000000000002070707070707070707 06000000040707070103000000030A0A0A0A0A0A0A0A0C070707070707070707 070B000004070707070908000004070707070707070707070707070707070707 07070B0004070707070704000004070707070707070707070707070707070707 07070705040707070707070C0004070707070707070707070707070707070707 0707070101070707070707070B04070707070707070707070707070707070707 0707070707070707070707070701070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707} OnClick = sbPrimeiroClick end object sbAnterior: TSpeedButton Left = 120 Top = 256 Width = 89 Height = 30 Glyph.Data = { 36080000424D3608000000000000360400002800000020000000200000000100 08000000000000040000120B0000120B0000000100000F00000000990000FFFF FF007FCC7F002FAC2F00BFE5BF009FD99F00CFECCF005FBF5F000F9F0F00EFF9 EF003FB23F008FD28F00AFDFAF001FA51F000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010901010101010101010101010101010101010101010101 0101010101010101070401010101010101010101010101010101010101010101 010101010101010B000401010101010101010101010101010101010101010101 0101010101010C00000401010101010101010101010101010101010101010101 0101010101060800000401010101010101010101010101010101010101010101 01010101090D000000030A0A0A0A0A0A0A0A0501010101010101010101010101 0101010103000000000000000000000000000201010101010101010101010101 0101010700000000000000000000000000000201010101010101010101010101 01010B0000000000000000000000000000000201010101010101010101010101 010C000000000000000000000000000000000201010101010101010101010101 010C000000000000000000000000000000000201010101010101010101010101 01010B0000000000000000000000000000000201010101010101010101010101 0101010700000000000000000000000000000201010101010101010101010101 0101010103000000000000000000000000000201010101010101010101010101 01010101090D000000030A0A0A0A0A0A0A0A0501010101010101010101010101 0101010101060800000401010101010101010101010101010101010101010101 0101010101010C00000401010101010101010101010101010101010101010101 010101010101010B000401010101010101010101010101010101010101010101 0101010101010101070401010101010101010101010101010101010101010101 0101010101010101010901010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101} OnClick = sbAnteriorClick end object sbProximo: TSpeedButton Left = 215 Top = 256 Width = 89 Height = 30 Glyph.Data = { 36080000424D3608000000000000360400002800000020000000200000000100 08000000000000040000120B0000120B0000000100000F00000000990000FFFF FF007FCC7F002FAC2F00BFE5BF009FD99F00CFECCF005FBF5F000F9F0F00EFF9 EF003FB23F008FD28F00AFDFAF001FA51F000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010109010101010101010101010101010101010101010101 0101010101010101010104070101010101010101010101010101010101010101 0101010101010101010104000B01010101010101010101010101010101010101 010101010101010101010400000C010101010101010101010101010101010101 0101010101010101010104000008060101010101010101010101010101010101 01050A0A0A0A0A0A0A0A030000000D0901010101010101010101010101010101 0102000000000000000000000000000301010101010101010101010101010101 0102000000000000000000000000000007010101010101010101010101010101 01020000000000000000000000000000000B0101010101010101010101010101 0102000000000000000000000000000000000C01010101010101010101010101 0102000000000000000000000000000000000C01010101010101010101010101 01020000000000000000000000000000000B0101010101010101010101010101 0102000000000000000000000000000007010101010101010101010101010101 0102000000000000000000000000000301010101010101010101010101010101 01050A0A0A0A0A0A0A0A030000000D0901010101010101010101010101010101 0101010101010101010104000008060101010101010101010101010101010101 010101010101010101010400000C010101010101010101010101010101010101 0101010101010101010104000B01010101010101010101010101010101010101 0101010101010101010104070101010101010101010101010101010101010101 0101010101010101010109010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101010101010101 0101010101010101010101010101010101010101010101010101} OnClick = sbProximoClick end object sbUltimo: TSpeedButton Left = 310 Top = 256 Width = 89 Height = 30 Glyph.Data = { 36080000424D3608000000000000360400002800000020000000200000000100 08000000000000040000120B0000120B0000000100000E00000000990000EFF9 EF007FCC7F002FAC2F00BFE5BF004FB94F009FD99F00FFFFFF003FB23F00CFEC CF000F9F0F00AFDFAF005FBF5F00000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707010107070707070707070707070707070707070707070707070707 0707070707040807070707070707010107070707070707070707070707070707 070707070704000C070707070707040301070707070707070707070707070707 0707070707040000060707070707040003010707070707070707070707070707 0707070707040000000407070707040000050707070707070707070706080808 0808080808030000000A09070707040000000C07070707070707070702000000 000000000000000000000301070704000000000C070707070707070702000000 0000000000000000000000080707040000000000060707070707070702000000 0000000000000000000000000C07040000000000000607070707070702000000 000000000000000000000000000604000000000000000B070707070702000000 000000000000000000000000000604000000000000000B070707070702000000 0000000000000000000000000C07040000000000000607070707070702000000 0000000000000000000000080707040000000000060707070707070702000000 000000000000000000000301070704000000000C070707070707070706080808 0808080808030000000A09070707040000000C07070707070707070707070707 0707070707040000000407070707040000050707070707070707070707070707 0707070707040000060707070707040003010707070707070707070707070707 070707070704000C070707070707040301070707070707070707070707070707 0707070707040807070707070707010107070707070707070707070707070707 0707070707010107070707070707070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707070707070707 0707070707070707070707070707070707070707070707070707} OnClick = sbUltimoClick end object sbNovo: TSpeedButton Left = 448 Top = 244 Width = 129 Height = 42 Caption = 'Novo' Glyph.Data = { 36080000424D3608000000000000360400002800000020000000200000000100 080000000000000400008692020086920200000100009D00000009086400AFCF E300535C8A00888EA80030347200F8F8FC001F1C9900727E9100AAB1BE001919 8200DADFE1003C3EAB00535BB5006A7ABC00302FA4008E91C600BFC5CD002A32 4C005365A200C9CFD200444E8C007B8CC00093B1D100EEF1F100647AB0002929 9B00A2A4D100606A8D009AA3B0000B0A700042526B006375B4001F1F8A004451 9300CFCFE700A3B9E200191B6A004649AF002C2BA2007D7DC500626FB0006769 B500C2C2E100859FC800BDD7EE000F1064007C82A1007C869900E3E6EA004750 7800FFFFFF001A1696005A5F8B003C486D00CED2DA0027279700F8FAF700A3AD B600D3D2EC0096A9DC001F236A00A5C5DD005C6BAD0011117200919CA7006A75 8F004A538A008E8ECC004D52B4007D83BD007B89CE0042457D006872B200E1E1 EF00B3BAC0003839A700BDBDE1004F609A00767EB900C3DFF5007A87CE006F87 AD0025239D004D55A3007070AD0084909E003B407800BDDEEA008C94CE002221 9500090869005B65B900B8B8DC000F106800748191009BBACC005C70A900B7D8 EA00D8DCE1004143AD00B2B8C200EEEEF600727DC800AEAFD700636CC000E5E5 EE00AAC1E8006A6F9200637BB5008383C700A4ACBA00DCE0E30025286C007993 BF00666D9200484D80008898D4006472BB004F55B40049579800313C7D00526B AD0045508E0022209B004447AF00BEDDF000C4C4E50011107900F1F4F2002119 9400939BAD00B4BAC600A0A6B400798794005E688D0055558F006D74940086A2 C800494DB2006B73BD00E8EBEE00B3CCEA009294C800CBD0D6008589C10095B2 D40065708E0014166300D4D9DC009597CA0010196B006879B800AAB0BF00E1E5 E500272C6F004D52830000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000323232323232 3232323232323232323232323232323232323232323232323232323232323232 328C648362170532323232323232323232323232323232323232323232323232 3284111E353188824A136F170532323232323232323232323232323232323232 326B782C575F514D7A421B2F4039833630803232323232323232323232323232 38731D598A506A7D611618771402920785558208106205323232323232323232 999A7F191906060E0C748D7D018960211434415E5E5E6E323232323232323232 10240926262626265206064B683B2C2C3D71127A42861C323232323232323232 825D202626262626262626267B06526366237D619118533A3232323232323232 725A592626262626262626262626265206062644464F2B293232323232323280 561D372626262626262626262626262626262652337C2B8E323232323232320A 3C7F192626262626262626262626262626262626524428223232323232323283 93092626262626262626262626262626262626267B753E053232323232323203 0020262626262626262626262626262626262626520D4E323232323232323234 5A592626262626262626262626262626262626264B1F1A323232323232328004 1D37262626262626262626262626262626262652763E49323232323232329424 7F1926262626262626262626262626262626267B753E3232323232323232982D 0926262626262626262626262626262626262626974532323232323232322E00 202626262626262626262626262626262626260B1F6732323232323232329B5A 592626262626262626262626262626262626520C3E693232323232323217701D 3726262626262626262626262626262626267B752832323232323232328F937F 192626262626262626262626262626262626260D903232323232323232840009 262626262626262626262626262626262626631F5C3232323232323232880020 2626262626262626262626262626262626520C79653232323232323232475A59 2626262626262626262626262626262626527548323232323232323232873F37 26262626262626262626262626262626260E970F32323232323232323269544B 262626262626262626262626262626262625282A323232323232323232323205 2A2763262626262626262626262626267B5B3E05323232323232323232323232 3232057E27632626262626262626262652979732323232323232323232323232 3232323232057E6D63262626262626260E1F9532323232323232323232323232 3232323232323232057E6D7C2626265244154932323232323232323232323232 3232323232323232323232322243764B43323232323232323232323232323232 3232323232323232323232323232054C32323232323232323232} OnClick = sbNovoClick end object sbAlterar: TSpeedButton Left = 583 Top = 244 Width = 129 Height = 42 Caption = 'Alterar' Glyph.Data = { 36080000424D3608000000000000360400002800000020000000200000000100 08000000000000040000120B0000120B000000010000DD000000FFFFFF00FFFE FE00FFFFFE00FFFEFC00FCFDFC00FFFDFB00FFFDF800FDFDFC00FBFAF700FBFA F600FCFAF600FCFAF700FCF9F700FCF9F500FFF9EE00FFFADD00FFFADE00FFF9 DD00FFFADB00FEF3E100F2EFED00FFF5D500EDECEC00EBEBEA00EDEAE900E8E9 ED00DAE7EF00FCEBCF00FDEBCE00B6E4FA00D7E5ED00B8E4F800B7E4FC00FFEA CB00FFE8C200FEE8C400E1E4D700FFE7C200FFE6BF00FFE6BE00FFE5BD00FFE5 BF00C4DDED00FFE3B500B3D8E600FFE1B000FEE0B000F4E1AE00B3D7E700FFDF AB00D6DFB500D5DFB700ACD3E600D5D4D400E0D7C400FFDDA50093D1F300FFDC A500FFDCA400FFDCA20098D0F000DFD8B900D3D2D100ECDAAD00EBDAAE00DED7 B900DFD8B800DDD7B800A3CFE600EBD9AD00EBD9AC00A4CFE500DED7B800EAD8 AC00A2CEE500EAD8AA00A2CEE100D0CDCC0098C3DC007DC0E70097C1DC00CACF 9A007DC0E200CFC7A9007ABCE3008ABCD800C4CA940073B6DB0087B5CD00E8C6 7000E5C4710076B2D200E2C27100E2C27000F4CA4C0064AED900F4C94A00A4BA 8E00F0C74800F6C84200F0C74700EFC54200EFC54000EFC44000ABABAB00EEC3 3F006CA8C6009CB48E0063A6CC00EEC23900F5C3360068A5C800ECC13A00ABA6 A200EDC03500EBBF3500EBBE3100EBBD3100EABD2F00E9BC2E00EEBD2500EABC 2A005F9DC300A2A09E00A5A19A00E8B92800F2BD1700F2BD1900E9B92400F2BC 1700E9B82400E8B82800E7B82300E9B82300EBB81A00E6B62500E4B52700E6B5 2400E3B42600E4B42700F0BA0F00E6B51E00E6B42300E6B52000E6B41B00E5B4 1C00EAB61600EDB61600EDB51700E5B31C00E6B41900E6B31500E7B41500E5B3 1700E0AF2300E8B20F00E4B01200DCAC2200DDAD2200E6B10900EDB30300DBAB 2100DAAA2200E3AF0F00DBAA2100E3AE0D00D9A92100E6AE0600E2AE0A00E3AE 0900E3AE0A00E3AD0A00E2AD0700D7A71E00E3AD0600E1AB0500E8AB0000E1AA 0600E1A90700E1AA0400E3AA0100E1AA0500E0AA0400DFA80400DFA80600DFA8 0700DFA70300DEA7030088858400898683008E7D5300676461005E5B5800575A 5A004C5151007E5E0000504B4700745907007A5B00003E484E00775700005346 3F00735500004B4541006B510800413C3900403B3600303638003A3531004C3B 130039342F004A3A130036312D00433314003C2E260042331300312D29003A2F 100034290E0026201C001F130C00000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000004D7B 16000000000000000000000000000000000000000000000000000000000017D0 CDBD3E00000000000000000000000000000000000000000000000000000000BC DBD2CEBF71180000000000000000000000000000000000000000000000000035 D8CBC4D6CF7A501E020000000000000000000000000000000000000000000000 C0D4C9C1574F5B6A552400000000000000000000000000000000000000000000 68DCC2523844343C61AD4B000000000000000000000000000000000000000000 14C76C38472C2051B09BA6490000000000000000000000000000000000000000 004E5F4A301F326EB2B298A14500000000000000000000000000000000000000 001A6F4C1D33636069B9B997A246000000000000000000000000000000000000 0000585456945E626270B8B897A4450000000000000000000000000000000000 00002A6B93B48D64656574B7B7979D4000000000000000000000000000000000 000004598E80AE96676D6D79B7B7989E3F000000000000000000000000000000 0000000D5C8885AC9973737684BAB1979A2F0000000000000000000000000000 000000000C5D8B80AA9C777D8795BBA781CC7C00000000000000000000000000 0000000000095D8880ABAB89899092A0CAD9530E000000000000000000000000 0000000000000B5D8B82A9A991867FC6D5411228130000000000000000000000 00000000000000085D8B80A89F7EC3D1420F262D2D0700000000000000000000 00000000000000000A5D8A788CC8D33D11292B3A230100000000000000000000 000000000000000000085A83C5D74811262B3722030000000000000000000000 0000000000000000000006BEDA4310262B392503000000000000000000000000 0000000000000000000000193615272B39220300000000000000000000000000 0000000000000000000000000021313B25030000000000000000000000000000 00000000000000000000000000001B1B03000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000} OnClick = sbAlterarClick end object sbExcluir: TSpeedButton Left = 717 Top = 244 Width = 129 Height = 42 Caption = 'Excluir' Enabled = False Glyph.Data = { 360C0000424D360C000000000000360000002800000020000000200000000100 180000000000000C0000120B0000120B00000000000000000000FFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5F5FCCECE EF7475D62929C60303C60403C62A2AC67475D6CECEEEF5F5FCFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD8D7F38282DD4342CD1515 CC0303D10000D60000D90000D90000D60000D00D0DCC3C3CCE8080DDD8D7F3FF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE8E8F86C6CD70F0FC50000D10000E50505 F41C1BFB3838FD5758FD7172FE7979FE6162FC3434F30607E30000D00808C56C 6CD7E8E8F8FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFB3B3E91F1FC40000CF0000EF0000FF0101FF0505 FF0605FE0606FE1011FE2D2EFD5E5EFD9E9EFEBBBBFFA8A9FF7070FE1E1EEE00 00CE1A1AC5B3B3E9FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFF9090E10000C10000E10000FF0000FF0000FE0000FE0000 FE0000FE0000FE0000FF0000FE0000FD0909FC4849FB9696FDB9B9FFABABFF62 63FE0000E00000C19090E1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFF9292E10000C20000EC0000FF0000FF0000FE0000FE0000FE0000 FE0000FE0000FE0000FE0000FE0000FE0000FE0000FD1313FB6161FB9E9EFEB1 B1FF8484FF1111EB0000C29292E1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFB3B3EA0000C10000EC0000FF0000FE0000FE0000FE0000FE0000FE0000 FE0000FE0000FE0000FE0000FE0000FE0000FE0000FE0000FF0000FC3939FB82 82FDA3A3FF8384FF0C0CEB0000C2B3B2EAFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF E9E9F91818C40000E20000FF0000FF0000FE0000FE0000FE0000FE0000FD0000 FE0000FE0000FE0000FE0000FE0000FE0000FE0000FE0000FE0000FE0000FE19 19FB6A6BFC9696FF6F6FFF0201E11817C5EAEAF9FFFFFFFFFFFFFFFFFFFFFFFF 6969D70000CF0000FF0000FF0000FE0000FE0000FE0000FE0000FD4D4EF81E1D FB0000FF0000FE0000FE0000FE0000FE0000FE1616FA4848F80000FE0000FF00 00FE0A0BFB5152FC8A8AFF4342FF0000CE6969D7FFFFFFFFFFFFFFFFFFDBDBF4 0909C50000F00000FF0000FE0000FE0000FE0000FF0000FD5454F8FCFDFDC9CA FB1212FA0000FF0000FE0000FE0000FE0C0BFABEBEF9FBFBFD5455F90000FE00 00FF0000FE0303FD4041FC7070FF1010EF0606C5DBDCF4FFFFFFFFFFFF8180DD 0000D10000FF0000FF0000FE0000FE0000FE0000FD5656F8F9F9FDFFFFFFFFFF FFBEBEFA0F0FFA0000FF0000FE0B0BF9B4B3F9FFFFFFFFFFFFF8F9FC5657F800 00FE0000FE0000FE0000FD3131FC2627FF0000D18080DEFFFFFFF8F8FD4040CE 0000E50000FF0000FE0000FE0000FE0000FE4A4AF9FFFFFDFFFFFFFFFFFFFFFF FFFFFFFFC2C2FA0C0CFA0404FAB6B6F9FFFFFFFFFFFFFFFFFFFFFFFFFFFFFD43 43F90000FE0000FE0000FE0000FE0303FF0000E64040CEF8F8FDCECEF01515CC 0303F50000FF0000FE0000FE0000FE0000FE2626FAC7C7FAFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFB1B1F9A9A9F9FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFB6B6FA1A 1AFB0000FE0000FE0000FE0000FE0000FF0000F71515CCCECEEF7475D80202D0 3131FC0B0BFE0000FE0000FE0000FE0000FE0000FF1111FAC0C0FAFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFB0B1F90A0AFA00 00FE0000FE0000FE0000FE0000FE0000FF0000FD0303D17474D72828C60000D6 5454FE393AFD0000FD0000FE0000FE0000FE0000FE0000FF1212FAC1C1FAFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFB1B1F90808FB0000FF00 00FE0000FE0000FE0000FE0000FE0000FF0000FF0001D72829C60302C60101D9 5B5AFF6E6EFF1A1AFC0000FE0000FE0000FE0000FE0000FE0000FF0A0AFAB1B2 F9FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA7A7F90303FB0000FF0000FE00 00FE0000FE0000FE0000FE0000FE0000FF0000FF0201DA0403C60302C60000D9 6162FF7D7EFF6262FC0808FC0000FE0000FE0000FE0000FE0000FE0404FAABAC F9FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFB1B1F90B0BFA0000FF0000FE00 00FE0000FE0000FE0000FE0000FE0000FF0000FF0101DA0403C52929C70000D6 6364FF8686FF7F80FF5C5CFC0404FC0000FE0000FE0000FE0B0BFAB5B5F9FFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC1C2FA1212FA0000FF00 00FE0000FE0000FE0000FE0000FE0000FF0000FF0001D72929C67474D70000D0 5859FB9999FF8382FF8A8AFF6060FC0D0DFC0000FF0C0CF9B6B5F9FFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC0C0FA1111FA00 00FF0000FE0000FE0000FE0000FE0000FF0000FD0303D17474D7CECEEF0C0CCC 3535F4A7A8FF9091FE8B8BFE8F8FFF6F6FFD3A3AF9B3B3F9FFFFFFFFFFFFFFFF FFFFFFFFFFFFFFA4A4F9AEAEFAFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC5C5FA22 22FA0000FE0000FE0000FE0000FE0000FF0000F71515CCCECEEFF8F8FD3A3ACE 0808E4A3A4FFA6A6FF9898FF9292FF8B8AFFAEADFCFFFFFEFFFFFFFFFFFFFFFF FFFFFFFEADADF90000F90C0DF9C7C7FAFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD60 60F90D0DFE1415FE0E0EFE0707FD0304FF0000E64040CEF8F8FDFFFFFF7F7FDD 0000D07474FEC0C0FFA6A6FFA0A1FF9A9AFF8B8BFFB1B1FCFBFCFEFFFFFFFFFF FFD4D4FB5C5CFB5554FE5252FE5B5CFBD5D5FBFFFFFFFFFFFFFBFBFD7A7AFA2B 2BFF3434FF2E2EFF2727FE2322FF1111FF0000D08180DDFFFFFFFFFFFFDCDCF4 0505C51D1DEDC1C1FFB8B8FEADADFFA8A8FEA0A1FF8E8EFEB5B6FCFDFDFEDCDD FC7F7EFD7877FF7C7DFF7576FF5F60FF6666FCDDDEFCFDFDFD8787FA3737FE44 45FF4040FF393AFF3333FE3030FF0505F00707C5DCDCF4FFFFFFFFFFFFFFFFFF 6969D70000CE6F6FFDDADAFFB9B8FFB5B5FFAFAEFFA7A8FF9A9BFFB6B7FC9B9B FD8A8AFF8A8AFF8384FF7D7DFF7878FF6768FF7A7BFC9292FB5252FE5858FF53 53FF4C4CFF4546FF4848FF2324FF0000CF6A69D7FFFFFFFFFFFFFFFFFFFFFFFF EAEAF91817C50404E0ABABFFDEDEFFC0C0FFBBBBFFB5B6FFAFAFFFA2A2FEA0A0 FF9E9EFF9696FF9190FF8B8AFF8584FF7F80FF7273FF6767FF6C6CFF6667FF5F 60FF5959FF5D5CFF4344FF0000E21718C4EAEAF9FFFFFFFFFFFFFFFFFFFFFFFF FFFFFFB3B2EA0000C21414EAC1C1FFE6E6FFC7C6FFC2C2FEBCBCFEB6B6FFB0B0 FFAAAAFEA3A4FE9E9EFF9898FF9192FF8B8BFF8685FF807FFF7979FF7373FF6B 6CFF7172FF595AFF0808EB0000C2B3B3EAFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFF9292E10000C21A1AE9BCBCFFF2F1FFD4D4FFC8C9FEC3C3FEBDBD FFB8B7FEB1B1FEABABFFA5A5FE9F9FFF9899FE9293FF8C8CFF8686FF8383FF89 8AFF6666FF0D0EEB0000C19292E1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFF8F90E20000C20202DF8C8CFDEBEBFFEEEEFFD6D6FFC8C8 FFC3C3FFBEBEFFB8B8FEB2B2FFABACFFA4A5FF9F9FFF9E9DFFA3A4FF9898FF56 56FE0000E10000C19090E1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFB3B2E91818C50000CE3535ECA3A4FEE3E4FFF0EF FFE5E6FFD9DAFFD1D1FFCACAFFC6C6FFC5C4FFC0C1FFACACFF7475FF2323EE00 00CF1B1BC4B2B2E9FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE8E8F86C6CD70404C50000CF1818E25E5E F29293FAAAA9FEB1B2FFACACFF9C9BFE7F7FFB4D4EF31110E30000D00707C56C 6CD7E8E8F8FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD7D7F37F7FDD3838CE0A0A CC0000D00000D50101D90101D80000D50000D00C0CCD3B3BCE8080DDD7D7F3FF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5F5FCCECE EE7575D72A29C70101C70101C52A29C67475D7CECEEFF5F5FCFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF} OnClick = sbExcluirClick end object sbSalvar: TSpeedButton Left = 852 Top = 244 Width = 129 Height = 42 Caption = 'Salvar' Enabled = False Glyph.Data = { 36080000424D3608000000000000360400002800000020000000200000000100 08000000000000040000120B0000120B000000010000A900000033333300D8D3 D1007C7C7C00ED842200D5722900DEC4B5009D411900DAA78400F2F6F800555A 5B00E6EFF300EE944000D7834600CD8349009A898C00EF9D4F00F2B57A00F0CB A300D6DAE000B56E45009BAAB700ED903800E27B1F00E8924100DBB8A3008B59 4C008D909100F1FEFF00CE661D00F0AD6D00CFD5DF003E404100B6856300D5A2 7F00FCDFC100F9C59500D8C2C200DD833400E5B69600D6916700ED8C3300B674 5100F6EBE000DCB69C00CE9479006B4E5100E5E5E500D9946500EFD3B4007E89 9100CEB9B900F6F3ED007D636400B7633200F4BF8D00FFFFFF00CA977400F39A 4300FACEA200E6822400EF943A00D6762F00CBCFD6008C5C5000C2ACAD00D4D8 DE00D9B8A200D7874E00E6EFF600AA959400EF8A2900F2BD8700D4DBE4009D6E 6200F0913500DEC0AD00F2B37400D0713200E39F6900DF914E00EDD0B300E4CF CE00EFA45900F4E9DF00DE732900DE843800C97E4500D7793300D38B5600E6BA 9B00E4AE80004F525300EF9D4C00C18F6C0094999D00C48157008E5F5400E1E4 E500FECFA000E7D9DC00F1F9FF00DD986100AAB3BA00D9D1D100F6F9FB00E782 2900E4C6B400DEAC8B00F7EFE600F0F2F500DE8A4300E0965700F7F7F700F2A4 5500EA8D3200E47A1A00DC9C7300B5A0A000D77C3A00F5B57600E2E2E1009494 9C00E4A87400E47E2600D8D5D600ECE6E300DF8E4800F7B57B00C17A4800EFB5 8400C3916D00EFEFEF00F7943A00F8FFFF00DDBCA500FDFAF800E47D1F004241 4100EDCEAF00E7E9EB00DEBDB500F6BD8600F6C69A00F7AD6B00F7BD9400F49A 4200F8D0AB00989FA500E68C2900DC975F00DEAB8600FCCFA300CD9A7600828C 9300A38D8E00585A5C00DC814000D16C2500DDC8C700F8D4B200E5A16C00D88E 5900E5BCA200DBE5EC00E49F6600E0CBCA00E5CBB800DED6D600000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000373737441E48 4848481212121212414141414141414112484848481E0A37373737377C49193F 3F3F3F3F6060606060606060606060603F3F3F3F3F3F343E3737377C139D5757 5757350E0E9A45754032249EA5A551632C1C5757574D062D3E377D8069919191 91910D9309095B1A618B0885373737375969393939179C06340A4B25913C0B0B 0B0B0D5E1F1F0002782E6D7087373737267B390B0B0B0B4D191E05553C0B0B0B 0B4A0D5E1F1F0002782E837087373737267B0B0B0B0B0B3D3F1E05553C3C3C3C 3C3C0D5E1F1F0002782E837087373737267B0B0B3C3C3C3D3F1E05253C3C3C3C 3C3C0D5E1F1F0002782E837087373737267B0B3C3C3C3C3D3F1E05253C3C3C3C 3C4A0D5E1F1F00027878837087373737267B0B3C3C3C3C043F1E05254A4A4A4A 4A4A561431319966A3441B8537373737A2163C15151515043F1E05254A151515 15154D205D5D3838982107969696969658693C15151515043F1E05254A151515 1515720303033B3B3B888888888888733B151515151515043F1E05254A151515 1515153C3C3C3C3C3C3C3C3C3C3C3C3C3C3C1515151515043F1E05254A4A4A4A 4A4A4A1515151515151515151515151515151528282828043F1E05254A282828 2828281515151515151515151515151528282828282828043F1E05254A4A2803 0303034646464646464646464646464646030303282828043F1E05254A281511 508A8A8A50505050505050505050508A8A8A8A3052464A043F1E05253C720B33 1B646464646464646464646464646464646464644C463C3D3F1E05550B150B53 6D838383838383838383838383838383838383084C720B3D3F1E0555390B5C2A 6D6D6D6D6D6D6D6D6D6D6D6D6D6D6D6D6D6D6D704C1539573F1E056E5C0B0F2A 6D83838383838383838383838383838383838308100B5C763F1E056E0F0F0F2A 6D83838383838383838383838383838383838308100B0F763F1E056E715C526C 086D6D6D6D6D6D6D6D6D6D6D6D6D6D6D6D6D6D688139719C3F1E4B7E5252522A 6D83838383838383838383838383838383838308475C520C3F1E4B4F8F521D6C 6D8383838383838383838383838383838383837036521D433F1E4B6F771D4C6C 6D838383838383838383838383838383838383708E1D4CA13F1E4B658D108D6C 83838383838383838383838383838383838383083A4C8D2F3F1E86A02347366C 6D83838383838383838383838383838383838370928D8D74191E6A953A238E33 83838383838383838383838383838383838383089F363A27490A876B4E979785 856464646464646464646464646464646464648522621029673737376B657AA2 86868686868686868686868686868686868686865AA45F013737373737A6422B 2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B18187D373737} OnClick = sbSalvarClick end object sbRelPendente: TSpeedButton Left = 717 Top = 151 Width = 237 Height = 42 Caption = 'Relat'#243'rio de Compromissos Pendentes' Glyph.Data = { 360C0000424D360C000000000000360000002800000020000000200000000100 180000000000000C0000C40E0000C40E00000000000000000000FFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD26A10 D26E16D16B11D16B11D16B11D16B11D16B11D16B11D16B11D16B11D16B11D16B 11D16B11D16B11D16B11D16B11D16B11D26E16D26C12FFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD36E16 EECBACF6E4D4F6E1CFF6E1CFF6E1CFF6E1CFF6E1CFF6E1CFF6E1CFF6E1CFF6E1 CFF6E1CFF6E1CFF6E1CFF6E1CFF6E4D4EECBACD36F17FFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD26B11 F6E5D6FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6E5D6D26C12FFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD26B11 F5E2D1FFFFFFFFFFFFDD914EE09B5EE09B5EE09B5EE09B5EE09B5EE09B5EE09B 5EE09B5EDF9A5CE19F65FFFFFFFFFFFFF5E2D1D26C12FFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD26B11 F5E2D1FFFFFFFFFFFFE4A771E6AF7FE6AF7FE6AF7FE6AF7FE6AF7FE6AF7FE6AF 7FE6AF7FE6AE7DE7B284FFFFFFFFFFFFF5E2D1D4721CF1D3B9CE5E00D0680BD0 680BD16A0FD67B2AFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD26B11 F5E2D1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5E2D1D26E15FFFFFFF7E4D4F7E6D8F9 EBDFEBBF9AD88134FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD26B11 F5E2D1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5E2D1D26C12FFFFFFFFFFFFFFFFFFFF FFFFF1D1B7D77F30FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD26B11 F5E2D1FFFFFFFFFFFFDE9758DF995ADF985ADF9758DF9757DE9655DE9553DE94 53DD9351DD904DDF9656FFFFFFFFFFFFF5E2D1D26C12FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3D77F31FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD26B11 F5E2D1FFFFFFFFFFFFE6AE7DE6B080E7B283E7B385E8B486E8B588E8B689E8B6 8AE9B88CE9B88CEABB93FFFFFFFFFFFFF5E2D1D26C12FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3DA873CECC29CCE6000D0680BD0680BD16A0FDA863CFFFFFFD26B11 F5E2D1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5E2D1D26C12FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3D88133FFFFFFF8EADDF9EBE0FAF0E7EDC5A2DC8C45FFFFFFD26B11 F5E2D1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5E2D1D26C12FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3D77F30FFFFFFFFFFFFFFFFFFFFFFFFF2D4BADB8A42FFFFFFD26B11 F5E2D1FFFFFFFFFFFFDE9555DF985ADF995BDF995BE09A5DE09A5DE09A5DE09A 5DE09A5DDF995BE19E64FFFFFFFFFFFFF5E2D1D26C12FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3D77F30FFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD26B11 F5E2D1FFFFFFFFFFFFE6AE7DE7B181E7B182E7B282E6B080E6B080E6B080E6B0 80E6B080E6AF7EE7B385FFFFFFFFFFFFF5E2D1D26C12FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3D77F30FFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD26B11 F5E2D1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5E2D1D26C12FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3D77F30FFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD26B11 F5E2D1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6E3D3D26C12FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3D77F30FFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD26B11 F5E2D1FFFFFFFFFFFFE2A168E2A269E1A066E09C60E2A066FFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFEFEFEFEFDFCFFFFFFF4DECAD26D15FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3D77F30FFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD26B11 F5E2D1FFFFFFFFFFFFE3A36CE4A772E5AA77E5AB79E7B283FFFFFFFFFFFFF6E1 CFD1690ED1690DD0680CD0680CD26E15D57826D36F18FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3D77F30FFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD26B11 F5E2D1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7E6 D7D26E15FBF5F1FBF2EBFFFFFFEEC9A8D16B11F0D0B3FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3D77F30FFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD26B11 F5E2D1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7E8 D9D26B10FFFFFFFFFFFFF4DDC8CF6405EFCBACFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFF0D0B5D77F30FFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD26B11 F5E2D1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8E9 DCD16A0FFFFFFFF5E1CECE6101EDC6A4FFFFFFFDFBF9FDFBF8FDF9F6FCF8F4FD FBFAEEC8A8D88032FFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD26B11 F6E5D6FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF9EE E4D26E16F8E9DBCF6304EBC09AFFFFFFF0CEB1D16A0FD0680CD0680CD0680CD3 7018D57825D88134FFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD36D15 EFCCADF7E6D7F6E3D2F6E3D2F6E3D2F6E3D2F6E3D2F6E3D2F6E3D2F7E5D6F2D4 BAD67928D26E15E9BA91FFFFFFFFFFFFF1D4B9D57825FFFFFFFCF7F2FFFFFFE9 B78BD26D14F7E9DBFFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD26C13 D37018D26D14D26D14D26D14D26D15D4731DD26E15D26D14D26D14D26D14D36F 18D3721BE8B589FFFFFFFFFFFFFFFFFFF1D5BCD57521FFFFFFFFFFFFECC4A0CF 6507F7E7D8FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2D3BADB8A42FFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF1D1B5FFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF3D7BFD4731EFFFFFFEDC8A6CE6202F6 E2D1FFFFFFFCF6F1FCF6F0FBF4EEFBF3ECFCF6F1EEC8A7DC8B44FFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFCD5F00FDF7F2FFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF4DCC6D57927F4DCC7CE6100F4DEC9FF FFFFF0D1B5D16A10D0680CD0680CD0680CD37019D57825DC8D47FFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD16A10F2D5BBF5DFCCF4DDC9F4DDC9F4DD C9F4DDC9F4DDC9F4DDC9F4DDC9F5E1CEECC39ED67A29D1690EF3D9C2FFFFFFFF FFFFF2D7BED57521FFFFFFFEFCFAFFFFFFE9B98FD26D14FAEFE5FFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD3711AD47521D4731ED4731ED4731ED474 1FD77D2ED47521D4731ED4731ED4731ED57623D47622F1D2B7FFFFFFFFFFFFFF FFFFF3D8C0D3721DFFFFFFFFFFFFEBC19ACF6507F8E8DAFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFE2A066FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFF3DAC3D3711AFFFFFFEDC4A1CF6303F6E4D3FFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFCF6303FCF5EFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFF5DFCCD57623F3DAC3CE6101F5E0CDFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFD16A10F0CEB1F3DAC3F3D8C0F3D8C0F3D8C0F3D8C0F3D8C0F3D8C0F3D8C0F4 DBC5EBC09AD67A28D1690EF4DBC5FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFD88236DA873ED9853BD9853BD9853BD9853BD9853BD9853BD9853BD9853BD9 853BDA8840DA873EF4DBC4FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF} Margin = 1 end object sbRelFinalizado: TSpeedButton Left = 717 Top = 196 Width = 237 Height = 42 Caption = 'Relat'#243'rio de Compromissos Finalizados' Glyph.Data = { 360C0000424D360C000000000000360000002800000020000000200000000100 180000000000000C0000C40E0000C40E00000000000000000000FFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD26A10 D26E16D16B11D16B11D16B11D16B11D16B11D16B11D16B11D16B11D16B11D16B 11D16B11D16B11D16B11D16B11D16B11D26E16D26C12FFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD36E16 EECBACF6E4D4F6E1CFF6E1CFF6E1CFF6E1CFF6E1CFF6E1CFF6E1CFF6E1CFF6E1 CFF6E1CFF6E1CFF6E1CFF6E1CFF6E4D4EECBACD36F17FFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD26B11 F6E5D6FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6E5D6D26C12FFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD26B11 F5E2D1FFFFFFFFFFFFDD914EE09B5EE09B5EE09B5EE09B5EE09B5EE09B5EE09B 5EE09B5EDF9A5CE19F65FFFFFFFFFFFFF5E2D1D26C12FFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD26B11 F5E2D1FFFFFFFFFFFFE4A771E6AF7FE6AF7FE6AF7FE6AF7FE6AF7FE6AF7FE6AF 7FE6AF7FE6AE7DE7B284FFFFFFFFFFFFF5E2D1D4721CF1D3B9CE5E00D0680BD0 680BD16A0FD67B2AFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD26B11 F5E2D1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5E2D1D26E15FFFFFFF7E4D4F7E6D8F9 EBDFEBBF9AD88134FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD26B11 F5E2D1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5E2D1D26C12FFFFFFFFFFFFFFFFFFFF FFFFF1D1B7D77F30FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD26B11 F5E2D1FFFFFFFFFFFFDE9758DF995ADF985ADF9758DF9757DE9655DE9553DE94 53DD9351DD904DDF9656FFFFFFFFFFFFF5E2D1D26C12FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3D77F31FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD26B11 F5E2D1FFFFFFFFFFFFE6AE7DE6B080E7B283E7B385E8B486E8B588E8B689E8B6 8AE9B88CE9B88CEABB93FFFFFFFFFFFFF5E2D1D26C12FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3DA873CECC29CCE6000D0680BD0680BD16A0FDA863CFFFFFFD26B11 F5E2D1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5E2D1D26C12FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3D88133FFFFFFF8EADDF9EBE0FAF0E7EDC5A2DC8C45FFFFFFD26B11 F5E2D1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5E2D1D26C12FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3D77F30FFFFFFFFFFFFFFFFFFFFFFFFF2D4BADB8A42FFFFFFD26B11 F5E2D1FFFFFFFFFFFFDE9555DF985ADF995BDF995BE09A5DE09A5DE09A5DE09A 5DE09A5DDF995BE19E64FFFFFFFFFFFFF5E2D1D26C12FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3D77F30FFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD26B11 F5E2D1FFFFFFFFFFFFE6AE7DE7B181E7B182E7B282E6B080E6B080E6B080E6B0 80E6B080E6AF7EE7B385FFFFFFFFFFFFF5E2D1D26C12FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3D77F30FFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD26B11 F5E2D1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5E2D1D26C12FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3D77F30FFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD26B11 F5E2D1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6E3D3D26C12FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3D77F30FFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD26B11 F5E2D1FFFFFFFFFFFFE2A168E2A269E1A066E09C60E2A066FFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFEFEFEFEFDFCFFFFFFF4DECAD26D15FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3D77F30FFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD26B11 F5E2D1FFFFFFFFFFFFE3A36CE4A772E5AA77E5AB79E7B283FFFFFFFFFFFFF6E1 CFD1690ED1690DD0680CD0680CD26E15D57826D36F18FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3D77F30FFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD26B11 F5E2D1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7E6 D7D26E15FBF5F1FBF2EBFFFFFFEEC9A8D16B11F0D0B3FFFFFFFFFFFFFFFFFFFF FFFFF0CFB3D77F30FFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD26B11 F5E2D1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7E8 D9D26B10FFFFFFFFFFFFF4DDC8CF6405EFCBACFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFF0D0B5D77F30FFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD26B11 F5E2D1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8E9 DCD16A0FFFFFFFF5E1CECE6101EDC6A4FFFFFFFDFBF9FDFBF8FDF9F6FCF8F4FD FBFAEEC8A8D88032FFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD26B11 F6E5D6FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF9EE E4D26E16F8E9DBCF6304EBC09AFFFFFFF0CEB1D16A0FD0680CD0680CD0680CD3 7018D57825D88134FFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD36D15 EFCCADF7E6D7F6E3D2F6E3D2F6E3D2F6E3D2F6E3D2F6E3D2F6E3D2F7E5D6F2D4 BAD67928D26E15E9BA91FFFFFFFFFFFFF1D4B9D57825FFFFFFFCF7F2FFFFFFE9 B78BD26D14F7E9DBFFFFFFFFFFFFFFFFFFFFFFFFF1D1B7DB8A42FFFFFFD26C13 D37018D26D14D26D14D26D14D26D15D4731DD26E15D26D14D26D14D26D14D36F 18D3721BE8B589FFFFFFFFFFFFFFFFFFF1D5BCD57521FFFFFFFFFFFFECC4A0CF 6507F7E7D8FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2D3BADB8A42FFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF1D1B5FFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF3D7BFD4731EFFFFFFEDC8A6CE6202F6 E2D1FFFFFFFCF6F1FCF6F0FBF4EEFBF3ECFCF6F1EEC8A7DC8B44FFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFCD5F00FDF7F2FFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF4DCC6D57927F4DCC7CE6100F4DEC9FF FFFFF0D1B5D16A10D0680CD0680CD0680CD37019D57825DC8D47FFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD16A10F2D5BBF5DFCCF4DDC9F4DDC9F4DD C9F4DDC9F4DDC9F4DDC9F4DDC9F5E1CEECC39ED67A29D1690EF3D9C2FFFFFFFF FFFFF2D7BED57521FFFFFFFEFCFAFFFFFFE9B98FD26D14FAEFE5FFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD3711AD47521D4731ED4731ED4731ED474 1FD77D2ED47521D4731ED4731ED4731ED57623D47622F1D2B7FFFFFFFFFFFFFF FFFFF3D8C0D3721DFFFFFFFFFFFFEBC19ACF6507F8E8DAFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFE2A066FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFF3DAC3D3711AFFFFFFEDC4A1CF6303F6E4D3FFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFCF6303FCF5EFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFF5DFCCD57623F3DAC3CE6101F5E0CDFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFD16A10F0CEB1F3DAC3F3D8C0F3D8C0F3D8C0F3D8C0F3D8C0F3D8C0F3D8C0F4 DBC5EBC09AD67A28D1690EF4DBC5FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFD88236DA873ED9853BD9853BD9853BD9853BD9853BD9853BD9853BD9853BD9 853BDA8840DA873EF4DBC4FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF} Margin = 1 end object Label11: TLabel Left = 32 Top = 11 Width = 56 Height = 19 Caption = 'C'#243'digo' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -16 Font.Name = 'Tahoma' Font.Style = [fsBold] ParentFont = False end object DBGrid1: TDBGrid Left = 8 Top = 304 Width = 984 Height = 192 DataSource = DataSource1 Options = [dgTitles, dgIndicator, dgColumnResize, dgColLines, dgRowLines, dgTabs, dgRowSelect, dgTitleClick, dgTitleHotTrack] ReadOnly = True TabOrder = 0 TitleFont.Charset = DEFAULT_CHARSET TitleFont.Color = clWindowText TitleFont.Height = -11 TitleFont.Name = 'Tahoma' TitleFont.Style = [] Columns = < item Expanded = False FieldName = 'idcompromisso' Title.Caption = 'C'#243'digo' Visible = True end item Expanded = False FieldName = 'nome_1' Title.Caption = 'Cliente' Width = 106 Visible = True end item Expanded = False FieldName = 'data_marcada' Title.Caption = 'Data' Visible = True end item Expanded = False FieldName = 'horario' Title.Caption = 'Hor'#225'rio' Visible = True end item Expanded = False FieldName = 'cidade' Title.Caption = 'Cidade' Width = 90 Visible = True end item Expanded = False FieldName = 'uf' Title.Caption = 'UF' Width = 74 Visible = True end item Expanded = False FieldName = 'urgencia' Title.Caption = 'Urg'#234'ncia' Width = 61 Visible = True end item Expanded = False FieldName = 'situacao' Title.Caption = 'Situa'#231#227'o' Width = 72 Visible = True end> end object memDescricao: TDBMemo Left = 32 Top = 105 Width = 292 Height = 89 DataField = 'descricao' DataSource = DataSource1 Enabled = False MaxLength = 2000 TabOrder = 1 end object memEndereco: TDBMemo Left = 360 Top = 108 Width = 294 Height = 89 DataField = 'endereco' DataSource = DataSource1 Enabled = False TabOrder = 2 end object cbCidade: TDBComboBox Left = 668 Top = 33 Width = 145 Height = 21 DataField = 'cidade' DataSource = DataSource1 Enabled = False Items.Strings = ( 'Barra do Pira'#237 'Barra Mansa' 'Engenheiros Passos' 'Itatiaia' 'Nova Igua'#231'u' 'Penedo' 'Pira'#237 'Porto Real' 'Quatis' 'Queimados' 'Resende' 'Valen'#231'a' 'Volta Redonda') Sorted = True TabOrder = 3 end object cbUF: TDBComboBox Left = 660 Top = 105 Width = 145 Height = 21 DataField = 'uf' DataSource = DataSource1 Enabled = False Items.Strings = ( 'Paran'#225 'Rio de Janeiro' 'S'#227'o Paulo') Sorted = True TabOrder = 4 end object cbSituacao: TDBComboBox Left = 32 Top = 222 Width = 145 Height = 21 DataField = 'situacao' DataSource = DataSource1 Enabled = False Items.Strings = ( 'Finalizado' 'Pendente') Sorted = True TabOrder = 5 end object cbUrgencia: TDBComboBox Left = 208 Top = 225 Width = 145 Height = 21 DataField = 'urgencia' DataSource = DataSource1 Enabled = False Items.Strings = ( 'Muito Baixa' 'Baixa' 'Moderada' 'Alta' 'Muito Alta' 'Emerg'#234'ncia') TabOrder = 6 end object txtId: TDBEdit Left = 32 Top = 33 Width = 78 Height = 21 DataField = 'idcompromisso' DataSource = DataSource1 Enabled = False TabOrder = 7 end object txtData: TDBEdit Left = 360 Top = 33 Width = 97 Height = 21 DataField = 'data_marcada' DataSource = DataSource1 TabOrder = 8 end object txtHora: TDBEdit Left = 520 Top = 33 Width = 89 Height = 21 DataField = 'horario' DataSource = DataSource1 TabOrder = 9 end object cbNome: TDBLookupComboBox Left = 162 Top = 33 Width = 170 Height = 21 DataField = 'nome' DataSource = DataSource1 Enabled = False KeyField = 'idcliente' ListField = 'nome' ListSource = SourceCliente TabOrder = 10 end object DataSource1: TDataSource DataSet = FDQuery1 Left = 920 Top = 80 end object FDQuery1: TFDQuery Active = True Connection = FDConnection1 SQL.Strings = ( 'select compromisso.*, cliente.nome' '' ' from compromisso' '' 'inner join cliente on compromisso.nome = cliente.idcliente' '' 'order by idcompromisso;') Left = 920 Top = 16 end object FDConnection1: TFDConnection ConnectionName = 'localhost' Params.Strings = ( 'Database=db_hefesto' 'User_Name=root' 'DataSource=db_hefesto' 'ODBCAdvanced=DESCRIPTION={Bano de Dados - Hefesto};SERVER=localh' + 'ost;PORT=3306' 'DriverID=ODBC') Connected = True LoginPrompt = False Left = 840 Top = 16 end object FDGUIxWaitCursor1: TFDGUIxWaitCursor Provider = 'Forms' Left = 720 Top = 64 end object DataSetCliente: TFDQuery Active = True Connection = FDConnection1 SQL.Strings = ( 'select * from cliente') Left = 664 Top = 144 object DataSetClienteidcliente: TLargeintField FieldName = 'idcliente' Origin = 'idcliente' ProviderFlags = [pfInUpdate, pfInWhere, pfInKey] Required = True end object DataSetClientenome: TStringField FieldName = 'nome' Origin = 'nome' Size = 80 end object DataSetClienterg: TStringField FieldName = 'rg' Origin = 'rg' end object DataSetClientecpf: TStringField FieldName = 'cpf' Origin = 'cpf' end object DataSetClienteendereco: TMemoField FieldName = 'endereco' Origin = 'endereco' BlobType = ftMemo end object DataSetClientecidade: TStringField FieldName = 'cidade' Origin = 'cidade' Size = 80 end object DataSetClienteuf: TStringField FieldName = 'uf' Origin = 'uf' Size = 80 end object DataSetClientetelefone: TStringField FieldName = 'telefone' Origin = 'telefone' Size = 30 end object DataSetClientetelefone2: TStringField FieldName = 'telefone2' Origin = 'telefone2' Size = 30 end end object SourceCliente: TDataSource DataSet = DataSetCliente Left = 664 Top = 200 end object frxPDFExport1: TfrxPDFExport UseFileCache = True ShowProgress = True OverwritePrompt = False DataOnly = False PrintOptimized = False Outline = False Background = False HTMLTags = True Quality = 95 Transparency = False Author = 'FastReport' Subject = 'FastReport PDF export' ProtectionFlags = [ePrint, eModify, eCopy, eAnnot] HideToolbar = False HideMenubar = False HideWindowUI = False FitWindow = False CenterWindow = False PrintScaling = False PdfA = False Left = 704 Top = 368 end object frxDBDataset1: TfrxDBDataset UserName = 'frxDBDataset1' CloseDataSource = False DataSet = FDQuery2 BCDToCurrency = False Left = 792 Top = 312 end object RelatórioPendente: TfrxReport Version = '5.1.5' DataSet = frxDBDataset1 DataSetName = 'frxDBDataset1' DotMatrixReport = False IniFile = '\Software\Fast Reports' PreviewOptions.Buttons = [pbPrint, pbLoad, pbSave, pbExport, pbZoom, pbFind, pbOutline, pbPageSetup, pbTools, pbEdit, pbNavigator, pbExportQuick] PreviewOptions.Zoom = 1.000000000000000000 PrintOptions.Printer = 'Default' PrintOptions.PrintOnSheet = 0 ReportOptions.CreateDate = 43072.047496400500000000 ReportOptions.LastChange = 43072.075793356480000000 ScriptLanguage = 'PascalScript' ScriptText.Strings = ( '' 'begin' '' 'end.') Left = 792 Top = 360 Datasets = < item DataSet = frxDBDataset1 DataSetName = 'frxDBDataset1' end> Variables = <> Style = <> object Data: TfrxDataPage Height = 1000.000000000000000000 Width = 1000.000000000000000000 end object Page1: TfrxReportPage Orientation = poLandscape PaperWidth = 279.400000000000000000 PaperHeight = 215.900000000000000000 PaperSize = 1 LeftMargin = 10.000000000000000000 RightMargin = 10.000000000000000000 TopMargin = 10.000000000000000000 BottomMargin = 10.000000000000000000 HGuides.Strings = ( '79,37013' '343,93723') object Shape1: TfrxShapeView Top = 1.779530000000000000 Width = 982.677800000000000000 Height = 49.133890000000000000 Fill.BackColor = 14211288 end object MasterData1: TfrxMasterData FillType = ftBrush Height = 343.937230000000000000 Top = 71.811070000000000000 Width = 980.410081999999900000 DataSet = frxDBDataset1 DataSetName = 'frxDBDataset1' RowCount = 2 object frxDBDataset1nome_1: TfrxMemoView Left = 22.677180000000000000 Top = 47.236239999999990000 Width = 241.889920000000000000 Height = 18.897650000000000000 DataField = 'nome_1' DataSet = frxDBDataset1 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Cambria' Font.Style = [fsBold] Memo.UTF8W = ( '[frxDBDataset1."nome_1"]') ParentFont = False end object frxDBDataset1data_marcada: TfrxMemoView Left = 317.480520000000000000 Top = 47.236239999999990000 Width = 79.370130000000000000 Height = 18.897650000000000000 DataField = 'data_marcada' DataSet = frxDBDataset1 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Cambria' Font.Style = [fsBold] Memo.UTF8W = ( '[frxDBDataset1."data_marcada"]') ParentFont = False end object frxDBDataset1horario: TfrxMemoView Left = 438.425480000000000000 Top = 47.236239999999990000 Width = 90.708720000000000000 Height = 18.897650000000000000 DataField = 'horario' DataSet = frxDBDataset1 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Cambria' Font.Style = [fsBold] Memo.UTF8W = ( '[frxDBDataset1."horario"]') ParentFont = False end object frxDBDataset1descricao: TfrxMemoView Left = 22.677180000000000000 Top = 102.047310000000000000 Width = 884.410020000000000000 Height = 68.031540000000000000 DataField = 'descricao' DataSet = frxDBDataset1 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Cambria' Font.Style = [fsBold] Memo.UTF8W = ( '[frxDBDataset1."descricao"]') ParentFont = False end object frxDBDataset1endereco: TfrxMemoView Left = 22.677180000000000000 Top = 226.771800000000000000 Width = 952.441560000000000000 Height = 45.354360000000000000 DataField = 'endereco' DataSet = frxDBDataset1 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Cambria' Font.Style = [fsBold] Memo.UTF8W = ( '[frxDBDataset1."endereco"]') ParentFont = False end object frxDBDataset1uf: TfrxMemoView Left = 230.551330000000000000 Top = 309.921460000000000000 Width = 200.315090000000000000 Height = 18.897650000000000000 DataField = 'uf' DataSet = frxDBDataset1 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Cambria' Font.Style = [fsBold] Memo.UTF8W = ( '[frxDBDataset1."uf"]') ParentFont = False end object frxDBDataset1cidade: TfrxMemoView Left = 22.677180000000000000 Top = 309.921460000000000000 Width = 196.535560000000000000 Height = 18.897650000000000000 DataField = 'cidade' DataSet = frxDBDataset1 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Cambria' Font.Style = [fsBold] Memo.UTF8W = ( '[frxDBDataset1."cidade"]') ParentFont = False end object frxDBDataset1urgencia: TfrxMemoView Left = 563.149970000000000000 Top = 47.236239999999990000 Width = 192.756030000000000000 Height = 18.897650000000000000 DataField = 'urgencia' DataSet = frxDBDataset1 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Cambria' Font.Style = [fsBold] Memo.UTF8W = ( '[frxDBDataset1."urgencia"]') ParentFont = False end object frxDBDataset1situacao: TfrxMemoView Left = 771.024120000000000000 Top = 47.236239999999990000 Width = 166.299320000000000000 Height = 18.897650000000000000 DataField = 'situacao' DataSet = frxDBDataset1 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Cambria' Font.Style = [fsBold] Memo.UTF8W = ( '[frxDBDataset1."situacao"]') ParentFont = False end object Line1: TfrxLineView Top = 340.157700000000000000 Width = 978.898270000000000000 Color = clBlack Diagonal = True end object Memo2: TfrxMemoView Left = 20.787415000000000000 Top = 8.503942499999994000 Width = 244.724567500000000000 Height = 33.070887500000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -15 Font.Name = 'Arial' Font.Style = [fsBold] Memo.UTF8W = ( 'Nome') ParentFont = False VAlign = vaBottom end object Memo3: TfrxMemoView Left = 317.480520000000000000 Top = 7.559060000000003000 Width = 78.425247500000000000 Height = 33.070887500000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -15 Font.Name = 'Arial' Font.Style = [fsBold] Memo.UTF8W = ( 'Data') ParentFont = False VAlign = vaBottom end object Memo4: TfrxMemoView Left = 442.205010000000000000 Top = 7.559060000000003000 Width = 78.425247500000000000 Height = 33.070887500000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -15 Font.Name = 'Arial' Font.Style = [fsBold] Memo.UTF8W = ( 'Hora') ParentFont = False VAlign = vaBottom end object Memo5: TfrxMemoView Left = 563.149970000000000000 Top = 7.559060000000003000 Width = 191.811147500000000000 Height = 33.070887500000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -15 Font.Name = 'Arial' Font.Style = [fsBold] Memo.UTF8W = ( 'Urgencia') ParentFont = False VAlign = vaBottom end object Memo6: TfrxMemoView Left = 771.024120000000000000 Top = 7.559060000000003000 Width = 165.354437500000000000 Height = 33.070887500000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -15 Font.Name = 'Arial' Font.Style = [fsBold] Memo.UTF8W = ( 'Situa'#231#227'o') ParentFont = False VAlign = vaBottom end object Memo7: TfrxMemoView Left = 22.677180000000000000 Top = 64.252010000000010000 Width = 244.724567500000000000 Height = 33.070887500000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -15 Font.Name = 'Arial' Font.Style = [fsBold] Memo.UTF8W = ( 'Descri'#231#227'o') ParentFont = False VAlign = vaBottom end object Memo8: TfrxMemoView Left = 22.677180000000000000 Top = 185.196970000000000000 Width = 244.724567500000000000 Height = 33.070887500000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -15 Font.Name = 'Arial' Font.Style = [fsBold] Memo.UTF8W = ( 'Endere'#231'o') ParentFont = False VAlign = vaBottom end object Memo9: TfrxMemoView Left = 22.677180000000000000 Top = 272.126160000000000000 Width = 199.370207500000000000 Height = 33.070887500000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -15 Font.Name = 'Arial' Font.Style = [fsBold] Memo.UTF8W = ( 'Cidade') ParentFont = False VAlign = vaBottom end object Memo10: TfrxMemoView Left = 230.551330000000000000 Top = 272.126160000000000000 Width = 199.370207500000000000 Height = 33.070887500000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -15 Font.Name = 'Arial' Font.Style = [fsBold] Memo.UTF8W = ( 'UF') ParentFont = False VAlign = vaBottom end object Line2: TfrxLineView Left = 480.000310000000000000 Top = 302.362400000000000000 Width = 230.551330000000000000 Color = clBlack Diagonal = True end object Line3: TfrxLineView Left = 737.008350000000000000 Top = 302.362400000000000000 Width = 230.551330000000000000 Color = clBlack Diagonal = True end object Memo11: TfrxMemoView Left = 498.897960000000000000 Top = 302.362400000000000000 Width = 199.370207500000000000 Height = 33.070887500000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -15 Font.Name = 'Arial' Font.Style = [fsBold] HAlign = haCenter Memo.UTF8W = ( 'T'#233'cnico em Inform'#225'tica') ParentFont = False VAlign = vaCenter end object Memo12: TfrxMemoView Left = 755.906000000000000000 Top = 302.362400000000000000 Width = 199.370207500000000000 Height = 33.070887500000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -15 Font.Name = 'Arial' Font.Style = [fsBold] HAlign = haCenter Memo.UTF8W = ( 'Cliente') ParentFont = False VAlign = vaCenter end end object Header1: TfrxHeader FillType = ftBrush Height = 30.236240000000000000 Top = 18.897650000000000000 Width = 980.410081999999900000 object Memo1: TfrxMemoView Left = 305.480512250000000000 Top = 0.944882499999998500 Width = 369.449057500000000000 Height = 28.346475000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -24 Font.Name = 'Arial' Font.Style = [fsBold] HAlign = haCenter Memo.UTF8W = ( 'RELAT'#211'RIO DE SERVI'#199'OS PENDENTES') ParentFont = False end end end end object FDQuery2: TFDQuery Active = True Connection = FDConnection1 SQL.Strings = ( 'select compromisso.*, cliente.nome' '' ' from compromisso' '' 'inner join cliente on compromisso.nome = cliente.idcliente' '' 'and situacao = '#39'pendente'#39 '' 'order by idcompromisso;') Left = 520 Top = 384 end object FDQuery3: TFDQuery Active = True Connection = FDConnection1 SQL.Strings = ( 'select compromisso.*, cliente.nome' '' ' from compromisso' '' 'inner join cliente on compromisso.nome = cliente.idcliente' '' 'and situacao = '#39'finalizado'#39 '' 'order by idcompromisso;') Left = 608 Top = 384 end object frxDBDataset2: TfrxDBDataset UserName = 'frxDBDataset1' CloseDataSource = False DataSet = FDQuery3 BCDToCurrency = False Left = 912 Top = 312 end object frxReport1: TfrxReport Version = '5.1.5' DotMatrixReport = False IniFile = '\Software\Fast Reports' PreviewOptions.Buttons = [pbPrint, pbLoad, pbSave, pbExport, pbZoom, pbFind, pbOutline, pbPageSetup, pbTools, pbEdit, pbNavigator, pbExportQuick] PreviewOptions.Zoom = 1.000000000000000000 PrintOptions.Printer = 'Default' PrintOptions.PrintOnSheet = 0 ReportOptions.CreateDate = 43072.103377245400000000 ReportOptions.LastChange = 43072.108077835600000000 ScriptLanguage = 'PascalScript' ScriptText.Strings = ( '' 'begin' '' 'end.') Left = 912 Top = 360 Datasets = < item DataSet = frxDBDataset2 DataSetName = 'frxDBDataset1' end> Variables = <> Style = < item Name = 'Title' Font.Charset = DEFAULT_CHARSET Font.Color = clWhite Font.Height = -16 Font.Name = 'Arial' Font.Style = [fsBold] Fill.BackColor = clGray end item Name = 'Header' Font.Charset = DEFAULT_CHARSET Font.Color = clMaroon Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] end item Name = 'Group header' Font.Charset = DEFAULT_CHARSET Font.Color = clMaroon Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] Fill.BackColor = 16053492 end item Name = 'Data' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Arial' Font.Style = [] end item Name = 'Group footer' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] end item Name = 'Header line' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Arial' Font.Style = [] Frame.Typ = [ftBottom] Frame.Width = 2.000000000000000000 end> object Data: TfrxDataPage Height = 1000.000000000000000000 Width = 1000.000000000000000000 end object Page1: TfrxReportPage Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] Orientation = poLandscape PaperWidth = 279.400000000000000000 PaperHeight = 215.900000000000000000 PaperSize = 1 LeftMargin = 10.000000000000000000 RightMargin = 10.000000000000000000 TopMargin = 10.000000000000000000 BottomMargin = 10.000000000000000000 object MasterData1: TfrxMasterData FillType = ftBrush Height = 192.756030000000000000 Top = 105.826840000000000000 Width = 980.410081999999900000 DataSet = frxDBDataset2 DataSetName = 'frxDBDataset1' RowCount = 3 object Memo3: TfrxMemoView Width = 93.000000000000000000 Height = 18.897650000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clMaroon Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] Memo.UTF8W = ( 'Nome') ParentFont = False Style = 'Header' end object Memo4: TfrxMemoView Left = 111.897650000000000000 Width = 593.000000000000000000 Height = 18.897650000000000000 DataField = 'nome_1' DataSet = frxDBDataset2 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Cambria' Font.Style = [] Memo.UTF8W = ( '[frxDBDataset1."nome_1"]') ParentFont = False end object Memo5: TfrxMemoView Top = 18.897650000000000000 Width = 93.000000000000000000 Height = 18.897650000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clMaroon Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] Memo.UTF8W = ( 'Data') ParentFont = False Style = 'Header' end object Memo6: TfrxMemoView Left = 111.897650000000000000 Top = 18.897650000000000000 Width = 78.000000000000000000 Height = 18.897650000000000000 DataField = 'data_marcada' DataSet = frxDBDataset2 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Cambria' Font.Style = [] Memo.UTF8W = ( '[frxDBDataset1."data_marcada"]') ParentFont = False end object Memo7: TfrxMemoView Top = 37.795300000000000000 Width = 93.000000000000000000 Height = 18.897650000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clMaroon Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] Memo.UTF8W = ( 'Hora') ParentFont = False Style = 'Header' end object Memo8: TfrxMemoView Left = 111.897650000000000000 Top = 37.795300000000000000 Width = 78.000000000000000000 Height = 18.897650000000000000 DataField = 'horario' DataSet = frxDBDataset2 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Cambria' Font.Style = [] Memo.UTF8W = ( '[frxDBDataset1."horario"]') ParentFont = False end object Memo9: TfrxMemoView Top = 56.692949999999990000 Width = 93.000000000000000000 Height = 18.897650000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clMaroon Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] Memo.UTF8W = ( 'Descri'#231#227'o') ParentFont = False Style = 'Header' end object Memo10: TfrxMemoView Left = 111.897650000000000000 Top = 56.692949999999990000 Width = 592.016080000000000000 Height = 18.897650000000000000 DataField = 'descricao' DataSet = frxDBDataset2 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Cambria' Font.Style = [] Memo.UTF8W = ( '[frxDBDataset1."descricao"]') ParentFont = False end object Memo11: TfrxMemoView Top = 75.590600000000000000 Width = 93.000000000000000000 Height = 18.897650000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clMaroon Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] Memo.UTF8W = ( 'Endere'#231'o') ParentFont = False Style = 'Header' end object Memo12: TfrxMemoView Left = 111.897650000000000000 Top = 75.590600000000000000 Width = 592.016080000000000000 Height = 18.897650000000000000 DataField = 'endereco' DataSet = frxDBDataset2 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Cambria' Font.Style = [] Memo.UTF8W = ( '[frxDBDataset1."endereco"]') ParentFont = False end object Memo13: TfrxMemoView Top = 94.488250000000000000 Width = 93.000000000000000000 Height = 18.897650000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clMaroon Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] Memo.UTF8W = ( 'Cidade') ParentFont = False Style = 'Header' end object Memo14: TfrxMemoView Left = 111.897650000000000000 Top = 94.488250000000000000 Width = 593.000000000000000000 Height = 18.897650000000000000 DataField = 'cidade' DataSet = frxDBDataset2 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Cambria' Font.Style = [] Memo.UTF8W = ( '[frxDBDataset1."cidade"]') ParentFont = False end object Memo15: TfrxMemoView Top = 113.385900000000000000 Width = 93.000000000000000000 Height = 18.897650000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clMaroon Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] Memo.UTF8W = ( 'Uf') ParentFont = False Style = 'Header' end object Memo16: TfrxMemoView Left = 111.897650000000000000 Top = 113.385900000000000000 Width = 593.000000000000000000 Height = 18.897650000000000000 DataField = 'uf' DataSet = frxDBDataset2 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Cambria' Font.Style = [] Memo.UTF8W = ( '[frxDBDataset1."uf"]') ParentFont = False end object Memo17: TfrxMemoView Top = 132.283550000000000000 Width = 93.000000000000000000 Height = 18.897650000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clMaroon Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] Memo.UTF8W = ( 'Urg'#234'ncia') ParentFont = False Style = 'Header' end object Memo18: TfrxMemoView Left = 111.897650000000000000 Top = 132.283550000000000000 Width = 225.000000000000000000 Height = 18.897650000000000000 DataField = 'urgencia' DataSet = frxDBDataset2 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Cambria' Font.Style = [] Memo.UTF8W = ( '[frxDBDataset1."urgencia"]') ParentFont = False end object Memo19: TfrxMemoView Top = 151.181200000000000000 Width = 93.000000000000000000 Height = 18.897650000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clMaroon Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] Memo.UTF8W = ( 'Situa'#231#227'o') ParentFont = False Style = 'Header' end object Memo20: TfrxMemoView Left = 111.897650000000000000 Top = 151.181200000000000000 Width = 225.000000000000000000 Height = 18.897650000000000000 DataField = 'situacao' DataSet = frxDBDataset2 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Cambria' Font.Style = [] Memo.UTF8W = ( '[frxDBDataset1."situacao"]') ParentFont = False end object Line1: TfrxLineView Top = 181.417440000000000000 Width = 978.898270000000000000 Color = clBlack Diagonal = True end object Line2: TfrxLineView Left = 755.906000000000000000 Top = 147.401670000000000000 Width = 207.874150000000000000 Color = clBlack Diagonal = True end object Memo2: TfrxMemoView Left = 751.706522220000000000 Top = 154.540782220000000000 Width = 209.973888890000000000 Height = 16.797911110000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] HAlign = haCenter Memo.UTF8W = ( 'T'#233'cnico em Inform'#225'tica') ParentFont = False VAlign = vaCenter end end object ReportTitle1: TfrxReportTitle FillType = ftBrush Height = 26.456710000000000000 Top = 18.897650000000000000 Width = 980.410081999999900000 object Memo1: TfrxMemoView Align = baWidth Width = 980.410081999999900000 Height = 22.677180000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clWhite Font.Height = -16 Font.Name = 'Arial' Font.Style = [fsBold] Fill.BackColor = clGray HAlign = haCenter Memo.UTF8W = ( 'Relat'#243'rio de Chamadas Finalizadas') ParentFont = False Style = 'Title' VAlign = vaCenter end end object PageFooter1: TfrxPageFooter FillType = ftBrush Height = 45.354360000000000000 Top = 359.055350000000000000 Width = 980.410081999999900000 object Memo21: TfrxMemoView Align = baWidth Top = 18.897650000000110000 Width = 980.410081999999900000 Frame.Typ = [ftTop] Frame.Width = 2.000000000000000000 end object Memo22: TfrxMemoView Top = 19.897650000000110000 Height = 22.677180000000000000 AutoWidth = True Memo.UTF8W = ( '[Date] [Time]') end object Memo23: TfrxMemoView Align = baRight Left = 904.819481999999900000 Top = 19.897650000000110000 Width = 75.590600000000000000 Height = 22.677180000000000000 HAlign = haRight Memo.UTF8W = ( 'Page [Page#]') end end end end end
42.207539
149
0.756835
835302df8de75cd50c92f80961343d667456ebfb
3,563
pas
Pascal
source/_ident.pas
cliffordwolf/kugelfu
d3da891efbe1132e86a42658db49c1731197915d
[ "0BSD" ]
null
null
null
source/_ident.pas
cliffordwolf/kugelfu
d3da891efbe1132e86a42658db49c1731197915d
[ "0BSD" ]
null
null
null
source/_ident.pas
cliffordwolf/kugelfu
d3da891efbe1132e86a42658db49c1731197915d
[ "0BSD" ]
1
2021-04-02T16:31:34.000Z
2021-04-02T16:31:34.000Z
UNIT _IDENT; INTERFACE TYPE _identblock = record username : string; usernumber : word; progsize : longint; chk1,chk2 : byte; end; VAR identblock : _identblock; PROCEDURE Ident_Lade(fname : string); PROCEDURE Ident_Save(fname : string); PROCEDURE Ident_ReadDat(fname : string); FUNCTION Ident_Teste(fname : string) : boolean; IMPLEMENTATION CONST chkxor = 123; falsch : boolean = false; TYPE _byte = ^byte; PROCEDURE Codiere(p : _byte); var h1,h2 : _byte; z1 : word; begin h1 := @identblock; h2 := p; for z1 := 1 to sizeof(_identblock) do begin h2^ := h1^ xor chkxor; h1 := ptr(seg(h1^),ofs(h1^)+1); h2 := ptr(seg(h2^),ofs(h2^)+1); end; h1 := @identblock; for z1 := 1 to sizeof(_identblock) do begin h2^ := h1^ xor $FF; h1 := ptr(seg(h1^),ofs(h1^)+1); h2 := ptr(seg(h2^),ofs(h2^)+1); end; end; PROCEDURE DeCodiere(p : _byte); var h1,h2 : _byte; z1 : word; begin h2 := @identblock; h1 := p; for z1 := 1 to sizeof(_identblock) do begin h2^ := h1^ xor chkxor; h1 := ptr(seg(h1^),ofs(h1^)+1); h2 := ptr(seg(h2^),ofs(h2^)+1); end; h2 := @identblock; for z1 := 1 to sizeof(_identblock) do begin if h2^ <> h1^ xor $FF then falsch := true; h1 := ptr(seg(h1^),ofs(h1^)+1); h2 := ptr(seg(h2^),ofs(h2^)+1); end; end; PROCEDURE Ident_Lade(fname : string); var f : file; p : _byte; begin assign(f,fname); reset(f,1); getmem(p,sizeof(_identblock)*2); blockread(f,p^,sizeof(_identblock)*2); decodiere(p); freemem(p,sizeof(_identblock)*2); close(f); end; PROCEDURE Ident_Save(fname : string); var f : file; p : _byte; begin assign(f,fname); rewrite(f,1); getmem(p,sizeof(_identblock)*2); codiere(p); blockwrite(f,p^,sizeof(_identblock)*2); freemem(p,sizeof(_identblock)*2); close(f); end; PROCEDURE Ident_ReadDat(fname : string); var f : file; p,h1 : _byte; gr,z1 : word; hck1,hck2 : byte; begin assign(f,fname); reset(f,1); hck1 := 0; hck2 := 0; repeat if filesize(f)-filepos(f) < $FF00 then gr := filesize(f)-filepos(f) else gr := $FF00; getmem(p,gr); blockread(f,p^,gr); h1 := p; for z1 := 1 to gr do begin hck1 := hck1 xor h1^; hck2 := hck2 + h1^; h1 := ptr(seg(h1^),ofs(h1^)+1); end; freemem(p,gr); until eof(f); with identblock do begin progsize := filesize(f); chk1 := hck1; chk2 := hck2; end; close(f); end; FUNCTION Ident_Teste(fname : string) : boolean; var f : file; p,h1 : _byte; gr,z1 : word; hck1,hck2 : byte; begin assign(f,fname); reset(f,1); if filesize(f) <> identblock.progsize then falsch := true; hck1 := 0; hck2 := 0; repeat if filesize(f)-filepos(f) < $FF00 then gr := filesize(f)-filepos(f) else gr := $FF00; getmem(p,gr); blockread(f,p^,gr); h1 := p; for z1 := 1 to gr do begin hck1 := hck1 xor h1^; hck2 := hck2 + h1^; h1 := ptr(seg(h1^),ofs(h1^)+1); end; freemem(p,gr); until eof(f); close(f); if hck1 <> identblock.chk1 then falsch := true; if hck2 <> identblock.chk2 then falsch := true; ident_teste := not falsch; end; BEGIN END.
21.72561
72
0.527645
6ac99ae16cc5be2260f79755063668bd250d53a9
1,926
pas
Pascal
rtl/test/dutil.sys.win32.PlatformTest.pas
stanleyxu2005/dutil
3dcf11b5894fc09ea97b7d803b7a9fcbb3bd83f0
[ "MIT" ]
1
2020-04-22T15:42:00.000Z
2020-04-22T15:42:00.000Z
rtl/test/dutil.sys.win32.PlatformTest.pas
stanleyxu2005/dutil
3dcf11b5894fc09ea97b7d803b7a9fcbb3bd83f0
[ "MIT" ]
3
2016-03-19T05:05:05.000Z
2016-03-24T14:10:19.000Z
rtl/test/dutil.sys.win32.PlatformTest.pas
stanleyxu2005/dutil
3dcf11b5894fc09ea97b7d803b7a9fcbb3bd83f0
[ "MIT" ]
null
null
null
unit dutil.sys.win32.PlatformTest; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, dutil.sys.win32.Platform, Windows; type // Test methods for class TPlatform TPlatformTest = class(TTestCase) strict private FPlatform: TPlatform; public procedure SetUp; override; procedure TearDown; override; published procedure TestVersionGreaterThanOrEquals; procedure TestVersionGreaterThanOrEquals_Failed; end; implementation procedure TPlatformTest.SetUp; begin FPlatform := TPlatform.Create; end; procedure TPlatformTest.TearDown; begin FPlatform.Free; FPlatform := nil; end; procedure TPlatformTest.TestVersionGreaterThanOrEquals; var ReturnValue: Boolean; ServicePackMinor: Word; ServicePackMajor: Word; Minor: System.Cardinal; Major: System.Cardinal; begin ServicePackMajor := 0; ServicePackMinor := 0; Minor := 5; Major := 0; ReturnValue := FPlatform.VersionGreaterThanOrEquals(Major, Minor, ServicePackMajor, ServicePackMinor); CheckTrue(ReturnValue, 'Operating system is older than Windows 2000?'); end; procedure TPlatformTest.TestVersionGreaterThanOrEquals_Failed; var ReturnValue: Boolean; ServicePackMinor: Word; ServicePackMajor: Word; Minor: System.Cardinal; Major: System.Cardinal; begin ServicePackMajor := 0; ServicePackMinor := 0; Minor := 0; Major := 99; ReturnValue := FPlatform.VersionGreaterThanOrEquals(Major, Minor, ServicePackMajor, ServicePackMinor); CheckFalse(ReturnValue, 'Operating system is too modern?'); end; initialization // Register any test cases with the test runner RegisterTest(TPlatformTest.Suite); end.
23.204819
105
0.728453
47ec6a92f4a2d8f793d50ad02dc1f7186e806f70
17,653
pas
Pascal
library/fhir/fhir_colour_utils.pas
grahamegrieve/fhirserver
28f69977bde75490adac663e31a3dd77bc016f7c
[ "BSD-3-Clause" ]
132
2015-02-02T00:22:40.000Z
2021-08-11T12:08:08.000Z
library/fhir/fhir_colour_utils.pas
grahamegrieve/fhirserver
28f69977bde75490adac663e31a3dd77bc016f7c
[ "BSD-3-Clause" ]
113
2015-03-20T01:55:20.000Z
2021-10-08T16:15:28.000Z
library/fhir/fhir_colour_utils.pas
grahamegrieve/fhirserver
28f69977bde75490adac663e31a3dd77bc016f7c
[ "BSD-3-Clause" ]
49
2015-04-11T14:59:43.000Z
2021-03-30T10:29:18.000Z
unit fhir_colour_utils; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) 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 HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } {$I fhir.inc} interface uses SysUtils, Math, SysConst, Graphics, fsl_utilities; type TColour = integer; THTMLColours = ( hcAliceblue, hcAntiquewhite, hcAqua, hcAquamarine, hcAzure, hcBeige, hcBisque, hcBlack, hcBlanchedalmond, hcBlue, hcBlueviolet, hcBrown, hcBurlywood, hcCadetblue, hcChartreuse, hcChocolate, hcCoral, hcCornflowerblue, hcCornsilk, hcCrimson, hcCyan, hcDarkblue, hcDarkcyan, hcDarkgoldenrod, hcDarkgray, hcDarkgreen, hcDarkkhaki, hcDarkmagenta, hcDarkolivegreen, hcDarkorange, hcDarkorchid, hcDarkred, hcDarksalmon, hcDarkseagreen, hcDarkslateblue, hcDarkslategray, hcDarkturquoise, hcDarkviolet, hcdeeppink, hcDeepskyblue, hcDimgray, hcDodgerblue, hcFirebrick, hcFloralwhite, hcForestgreen, hcFuchsia, hcGainsboro, hcGhostwhite, hcGold, hcGoldenrod, hcGray, hcGreen, hcGreenyellow, hcHoneydew, hcHotpink, hcIndianred, hcIndigo, hcIvory, hcKhaki, hcLavendar, hcLavenderblush, hcLawngreen, hcLemonchiffon, hcLightblue, hcLightcoral, hcLightcyan, hcLightgoldenrodyellow, hcLightgreen, hcLightgrey, hcLightpink, hcLightsalmon, hcLightseagreen, hcLightskyblue, hcLightslategray, hcLightsteelblue, hcLightyellow, hcLime, hcLimegreen, hcLinen, hcMagenta, hcMaroon, hcMediumauqamarine, hcMediumblue, hcMediumorchid, hcMediumpurple, hcMediumseagreen, hcMediumslateblue, hcMediumspringgreen, hcMediumturquoise, hcMediumvioletred, hcMidnightblue, hcMintcream, hcMistyrose, hcMoccasin, hcNavajowhite, hcNavy, hcOldlace, hcOlive, hcOlivedrab, hcOrange, hcOrangered, hcOrchid, hcPalegoldenrod, hcPalegreen, hcPaleturquoise, hcPalevioletred, hcPapayawhip, hcPeachpuff, hcPeru, hcPink, hcPlum, hcPowderblue, hcPurple, hcRed, hcRosybrown, hcRoyalblue, hcSaddlebrown, hcSalmon, hcSandybrown, hcSeagreen, hcSeashell, hcSienna, hcSilver, hcSkyblue, hcSlateblue, hcSlategray, hcSnow, hcSpringgreen, hcSteelblue, hcTan, hcTeal, hcThistle, hcTomato, hcTurquoise, hcViolet, hcWheat, hcWhite, hcWhitesmoke, hcYellow, hcYellowGreen); Const CURRENCY_MINIMUM = -922337203685477.58; CURRENCY_MAXIMUM = 922337203685477.58; clTransparent = -1; HTML_COLOUR_VALUES : Array [THTMLColours] Of TColour = ( $00FFF8F0, $00D7EBFA, $00FFFF00, $00D4FF7F, $00FFFFF0, $00DCF5F5, $00C4E4FF, $00000000, $00CDEBFF, $00FF0000, $00E22B8A, $002A2AA5, $0087B8DE, $00A09E5F, $0000FF7F, $001E69D2, $00507FFF, $00ED9564, $00DCF8FF, $003C14DC, $00FFFF00, $008B0000, $008B8B00, $000B86B8, $00A9A9A9, $00006400, $006BB7BD, $008B008B, $002F6B55, $00008CFF, $00CC3299, $0000008B, $007A96E9, $008FBC8F, $008B3D48, $004F4F2F, $00D1CE00, $00D30094, $009314FF, $00FFBF00, $00696969, $00FF901E, $002222B2, $00F0FAFF, $00228B22, $00FF00FF, $00DCDCDC, $00FFF8F8, $0000D7FF, $0020A5DA, $00808080, $00008000, $002FFFAD, $00F0FFF0, $00B469FF, $005C5CCD, $0082004B, $00F0FFFF, $008CE6F0, $00FAE6E6, $00F5F0FF, $0000FC7C, $00CDFAFF, $00E6D8AD, $008080F0, $00FFFFE0, $00D2FAFA, $0090EE90, $00D3D3D3, $00C1B6FF, $007AA0FF, $00AAB220, $00FACE87, $00998877, $00DEC4B0, $00E0FFFF, $0000FF00, $0032CD32, $00E6F0FA, $00FF00FF, $00000080, $00AACD66, $00CD0000, $00D355BA, $00D87093, $0071B33C, $00EE687B, $009AFA00, $00CCD148, $008515C7, $00701919, $00FAFFF5, $00E1E4FF, $00B5E4FF, $00ADDEFF, $00800000, $00E6F5FD, $00008080, $00238E68, $0000A5FF, $000045FF, $00D670DA, $00AAE8EE, $0098FB98, $00EEEEAF, $009370D8, $00D5EFFF, $00B9DAFF, $003F85CD, $00CBC0FF, $00DDA0DD, $00E6E0B0, $00800080, $000000FF, $008F8FBC, $00E16941, $0013458B, $007280FA, $0060A4F4, $00578B2E, $00EEF5FF, $002D52A0, $00C0C0C0, $00EBCE87, $00CD5A6A, $00908070, $00FAFAFF, $007FFF00, $00B48246, $008CB4D2, $00808000, $00D8BFD8, $004763FF, $00D0E040, $00EE82EE, $00B3DEF5, $00FFFFFF, $00F5F5F5, $0000FFFF, $0032CD9A); HTML_COLOUR_NAMES : Array [THTMLColours] Of String = ( 'Aliceblue', 'Antiquewhite', 'Aqua', 'Aquamarine', 'Azure', 'Beige', 'Bisque', 'Black', 'Blanchedalmond', 'Blue', 'Blueviolet', 'Brown', 'Burlywood', 'Cadetblue', 'Chartreuse', 'Chocolate', 'Coral', 'Cornflowerblue', 'Cornsilk', 'Crimson', 'Cyan', 'Darkblue', 'Darkcyan', 'Darkgoldenrod', 'Darkgray', 'Darkgreen', 'Darkkhaki', 'Darkmagenta', 'Darkolivegreen', 'Darkorange', 'Darkorchid', 'Darkred', 'Darksalmon', 'Darkseagreen', 'Darkslateblue', 'Darkslategray', 'Darkturquoise', 'Darkviolet', 'deeppink', 'Deepskyblue', 'Dimgray', 'Dodgerblue', 'Firebrick', 'Floralwhite', 'Forestgreen', 'Fuchsia', 'Gainsboro', 'Ghostwhite', 'Gold', 'Goldenrod', 'Gray', 'Green', 'Greenyellow', 'Honeydew', 'Hotpink', 'Indianred', 'Indigo', 'Ivory', 'Khaki', 'Lavendar', 'Lavenderblush', 'Lawngreen', 'Lemonchiffon', 'Lightblue', 'Lightcoral', 'Lightcyan', 'Lightgoldenrodyellow', 'Lightgreen', 'Lightgrey', 'Lightpink', 'Lightsalmon', 'Lightseagreen', 'Lightskyblue', 'Lightslategray', 'Lightsteelblue', 'Lightyellow', 'Lime', 'Limegreen', 'Linen', 'Magenta', 'Maroon', 'Mediumauqamarine', 'Mediumblue', 'Mediumorchid', 'Mediumpurple', 'Mediumseagreen', 'Mediumslateblue', 'Mediumspringgreen', 'Mediumturquoise', 'Mediumvioletred', 'Midnightblue', 'Mintcream', 'Mistyrose', 'Moccasin', 'Navajowhite', 'Navy', 'Oldlace', 'Olive', 'Olivedrab', 'Orange', 'Orangered', 'Orchid', 'Palegoldenrod', 'Palegreen', 'Paleturquoise', 'Palevioletred', 'Papayawhip', 'Peachpuff', 'Peru', 'Pink', 'Plum', 'Powderblue', 'Purple', 'Red', 'Rosybrown', 'Royalblue', 'Saddlebrown', 'Salmon', 'Sandybrown', 'Seagreen', 'Seashell', 'Sienna', 'Silver', 'Skyblue', 'Slateblue', 'Slategray', 'Snow', 'Springgreen', 'Steelblue', 'Tan', 'Teal', 'Thistle', 'Tomato', 'Turquoise', 'Violet', 'Wheat', 'White', 'Whitesmoke', 'Yellow', 'YellowGreen'); HTML_COLOUR_TITLES : Array [THTMLColours] Of String = ( 'Alice Blue', 'Antique White', 'Aqua', 'Aquamarine', 'Azure', 'Beige', 'Bisque', 'Black', 'Blanched Almond', 'Blue', 'Blue Violet', 'Brown', 'Burlywood', 'Cadet Blue', 'Chartreuse', 'Chocolate', 'Coral', 'Cornflower Blue', 'Cornsilk', 'Crimson', 'Cyan', 'Dark Blue', 'Dark Cyan', 'Dark Goldenrod', 'Dark Gray', 'Dark Green', 'Dark Khaki', 'Dark Magenta', 'Dark Olive Green', 'Dark Orange', 'Dark Orchid', 'Dark Red', 'Dark Salmon', 'Dark Sea Green', 'Dark Slate Blue', 'Dark Slate Gray', 'Dark Turquoise', 'Dark Violet', 'Deep Pink', 'Deep Sky Blue', 'Dim Gray', 'Dodger Blue', 'Firebrick', 'Floral White', 'Forest Green', 'Fuchsia', 'Gainsboro', 'Ghost White', 'Gold', 'Goldenrod', 'Gray', 'Green', 'Green Yellow', 'Honeydew', 'Hot Pink', 'Indian Red', 'Indigo', 'Ivory', 'Khaki', 'Lavendar', 'Lavender Blush', 'Lawn Green', 'Lemon Chiffon', 'Light Blue', 'Light Coral', 'Light Cyan', 'Light Goldenrod Yellow', 'Light Green', 'Light Grey', 'Light Pink', 'Light Salmon', 'Light Sea Green', 'Light Sky Blue', 'Light Slate Gray', 'Light Steel Blue', 'Light Yellow', 'Lime', 'Lime Green', 'Linen', 'Magenta', 'Maroon', 'Medium Aquamarine', 'Medium Blue', 'Medium Orchid', 'Medium Purple', 'Medium Seagreen', 'Medium Slate Blue', 'Medium Spring Green', 'Medium Turquoise', 'Medium Violet Red', 'Midnight Blue', 'Mint Cream', 'Misty Rose', 'Moccasin', 'Navajo White', 'Navy', 'Old Lace', 'Olive', 'Olive Drab', 'Orange', 'Orange Red', 'Orchid', 'Pale Goldenrod', 'Pale Green', 'Pale Turquoise', 'Pale Violet Red', 'Papaya Whip', 'Peach Puff', 'Peru', 'Pink', 'Plum', 'Powder Blue', 'Purple', 'Red', 'Rosy Brown', 'Royal Blue', 'Saddle Brown', 'Salmon', 'Sandy Brown', 'Sea Green', 'Seashell', 'Sienna', 'Silver', 'Sky Blue', 'Slate Blue', 'Slate Gray', 'Snow', 'Spring Green', 'Steel Blue', 'Tan', 'Teal', 'Thistle', 'Tomato', 'Turquoise', 'Violet', 'Wheat', 'White', 'White Smoke', 'Yellow', 'Yellow Green'); Type TColourRatio = Record Blue : Real; Green : Real; Red : Real; Alpha : Real; End; TColourParts = Packed Record Red : Byte; Green : Byte; Blue : Byte; Alpha : Byte; End; Function ColourCompose(iRed, iGreen, iBlue, iAlpha : Byte) : TColour; Overload; Function HTMLColourStringToColour(Const sColour : String; Const aDefault : TColour) : TColour; Overload; Function HTMLColourStringToColour(Const sColour : String) : TColour; Overload; Function StringIsHTMLColour(Const sColour : String) : Boolean; Overload; Function HTMLEncodedColourStringToColour(Const sColour : String) : TColour; Overload; Function HTMLEncodedColourStringToColour(Const sColour : String; Const aDefault : TColour) : TColour; Overload; Function ColourToHTMLColourString(Const iColour : TColour) : String; Overload; Function ColourToHTMLColourTitleString(Const iColour : TColour) : String; Overload; Function ColourToXMLColourString(Const iColour : TColour) : String; Overload; Function XMLColourStringToColour(Const sColour : String) : TColour; Overload; Function XMLColourStringToColourOrDefault(Const sColour : String; Const aDefault : TColour) : TColour; Overload; Function ColourMakeGrey(iColour : TColour) : TColour; Overload; Function ColourMultiply(iColour : TColour; Const aRatio : TColourRatio) : TColour; Overload; Function ColourMultiply(iColour : TColour; Const iRatio : Real) : TColour; Overload; Function ColourInverse(iColour : TColour) : TColour; Function ColourToString(iColour : TColour) : String; Overload; implementation Function ColourCompose(iRed, iGreen, iBlue, iAlpha : Byte) : TColour; Begin TColourParts(Result).Red := iRed; TColourParts(Result).Green := iGreen; TColourParts(Result).Blue := iBlue; TColourParts(Result).Alpha := iAlpha; End; Function ColourMultiply(iColour : TColour; Const iRatio : Real) : TColour; Begin TColourParts(Result).Red := Trunc(RealMin(TColourParts(iColour).Red * iRatio, 255)); TColourParts(Result).Green := Trunc(RealMin(TColourParts(iColour).Green * iRatio, 255)); TColourParts(Result).Blue := Trunc(RealMin(TColourParts(iColour).Blue * iRatio, 255)); TColourParts(Result).Alpha := Trunc(RealMin(TColourParts(iColour).Alpha * iRatio, 255)); End; Function ColourMultiply(iColour : TColour; Const aRatio : TColourRatio) : TColour; Begin TColourParts(Result).Red := Trunc(RealMin(TColourParts(iColour).Red * aRatio.Red, 255)); TColourParts(Result).Green := Trunc(RealMin(TColourParts(iColour).Green * aRatio.Green, 255)); TColourParts(Result).Blue := Trunc(RealMin(TColourParts(iColour).Blue * aRatio.Blue, 255)); TColourParts(Result).Alpha := Trunc(RealMin(TColourParts(iColour).Alpha * aRatio.Alpha, 255)); End; Function ColourInverse(iColour : TColour) : TColour; Begin TColourParts(Result).Red := Abs(255 - TColourParts(iColour).Red); TColourParts(Result).Green := Abs(255 - TColourParts(iColour).Green); TColourParts(Result).Blue := Abs(255 - TColourParts(iColour).Blue); TColourParts(Result).Alpha := TColourParts(iColour).Alpha; End; Function ColourToString(iColour : TColour) : String; Begin {$IFDEF FPC} result := Graphics.ColorToString(iColour); {$ELSE} Result := ColorToString(iColour); {$ENDIF} End; Function ColourMakeGrey(iColour : TColour) : TColour; Overload; var c : Word; Begin c := Trunc((TColourParts(iColour).Red + TColourParts(iColour).Green + TColourParts(iColour).Blue) / 3); TColourParts(Result).Red := c; TColourParts(Result).Green := c; TColourParts(Result).Blue := c; TColourParts(Result).Alpha := TColourParts(iColour).Alpha; End; Function HTMLColourStringToColour(Const sColour : String; Const aDefault : TColour) : TColour; Var iIndex : Integer; Begin iIndex := StringArrayIndexOf(HTML_COLOUR_NAMES, sColour); If iIndex = -1 Then iIndex := StringArrayIndexOf(HTML_COLOUR_TITLES, sColour); If iIndex > -1 Then Result := HTML_COLOUR_VALUES[THTMLColours(iIndex)] Else Result := HTMLEncodedColourStringToColour(sColour, aDefault); End; Function HTMLColourStringToColour(Const sColour : String) : TColour; Begin Result := HTMLColourStringToColour(sColour, 0); End; Function StringIsHTMLColour(Const sColour : String) : Boolean; Begin Result := StringArrayExistsInsensitive(HTML_COLOUR_NAMES, sColour) Or StringArrayExistsInsensitive(HTML_COLOUR_TITLES, sColour) Or ((Length(sColour) = 7) And (sColour[1] = '#') And StringIsHexadecimal(Copy(sColour, 2, 2)) And StringIsHexadecimal(Copy(sColour, 4, 2)) And StringIsHexadecimal(Copy(sColour, 6, 2))); End; Function HTMLEncodedColourStringToColour(Const sColour : String; Const aDefault : TColour) : TColour; Begin If (Length(sColour) < 7) Or (sColour[1] <> '#') Then Result := aDefault Else Begin TColourParts(Result).Red := DecodeHexadecimal(AnsiChar(sColour[2]), AnsiChar(sColour[3])); TColourParts(Result).Green := DecodeHexadecimal(AnsiChar(sColour[4]), AnsiChar(sColour[5])); TColourParts(Result).Blue := DecodeHexadecimal(AnsiChar(sColour[6]), AnsiChar(sColour[7])); TColourParts(Result).Alpha := 0; End; End; Function HTMLEncodedColourStringToColour(Const sColour : String) : TColour; Begin Result := HTMLEncodedColourStringToColour(sColour, 0); End; Function ColourToHTMLEncodedColourString(Const iColour : TColour) : String; Begin Result := '#' + string(EncodeHexadecimal(TColourParts(iColour).Red) + EncodeHexadecimal(TColourParts(iColour).Green) + EncodeHexadecimal(TColourParts(iColour).Blue)); End; Function ColourToHTMLColourString(Const iColour : TColour) : String; Var iIndex : Integer; Begin iIndex := IntegerArrayIndexOf(HTML_COLOUR_VALUES, iColour); If iIndex > -1 Then Result := HTML_COLOUR_NAMES[THTMLColours(iIndex)] Else Result := ColourToHTMLEncodedColourString(iColour); End; Function ColourToHTMLColourTitleString(Const iColour : TColour) : String; Var iIndex : Integer; Begin iIndex := IntegerArrayIndexOf(HTML_COLOUR_VALUES, iColour); If iIndex > -1 Then Result := HTML_COLOUR_TITLES[THTMLColours(iIndex)] Else Result := ColourToHTMLEncodedColourString(iColour); End; Function ColourToXMLColourString(Const iColour : TColour) : String; Begin If TColourParts(iColour).Alpha > 0 Then Result := string(EncodeHexadecimal(TColourParts(iColour).Alpha)) Else Result := ''; Result := '#' + string(EncodeHexadecimal(TColourParts(iColour).Red) + EncodeHexadecimal(TColourParts(iColour).Green) + EncodeHexadecimal(TColourParts(iColour).Blue)) + Result; End; Function XMLColourStringToColour(Const sColour : String) : TColour; Begin If (Length(sColour) >= 7) And (sColour[1] = '#') And StringIsHexadecimal(Copy(sColour, 2, Length(sColour))) Then Begin TColourParts(Result).Red := DecodeHexadecimal(AnsiChar(sColour[2]), AnsiChar(sColour[3])); TColourParts(Result).Green := DecodeHexadecimal(AnsiChar(sColour[4]), AnsiChar(sColour[5])); TColourParts(Result).Blue := DecodeHexadecimal(AnsiChar(sColour[6]), AnsiChar(sColour[7])); If (Length(sColour) >= 9) Then TColourParts(Result).Alpha := DecodeHexadecimal(AnsiChar(sColour[8]), AnsiChar(sColour[9])) Else TColourParts(Result).Alpha := $00; End Else Begin Result := HTMLEncodedColourStringToColour(sColour); End; End; Function XMLColourStringToColourOrDefault(Const sColour : String; Const aDefault : TColour) : TColour; Begin If sColour = '' Then Result := aDefault Else Result := XMLColourStringToColour(sColour); End; end.
46.949468
188
0.697558
47e1c5566f462e8cddbca7cc31e6d5f7e8824d87
5,808
pas
Pascal
kspconstsvars.pas
Tallefer/kspnew
57c69ac319c19e61ceb23e5a02759b98c9e4f8cd
[ "BSD-3-Clause" ]
1
2018-10-06T02:12:58.000Z
2018-10-06T02:12:58.000Z
kspconstsvars.pas
Tallefer/kspnew
57c69ac319c19e61ceb23e5a02759b98c9e4f8cd
[ "BSD-3-Clause" ]
null
null
null
kspconstsvars.pas
Tallefer/kspnew
57c69ac319c19e61ceb23e5a02759b98c9e4f8cd
[ "BSD-3-Clause" ]
1
2018-10-06T02:13:13.000Z
2018-10-06T02:13:13.000Z
{ -------------------------------------------------------------------- Copyright (c) 2009 KSP Developers Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 KSPConstsVars; {$I ksp_version.inc} interface uses FileSupportLst, SysUtils, BASSPlayer, Graphics, Classes, PresetsU, Playlists, app_db_utils, LCLType, ksplua, mplayer; const KSPHost = 'http://ksplayer.com'; KSPHost2 = KSPHost + '/?kmajor=%s&kminor=%s&krelease=%s&kbuild=%s&from_ksp=1'; KSPHowHelp = KSPHost + '/what-is-ksp/help-wanted'; KSPSupportURL = 'http://project.ksplayer.com'; KSPUpdates = 'http://ksplayer.com/updates.php?kbuild='; KSPTellAFriend = 'http://www.freetellafriend.com/tell/?u=5653&title=KSPSoundPlayer&url=http://ksplayer.com'; KSPMDir = KSPHost + '/music-links'; KSPMDirAdd = KSPMDir + '/add'; KSPForum = KSPHost + '/support/forum'; LWIKIA_MAIN = 'http://lyrics.wikia.com/'; DefSetupFileName = 'data\setup.opt'; BlockWidth = 6; VLimit = 59; HBlockCount = NumFFTBands; HBlockGap = 1; KSPPlaylistsVersion = '1'; CDefPlaylistFormat = '[%title] - [%artist] - [%album] ([%length])'; CFormatedHintInfo = '[%title] ([%length])- [%artist] - [%album]'; CDefSuggHintFormat = '[%title]' + #13 + '[%artist]' + #13 + '[%album]'; CFormatedHintInfoPls = '[%title] ([%length])- [%artist] - [%album]\n[%comment]'; DB_MAX_THREADS = 1; DB_MAX_THREADS2 = 1; //To be var MaxSuggestions = 10; TopItems = 10; VDJTimeOut = 5; //60sec const art = '[%artist]'; album = '[%album]'; title = '[%title]'; genre = '[%genre]'; year = '[%year]'; comment = '[%comment]'; track = '[%track]'; //database const InsStat = 'INSERT INTO meta (GID, Track, Comment, metaYear, Album,' + ' Artist, Title, PlayedEver, Meta, PlayCount, Fav, LastPlay, FirstPlay,' + ' FileName, Genre) Values(%s, %s, ''%s'', ''%s'', ''%s'', ''%s''' + ', ''%s'', %s, %s, %s, %s, ''%s'', ''%s'', ''%s'', ''%s'')'; InsStatNew = 'INSERT INTO meta (GID, Track, Comment, metaYear, Album,' + ' Artist, Title, PlayedEver, Meta, PlayCount, Fav, LastPlay, FirstPlay,' + ' FileName, Genre) Values(%s, %s, ''%s'', ''%s'', ''%s'', ''%s''' + ', ''%s'', %s, %s, %s, %s, ''%s'', ''%s'', ''%s'', ''%s'');'; UpdateStat = 'UPDATE meta SET GID = %s, Track = %s, Comment = ''%s''' + ', metaYear = ''%s'', Album = ''%s'', Artist = ''%s'', Title = ''%s''' + ', PlayedEver = %s, Meta = %s, PlayCount =%s, Fav =%s, LastPlay = ''%s''' + ', FirstPlay = ''%s'', FileName = ''%s'', Genre = ''%s'' WHERE FileName = ''%s'''; SelectGetItem = 'SELECT * FROM meta WHERE FileName=''%s'''; SelectGetItemLike = 'SELECT * FROM meta WHERE FileName LIKE ''%s'''; RemoveItem = 'DELETE FROM meta WHERE FileName = ''%s'''; RemoveItemDupl = 'DELETE FROM meta WHERE FileName = ''%s'' AND PlayCount=%s'; InsLyrics = 'INSERT INTO lyrics (lyric, item_id) VALUES (''%s'', %s)'; SelectLyrics = 'SELECT * FROM lyrics WHERE item_id=%s'; DelLyrics = 'DELETE FROM lyrics WHERE item_id=%s'; DB_VERSION = 5; {$IFNDEF WINDOWS} KSP_APP_FOLDER = '/usr/share/KSP/'; {$ENDIF} MAX_PATH_KSP = 4096; var SaveRemFolder: string; SetupFileName: string; HotKeyList: TList; KSPDataFolder: string; KSPVersion2: string; KSPVersion: string; AllSongs: TAppDBConnection; SuggestionList: TPlayList; SuggFindHelpPlaylist: TPlaylist; ScriptedAddons: TAddonManager; DefaultScript: string; FindApproxVals: TPlayList; EqList: TEqList; InsertingDataInThread: boolean; KSPAssociatedFiles: TStringList; AlreadyEncoding: boolean; KSPStartupTime: TDateTime; KSPLogFilename: string; KSPPluginsBlacklist: string; const ASKey = '053e8f8c040a00ba100a2eaf5aa17fd9'; ASTrackFeed = 'ws.audioscrobbler.com/2.0/?method=track.getsimilar&artist=%s&track=%s&api_key=' + ASKey; var {$IFDEF MULTI_PLAYER} Player: TMainPlayer; {$ELSE} Player: TBassPlayer; {$ENDIF} OSName: string; var FileSupportList: TFileSupportList; PeakValue: array[1..NumFFTBands] of single; PassedCounter: array[1..NumFFTBands] of integer; //Semaphores GetCountSem2: integer; LoadPlsSem2: integer; DBCritSection: LCLType.TCriticalSection; KSPCPUID: string; KSPMP3SettingsList: TStringList; implementation end.
33.572254
96
0.644284
472a92766b4a5e36b7e6ea6451c3bc39716aa313
936
pas
Pascal
Model/Entity/Menus.Model.Entity.Produtos.pas
FranlleyGomes/CertificacaoMVC
d62983ca106a8e9feee1df6a0d81bdad3798f07c
[ "MIT" ]
null
null
null
Model/Entity/Menus.Model.Entity.Produtos.pas
FranlleyGomes/CertificacaoMVC
d62983ca106a8e9feee1df6a0d81bdad3798f07c
[ "MIT" ]
null
null
null
Model/Entity/Menus.Model.Entity.Produtos.pas
FranlleyGomes/CertificacaoMVC
d62983ca106a8e9feee1df6a0d81bdad3798f07c
[ "MIT" ]
null
null
null
unit Menus.Model.Entity.Produtos; interface uses Menus.Model.Entity.Interfaces, System.Classes, Menus.Model.Conexoes.Interfaces; Type TModelEntityProdutos = class(TInterfacedObject, iModelEntity) private FDataSet : iModelDataSet; public constructor Create(DataSet : iModelDataSet); destructor Destroy; override; class function New(DataSet : iModelDataSet): iModelEntity; function Listar: TComponent; end; implementation const FTABLENAME = 'PRODUTOS'; { TModelEntityProdutos } constructor TModelEntityProdutos.Create(DataSet : iModelDataSet); begin FDataSet := DataSet; end; destructor TModelEntityProdutos.Destroy; begin inherited; end; function TModelEntityProdutos.Listar: TComponent; begin Result := FDataSet.Open(FTABLENAME).EndDataSet; end; class function TModelEntityProdutos.New(DataSet : iModelDataSet): iModelEntity; begin Result := Self.Create(DataSet); end; end.
19.102041
79
0.769231
47e949c918cd6f68235602e06c273ed206e885f1
19,248
pas
Pascal
Source/Windows/AT.Windows.Printers.dxProxy.pas
AngelicTech/ATLibrary
b4b629234e3eeee684a6bb49ca4d88e29d9e78ba
[ "BSL-1.0" ]
1
2021-08-09T18:45:25.000Z
2021-08-09T18:45:25.000Z
Source/Windows/AT.Windows.Printers.dxProxy.pas
AngelicTech/ATLibrary
b4b629234e3eeee684a6bb49ca4d88e29d9e78ba
[ "BSL-1.0" ]
null
null
null
Source/Windows/AT.Windows.Printers.dxProxy.pas
AngelicTech/ATLibrary
b4b629234e3eeee684a6bb49ca4d88e29d9e78ba
[ "BSL-1.0" ]
2
2021-08-09T18:45:27.000Z
2021-08-10T05:57:32.000Z
unit AT.Windows.Printers.dxProxy; interface uses Winapi.Windows, System.Classes, Vcl.Printers, Vcl.Graphics, dxPrnDev, Spring, Spring.Collections; type TATdxPrintProxy = class( TPrinter ) strict protected function GetAborted: Boolean; function GetAutoRefresh: Boolean; function GetBinIndex: Integer; function GetBins: TStrings; function GetCanvas: TCanvas; function GetCapabilities: TPrinterCapabilities; function GetCollate: Boolean; function GetColorMode: Boolean; function GetCopies: Integer; function GetCurrentDevice: PChar; function GetCurrentDriver: PChar; function GetCurrentPort: PChar; function GetDefaultDMPaper: Integer; function GetDeviceMode: PDeviceMode; function GetDuplex: TdxDuplexMode; function GetFileName: string; function GetFonts: TStrings; function GetHandle: HDC; function GetHDeviceMode: THandle; function GetIsDefault: Boolean; function GetIsDeviceModePersistent: Boolean; function GetIsInitialized: Boolean; function GetIsNetwork: Boolean; function GetMaxCopies: LongInt; function GetMaxExtentX: Integer; function GetMaxExtentY: Integer; function GetMinExtentX: Integer; function GetMinExtentY: Integer; function GetOnNewPage: TNotifyEvent; function GetOnPrinterChange: TNotifyEvent; function GetOnRefresh: TNotifyEvent; function GetOrientation: TPrinterOrientation; function GetPageHeight: Integer; function GetPageHeightLoMetric: Integer; function GetPageNumber: Integer; function GetPageWidth: Integer; function GetPageWidthLoMetric: Integer; function GetPaperCount: Integer; function GetPaperIndex: Integer; function GetPapers: TStrings; function GetPhysOffsetX: Integer; function GetPhysOffsetY: Integer; function GetPrinterCount: Integer; function GetPrinterIndex: Integer; function GetPrinterInfos( Index: Integer ): TdxPrintDeviceInfo; function GetPrinters: TStrings; function GetPrinting: Boolean; function GetTitle: string; procedure SetAutoRefresh( const Value: Boolean ); procedure SetBinIndex( const Value: Integer ); procedure SetCollate( const Value: Boolean ); procedure SetColorMode( const Value: Boolean ); procedure SetCopies( const Value: Integer ); procedure SetDuplex( const Value: TdxDuplexMode ); procedure SetFileName( const Value: string ); procedure SetIsDefault( const Value: Boolean ); procedure SetIsDeviceModePersistent( const Value: Boolean ); procedure SetOnNewPage( const Value: TNotifyEvent ); procedure SetOnPrinterChange( const Value: TNotifyEvent ); procedure SetOnRefresh( const Value: TNotifyEvent ); procedure SetOrientation( const Value: TPrinterOrientation ); procedure SetPaperIndex( const Value: Integer ); procedure SetPrinterIndex( const Value: Integer ); procedure SetTitle( const Value: string ); public procedure Abort; reintroduce; function BeginDoc: Integer; reintroduce; overload; procedure EndDoc; reintroduce; function FindBin( ABin: Integer ): Integer; overload; function FindBin( const AName: string ): Integer; overload; function FindPaper( ADMPaper: Integer ): Integer; overload; function FindPaper( AWidth, AHeight: Integer ): Integer; overload; function FindPaper( const AName: string ): Integer; overload; function FindPaper( const ASize: TPoint ): Integer; overload; function FindPrintDevice( ADevice, APort: PChar ): Integer; function IsAutoSelectBin( AIndex: Integer ): Boolean; function IsDeviceModeChanged: Boolean; function IsEnvelopePaper( AIndex: Integer ): Boolean; function IsSupportColoration: Boolean; function IsSupportDuplex: Boolean; function IsUserPaperSize( AIndex: Integer ): Boolean; function IsUserPaperSource( AIndex: Integer ): Boolean; procedure NewPage; reintroduce; procedure Refresh; reintroduce; procedure ResetDC( IsForced: Boolean ); procedure ResetPrintDevice; function SelectBin( Value: Integer ): Boolean; overload; function SelectBin( const AName: string ): Boolean; overload; function SelectPaper( ADMPaper: Integer ): Boolean; overload; function SelectPaper( var AWidth, AHeight: Integer ) : Boolean; overload; function SelectPaper( const AName: string ): Boolean; overload; property Aborted: Boolean read GetAborted; property AutoRefresh: Boolean read GetAutoRefresh write SetAutoRefresh; property BinIndex: Integer read GetBinIndex write SetBinIndex; property Bins: TStrings read GetBins; property Canvas: TCanvas read GetCanvas; property Capabilities: TPrinterCapabilities read GetCapabilities; property Collate: Boolean read GetCollate write SetCollate; property ColorMode: Boolean read GetColorMode write SetColorMode; property Copies: Integer read GetCopies write SetCopies; property CurrentDevice: PChar read GetCurrentDevice; property CurrentDriver: PChar read GetCurrentDriver; property CurrentPort: PChar read GetCurrentPort; property DefaultDMPaper: Integer read GetDefaultDMPaper; property DeviceMode: PDeviceMode read GetDeviceMode; property Duplex: TdxDuplexMode read GetDuplex write SetDuplex; property FileName: string read GetFileName write SetFileName; property Fonts: TStrings read GetFonts; property Handle: HDC read GetHandle; property HDeviceMode: THandle read GetHDeviceMode; property IsDefault: Boolean read GetIsDefault write SetIsDefault; property IsDeviceModePersistent: Boolean read GetIsDeviceModePersistent write SetIsDeviceModePersistent; property IsInitialized: Boolean read GetIsInitialized; property IsNetwork: Boolean read GetIsNetwork; property MaxCopies: LongInt read GetMaxCopies; property MaxExtentX: Integer read GetMaxExtentX; property MaxExtentY: Integer read GetMaxExtentY; property MinExtentX: Integer read GetMinExtentX; property MinExtentY: Integer read GetMinExtentY; property Orientation: TPrinterOrientation read GetOrientation write SetOrientation; property PageHeight: Integer read GetPageHeight; property PageHeightLoMetric: Integer read GetPageHeightLoMetric; property PageNumber: Integer read GetPageNumber; property PageWidth: Integer read GetPageWidth; property PageWidthLoMetric: Integer read GetPageWidthLoMetric; property PaperCount: Integer read GetPaperCount; property PaperIndex: Integer read GetPaperIndex write SetPaperIndex; property Papers: TStrings read GetPapers; property PhysOffsetX: Integer read GetPhysOffsetX; property PhysOffsetY: Integer read GetPhysOffsetY; property PrinterCount: Integer read GetPrinterCount; property PrinterIndex: Integer read GetPrinterIndex write SetPrinterIndex; property PrinterInfos[ Index: Integer ]: TdxPrintDeviceInfo read GetPrinterInfos; property Printers: TStrings read GetPrinters; property Printing: Boolean read GetPrinting; property Title: string read GetTitle write SetTitle; property OnNewPage: TNotifyEvent read GetOnNewPage write SetOnNewPage; property OnPrinterChange: TNotifyEvent read GetOnPrinterChange write SetOnPrinterChange; property OnRefresh: TNotifyEvent read GetOnRefresh write SetOnRefresh; end; function ATdxPrintProxy: TATdxPrintProxy; function Printer: TATdxPrintProxy; implementation uses System.SysUtils, System.UITypes, AT.GarbageCollector; var gPrintProxy: TATdxPrintProxy; function ATdxPrintProxy: TATdxPrintProxy; begin if ( NOT Assigned( gPrintProxy ) ) then gPrintProxy := TATdxPrintProxy.Create; Result := gPrintProxy; end; function Printer: TATdxPrintProxy; begin Result := ATdxPrintProxy; end; procedure TATdxPrintProxy.Abort; begin dxPrintDevice.Abort; end; function TATdxPrintProxy.BeginDoc: Integer; begin Result := dxPrintDevice.BeginDoc; end; procedure TATdxPrintProxy.EndDoc; begin dxPrintDevice.EndDoc; end; function TATdxPrintProxy.FindBin( ABin: Integer ): Integer; begin Result := dxPrintDevice.FindBin( ABin ); end; function TATdxPrintProxy.FindBin( const AName: string ): Integer; begin Result := dxPrintDevice.FindBin( AName ); end; function TATdxPrintProxy.FindPaper( ADMPaper: Integer ): Integer; begin Result := dxPrintDevice.FindPaper( ADMPaper ); end; function TATdxPrintProxy.FindPaper( AWidth, AHeight: Integer ): Integer; begin Result := dxPrintDevice.FindPaper( AWidth, AHeight ); end; function TATdxPrintProxy.FindPaper( const AName: string ): Integer; begin Result := dxPrintDevice.FindPaper( AName ); end; function TATdxPrintProxy.FindPaper( const ASize: TPoint ): Integer; begin Result := dxPrintDevice.FindPaper( ASize ); end; function TATdxPrintProxy.FindPrintDevice( ADevice, APort: PChar ): Integer; begin Result := dxPrintDevice.FindPrintDevice( ADevice, APort ); end; function TATdxPrintProxy.GetAborted: Boolean; begin Result := dxPrintDevice.Aborted; end; function TATdxPrintProxy.GetAutoRefresh: Boolean; begin Result := dxPrintDevice.AutoRefresh; end; function TATdxPrintProxy.GetBinIndex: Integer; begin Result := dxPrintDevice.BinIndex; end; function TATdxPrintProxy.GetBins: TStrings; begin Result := dxPrintDevice.Bins; end; function TATdxPrintProxy.GetCanvas: TCanvas; begin Result := dxPrintDevice.Canvas; end; function TATdxPrintProxy.GetCapabilities: TPrinterCapabilities; var AdxCaps: TdxPrinterCapabilities; begin Result := [ ]; AdxCaps := dxPrintDevice.Capabilities; if ( TdxPrinterCapability.pcCopies IN AdxCaps ) then Include( Result, TPrinterCapability.pcCopies ); if ( TdxPrinterCapability.pcOrientation IN AdxCaps ) then Include( Result, TPrinterCapability.pcOrientation ); if ( TdxPrinterCapability.pcCollation IN AdxCaps ) then Include( Result, TPrinterCapability.pcCollation ); end; function TATdxPrintProxy.GetCollate: Boolean; begin Result := dxPrintDevice.Collate; end; function TATdxPrintProxy.GetColorMode: Boolean; begin Result := dxPrintDevice.ColorMode; end; function TATdxPrintProxy.GetCopies: Integer; begin Result := dxPrintDevice.Copies; end; function TATdxPrintProxy.GetCurrentDevice: PChar; begin Result := dxPrintDevice.CurrentDevice; end; function TATdxPrintProxy.GetCurrentDriver: PChar; begin Result := dxPrintDevice.CurrentDriver; end; function TATdxPrintProxy.GetCurrentPort: PChar; begin Result := dxPrintDevice.CurrentPort; end; function TATdxPrintProxy.GetDefaultDMPaper: Integer; begin Result := dxPrintDevice.DefaultDMPaper; end; function TATdxPrintProxy.GetDeviceMode: PDeviceMode; begin Result := dxPrintDevice.DeviceMode; end; function TATdxPrintProxy.GetDuplex: TdxDuplexMode; begin Result := dxPrintDevice.Duplex; end; function TATdxPrintProxy.GetFileName: string; begin Result := dxPrintDevice.FileName; end; function TATdxPrintProxy.GetFonts: TStrings; begin Result := dxPrintDevice.Fonts; end; function TATdxPrintProxy.GetHandle: HDC; begin Result := dxPrintDevice.Handle; end; function TATdxPrintProxy.GetHDeviceMode: THandle; begin Result := dxPrintDevice.HDeviceMode; end; function TATdxPrintProxy.GetIsDefault: Boolean; begin Result := dxPrintDevice.IsDefault; end; function TATdxPrintProxy.GetIsDeviceModePersistent: Boolean; begin Result := dxPrintDevice.IsDeviceModePersistent; end; function TATdxPrintProxy.GetIsInitialized: Boolean; begin Result := dxPrintDevice.IsInitialized; end; function TATdxPrintProxy.GetIsNetwork: Boolean; begin Result := dxPrintDevice.IsNetwork; end; function TATdxPrintProxy.GetMaxCopies: LongInt; begin Result := dxPrintDevice.MaxCopies; end; function TATdxPrintProxy.GetMaxExtentX: Integer; begin Result := dxPrintDevice.MaxExtentX; end; function TATdxPrintProxy.GetMaxExtentY: Integer; begin Result := dxPrintDevice.MaxExtentY; end; function TATdxPrintProxy.GetMinExtentX: Integer; begin Result := dxPrintDevice.MinExtentX; end; function TATdxPrintProxy.GetMinExtentY: Integer; begin Result := dxPrintDevice.MinExtentY; end; function TATdxPrintProxy.GetOnNewPage: TNotifyEvent; begin Result := dxPrintDevice.OnNewPage; end; function TATdxPrintProxy.GetOnPrinterChange: TNotifyEvent; begin Result := dxPrintDevice.OnPrinterChange; end; function TATdxPrintProxy.GetOnRefresh: TNotifyEvent; begin Result := dxPrintDevice.OnRefresh; end; function TATdxPrintProxy.GetOrientation: TPrinterOrientation; var AOrient: TPrinterOrientation; begin case dxPrintDevice.Orientation of TdxPrinterOrientation.poPortrait: AOrient := TPrinterOrientation.poPortrait; TdxPrinterOrientation.poLandscape: AOrient := TPrinterOrientation.poLandscape; else AOrient := TPrinterOrientation.poPortrait; end; Result := AOrient; end; function TATdxPrintProxy.GetPageHeight: Integer; begin Result := dxPrintDevice.PageHeight; end; function TATdxPrintProxy.GetPageHeightLoMetric: Integer; begin Result := dxPrintDevice.PageHeightLoMetric; end; function TATdxPrintProxy.GetPageNumber: Integer; begin Result := dxPrintDevice.PageNumber; end; function TATdxPrintProxy.GetPageWidth: Integer; begin Result := dxPrintDevice.PageWidth; end; function TATdxPrintProxy.GetPageWidthLoMetric: Integer; begin Result := dxPrintDevice.PageWidthLoMetric; end; function TATdxPrintProxy.GetPaperCount: Integer; begin Result := dxPrintDevice.PaperCount; end; function TATdxPrintProxy.GetPaperIndex: Integer; begin Result := dxPrintDevice.PaperIndex; end; function TATdxPrintProxy.GetPapers: TStrings; begin Result := dxPrintDevice.Papers; end; function TATdxPrintProxy.GetPhysOffsetX: Integer; begin Result := dxPrintDevice.PhysOffsetX; end; function TATdxPrintProxy.GetPhysOffsetY: Integer; begin Result := dxPrintDevice.PhysOffsetY; end; function TATdxPrintProxy.GetPrinterCount: Integer; begin Result := dxPrintDevice.PrinterCount; end; function TATdxPrintProxy.GetPrinterIndex: Integer; begin Result := dxPrintDevice.PrinterIndex; end; function TATdxPrintProxy.GetPrinterInfos( Index: Integer ) : TdxPrintDeviceInfo; begin Result := dxPrintDevice.PrinterInfos[ Index ]; end; function TATdxPrintProxy.GetPrinters: TStrings; begin Result := dxPrintDevice.Printers; end; function TATdxPrintProxy.GetPrinting: Boolean; begin Result := dxPrintDevice.Printing; end; function TATdxPrintProxy.GetTitle: string; begin Result := dxPrintDevice.Title; end; function TATdxPrintProxy.IsAutoSelectBin( AIndex: Integer ): Boolean; begin Result := dxPrintDevice.IsAutoSelectBin( AIndex ); end; function TATdxPrintProxy.IsDeviceModeChanged: Boolean; begin Result := dxPrintDevice.IsDeviceModeChanged; end; function TATdxPrintProxy.IsEnvelopePaper( AIndex: Integer ): Boolean; begin Result := dxPrintDevice.IsEnvelopePaper( AIndex ); end; function TATdxPrintProxy.IsSupportColoration: Boolean; begin Result := dxPrintDevice.IsSupportColoration; end; function TATdxPrintProxy.IsSupportDuplex: Boolean; begin Result := dxPrintDevice.IsSupportDuplex; end; function TATdxPrintProxy.IsUserPaperSize( AIndex: Integer ): Boolean; begin Result := dxPrintDevice.IsUserPaperSize( AIndex ); end; function TATdxPrintProxy.IsUserPaperSource( AIndex: Integer ) : Boolean; begin Result := dxPrintDevice.IsUserPaperSource( AIndex ); end; procedure TATdxPrintProxy.NewPage; begin dxPrintDevice.NewPage; end; procedure TATdxPrintProxy.Refresh; begin dxPrintDevice.Refresh; end; procedure TATdxPrintProxy.ResetDC( IsForced: Boolean ); begin dxPrintDevice.ResetDC( IsForced ); end; procedure TATdxPrintProxy.ResetPrintDevice; begin dxPrintDevice.ResetPrintDevice; end; function TATdxPrintProxy.SelectBin( Value: Integer ): Boolean; begin Result := dxPrintDevice.SelectBin( Value ); end; function TATdxPrintProxy.SelectBin( const AName: string ): Boolean; begin Result := dxPrintDevice.SelectBin( AName ); end; function TATdxPrintProxy.SelectPaper( ADMPaper: Integer ): Boolean; begin Result := dxPrintDevice.SelectPaper( ADMPaper ); end; function TATdxPrintProxy.SelectPaper( var AWidth, AHeight: Integer ): Boolean; begin Result := dxPrintDevice.SelectPaper( AWidth, AHeight ); end; function TATdxPrintProxy.SelectPaper( const AName: string ): Boolean; begin Result := dxPrintDevice.SelectPaper( AName ); end; procedure TATdxPrintProxy.SetAutoRefresh( const Value: Boolean ); begin dxPrintDevice.AutoRefresh := Value; end; procedure TATdxPrintProxy.SetBinIndex( const Value: Integer ); begin dxPrintDevice.BinIndex := Value; end; procedure TATdxPrintProxy.SetCollate( const Value: Boolean ); begin dxPrintDevice.Collate := Value; end; procedure TATdxPrintProxy.SetColorMode( const Value: Boolean ); begin dxPrintDevice.ColorMode := Value; end; procedure TATdxPrintProxy.SetCopies( const Value: Integer ); begin dxPrintDevice.Copies := Value; end; procedure TATdxPrintProxy.SetDuplex( const Value: TdxDuplexMode ); begin dxPrintDevice.Duplex := Value; end; procedure TATdxPrintProxy.SetFileName( const Value: string ); begin dxPrintDevice.FileName := Value; end; procedure TATdxPrintProxy.SetIsDefault( const Value: Boolean ); begin dxPrintDevice.IsDefault := Value; end; procedure TATdxPrintProxy.SetIsDeviceModePersistent( const Value : Boolean ); begin dxPrintDevice.IsDeviceModePersistent := Value; end; procedure TATdxPrintProxy.SetOnNewPage( const Value: TNotifyEvent ); begin dxPrintDevice.OnNewPage := Value; end; procedure TATdxPrintProxy.SetOnPrinterChange( const Value : TNotifyEvent ); begin dxPrintDevice.OnPrinterChange := Value; end; procedure TATdxPrintProxy.SetOnRefresh( const Value: TNotifyEvent ); begin dxPrintDevice.OnRefresh := Value; end; procedure TATdxPrintProxy.SetOrientation( const Value : TPrinterOrientation ); var AOrient: TdxPrinterOrientation; begin case Value of TPrinterOrientation.poPortrait: AOrient := TdxPrinterOrientation.poPortrait; TPrinterOrientation.poLandscape: AOrient := TdxPrinterOrientation.poLandscape; else exit; end; dxPrintDevice.Orientation := AOrient; end; procedure TATdxPrintProxy.SetPaperIndex( const Value: Integer ); begin dxPrintDevice.PaperIndex := Value; end; procedure TATdxPrintProxy.SetPrinterIndex( const Value: Integer ); begin dxPrintDevice.PrinterIndex := Value; end; procedure TATdxPrintProxy.SetTitle( const Value: string ); begin dxPrintDevice.Title := Value; end; end.
20.696774
70
0.751195
47e4cb1c3f8c9d81d17097c4fe1fb9b80744f7e0
501
dfm
Pascal
Lego/bricxcc/CodeUnit.dfm
jodosh/Personal
92c943b95d3a07789d5f24faf60d4708040e22cb
[ "MIT" ]
null
null
null
Lego/bricxcc/CodeUnit.dfm
jodosh/Personal
92c943b95d3a07789d5f24faf60d4708040e22cb
[ "MIT" ]
1
2017-09-18T14:15:00.000Z
2017-09-18T14:15:00.000Z
Lego/bricxcc/CodeUnit.dfm
jodosh/Personal
92c943b95d3a07789d5f24faf60d4708040e22cb
[ "MIT" ]
null
null
null
object CodeForm: TCodeForm Left = 200 Top = 128 Width = 544 Height = 375 HelpContext = 10 BorderIcons = [biSystemMenu, biHelp] BorderStyle = bsSizeToolWin Caption = 'Code Listing' Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = True Position = poDefault OnCreate = FormCreate OnShow = FormShow PixelsPerInch = 96 TextHeight = 13 end
21.782609
39
0.668663
f1bf8c4c9d4bf132d46e7b28ad0bb364e0e0ff3f
1,153
pas
Pascal
turtle/rekpic22.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
11
2015-12-12T05:13:15.000Z
2020-10-14T13:32:08.000Z
turtle/rekpic22.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
null
null
null
turtle/rekpic22.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
8
2017-05-05T05:24:01.000Z
2021-07-03T20:30:09.000Z
(* ┌───────────────────────────────────────────────────────────┐ │ Programated by Vladimir Zahoransky │ │ Vladko software │ │ Contact : zahoran@cezap.ii.fmph.uniba.sk │ │ Program tema : Triangles in triangle - rekusion │ └───────────────────────────────────────────────────────────┘ *) { Well, this is nice effekt. It is easy to undestand if you undestand rekpic20.pas. There are only two variables. Parameter of cycle (in rekusion and angle. The just modify parameter 1 to 3 and angle 120. } Uses Okor; Type Mykor=Object(kor) Procedure Triangle(n:integer;s:real); End; procedure Mykor.Triangle(n:integer;s:real); var i:integer; begin if n=0 then else for i:=1 to 3 do begin Zmenfp(i); dopredu(s); vlavo(120); Triangle(n-1,s/2.5); end; end; Var k:Mykor; Begin With k do Begin Init(240,-240,-30); Triangle(6,480); CakajKlaves; Koniec; End; End. 
26.204545
71
0.456201
f1a2fe4d7a5a2ab10a3680b6bc8edb1c4d51ef9a
13,195
pas
Pascal
src/thirdparty/pascal_rem/uPSC_graphics.pas
atkins126/underscript
f6961044ca4fe87389e30c68acef2d5efed2c905
[ "MIT" ]
14
2018-05-26T19:34:13.000Z
2020-10-19T12:08:10.000Z
src/thirdparty/pascal_rem/uPSC_graphics.pas
atkins126/underscript
f6961044ca4fe87389e30c68acef2d5efed2c905
[ "MIT" ]
null
null
null
src/thirdparty/pascal_rem/uPSC_graphics.pas
atkins126/underscript
f6961044ca4fe87389e30c68acef2d5efed2c905
[ "MIT" ]
2
2020-12-18T21:33:46.000Z
2021-03-28T03:07:04.000Z
{ Compiletime Graphics support } unit uPSC_graphics; {$I PascalScript.inc} interface uses uPSCompiler, uPSUtils; procedure SIRegister_Graphics_TypesAndConsts(Cl: TPSPascalCompiler); procedure SIRegisterTGRAPHICSOBJECT(Cl: TPSPascalCompiler); procedure SIRegisterTFont(Cl: TPSPascalCompiler); procedure SIRegisterTPEN(Cl: TPSPascalCompiler); procedure SIRegisterTBRUSH(Cl: TPSPascalCompiler); procedure SIRegisterTCanvas(cl: TPSPascalCompiler); procedure SIRegisterTGraphic(CL: TPSPascalCompiler); procedure SIRegisterTBitmap(CL: TPSPascalCompiler; Streams: Boolean); procedure SIRegisterTPicture(CL: TPSPascalCompiler); procedure SIRegister_Graphics(Cl: TPSPascalCompiler; Streams: Boolean); implementation {$IFNDEF PS_NOGRAPHCONST} uses {$IFDEF CLX}QGraphics{$ELSE}Vcl.Graphics{$ENDIF}; {$ELSE} {$IFNDEF CLX} {$IFNDEF FPC} uses Windows; {$ENDIF} {$ENDIF} {$ENDIF} procedure SIRegisterTGRAPHICSOBJECT(Cl: TPSPascalCompiler); begin with Cl.AddClassN(cl.FindClass('TPersistent'), 'TGraphicsObject') do begin RegisterProperty('OnChange', 'TNotifyEvent', iptrw); end; end; procedure SIRegisterTFont(Cl: TPSPascalCompiler); begin with Cl.AddClassN(cl.FindClass('TGraphicsObject'), 'TFont') do begin RegisterMethod('constructor Create;'); {$IFNDEF CLX} RegisterProperty('Handle', 'Integer', iptRW); {$ENDIF} RegisterProperty('Color', 'TColor', iptRW); RegisterProperty('Height', 'Integer', iptRW); RegisterProperty('Name', 'string', iptRW); RegisterProperty('Pitch', 'Byte', iptRW); RegisterProperty('Size', 'Integer', iptRW); RegisterProperty('PixelsPerInch', 'Integer', iptRW); RegisterProperty('Style', 'TFontStyles', iptrw); end; end; procedure SIRegisterTCanvas(cl: TPSPascalCompiler); // requires TPersistent begin with Cl.AddClassN(cl.FindClass('TPersistent'), 'TCanvas') do begin RegisterMethod('procedure Arc(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer);'); RegisterMethod('procedure Chord(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer);'); RegisterMethod('procedure Draw(X, Y: Integer; Graphic: TGraphic);'); RegisterMethod('procedure Ellipse(X1, Y1, X2, Y2: Integer);'); RegisterMethod('procedure FillRect(const Rect: TRect);'); {$IFNDEF CLX} RegisterMethod('procedure FloodFill(X, Y: Integer; Color: TColor; FillStyle: Byte);'); {$ENDIF} RegisterMethod('procedure LineTo(X, Y: Integer);'); RegisterMethod('procedure MoveTo(X, Y: Integer);'); RegisterMethod('procedure Pie(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer);'); RegisterMethod('procedure Rectangle(X1, Y1, X2, Y2: Integer);'); RegisterMethod('procedure Refresh;'); RegisterMethod('procedure RoundRect(X1, Y1, X2, Y2, X3, Y3: Integer);'); RegisterMethod('function TextHeight(Text: string): Integer;'); RegisterMethod('procedure TextOut(X, Y: Integer; Text: string);'); RegisterMethod('function TextWidth(Text: string): Integer;'); {$IFNDEF CLX} RegisterProperty('Handle', 'Integer', iptRw); {$ENDIF} RegisterProperty('Pixels', 'Integer Integer Integer', iptRW); RegisterProperty('Brush', 'TBrush', iptR); RegisterProperty('CopyMode', 'Byte', iptRw); RegisterProperty('Font', 'TFont', iptR); RegisterProperty('Pen', 'TPen', iptR); end; end; procedure SIRegisterTPEN(Cl: TPSPascalCompiler); begin with Cl.AddClassN(cl.FindClass('TGraphicsObject'), 'TPen') do begin RegisterMethod('constructor Create'); RegisterProperty('Color', 'TColor', iptrw); RegisterProperty('Mode', 'TPenMode', iptrw); RegisterProperty('Style', 'TPenStyle', iptrw); RegisterProperty('Width', 'Integer', iptrw); end; end; procedure SIRegisterTBRUSH(Cl: TPSPascalCompiler); begin with Cl.AddClassN(cl.FindClass('TGraphicsObject'), 'TBrush') do begin RegisterMethod('constructor Create'); RegisterProperty('Color', 'TColor', iptrw); RegisterProperty('Style', 'TBrushStyle', iptrw); end; end; procedure SIRegister_Graphics_TypesAndConsts(Cl: TPSPascalCompiler); {$IFDEF PS_NOGRAPHCONST} const clSystemColor = {$IFDEF DELPHI7UP} $FF000000 {$ELSE} $80000000 {$ENDIF}; {$ENDIF} begin {$IFNDEF PS_NOGRAPHCONST} cl.AddConstantN('clScrollBar', 'Integer').Value.ts32 := clScrollBar; cl.AddConstantN('clBackground', 'Integer').Value.ts32 := clBackground; cl.AddConstantN('clActiveCaption', 'Integer').Value.ts32 := clActiveCaption; cl.AddConstantN('clInactiveCaption', 'Integer').Value.ts32 := clInactiveCaption; cl.AddConstantN('clMenu', 'Integer').Value.ts32 := clMenu; cl.AddConstantN('clWindow', 'Integer').Value.ts32 := clWindow; cl.AddConstantN('clWindowFrame', 'Integer').Value.ts32 := clWindowFrame; cl.AddConstantN('clMenuText', 'Integer').Value.ts32 := clMenuText; cl.AddConstantN('clWindowText', 'Integer').Value.ts32 := clWindowText; cl.AddConstantN('clCaptionText', 'Integer').Value.ts32 := clCaptionText; cl.AddConstantN('clActiveBorder', 'Integer').Value.ts32 := clActiveBorder; cl.AddConstantN('clInactiveBorder', 'Integer').Value.ts32 := clInactiveCaption; cl.AddConstantN('clAppWorkSpace', 'Integer').Value.ts32 := clAppWorkSpace; cl.AddConstantN('clHighlight', 'Integer').Value.ts32 := clHighlight; cl.AddConstantN('clHighlightText', 'Integer').Value.ts32 := clHighlightText; cl.AddConstantN('clBtnFace', 'Integer').Value.ts32 := clBtnFace; cl.AddConstantN('clBtnShadow', 'Integer').Value.ts32 := clBtnShadow; cl.AddConstantN('clGrayText', 'Integer').Value.ts32 := clGrayText; cl.AddConstantN('clBtnText', 'Integer').Value.ts32 := clBtnText; cl.AddConstantN('clInactiveCaptionText', 'Integer').Value.ts32 := clInactiveCaptionText; cl.AddConstantN('clBtnHighlight', 'Integer').Value.ts32 := clBtnHighlight; cl.AddConstantN('cl3DDkShadow', 'Integer').Value.ts32 := cl3DDkShadow; cl.AddConstantN('cl3DLight', 'Integer').Value.ts32 := cl3DLight; cl.AddConstantN('clInfoText', 'Integer').Value.ts32 := clInfoText; cl.AddConstantN('clInfoBk', 'Integer').Value.ts32 := clInfoBk; {$ELSE} {$IFNDEF CLX} // These are VCL-only; CLX uses different constant values cl.AddConstantN('clScrollBar', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_SCROLLBAR); cl.AddConstantN('clBackground', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_BACKGROUND); cl.AddConstantN('clActiveCaption', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_ACTIVECAPTION); cl.AddConstantN('clInactiveCaption', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_INACTIVECAPTION); cl.AddConstantN('clMenu', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_MENU); cl.AddConstantN('clWindow', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_WINDOW); cl.AddConstantN('clWindowFrame', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_WINDOWFRAME); cl.AddConstantN('clMenuText', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_MENUTEXT); cl.AddConstantN('clWindowText', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_WINDOWTEXT); cl.AddConstantN('clCaptionText', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_CAPTIONTEXT); cl.AddConstantN('clActiveBorder', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_ACTIVEBORDER); cl.AddConstantN('clInactiveBorder', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_INACTIVEBORDER); cl.AddConstantN('clAppWorkSpace', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_APPWORKSPACE); cl.AddConstantN('clHighlight', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_HIGHLIGHT); cl.AddConstantN('clHighlightText', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_HIGHLIGHTTEXT); cl.AddConstantN('clBtnFace', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_BTNFACE); cl.AddConstantN('clBtnShadow', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_BTNSHADOW); cl.AddConstantN('clGrayText', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_GRAYTEXT); cl.AddConstantN('clBtnText', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_BTNTEXT); cl.AddConstantN('clInactiveCaptionText', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_INACTIVECAPTIONTEXT); cl.AddConstantN('clBtnHighlight', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_BTNHIGHLIGHT); cl.AddConstantN('cl3DDkShadow', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_3DDKSHADOW); cl.AddConstantN('cl3DLight', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_3DLIGHT); cl.AddConstantN('clInfoText', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_INFOTEXT); cl.AddConstantN('clInfoBk', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_INFOBK); {$ENDIF} {$ENDIF} cl.AddConstantN('clBlack', 'Integer').Value.ts32 := $000000; cl.AddConstantN('clMaroon', 'Integer').Value.ts32 := $000080; cl.AddConstantN('clGreen', 'Integer').Value.ts32 := $008000; cl.AddConstantN('clOlive', 'Integer').Value.ts32 := $008080; cl.AddConstantN('clNavy', 'Integer').Value.ts32 := $800000; cl.AddConstantN('clPurple', 'Integer').Value.ts32 := $800080; cl.AddConstantN('clTeal', 'Integer').Value.ts32 := $808000; cl.AddConstantN('clGray', 'Integer').Value.ts32 := $808080; cl.AddConstantN('clSilver', 'Integer').Value.ts32 := $C0C0C0; cl.AddConstantN('clRed', 'Integer').Value.ts32 := $0000FF; cl.AddConstantN('clLime', 'Integer').Value.ts32 := $00FF00; cl.AddConstantN('clYellow', 'Integer').Value.ts32 := $00FFFF; cl.AddConstantN('clBlue', 'Integer').Value.ts32 := $FF0000; cl.AddConstantN('clFuchsia', 'Integer').Value.ts32 := $FF00FF; cl.AddConstantN('clAqua', 'Integer').Value.ts32 := $FFFF00; cl.AddConstantN('clLtGray', 'Integer').Value.ts32 := $C0C0C0; cl.AddConstantN('clDkGray', 'Integer').Value.ts32 := $808080; cl.AddConstantN('clWhite', 'Integer').Value.ts32 := $FFFFFF; cl.AddConstantN('clNone', 'Integer').Value.ts32 := $1FFFFFFF; cl.AddConstantN('clDefault', 'Integer').Value.ts32 := $20000000; Cl.addTypeS('TFontStyle', '(fsBold, fsItalic, fsUnderline, fsStrikeOut)'); Cl.addTypeS('TFontStyles', 'set of TFontStyle'); cl.AddTypeS('TFontPitch', '(fpDefault, fpVariable, fpFixed)'); cl.AddTypeS('TPenStyle', '(psSolid, psDash, psDot, psDashDot, psDashDotDot, psClear, psInsideFrame)'); cl.AddTypeS('TPenMode', '(pmBlack, pmWhite, pmNop, pmNot, pmCopy, pmNotCopy, pmMergePenNot, pmMaskPenNot, pmMergeNotPen, pmMaskNotPen, pmMerge, pmNotMerge, pmMask, pmNotMask, pmXor, pmNotXor)'); cl.AddTypeS('TBrushStyle', '(bsSolid, bsClear, bsHorizontal, bsVertical, bsFDiagonal, bsBDiagonal, bsCross, bsDiagCross)'); cl.addTypeS('TColor', 'Integer'); {$IFNDEF CLX} cl.addTypeS('HBITMAP', 'Integer'); cl.addTypeS('HPALETTE', 'Integer'); {$ENDIF} end; procedure SIRegisterTGraphic(CL: TPSPascalCompiler); begin with CL.AddClassN(CL.FindClass('TPersistent'),'TGraphic') do begin RegisterMethod('constructor Create'); RegisterMethod('procedure LoadFromFile(const FileName: string)'); RegisterMethod('procedure SaveToFile(const FileName: string)'); RegisterProperty('Empty', 'Boolean', iptr); RegisterProperty('Height', 'Integer', iptrw); RegisterProperty('Modified', 'Boolean', iptrw); RegisterProperty('Width', 'Integer', iptrw); RegisterProperty('OnChange', 'TNotifyEvent', iptrw); end; end; procedure SIRegisterTBitmap(CL: TPSPascalCompiler; Streams: Boolean); begin with CL.AddClassN(CL.FindClass('TGraphic'),'TBitmap') do begin if Streams then begin RegisterMethod('procedure LoadFromStream(Stream: TStream)'); RegisterMethod('procedure SaveToStream(Stream: TStream)'); end; RegisterProperty('Canvas', 'TCanvas', iptr); {$IFNDEF CLX} RegisterProperty('Handle', 'HBITMAP', iptrw); {$ENDIF} {$IFNDEF IFPS_MINIVCL} RegisterMethod('procedure Dormant'); RegisterMethod('procedure FreeImage'); {$IFNDEF CLX} RegisterMethod('procedure LoadFromClipboardFormat(AFormat: Word; AData: THandle; APalette: HPALETTE)'); {$ENDIF} RegisterMethod('procedure LoadFromResourceName(Instance: THandle; const ResName: string)'); RegisterMethod('procedure LoadFromResourceID(Instance: THandle; ResID: Integer)'); {$IFNDEF CLX} RegisterMethod('function ReleaseHandle: HBITMAP'); RegisterMethod('function ReleasePalette: HPALETTE'); RegisterMethod('procedure SaveToClipboardFormat(var Format: Word; var Data: THandle; var APalette: HPALETTE)'); RegisterProperty('Monochrome', 'Boolean', iptrw); RegisterProperty('Palette', 'HPALETTE', iptrw); RegisterProperty('IgnorePalette', 'Boolean', iptrw); {$ENDIF} RegisterProperty('TransparentColor', 'TColor', iptr); {$ENDIF} end; end; procedure SIRegisterTPicture(CL: TPSPascalCompiler); begin with CL.AddClassN(CL.FindClass('TPersistent'),'TPicture') do begin RegisterProperty('Bitmap','TBitmap',iptrw); end; end; procedure SIRegister_Graphics(Cl: TPSPascalCompiler; Streams: Boolean); begin SIRegister_Graphics_TypesAndConsts(Cl); SIRegisterTGRAPHICSOBJECT(Cl); SIRegisterTGraphic(Cl); SIRegisterTFont(Cl); SIRegisterTPEN(cl); SIRegisterTBRUSH(cl); SIRegisterTCanvas(cl); SIRegisterTBitmap(Cl, Streams); SIRegisterTPicture(cl); end; // PS_MINIVCL changes by Martijn Laan (mlaan at wintax _dot_ nl) End.
46.136364
196
0.737325
f1a5c728eb9a30deecc3a87eda0632bee2a01ade
2,920
pas
Pascal
LogViewer.Settings.Dialog.ConfigNode.pas
thachngopl/LogViewer
a35be3aa95cbde752bac59775fd14df24684f564
[ "Apache-2.0" ]
null
null
null
LogViewer.Settings.Dialog.ConfigNode.pas
thachngopl/LogViewer
a35be3aa95cbde752bac59775fd14df24684f564
[ "Apache-2.0" ]
null
null
null
LogViewer.Settings.Dialog.ConfigNode.pas
thachngopl/LogViewer
a35be3aa95cbde752bac59775fd14df24684f564
[ "Apache-2.0" ]
null
null
null
{ Copyright (C) 2013-2018 Tim Sinaeve tim.sinaeve@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } unit LogViewer.Settings.Dialog.ConfigNode; { Node datastructure used in the settings dialog. } interface {$REGION 'documentation'} { See this topic for more information: https://stackoverflow.com/questions/5365365/tree-like-datastructure-for-use-with-virtualtreeview } {$ENDREGION} uses Vcl.ComCtrls, Spring, Spring.Collections, VirtualTrees; type TConfigNode = class private FText : string; FVTNode : PVirtualNode; FNodes : Lazy<IList<TConfigNode>>; FTabSheet : TTabSheet; protected {$REGION 'property access methods'} function GetNodes: IList<TConfigNode>; function GetText: string; procedure SetText(const Value: string); function GetVTNode: PVirtualNode; procedure SetVTNode(const Value: PVirtualNode); {$ENDREGION} public constructor Create( const AText : string = ''; ATabSheet : TTabSheet = nil ); procedure AfterConstruction; override; procedure BeforeDestruction; override; property Nodes: IList<TConfigNode> read GetNodes; property Text: string read GetText write SetText; property TabSheet: TTabSheet read FTabSheet write FTabSheet; property VTNode : PVirtualNode read GetVTNode write SetVTNode; end; implementation {$REGION 'construction and destruction'} procedure TConfigNode.AfterConstruction; begin inherited AfterConstruction; FNodes.Create( function: IList<TConfigNode> begin Result := TCollections.CreateObjectList<TConfigNode>(False); end, True ); end; procedure TConfigNode.BeforeDestruction; begin FNodes := nil; FTabSheet := nil; inherited BeforeDestruction; end; constructor TConfigNode.Create(const AText: string; ATabSheet: TTabSheet); begin inherited Create; FText := AText; FTabSheet := ATabSheet; end; {$ENDREGION} {$REGION 'property access methods'} function TConfigNode.GetNodes: IList<TConfigNode>; begin Result := FNodes; end; function TConfigNode.GetText: string; begin Result := FText; end; procedure TConfigNode.SetText(const Value: string); begin FText := Value; end; function TConfigNode.GetVTNode: PVirtualNode; begin Result := FVTNode; end; procedure TConfigNode.SetVTNode(const Value: PVirtualNode); begin FVTNode := Value; end; {$ENDREGION} end.
21.954887
98
0.730137
47eebe84f65fb7d4c2aa9039cca4e04a0f2ffcda
1,726
pas
Pascal
Source/BCEditor.Editor.Selection.Colors.pas
EricGrange/TBCEditor
ef037fc3638b9bcf4ecacafcfc30fac745712460
[ "MIT" ]
2
2018-01-03T03:48:19.000Z
2021-12-08T14:54:20.000Z
Source/BCEditor.Editor.Selection.Colors.pas
EricGrange/TBCEditor
ef037fc3638b9bcf4ecacafcfc30fac745712460
[ "MIT" ]
null
null
null
Source/BCEditor.Editor.Selection.Colors.pas
EricGrange/TBCEditor
ef037fc3638b9bcf4ecacafcfc30fac745712460
[ "MIT" ]
1
2021-04-29T08:09:41.000Z
2021-04-29T08:09:41.000Z
unit BCEditor.Editor.Selection.Colors; interface uses Classes, Graphics, BCEditor.Consts; type TBCEditorSelectionColors = class(TPersistent) strict private FBackground: TColor; FForeground: TColor; FOnChange: TNotifyEvent; procedure SetBackground(AValue: TColor); procedure SetForeground(AValue: TColor); public constructor Create; procedure Assign(ASource: TPersistent); override; published property Background: TColor read FBackground write SetBackground default clSelectionColor; property Foreground: TColor read FForeground write SetForeground default clHighLightText; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; implementation constructor TBCEditorSelectionColors.Create; begin inherited; FBackground := clSelectionColor; FForeground := clHighLightText; end; procedure TBCEditorSelectionColors.Assign(ASource: TPersistent); begin if Assigned(ASource) and (ASource is TBCEditorSelectionColors) then with ASource as TBCEditorSelectionColors do begin Self.FBackground := FBackground; Self.FForeground := FForeground; if Assigned(Self.FOnChange) then Self.FOnChange(Self); end else inherited Assign(ASource); end; procedure TBCEditorSelectionColors.SetBackground(AValue: TColor); begin if FBackground <> AValue then begin FBackground := AValue; if Assigned(FOnChange) then FOnChange(Self); end; end; procedure TBCEditorSelectionColors.SetForeground(AValue: TColor); begin if FForeground <> AValue then begin FForeground := AValue; if Assigned(FOnChange) then FOnChange(Self); end; end; end.
24.657143
95
0.732329
f1e9025014f9cbe9fd55798c58c9af3b05e791d6
413
pas
Pascal
u_notes_list.pas
maximejournet54/Projet_IHM
fd849dc2c65069b464f3bbbe8d11af23126c3d30
[ "MIT" ]
null
null
null
u_notes_list.pas
maximejournet54/Projet_IHM
fd849dc2c65069b464f3bbbe8d11af23126c3d30
[ "MIT" ]
null
null
null
u_notes_list.pas
maximejournet54/Projet_IHM
fd849dc2c65069b464f3bbbe8d11af23126c3d30
[ "MIT" ]
null
null
null
unit u_notes_list; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, u_liste; type { Tf_notes_list } Tf_notes_list = class(TF_liste) private { private declarations } public { public declarations } end; var f_notes_list: Tf_notes_list; implementation {$R *.lfm} { Tf_releve_list } uses u_feuille_style; { Tf_notes_list } end.
11.472222
75
0.699758
f1eebe65b45164632aed0a978948a7a7d377e80a
3,695
dpr
Pascal
delcos.dpr
CWBudde/delcos
656384c43c2980990ea691e4e52752d718fb0277
[ "Apache-2.0" ]
2
2017-01-18T13:27:34.000Z
2020-04-18T22:12:59.000Z
delcos.dpr
CWBudde/delcos
656384c43c2980990ea691e4e52752d718fb0277
[ "Apache-2.0" ]
null
null
null
delcos.dpr
CWBudde/delcos
656384c43c2980990ea691e4e52752d718fb0277
[ "Apache-2.0" ]
4
2016-10-16T17:52:49.000Z
2020-11-24T11:36:05.000Z
program delcos; {$APPTYPE CONSOLE} uses Classes, SysUtils, IniFiles, PascalParser, Options in 'cui\Options.pas', OptionsValidator in 'cui\OptionsValidator.pas', SourceTreeWalker in 'core\SourceTreeWalker.pas', SourceTreeDumperVisitor in 'core\SourceTreeDumperVisitor.pas', UnitRegistry in 'core\UnitRegistry.pas', CommentRemovalVisitor in 'core\CommentRemovalVisitor.pas', WhitespaceRemovalVisitor in 'core\WhitespaceRemovalVisitor.pas', IncludeParser in 'core\IncludeParser.pas', ProjectUnitsRegistratorVisitor in 'core\ProjectUnitsRegistratorVisitor.pas', UsesTreeBuilderVisitor in 'core\UsesTreeBuilderVisitor.pas', CyclomaticComplexityCalculatorVisitor in 'core\CyclomaticComplexityCalculatorVisitor.pas'; procedure DumpCyclomaticComplexity; var Methods: TMethodList; Units: TStrings; I, J: Integer; begin Units := TStringList.Create; try TUnitRegistry.Instance.GetProjectRegisteredUnitsNames(Units); for I := 0 to Units.Count - 1 do begin Methods := TMethodList.Create; try TSourceTreeWalker.Create.Walk(TUnitRegistry.Instance.UnitParser[Units[I]].Root, TCyclomaticComplexityCalculatorVisitor.Create(Methods) as INodeVisitor); for J := 0 to Methods.Count - 1 do Writeln(Units[I], '::', Methods[J].Name, ' (CC = ', Methods[J].CyclomaticComplexity, ')'); finally Methods.Free; end; end; finally Units.Free; end; end; function ExtractUnitNameFromFileName(FileName: String): String; begin Result := ExtractFileName(FileName); Result := Copy(Result, 1, Length(Result) - Length(ExtractFileExt(Result))); end; procedure DumpIncludes; var I, J: Integer; Units, AllIncludes, Includes: TStrings; begin AllIncludes := TStringList.Create; try Includes := TStringList.Create; try Units := TStringList.Create; try TUnitRegistry.Instance.GetAllRegisteredUnitsNames(Units); for I := 0 to Units.Count - 1 do begin TUnitRegistry.Instance.GetUnitIncludes(Units[I], Includes); for J := 0 to Includes.Count - 1 do if AllIncludes.IndexOf(UpperCase(Trim(Includes[J]))) = -1 then AllIncludes.Add(UpperCase(Trim(Includes[J]))) end; finally Units.Free; end; finally Includes.Free; end; Write(AllIncludes.Text); finally AllIncludes.Free; end; end; var Output: TStrings; RootUnit: String; begin with TSourceTreeWalker.Create do begin RootUnit := ExtractUnitNameFromFileName(TOptions.Instance.InputFile); TUnitRegistry.Instance.RegisterUnit(RootUnit, TOptions.Instance.InputFile, True); with TUnitRegistry.Instance.UnitParser[RootUnit] do begin Walk(Root, TProjectUnitsRegistratorVisitor.Create as INodeVisitor); Output := TStringList.Create; try if TOptions.Instance.DumpDebugTree then Walk(Root, TSourceTreeDumperVisitor.Create(Output) as INodeVisitor); if TOptions.Instance.DumpUsesTree then begin Walk(Root, TUsesTreeBuilderVisitor.Create(vmSimple, Output) as INodeVisitor); Write(Output.Text); DumpIncludes; end; if TOptions.Instance.DumpAdvancedUsesTree then begin Walk(Root, TUsesTreeBuilderVisitor.Create(vmFull, Output) as INodeVisitor); Write(Output.Text); DumpIncludes; end; if TOptions.Instance.DumpCyclomaticComplexity then DumpCyclomaticComplexity; finally Output.Free; end; end; end; end.
30.791667
161
0.677131
4743ef8b8766f1abc3f9812467f694a07e724a49
12,445
pas
Pascal
Lib/Classes/1D Barcodes/ZXing.OneD.Code93Reader.pas
pult/ZXing.Delphi
85eca127ff0a7714ea48b187bc64085bf526dd08
[ "Apache-2.0" ]
null
null
null
Lib/Classes/1D Barcodes/ZXing.OneD.Code93Reader.pas
pult/ZXing.Delphi
85eca127ff0a7714ea48b187bc64085bf526dd08
[ "Apache-2.0" ]
null
null
null
Lib/Classes/1D Barcodes/ZXing.OneD.Code93Reader.pas
pult/ZXing.Delphi
85eca127ff0a7714ea48b187bc64085bf526dd08
[ "Apache-2.0" ]
null
null
null
{ * Copyright 2010 ZXing authors * * 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. * Original Authors: Sean Owen * Delphi Implementation by E. Spelt and K. Gossens } unit ZXing.OneD.Code93Reader; interface uses System.SysUtils, System.Generics.Collections, Math, ZXing.OneD.OneDReader, ZXing.Common.BitArray, ZXing.ReadResult, ZXing.DecodeHintType, ZXing.ResultPoint, ZXing.BarcodeFormat, ZXing.Common.Detector.MathUtils; type /// <summary> /// <p>Decodes Code 93 barcodes.</p> /// <see cref="TCode39Reader" /> /// </summary> TCode93Reader = class sealed(TOneDReader) private class var ALPHABET: TArray<Char>; class function checkChecksums(pResult: TStringBuilder): boolean; static; class function checkOneChecksum(pResult: TStringBuilder; checkPosition, weightMax: Integer): boolean; class function decodeExtended(encoded: TStringBuilder): string; static; function findAsteriskPattern(row: IBitArray): TArray<Integer>; class function patternToChar(pattern: Integer; var c: Char) : boolean; static; class function toPattern(counters: TArray<Integer>): Integer; static; const ALPHABET_STRING : string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*'; class var ASTERISK_ENCODING: Integer; class var CHARACTER_ENCODINGS: TArray<Integer>; counters: TArray<Integer>; decodeRowResult: TStringBuilder; public constructor Create; destructor Destroy; override; function decodeRow(const rowNumber: Integer; const row: IBitArray; const hints: TDictionary<TDecodeHintType, TObject>): TReadResult; override; end; implementation { Code93Reader } constructor TCode93Reader.Create; begin ALPHABET := '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*'.ToCharArray; CHARACTER_ENCODINGS := TArray<Integer>.Create($114, $148, $144, $142, $128, $124, 290, $150, $112, $10A, $1A8, 420, $1A2, $194, $192, $18A, 360, $164, $162, $134, $11A, $158, $14C, $146, 300, $116, $1B4, $1B2, $1AC, $1A6, $196, 410, $16C, $166, 310, $13A, $12E, $1D4, $1D2, $1CA, $16E, $176, 430, $126, $1DA, 470, $132, 350); ASTERISK_ENCODING := TCode93Reader.CHARACTER_ENCODINGS[$2F]; counters := TArray<Integer>.Create(); SetLength(counters, 6); decodeRowResult := TStringBuilder.Create(); end; destructor TCode93Reader.Destroy; begin ALPHABET := nil; CHARACTER_ENCODINGS := nil; counters := nil; FreeAndNil(decodeRowResult); inherited; end; class function TCode93Reader.checkChecksums(pResult: TStringBuilder): boolean; var length: Integer; begin length := pResult.length; if (not TCode93Reader.checkOneChecksum(pResult, (length - 2), 20)) then begin Result := false; exit end; if (not TCode93Reader.checkOneChecksum(pResult, (length - 1), 15)) then begin Result := false; exit end; begin Result := true; exit end end; class function TCode93Reader.checkOneChecksum(pResult: TStringBuilder; checkPosition, weightMax: Integer): boolean; var weight, total, i: Integer; begin weight := 1; total := 0; i := (checkPosition - 1); while ((i >= 0)) do begin inc(total, (weight * ALPHABET_STRING.IndexOf(pResult.Chars[i]))); inc(weight); if (weight > weightMax) then weight := 1; dec(i) end; if (pResult.Chars[checkPosition] <> TCode93Reader.ALPHABET[(total mod $2F)]) then begin Result := false; exit end; begin Result := true; exit end end; class function TCode93Reader.decodeExtended(encoded: TStringBuilder): string; var next, c: Char; decodedChar: Char; length, i: Integer; decoded: TStringBuilder; label Label_0179, Label_0169, Label_014A; begin length := encoded.length; decoded := TStringBuilder.Create(length); try i := 0; next := Char(0); c := Char(0); {+} if c <> Char(0) then ; decodedChar := #0; if decodedChar <> #0 then ; {+.} while ((i < length)) do begin c := encoded.Chars[i]; if ((c < 'a') or (c > 'd')) then goto Label_0179; if (i < (length - 1)) then begin next := encoded.Chars[(i + 1)]; decodedChar := #0; case c of 'a': begin if ((next < 'A') or (next > 'Z')) then begin Result := ''; exit end; decodedChar := Char(ord(next) - ord('@')); goto Label_0169 end; 'b': begin if ((next < 'A') or (next > 'E')) then break;; decodedChar := Char(ord(next) - ord('&')); goto Label_0169 end; 'c': begin if ((next < 'A') or (next > 'O')) then goto Label_014A; decodedChar := Char(ord(next) - ord(' ')); goto Label_0169 end; 'd': begin if ((next < 'A') or (next > 'Z')) then begin Result := ''; exit end; decodedChar := Char(ord(next) + ord(' ')); goto Label_0169 end; else begin goto Label_0169 end; end; if ((next >= 'F') and (next <= 'W')) then begin decodedChar := Char(ord(next) - ord(' ')); goto Label_0169 end end; begin Result := ''; exit end; Label_014A: if (next = 'Z') then decodedChar := ':' else begin Result := ''; exit end; Label_0169: decoded.Append(decodedChar); inc(i); continue; Label_0179: decoded.Append(c); inc(i) end; Result := decoded.ToString; finally FreeAndNil(decoded); end; end; function TCode93Reader.decodeRow(const rowNumber: Integer; const row: IBitArray; const hints: TDictionary<TDecodeHintType, TObject>): TReadResult; var decodedChar: Char; lastStart: Integer; index, nextStart, counter, aEnd, pattern, lastPatternSize: Integer; start: TArray<Integer>; resultString: String; Left, Right: Single; resultPointCallback: TResultPointCallback; obj: TObject; resultPoints: TArray<IResultPoint>; resultPointLeft, resultPointRight: IResultPoint; begin for index := 0 to length(counters) - 1 do counters[index] := 0; decodeRowResult.length := 0; start := self.findAsteriskPattern(row); if (start = nil) then begin Result := nil; exit end; nextStart := row.getNextSet(start[1]); aEnd := row.Size; repeat if (not TOneDReader.recordPattern(row, nextStart, self.counters)) then begin Result := nil; exit end; pattern := TCode93Reader.toPattern(self.counters); if (pattern < 0) then begin Result := nil; exit end; if (not TCode93Reader.patternToChar(pattern, decodedChar)) then begin Result := nil; exit end; self.decodeRowResult.Append(decodedChar); lastStart := nextStart; for counter in self.counters do begin inc(nextStart, counter) end; nextStart := row.getNextSet(nextStart) until (decodedChar = '*'); self.decodeRowResult.Remove((self.decodeRowResult.length - 1), 1); lastPatternSize := 0; for counter in self.counters do begin inc(lastPatternSize, counter) end; if (not((nextStart <> aEnd) and row[nextStart])) then begin Result := nil; exit end; if (self.decodeRowResult.length < 2) then begin Result := nil; exit end; if (not TCode93Reader.checkChecksums(self.decodeRowResult)) then begin Result := nil; exit end; self.decodeRowResult.length := self.decodeRowResult.length - 2; resultString := TCode93Reader.decodeExtended(self.decodeRowResult); if (resultString = '') then begin Result := nil; exit end; Left := (start[1] + start[0]) div 2; Right := (lastStart + lastPatternSize) div 2; resultPointLeft := TResultPointHelpers.CreateResultPoint(Left, rowNumber); resultPointRight := TResultPointHelpers.CreateResultPoint(Right, rowNumber); {+} {$IF CompilerVersion >= 33.00} resultPoints := [resultPointLeft, resultPointRight]; {$ELSE} SetLength(resultPoints, 2); resultPoints[0] := resultPointLeft; resultPoints[1] := resultPointRight; {$IFEND} {+.} resultPointCallback := nil; // it is a local variable: it doesn't get NIL as default value, and the following ifs do not assign a value for all possible cases if ((hints = nil) or (not hints.ContainsKey(TDecodeHintType.NEED_RESULT_POINT_CALLBACK))) then resultPointCallback := nil else begin obj := hints[TDecodeHintType.NEED_RESULT_POINT_CALLBACK]; if (obj is TResultPointEventObject) then resultPointCallback := TResultPointEventObject(obj).Event; end; if Assigned(resultPointCallback) then begin resultPointCallback(resultPointLeft); resultPointCallback(resultPointRight); end; Result := TReadResult.Create(resultString, nil, resultPoints, TBarcodeFormat.CODE_39); end; function TCode93Reader.findAsteriskPattern(row: IBitArray): TArray<Integer>; var i, l, patternStart, patternLength, width, counterPosition, rowOffset, index: Integer; isWhite: boolean; begin width := row.Size; rowOffset := row.getNextSet(0); index := 0; while (index < length(self.counters)) do begin self.counters[index] := 0; inc(index) end; counterPosition := 0; patternStart := rowOffset; isWhite := false; patternLength := length(counters); for i := rowOffset to width - 1 do begin if (row[i] xor isWhite) then begin inc(counters[counterPosition]) end else begin if (counterPosition = (patternLength - 1)) then begin if (TCode93Reader.toPattern(counters) = TCode93Reader.ASTERISK_ENCODING) then begin Result := TArray<Integer>.Create(patternStart, i); exit end; inc(patternStart, (counters[0] + counters[1])); for l := 2 to patternLength - 2 do begin counters[l - 2] := counters[l]; end; counters[(patternLength - 2)] := 0; counters[(patternLength - 1)] := 0; dec(counterPosition) end else inc(counterPosition); counters[counterPosition] := 1; isWhite := not isWhite end; end; Result := nil; end; class function TCode93Reader.patternToChar(pattern: Integer; var c: Char): boolean; var i: Integer; begin i := 0; while (i < length(TCode93Reader.CHARACTER_ENCODINGS)) do begin if (TCode93Reader.CHARACTER_ENCODINGS[i] = pattern) then begin c := TCode93Reader.ALPHABET[i]; begin Result := true; exit end end; inc(i) end; c := '*'; Result := false; end; class function TCode93Reader.toPattern(counters: TArray<Integer>): Integer; var counter, max, sum, pattern, i, j, scaledShifted, scaledUnshifted: Integer; begin max := length(counters); sum := 0; for counter in counters do begin inc(sum, counter) end; pattern := 0; i := 0; while ((i < max)) do begin scaledShifted := (((counters[i] shl TOneDReader.INTEGER_MATH_SHIFT) * 9) div sum); scaledUnshifted := TMathUtils.Asr(scaledShifted, TOneDReader.INTEGER_MATH_SHIFT); if ((scaledShifted and $FF) > $7F) then inc(scaledUnshifted); if ((scaledUnshifted < 1) or (scaledUnshifted > 4)) then begin Result := -1; exit end; if ((i and 1) = 0) then begin j := 0; while ((j < scaledUnshifted)) do begin pattern := ((pattern shl 1) or 1); inc(j) end end else pattern := (pattern shl scaledUnshifted); inc(i) end; Result := pattern; end; end.
23.218284
132
0.623463
4757e372ca8592b6207ffd88f19c924f5b812788
1,582
pas
Pascal
FirstQuarter/informatics/exercices/TP1/04/exercice.pas
AndresNakanishi/CAECE-LESYN
3537a198b4392b259d12cb8c6214f1f618a7ca50
[ "MIT" ]
null
null
null
FirstQuarter/informatics/exercices/TP1/04/exercice.pas
AndresNakanishi/CAECE-LESYN
3537a198b4392b259d12cb8c6214f1f618a7ca50
[ "MIT" ]
null
null
null
FirstQuarter/informatics/exercices/TP1/04/exercice.pas
AndresNakanishi/CAECE-LESYN
3537a198b4392b259d12cb8c6214f1f618a7ca50
[ "MIT" ]
null
null
null
Program precio; uses crt; var // Quantity => Cantidad quantity: integer; // Price => Precio // Res => Resultado (Subtotal) // Des => Descuento (Descuento) price, res, des: real; BEGIN clrscr; writeln('Ingrese el precio unitario: '); readln(price); clrscr; writeln('Ingrese la cantidad de articulos vendidos: '); readln(quantity); clrscr; // Calculo del Subtotal res:= price * quantity; if(quantity < 100) then // Caso donde se compraron menos de 100 unidades begin des:= 0; end else if((quantity >= 100) and (quantity < 500)) then // Caso donde se compraron 100 o más unidades y menos de 500 begin des:= res * 0.05; end else if((quantity >= 500) and (quantity < 2000)) then // Caso donde se compraron 500 o más unidades y menos de 2.000 begin des:= res * 0.07; end else if((quantity >= 2000) and (quantity < 10000)) then // Caso donde se compraron 2.000 o más unidades y menos de 10.000 begin des:= res * 0.10; end else // Caso donde se compraron más unidades de 10.000 begin des:= res * 0.15; end; // Solo para recordar lo ingresado writeln('Precio Unitario: $', price:5:2); writeln('Cantidad: ', quantity); // Mostrar toda la data writeln('Subtotal: $', res:5:2); writeln('Descuento: $', des:5:2); writeln('Total: $', (res-des):5:2); readln(); END.
27.754386
73
0.549305
f1f412cfdb0edeed42affa8abb5ec6ba874530a3
61,019
pas
Pascal
comm/0046.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
11
2015-12-12T05:13:15.000Z
2020-10-14T13:32:08.000Z
comm/0046.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
null
null
null
comm/0046.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
8
2017-05-05T05:24:01.000Z
2021-07-03T20:30:09.000Z
{---------------------------------------------------------} { Project : Async12 for Windows } { By : Ir. G.W van der Vegt } {---------------------------------------------------------} { Based on the following TP product : } { } { ASYNC12 - Interrupt-driven asyncronous } { communications for Turbo Pascal. } { } { Version 1.2 - Wedensday June 14, 1989 } { Copyright (C) 1989, Rising Edge Data Services} { } { Permission is granted for non-commercial } { use and distribution. } { } { Author : Mark Schultz } { } {---------------------------------------------------------} { } { -Because of the complex nature of serial I/O not all } { routines are 100% tested. I don't feel/am/will ever be } { responsible for any damage caused by this routines. } { } { -Some routines don't work (yet) because some fields are } { mentioned in the BP7 help file but are missing in } { Wintypes. The routines are SetCTSmode, SetRTSMode & } { SoftHandshake. } { } { -Some routines can't be implemented in windows. They } { are listed behind the end. } { } { -From the original ASYNC12 code, only the syntax, some } { high level pascal code and pieces of comment are used. } { Due to the different way windows handels devices, all } { assembly codes couldn't be reused and was rewritten in } { Borland Pascal. I used parts of ASYNC12 because I find } { it a very complete package for Serial I/O and it works } { very well too. Sources were supplied and documented } { very well. } { } {---------------------------------------------------------} { Date .Time Revision } { ------- ---- ---------------------------------------- } { 9406017.1200 Creation. } {---------------------------------------------------------} Library Async12w; Uses Winprocs, Wintypes; {****************************************************************************} {----Public definition section} TYPE T_eoln = (C_cr,C_lf); CONST C_MaxCom = 4; {----Supports COM1..COM4} C_MinBaud = 110; C_MaxBaud = 256000; TYPE C_ports = 1..C_MaxCom; {----Subrange type to minimize programming errors} {****************************************************************************} {----Private definition section} CONST portopen : Array[C_ports] OF Boolean = (false,false,false,false); {----Open port flags } cids : ARRAY[C_ports] OF Integer = (-1,-1,-1,-1); {----Device ID's } inbs : ARRAY[C_ports] OF Word = ( 0, 0, 0, 0); {----Input buffer sizes} outbs : ARRAY[C_ports] OF Word = ( 0, 0, 0, 0); {----Output buffer sizes} txdir = 0; {----Used for FlushCom } rxdir = 1; {----Used for FlushCom } fon = 1; {----Used for Handshakes} foff = 0; {----Used for Handshakes} eolns : ARRAY[C_ports] OF T_eoln = (C_cr,C_cr,C_cr,C_cr); {----Eoln characters } VAR {----Don't seem to be declared in Wintypes, neccesary to fake} foutx, foutxCTSflow, fRTSflow : Byte; {****************************************************************************} {* *} {* Procedure ComReadCh(ComPort:Byte) : Char; External; *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom) *} {* *} {* Returns character from input buffer of specified port. If the buffer *} {* is empty, the port # invalid or not opened, a Chr(0) is returned. *} {* *} {****************************************************************************} Function ComReadCh(comport:C_ports) : Char; Export; Var stat : TComStat; ch : Char; cid : Integer; Begin ComReadCh:=#0; If (ComPort IN [1..C_MaxCom]) And (portopen[ComPort]) Then Begin cid:=cids[comport]; {----See how many characters are in the rx buffer} If (GetCommError(cid,stat)=0) AND (stat.cbInQue>0) AND (ReadComm(cid,@ch,1)=1) THEN ComReadCh:=ch; End; END; {of ComReadCh} {****************************************************************************} {* *} {* Function ComReadChW(ComPort:Byte) : Char; External; *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom) *} {* *} {* Works like ComReadCh, but will wait until at least 1 character is *} {* present in the specified input buffer before exiting. Thus, ComReadChW *} {* works much like the ReadKey predefined function. *} {* *} {****************************************************************************} Function ComReadChW(comport:C_ports) : Char; Export; Var stat : TComStat; ch : Char; ok : Boolean; cid : Integer; Begin ComReadChW:=#00; If (ComPort IN [1..C_MaxCom]) And (portopen[ComPort]) Then Begin cid:=cids[comport]; ok :=false; {----See how many characters are in the rx buffer} REPEAT IF (GetCommError(cid,stat)<>0) THEN ok:=True ELSE BEGIN IF (stat.cbInQue<>0) AND (ReadComm(cid,@ch,1)=1) THEN ComReadChW:=ch; ok:=true; END; UNTIL ok; End; END; {of ComReadChW} {****************************************************************************} {* *} {* Procedure ComWriteCh(ComPort:Byte; Ch:Char); External *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom) *} {* Ch:Char -> Character to send *} {* *} {* Places the character [Ch] in the transmit buffer of the specified port. *} {* If the port specified is not open or nonexistent, or if the buffer is *} {* filled, the character is discarded. *} {* *} {****************************************************************************} Procedure ComWriteCh(comport:C_ports; Ch:Char); Export; VAR stat : TComStat; cid : Integer; BEGIN If (ComPort IN [1..C_MaxCom]) And (portopen[ComPort]) Then Begin cid:=cids[comport]; IF (GetCommError(cid,stat)=0) AND (stat.cbOutQue<outbs[comport]) THEN TransmitCommChar(cid,ch); End; END; {of CommWriteCh} {****************************************************************************} {* *} {* Procedure ComWriteChW(ComPort:Byte; Ch:Char); External; *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom) *} {* Ch:Char -> Character to send *} {* *} {* Works as ComWriteCh, but will wait until at least 1 free position is *} {* available in the output buffer before attempting to place the character *} {* [Ch] in it. Allows the programmer to send characters without regard to *} {* available buffer space. *} {* *} {****************************************************************************} Procedure ComWriteChW(comport:C_ports; Ch:Char); Export; VAR stat : TComStat; cid : Integer; rdy : Boolean; BEGIN If (ComPort IN [1..C_MaxCom]) And (portopen[ComPort]) Then Begin cid:=cids[comport]; rdy:=False; REPEAT IF (GetCommError(cid,stat)<>0) THEN rdy:=true ELSE IF (stat.cbOutQue<outbs[comport]) THEN rdy:=TransmitCommChar(cid,ch)=0; UNTIL rdy; End; End; {of ComWriteChW} {****************************************************************************} {* *} {* Procedure ClearCom(ComPort:Byte); IO:Char) *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom). *} {* Request ignored if out of range or unopened. *} {* IO:Char -> Action code; I=Input, O=Output, B=Both *} {* No action taken if action code unrecognized. *} {* *} {* ClearCom allows the user to completely clear the contents of either *} {* the input (receive) and/or output (transmit) buffers. The "action *} {* code" passed in <IO> determines if the input (I) or output (O) buffer *} {* is cleared. Action code (B) will clear both buffers. This is useful *} {* if you wish to cancel a transmitted message or ignore part of a *} {* received message. *} {* *} {****************************************************************************} Procedure ClearCom(ComPort:C_Ports;IO:Char); Export; Var cid : Integer; Begin If (ComPort IN [1..C_MaxCom]) And (portopen[ComPort]) Then Begin cid:=cids[comport]; Case Upcase(IO) OF 'I' : FlushComm(cid,rxdir); 'B' : Begin FlushComm(cid,rxdir); FlushComm(cid,txdir); End; 'O' : FlushComm(cid,txdir); End; End; End; {of ClearComm} {****************************************************************************} {* *} {* Procedure ComBufferLeft(ComPort:Byte; IO:Char) : Word *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom). *} {* Returns 0 if Port # invalid or unopened. *} {* IO:Char -> Action code; I=Input, O=Output *} {* Returns 0 if action code unrecognized. *} {* *} {* ComBufferLeft will return a number (bytes) indicating how much space *} {* remains in the selected buffer. The INPUT buffer is checked if <IO> is *} {* (I), and the output buffer is interrogated when <IO> is (O). Any other *} {* "action code" will return a result of 0. Use this function when it is *} {* important to avoid program delays due to calls to output procedures or *} {* to prioritize the reception of data (to prevent overflows). *} {* *} {****************************************************************************} Function ComBufferLeft(ComPort:C_ports; IO:Char) : Word; Export; VAR stat : TComStat; cid : Integer; Begin ComBufferLeft := 0; If (ComPort IN [1..C_MaxCom]) And (portopen[ComPort]) Then Begin cid:=cids[comport]; IF (GetCommError(cid,stat)=0) THEN CASE Upcase(IO) OF 'I' : ComBufferLeft:=inbs [comport]-stat.cbInQue; 'O' : ComBufferLeft:=outbs[comport]-stat.cbOutQue; END; End; End; {ComBufferLeft} {****************************************************************************} {* *} {* Procedure ComWaitForClear(ComPort:Byte) *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom). *} {* Exits immediately if out of range or port unopened. *} {* *} {* A call to ComWaitForClear will stop processing until the selected out- *} {* put buffer is completely emptied. Typically used just before a call *} {* to the CloseCom procedure to prevent premature cut-off of messages in *} {* transit. *} {* *} {****************************************************************************} Procedure ComWaitForClear(ComPort:C_ports); Export; Var stat : TComStat; cid : Integer; Empty : Boolean; Begin If (ComPort IN [1..C_MaxCom]) And (portopen[ComPort]) Then Begin cid :=cids[comport]; empty:=false; REPEAT IF (GetCommError(cid,stat)<>0) THEN empty:=true ELSE empty:=stat.cbOutQue=0 UNTIL empty; End; End; {ComWaitForClear} {****************************************************************************} {* *} {* Procedure ComWrite(ComPort:Byte; St:String) *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom). *} {* Exits immediately if out of range or port unopened. *} {* St:String -> String to send *} {* *} {* Sends string <St> out communications port <ComPort>. *} {* *} {****************************************************************************} Procedure ComWrite(ComPort:C_ports; St:String); Export; Var X : Byte; Begin If (ComPort IN [1..C_MaxCom]) And (portopen[ComPort]) Then For X := 1 To Length(St) Do ComWriteChW(ComPort,St[X]); End; {of ComWrite} {****************************************************************************} {* *} {* Procedure ComWriteln(ComPort:Byte; St:String); *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom). *} {* Exits immediately if out of range or port unopened. *} {* St:String -> String to send *} {* *} {* Sends string <St> with a CR and LF appended. *} {* *} {****************************************************************************} Procedure ComWriteln(ComPort:C_ports; St:String); Export; Var X : Byte; Begin If (ComPort IN [1..C_MaxCom]) And (portopen[ComPort]) Then Begin For X := 1 To Length(St) Do ComWriteChW(ComPort,St[X]); ComWriteChW(ComPort,#13); ComWriteChW(ComPort,#10); End; End; {of ComWriteln} {****************************************************************************} {* *} {* Procedure Delay(ms:word); *} {* *} {* ms:word -> Number of msec to wait. *} {* *} {* A substitute for CRT's Delay under DOS. This one will wait for at least *} {* the amount of msec specified, probably even more because of the task- *) {* switching nature of Windows. So a msec can end up as a second if ALT-TAB*} {* or something like is pressed. Minumum delays are guaranteed independend *} {* of task-switches. *} {* *} {****************************************************************************} Procedure Delay(ms : Word); Var theend, marker : Longint; Begin {----Potentional overflow if windows runs for 49 days without a stop} marker:=GetTickCount; {$R-} theend:=Longint(marker+ms); {$R+} {----First see if timer overrun will occure and wait for this, then test as usual} If (theend<marker) Then While (GetTickCount>=0) DO; {----Wait for projected time to pass} While (theend>=GettickCount) Do; End; {of Delay} {****************************************************************************} {* *} {* Procedure ComWriteWithDelay(ComPort:Byte; St:String; Dly:Word); *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom). *} {* Exits immediately if out of range or port unopened. *} {* St:String -> String to send *} {* Dly:Word -> Time, in milliseconds, to delay between each char. *} {* *} {* ComWriteWithDelay will send string <St> to port <ComPort>, delaying *} {* for <Dly> milliseconds between each character. Useful for systems that *} {* cannot keep up with transmissions sent at full speed. *} {* *} {****************************************************************************} Procedure ComWriteWithDelay(ComPort:C_ports; St:String; Dly:Word); Export; Var X : Byte; Begin If (ComPort IN [1..C_MaxCom]) And (portopen[ComPort]) Then Begin ComWaitForClear(ComPort); For X := 1 To Length(St) Do Begin ComWriteChW(ComPort,St[X]); ComWaitForClear(ComPort); Delay(dly); End; End; End; {of ComWriteWithDelay} {****************************************************************************} {* *} {* Procedure ComReadln(ComPort:Byte; Var St:String; Size:Byte; Echo:Boolean)*} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom). *} {* Exits immediately if out of range or port unopened. *} {* St:String <- Edited string from remote *} {* Size:Byte; -> Maximum allowable length of input *} {* Echo:Boolean; -> Set TRUE to echo received characters *} {* *} {* ComReadln is the remote equivalent of the standard Pascal READLN pro- *} {* cedure with some enhancements. ComReadln will accept an entry of up to *} {* 40 printable ASCII characters, supporting ^H and ^X editing commands. *} {* Echo-back of the entry (for full-duplex operation) is optional. All *} {* control characters, as well as non-ASCII (8th bit set) characters are *} {* stripped. If <Echo> is enabled, ASCII BEL (^G) characters are sent *} {* when erroneous characters are intercepted. Upon receipt of a ^M (CR), *} {* the procedure is terminated and the final string result returned. *} {* *} {****************************************************************************} Procedure ComReadln(ComPort:C_ports; Var St:String; Size:Byte; Echo:Boolean); Export; Var Len,X : Byte; Ch : Char; Done : Boolean; Begin St:=''; If (ComPort IN [1..C_MaxCom]) And (portopen[ComPort]) Then Begin Done := False; Repeat Len:=Length(St); Ch :=Chr(Ord(ComReadChW(ComPort)) And $7F); Case Ch Of ^H : If Len>0 Then Begin Dec(Len); St[0]:=Chr(Len); If Echo Then ComWrite(ComPort,#8#32#8); End Else ComWriteChW(ComPort,^G); ^J : If eolns[comport]=C_lf Then Begin Done:=True; If Echo Then ComWrite(ComPort,#13#10); End; ^M : If eolns[comport]=C_cr Then Begin Done:=True; If Echo Then ComWrite(ComPort,#13#10); End; ^X : Begin St:=''; If Len=0 Then ComWriteCh(ComPort,^G); If Echo Then For X:=1 to Len Do ComWrite(ComPort,#8#32#8); End; #32.. #127 : If Len<Size Then Begin Inc(Len); St[Len]:=Ch; St[0]:=Chr(Len); If Echo Then ComWriteChW(ComPort,Ch); End Else If Echo Then ComWriteChW(ComPort,^G); Else If Echo Then ComWriteChW(ComPort,^G) End; Until Done; End; End; {of ComReadln} {****************************************************************************} {* *} {* Procedure SetRTSMode(ComPort:Byte; Mode:Boolean; RTSOn,RTSOff:Word) *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom). *} {* Request ignored if out of range or unopened. *} {* Mode:Boolean -> TRUE to enable automatic RTS handshake *} {* RTSOn:Word -> Buffer-usage point at which the RTS line is asserted *} {* RTSOff:Word -> Buffer-usage point at which the RTS line is dropped *} {* *} {* SetRTSMode enables or disables automated RTS handshaking. If [MODE] is *} {* TRUE, automated RTS handshaking is enabled. If enabled, the RTS line *} {* will be DROPPED when the # of buffer bytes used reaches or exceeds that *} {* of [RTSOff]. The RTS line will then be re-asserted when the buffer is *} {* emptied down to the [RTSOn] usage point. If either [RTSOn] or [RTSOff] *} {* exceeds the input buffer size, they will be forced to (buffersize-1). *} {* If [RTSOn] > [RTSOff] then [RTSOn] will be the same as [RTSOff]. *} {* The actual handshaking control is located in the interrupt driver for *} {* the port (see ASYNC12.ASM). *} {* *} {****************************************************************************} Procedure SetRTSmode(ComPort:C_ports; Mode:Boolean; RTSOn,RTSOff:Word); Export; Var dcb : tdcb; cid : Integer; Begin If (ComPort IN [1..C_MaxCom]) And (portopen[ComPort]) Then Begin cid:=cids[comport]; If GetCommState(cid,dcb)=0 Then Begin With dcb Do Case mode of True : Begin fRTSflow:=fon; Xonlim :=inbs[comport]-RTSon ; Xofflim :=inbs[comport]-RTSoff; End; False : Begin fRTSflow:=foff; End; End; SetCommState(dcb); End; End; End; {of SetRTSmode} {****************************************************************************} {* *} {* Procedure SetCTSMode(ComPort:Byte; Mode:Boolean) *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom). *} {* Request ignored if out of range or unopened. *} {* Mode:Boolean -> Set to TRUE to enable automatic CTS handshake. *} {* *} {* SetCTSMode allows the enabling or disabling of automated CTS handshak- *} {* ing. If [Mode] is TRUE, CTS handshaking is enabled, which means that *} {* if the remote drops the CTS line, the transmitter will be disabled *} {* until the CTS line is asserted again. Automatic handshake is disabled *} {* if [Mode] is FALSE. CTS handshaking and "software" handshaking (pro- *} {* vided by the SoftHandshake procedure) ARE compatable and may be used *} {* in any combination. *} {* *} {****************************************************************************} Procedure SetCTSMode(ComPort:Byte; Mode:Boolean); Export; Var dcb : tdcb; cid : Integer; Begin If (ComPort IN [1..C_MaxCom]) And (portopen[ComPort]) Then Begin cid:=cids[comport]; If GetCommState(cid,dcb)=0 Then Begin Case mode of True : foutxCTSflow:=fon; False : foutxCTSflow:=foff; End; SetCommState(dcb); End; End; End; {of SetCTSmode} {****************************************************************************} {* *} {* Procedure SoftHandshake(ComPort:Byte; Mode:Boolean; Start,Stop:Char) *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom). *} {* Request ignored if out of range or unopened. *} {* Mode:Boolean -> Set to TRUE to enable transmit software handshake *} {* Start:Char -> START control character (usually ^Q) *} {* Defaults to ^Q if character passed is >= <Space> *} {* Stop:Char -> STOP control character (usually ^S) *} {* Defaults to ^S if character passed is >= <Space> *} {* *} {* SoftHandshake controls the usage of "Software" (control-character) *} {* handshaking on transmission. If "software handshake" is enabled *} {* ([Mode] is TRUE), transmission will be halted if the character in *} {* [Stop] is received. Transmission is re-enabled if the [Start] char- *} {* acter is received. Both the [Start] and [Stop] characters MUST be *} {* CONTROL characters (i.e. Ord(Start) and Ord(Stop) must both be < 32). *} {* Also, <Start> and <Stop> CANNOT be the same character. If either one *} {* of these restrictions are violated, the defaults (^Q for <Start> and ^S *} {* for <Stop>) will be used. *} {* *} {****************************************************************************} Procedure SoftHandshake(ComPort:Byte; Mode:Boolean; Start,Stop:Char); Export; Var dcb : tdcb; cid : integer; Begin If (ComPort IN [1..C_MaxCom]) And (portopen[ComPort]) Then Begin cid:=cids[comport]; If GetCommState(cid,dcb)=0 Then Begin Case mode of True : Begin foutx:=fon; If (start IN [#00..#31]) And (start<>stop) Then dcb.Xonchar:=start Else dcb.Xonchar:=^Q; If (stop IN [#00..#31]) And (start<>stop) Then dcb.Xoffchar:=stop Else dcb.Xoffchar:=^S; End; False : foutx:=foff; End; SetCommState(dcb); End; End; End; {of Softhandshake} {****************************************************************************} {* *} {* Function ComExist(ComPort:Byte) : Boolean *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom) *} {* Returns FALSE if out of range *} {* Returns TRUE if hardware for selected port is detected & tests OK *} {* *} {****************************************************************************} Function ComExist(ComPort:C_ports) : Boolean; Export; VAR mode : String; dcb : tdcb; Begin If (ComPort IN [1..C_MaxCom]) Then Begin mode:='COM'+Chr(Comport+Ord('0'))+' 19200,N,8,1'#0; ComExist:=(BuildCommDCB(@mode[1],dcb)=0); End Else ComExist:=false; End; {of Comexist} {****************************************************************************} {* *} {* Function ComTrueBaud(Baud:Longint) : Real *} {* *} {* Baud:Longint -> User baud rate to test. *} {* Should be between C_MinBaud and C_MaxBaud. *} {* Returns the actual baud rate based on the accuracy of the 8250 divider. *} {* *} {* The ASYNC12 communications package allows the programmer to select ANY *} {* baud rate, not just those that are predefined by the BIOS or other *} {* agency. Since the 8250 uses a divider/counter chain to generate it's *} {* baud clock, many non-standard baud rates can be generated. However, *} {* the binary counter/divider is not always capable of generating the *} {* EXACT baud rate desired by a user. This function, when passed a valid *} {* baud rate, will return the ACTUAL baud rate that will be generated. *} {* The baud rate is based on a 8250 input clock rate of 1.73728 MHz. *} {* *} {****************************************************************************} Function ComTrueBaud(Baud:Longint) : Real; Export; Var X : Real; Y : Word; Begin X := Baud; If X < C_MinBaud Then X := C_MinBaud; If X > C_MaxBaud Then X := C_MaxBaud; ComTrueBaud := C_MaxBaud / Round($900/(X/50)); End; {of ComTrueBaud} {****************************************************************************} {* *} {* Function Lstr(l : Longint) : String; *} {* *} {* l:Longint -> Number converted to a string *} {* *} {* This function converts longint l to a string. *} {* *} {****************************************************************************} Function Lstr(l : Longint) : String; Var s : String; Begin Str(l:0,s); Lstr:=s; End; {of Lstr} {****************************************************************************} {* *} {* Procedure ComParams(ComPort:Byte; Baud:Longint; *} {* WordSize:Byte; Parity:Char; StopBits:Byte); *} {* *} {* ComPort:Byte -> Port # to initialize. Must be (1 - C_MaxCom) *} {* Procedure aborted if port # invalid or unopened. *} {* Baud:Longint -> Desired baud rate. Should be (C_MinBaud - C_MaxBaud)*} {* C_MinBaud or C_MaxBaud used if out of range. *} {* WordSize:Byte -> Word size, in bits. Must be 5 - 8 bits. *} {* 8-bit word used if out of range. *} {* Parity:Char -> Parity classification. *} {* May be N)one, E)ven, O)dd, M)ark or S)pace. *} {* N)one selected if classification unknown. *} {* StopBits:Byte -> # of stop bits to pad character with. Range (1-2) *} {* 1 stop bit used if out of range. *} {* *} {* ComParams is used to configure an OPEN'ed port for the desired comm- *} {* unications parameters, namely baud rate, word size, parity form and *} {* # of stop bits. A call to this procedure will set up the port approp- *} {* riately, as well as assert the DTR, RTS and OUT2 control lines and *} {* clear all buffers. *} {* *} {****************************************************************************} Procedure ComParams(ComPort:C_ports; Baud:LongInt; WordSize:Byte; Parity:Char; StopBits:Byte); Export; Var mode : String; cid : Integer; dcb : tdcb; Begin If (ComPort IN [1..C_MaxCom]) And (portopen[ComPort]) Then Begin cid:=cids[comport]; {----Like COM1 9600,N,8,1} mode:='COM'+Chr(Comport+Ord('0'))+' '+Lstr(baud)+','+Upcase(Parity)+','+Lstr(Wordsize)+','+Lstr(stopbits)+#0; IF (BuildCommDCB(@mode[1],dcb)=0) Then Begin dcb.id:=cid; SetCommState(dcb); End; End; End; {of ComParams} {****************************************************************************} {* *} {* Function OpenCom(ComPort:Byte; InBufferSize,OutBufferSize:Word):Boolean *} {* *} {* ComPort:Byte -> Port # to OPEN (1 - C_MaxCom) *} {* Request will fail if out of range or port OPEN *} {* InBufferSize:Word -> Requested size of input (receive) buffer *} {* OutBufferSize:Word -> Requested size of output (transmit) buffer *} {* Returns success/fail status of OPEN request (TRUE if OPEN successful) *} {* *} {* OpenCom must be called before any activity (other than existence check, *} {* see the ComExist function) takes place. OpenCom initializes the *} {* interrupt drivers and serial communications hardware for the selected *} {* port, preparing it for I/O. Once a port has been OPENed, a call to *} {* ComParams should be made to set up communications parameters (baud rate,*} {* parity and the like). Once this is done, I/O can take place on the *} {* port. OpenCom will return a TRUE value if the opening procedure was *} {* successful, or FALSE if it is not. *} {* *} {****************************************************************************} Function OpenCom(ComPort:C_ports; InBufferSize,OutBufferSize:Word) : Boolean; Export; Var cid : Integer; comp : String; Begin OpenCom := False; If (ComPort IN [1..C_MaxCom]) And Not(portopen[ComPort]) And ComExist(comport) Then Begin comp:='COM'+Chr(comport+Ord('0'))+#0; cid:=OpenComm(@comp[1],InBufferSize,OutBufferSize); If (cid>=0) Then Begin cids [comport] :=cid; inbs [comport] :=InBufferSize; outbs[comport] :=OutBufferSize; portopen[comport]:=true; End; OpenCom:=(cid>=0); End; End; {of OpenCom} {****************************************************************************} {* *} {* Procedure CloseCom(ComPort:Byte) *} {* *} {* ComPort:Byte -> Port # to close *} {* Request ignored if port closed or out of range. *} {* *} {* CloseCom will un-link the interrupt drivers for a port, deallocate it's *} {* buffers and drop the DTR and RTS signal lines for a port opened with *} {* the OpenCom function. It should be called before exiting your program *} {* to ensure that the port is properly shut down. *} {* NOTE: CloseCom shuts down a communications channel IMMEDIATELY, *} {* even if there is data present in the input or output buffers. *} {* Therefore, you may wish to call the ComWaitForClear procedure *} {* before closing the ports. *} {* *} {****************************************************************************} Procedure CloseCom(ComPort:C_ports); Export; Var cid : integer; Begin If (ComPort IN [1..C_MaxCom]) And (portopen[ComPort]) Then Begin cid:=cids[comport]; portopen[comport]:=Not(CloseComm(cid)=0); End; End; {of CloseCom} {****************************************************************************} {* *} {* Procedure CloseAllComs *} {* *} {* CloseAllComs will CLOSE all currently OPENed ports. See the CloseCom *} {* procedure description for more details. *} {* *} {****************************************************************************} Procedure CloseAllComs; Export; Var X : C_ports; Begin For X := 1 To C_MaxCom Do If portopen[X] Then CloseCom(X); End; {of CloseAllComs} {****************************************************************************} {* *} {* Procedure ComSetEoln(ComPort:C_ports;EolnCh : T_eoln) *} {* *} {* ComPort:Byte -> Port # for which to alter the eoln character *} {* Request ignored if port closed or out of range. *} {* EolnCh:T_eoln -> Eoln character needed *} {* *} {* With this function one can toggle the eoln character between cr and lf. *} {* *} {****************************************************************************} Procedure ComSetEoln(ComPort:C_ports;EolnCh : T_eoln); Export; Begin If (ComPort IN [1..C_MaxCom]) And (portopen[ComPort]) Then eolns[comport]:=EolnCh; End; {of ComSetEoln} {****************************************************************************} {* *} {* Function ComGetBufsize(ComPort:C_ports;IO : char) *} {* *} {* ComPort:Byte -> Port # for which to retrieve the buffersize *} {* Request ignored if port closed or out of range. *} {* IO:Char -> Action code; I=Input, O=Output *} {* Returns 0 if action code unrecognized. *} {* *} {* This function will return the buffer size defined for a serial port. *} {* *} {****************************************************************************} Function ComGetBufsize(ComPort:C_ports;IO : Char) : WORD; Export; Begin ComGetBufSize:=0; If (ComPort IN [1..C_MaxCom]) And (portopen[ComPort]) Then CASE Upcase(IO) OF 'I' : ComgetBufSize:=inbs [comport]; 'O' : ComgetBufSize:=outbs[comport]; END; End; {of ComGetBufferSize} {****************************************************************************} Exports ComReadCh index 1, ComReadChW index 2, ComWriteCh index 3, ComWriteChW index 4, ClearCom index 5, ComBufferLeft index 6, ComWaitForClear index 7, ComWrite index 8, ComWriteln index 9, ComWriteWithDelay index 10, ComReadln index 11, SetRTSmode index 12, SetCTSMode index 13, SoftHandshake index 14, ComExist index 15, ComTrueBaud index 16, ComParams index 17, OpenCom index 18, CloseCom index 19, CloseAllComs index 20, ComSetEoln index 21, ComGetBufSize index 22; Begin End. {----The following procedures/functions from the async12 } { package are not available } {****************************************************************************} {* *} {* Procedure SetDTR(ComPort:Byte; Assert:Boolean); *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom) *} {* Call ignored if out-of-range *} {* Assert:Boolean -> DTR assertion flag (TRUE to assert DTR) *} {* *} {* Provides a means to control the port's DTR (Data Terminal Ready) signal *} {* line. When [Assert] is TRUE, the DTR line is placed in the "active" *} {* state, signalling to a remote system that the host is "on-line" *} {* (although not nessesarily ready to receive data - see SetRTS). *} {* *} {****************************************************************************} Procedure SetDTR(ComPort:Byte; Assert:Boolean); Begin End; {of SetDTR} {****************************************************************************} {* *} {* Procedure SetRTS(ComPort:Byte; Assert:Boolean) *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom) *} {* Call ignored if out-of-range *} {* Assert:Boolean -> RTS assertion flag (Set TRUE to assert RTS) *} {* *} {* SetRTS allows a program to manually control the Request-To-Send (RTS) *} {* signal line. If RTS handshaking is disabled (see C_Ctrl definition *} {* and the the SetRTSMode procedure), this procedure may be used. SetRTS *} {* should NOT be used if RTS handshaking is enabled. *} {* *} {****************************************************************************} Procedure SetRTS(ComPort:Byte; Assert:Boolean); Begin End; {of SetRTS} {****************************************************************************} {* *} {* Procedure SetOUT1(ComPort:Byte; Assert:Boolean) *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom) *} {* Call ignored if out-of-range *} {* Assert:Boolean -> OUT1 assertion flag (set TRUE to assert OUT1 line) *} {* *} {* SetOUT1 is provided for reasons of completeness only, since the *} {* standard PC/XT/AT configurations do not utilize this control signal. *} {* If [Assert] is TRUE, the OUT1 signal line on the 8250 will be set to a *} {* LOW logic level (inverted logic). The OUT1 signal is present on pin 34 *} {* of the 8250 (but not on the port itself). *} {* *} {****************************************************************************} Procedure SetOUT1(ComPort:Byte; Assert:Boolean); Begin End; {of SetOUT1} {****************************************************************************} {* *} {* Procedure SetOUT2(ComPort:Byte; Assert:Boolean) *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom) *} {* Call ignored if out-of-range *} {* Assert:Boolean -> OUT2 assertion flag (set TRUE to assert OUT2 line) *} {* *} {* The OUT2 signal line, although not available on the port itself, is *} {* used to gate the 8250 <INTRPT> (interrupt) line and thus acts as a *} {* redundant means of controlling 8250 interrupts. When [Assert] is TRUE, *} {* the /OUT2 line on the 8250 is lowered, which allows the passage of the *} {* <INTRPT> signal through a gating arrangement, allowing the 8250 to *} {* generate interrupts. Int's can be disabled bu unASSERTing this line. *} {* *} {****************************************************************************} Procedure SetOUT2(ComPort:Byte; Assert:Boolean); Begin End; {of SetOUT2} {****************************************************************************} {* *} {* Function CTSStat(ComPort:Byte) : Boolean *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom) *} {* Call ignored if out-of-range *} {* Returns status of Clear-To-Send line (TRUE if CTS asserted) *} {* *} {* CTSStat provides a means to interrogate the Clear-To-Send hardware *} {* handshaking line. In a typical arrangement, when CTS is asserted, this *} {* signals the host (this computer) that the receiver is ready to accept *} {* data (in contrast to the DSR line, which signals the receiver as *} {* on-line but not nessesarily ready to accept data). An automated mech- *} {* ansim (see CTSMode) is provided to do this, but in cases where this is *} {* undesirable or inappropriate, the CTSStat function can be used to int- *} {* terrogate this line manually. *} {* *} {****************************************************************************} Function CTSStat(ComPort:Byte) : Boolean; Begin End; {of CTSstat} {****************************************************************************} {* *} {* Function DSRStat(ComPort:Byte) : Boolean *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom) *} {* Call ignored if out-of-range *} {* Returns status of Data Set Ready (DSR) signal line. *} {* *} {* The Data Set Ready (DSR) line is typically used by a remote station *} {* to signal the host system that it is on-line (although not nessesarily *} {* ready to receive data yet - see CTSStat). A remote station has the DSR *} {* line asserted if DSRStat returns TRUE. *} {* *} {****************************************************************************} Function DSRStat(ComPort:Byte) : Boolean; Begin End; {of DSRstat} {****************************************************************************} {* *} {* Function RIStat(ComPort:Byte) : Boolean *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom) *} {* Call ignored if out-of-range *} {* *} {* Returns the status of the Ring Indicator (RI) line. This line is *} {* typically used only by modems, and indicates that the modem has detect- *} {* ed an incoming call if RIStat returns TRUE. *} {* *} {****************************************************************************} Function RIStat(ComPort:Byte) : Boolean; Begin End; {of RIstat} {****************************************************************************} {* *} {* Function DCDStat(ComPort:Byte) : Boolean *} {* *} {* ComPort:Byte -> Port # to use (1 - C_MaxCom) *} {* Call ignored if out-of-range *} {* *} {* Returns the status of the Data Carrier Detect (DCD) line from the rem- *} {* ote device, typically a modem. When asserted (DCDStat returns TRUE), *} {* the modem indicates that it has successfuly linked with another modem *} {* device at another site. *} {* *} {****************************************************************************} Function DCDStat(ComPort:Byte) : Boolean; Begin End; {of DCDstat} { --------------- WINDOWS INTERFACE UNIT -------------------- } Unit WinAsync; Interface CONST C_MaxCom = 4; {----supports COM1..COM4 } C_MinBaud = 110; {----min baudrate supported by windows 3.1 } C_MaxBaud = 256000; {----max baudrate supported by windows 3.1 } TYPE T_eoln = (C_cr,C_lf); {----used to change EOLN character from cr to lf} C_ports = 1..C_MaxCom; {----subrange type to minimize programming errors} Function ComReadCh(comport:C_ports) : Char; Function ComReadChW(comport:C_ports) : Char; Procedure ComReadln(ComPort:C_ports; Var St:String; Size:Byte; Echo:Boolean); Procedure ComWriteCh(comport:C_ports; Ch:Char); Procedure ComWriteChW(comport:C_ports; Ch:Char); Procedure ComWrite(ComPort:C_ports; St:String); Procedure ComWriteln(ComPort:C_ports; St:String); Procedure ComWriteWithDelay(ComPort:C_ports; St:String; Dly:Word); Procedure ClearCom(ComPort:C_Ports;IO:Char); Function ComBufferLeft(ComPort:C_ports; IO:Char) : Word; Procedure ComWaitForClear(ComPort:C_ports); Procedure SetRTSmode(ComPort:C_ports; Mode:Boolean; RTSOn,RTSOff:Word); Procedure SetCTSMode(ComPort:Byte; Mode:Boolean); Procedure SoftHandshake(ComPort:Byte; Mode:Boolean; Start,Stop:Char); Function ComExist(ComPort:C_ports) : Boolean; Procedure ComParams(ComPort:C_ports; Baud:LongInt; WordSize:Byte; Parity:Char; StopBits:Byte); Function ComTrueBaud(Baud:Longint) : Real; Function OpenCom(ComPort:C_ports; InBufferSize,OutBufferSize:Word) : Boolean; Procedure CloseCom(ComPort:C_ports); Procedure CloseAllComs; Procedure ComSetEoln(ComPort:C_ports;EolnCh : T_eoln); Function ComGetBufsize(ComPort:C_ports;IO : Char) : WORD; Implementation Function ComReadCh(comport:C_ports) : Char; external 'async12w'; Function ComReadChW(comport:C_ports) : Char; external 'async12w'; Procedure ComWriteCh(comport:C_ports; Ch:Char); external 'async12w'; Procedure ComWriteChW(comport:C_ports; Ch:Char); external 'async12w'; Procedure ClearCom(ComPort:C_Ports;IO:Char); external 'async12w'; Function ComBufferLeft(ComPort:C_ports; IO:Char) : Word; external 'async12w'; Procedure ComWaitForClear(ComPort:C_ports); external 'async12w'; Procedure ComWrite(ComPort:C_ports; St:String); external 'async12w'; Procedure ComWriteln(ComPort:C_ports; St:String); external 'async12w'; Procedure ComWriteWithDelay(ComPort:C_ports; St:String; Dly:Word); external 'async12w'; Procedure ComReadln(ComPort:C_ports; Var St:String;Size:Byte; Echo:Boolean); external 'async12w'; Procedure SetRTSmode(ComPort:C_ports; Mode:Boolean; RTSOn,RTSOff:Word); external 'async12w'; Procedure SetCTSMode(ComPort:Byte; Mode:Boolean); external 'async12w'; Procedure SoftHandshake(ComPort:Byte; Mode:Boolean; Start,Stop:Char); external 'async12w'; Function ComExist(ComPort:C_ports) : Boolean; external 'async12w'; Function ComTrueBaud(Baud:Longint) : Real; external 'async12w'; Procedure ComParams(ComPort:C_ports; Baud:LongInt; WordSize:Byte; Parity:Char; StopBits:Byte); external 'async12w'; Function OpenCom(ComPort:C_ports; InBufferSize,OutBufferSize:Word) : Boolean; external 'async12w'; Procedure CloseCom(ComPort:C_ports); external 'async12w'; Procedure CloseAllComs; external 'async12w'; Procedure ComSetEoln(ComPort:C_ports;EolnCh : T_eoln); external 'async12w'; Function ComGetBufsize(ComPort:C_ports;IO : Char) : WORD; external 'async12w'; End. { ------------------------------ TEST PROGRAM ----------------------- } Program Asynctst; Uses Wincrt, Asyncwin; {----Demo main program for Async12w} Var p : Byte; s : string; i : Integer; Begin Write('Enter serial port number [1..4] : '); readln(p); IF ComExist(p) And OpenCom(p,1024,1024) Then Begin ComParams(p,9600,8,'N',1); {----Hayes modems echo a cr,lf so lf as eoln char is easier to program. The cr is skipped also. Default eoln character is cr, equivalent to BP's readln procedure} ComSetEoln(p,c_lf); Writeln('Enter a Hayes Command, like ATX1'); Readln(s); If (s<>'') THEN BEGIN Write('Sending...'); ComWriteWithDelay(p,s+#13#10,500); Writeln(' ok, press <enter> to continue.'); Readln; Repeat Write('[',CombufferLeft(p,'I'):3,']'); ComReadln(p,s,255,false); Writeln('[',ComBufferLeft(p,'I'):3,']',s); Until (ComBufferLeft(p,'I')=1024); END; CloseCom(p); End Else Writeln('Error opening COM',p,' port'); END. 
46.261562
118
0.388715
839404fc2f584379b02f2a3bab6051763aa7890d
196
pas
Pascal
111219/4.pas
irasap05/pascal
9ec73a80cddef094ed56969f003b498f73c9cbb5
[ "Apache-2.0" ]
null
null
null
111219/4.pas
irasap05/pascal
9ec73a80cddef094ed56969f003b498f73c9cbb5
[ "Apache-2.0" ]
null
null
null
111219/4.pas
irasap05/pascal
9ec73a80cddef094ed56969f003b498f73c9cbb5
[ "Apache-2.0" ]
null
null
null
var n, s, f: integer; Begin read(n); s := 0; for var i := 1 to n do begin f := 1; for var d := 1 to i do begin f *= d; end; s += f; end; write(s); end.
11.529412
26
0.418367
471e895a811d93d8de3959e3c2a73d767ab66f67
40,209
pas
Pascal
libs/superxmlparser.pas
AndanTeknomedia/bazda-delphi-xe8
3cb9589e41bf7a7492323348a429a6ef7f357817
[ "MIT" ]
150
2015-11-27T16:00:15.000Z
2021-12-02T03:41:21.000Z
libs/superxmlparser.pas
AndanTeknomedia/bazda-delphi-xe8
3cb9589e41bf7a7492323348a429a6ef7f357817
[ "MIT" ]
null
null
null
libs/superxmlparser.pas
AndanTeknomedia/bazda-delphi-xe8
3cb9589e41bf7a7492323348a429a6ef7f357817
[ "MIT" ]
70
2015-12-03T09:51:57.000Z
2021-12-02T03:41:23.000Z
unit superxmlparser; {$IFDEF FPC} {$MODE OBJFPC}{$H+} {$ENDIF} interface uses superobject, classes; type TOnProcessingInstruction = procedure(const PI, PIParent: ISuperObject); function XMLParseString(const data: SOString; pack: Boolean = false; onpi: TOnProcessingInstruction = nil): ISuperObject; function XMLParseStream(stream: TStream; pack: Boolean = false; onpi: TOnProcessingInstruction = nil): ISuperObject; function XMLParseFile(const FileName: string; pack: Boolean = false; onpi: TOnProcessingInstruction = nil): ISuperObject; const xmlname = '#name'; xmlattributes = '#attributes'; xmlchildren = '#children'; dtdname = '#name'; dtdPubidLiteral = '#pubidliteral'; dtdSystemLiteral = '#systemliteral'; implementation uses sysutils {$IFNDEF UNIX}, windows{$ENDIF}; const XML_SPACE : PSOChar = #32; // XML_ARL: PSOChar = '['; XML_ARR: PSOChar = ']'; XML_BIG: PSOChar = '>'; XML_LOW: PSOChar = '<'; XML_AMP: PSOChar = '&'; XML_SQU: PSOChar = ''''; XML_DQU: PSOChar = '"'; type TSuperXMLState = ( xsStart, // | xsEatSpaces, // xsElement, // <| xsElementName, // <[a..z]| xsAttributes, // <xml | xsAttributeName, // <xml a| xsEqual, // |= ... xsAttributeValue, // = |"... xsCloseEmptyElement, // <xml/| xsTryCloseElement, // <xml>..<| xsCloseElementName, // <xml>..</| xsChildren, // <xml>| xsElementString, // <xml> |azer xsElementComment, // <!|-- ... xsElementDocType, // <!D| xsElementDocTypeName, // <!DOCTYPE |... xsElementDocTypeExternId, // <!DOCTYPE xml | xsElementDocTypeExternIdPublic, // <!DOCTYPE xml P| xsElementDocTypeExternIdSystem, // <!DOCTYPE xml S| xsElementDocTypePubIdLiteral, // <!DOCTYPE xml SYSTEM |" xsElementDocTypeSystemLiteral, // <!DOCTYPE xml SYSTEM "" |"" xsElementDocTypeTryIntSubset, xsElementDocTypeIntSubset, xsElementDocTypeTryClose, xsElementDocTypeEat, // xsCloseElementComment, // <!-- -|-> xsElementPI, // <?| xsElementDataPI, // not an xml PI xsCloseElementPI, // <? ?|> xsElementCDATA, // <![|CDATA[ xsClodeElementCDATA, // ]|]> xsEscape, // &| xsEscape_lt, // &l|t; xsEscape_gt, // &g|t; xsEscape_amp, // &a|mp; xsEscape_apos, // &a|pos; xsEscape_quot, // &q|uot; xsEscape_char, // &#|; xsEscape_char_num, // &#1|123456; xsEscape_char_hex, // &#x|000FFff; xsEnd); TSuperXMLError = (xeSuccess, xeContinue, xeProcessInst, xeError); TSuperXMLElementClass = (xcNone, xcElement, xcComment, xcString, xcCdata, xcDocType, xcProcessInst); TSuperXMLEncoding = ({$IFNDEF UNIX}xnANSI,{$ENDIF} xnUTF8, xnUnicode); PSuperXMLStack = ^TSuperXMLStack; TSuperXMLStack = record state: TSuperXMLState; savedstate: TSuperXMLState; prev: PSuperXMLStack; next: PSuperXMLStack; clazz: TSuperXMLElementClass; obj: ISuperObject; end; TSuperXMLParser = class private FStack: PSuperXMLStack; FDocType: ISuperObject; FError: TSuperXMLError; FStr: TSuperWriterString; FValue: TSuperWriterString; FPosition: Integer; FAChar: SOChar; FPack: Boolean; procedure StackUp; procedure StackDown; procedure Reset; function ParseBuffer(data: PSOChar; var PI, PIParent: ISuperObject; len: Integer = -1): Integer; public constructor Create(pack: Boolean); destructor Destroy; override; end; { TXMLContext } constructor TSuperXMLParser.Create(pack: Boolean); begin FDocType := nil; FStr := TSuperWriterString.Create; FValue := TSuperWriterString.Create; StackUp; FError := xeSuccess; FPack := pack; end; destructor TSuperXMLParser.Destroy; begin while FStack <> nil do StackDown; FStr.Free; FValue.Free; end; procedure TSuperXMLParser.Reset; begin while FStack <> nil do StackDown; StackUp; FError := xeSuccess; end; function TSuperXMLParser.ParseBuffer(data: PSOChar; var PI, PIParent: ISuperObject; len: integer): Integer; const spaces = [#32,#9,#10,#13]; alphas = ['a'..'z', 'A'..'Z', '_', ':', #161..#255]; nums = ['0'..'9', '.', '-']; hex = nums + ['a'..'f','A'..'F']; alphanums = alphas + nums; publitteral = [#32, #13, #10, 'a'..'z', 'A'..'Z', '0'..'9', '-', '''', '"', '(', ')', '+', ',', '.', '/', ':', '=', '?', ';', '!', '*', '#', '@', '$', '_', '%']; function hexdigit(const x: SOChar): byte; begin if x <= '9' then Result := byte(x) - byte('0') else Result := (byte(x) and 7) + 9; end; procedure putchildrenstr; var anobject: ISuperObject; begin anobject := FStack^.obj.AsObject[xmlchildren]; if anobject = nil then begin anobject := TSuperObject.Create(stArray); FStack^.obj.AsObject[xmlchildren] := anobject; end; anobject.AsArray.Add(TSuperObject.Create(FValue.Data)); end; procedure AddProperty(const parent, value: ISuperObject; const name: SOString); var anobject: ISuperObject; arr: ISuperObject; begin anobject := parent.AsObject[name]; if anobject = nil then parent.AsObject[name] := value else begin if (anobject.DataType = stArray) then anobject.AsArray.Add(value) else begin arr := TSuperObject.Create(stArray); arr.AsArray.Add(anobject); arr.AsArray.Add(value); parent.AsObject[name] := arr; end; end; end; procedure packend; var anobject, anobject2: ISuperObject; n: Integer; begin anobject := FStack^.obj.AsObject[xmlchildren]; if (anobject <> nil) and (anobject.AsArray.Length = 1) and (anobject.AsArray[0].DataType = stString) then begin if FStack^.obj.AsObject.count = 2 then // name + children begin if FStack^.prev <> nil then AddProperty(FStack^.prev^.obj, anobject.AsArray[0], FStack^.obj.AsObject.S[xmlname]) else begin AddProperty(FStack^.obj, anobject.AsArray[0], '#text'); FStack^.obj.AsObject.Delete(xmlchildren); end; end else begin AddProperty(FStack^.obj, anobject.AsArray[0], FStack^.obj.AsObject.S[xmlname]); FStack^.obj.AsObject.Delete(xmlchildren); if FStack^.prev <> nil then AddProperty(FStack^.prev^.obj, FStack^.obj, FStack^.obj.AsObject.S[xmlname]) else FStack^.obj.AsObject.Delete(xmlchildren); FStack^.obj.AsObject.Delete(xmlname); end; end else begin if (anobject <> nil) then begin for n := 0 to anobject.AsArray.Length - 1 do begin anobject2 := anobject.AsArray[n]; if ObjectIsType(anobject2, stObject) then begin AddProperty(FStack^.obj, anobject2, anobject2.AsObject.S[xmlname]); anobject2.AsObject.Delete(xmlname); end else AddProperty(FStack^.obj, anobject2, '#text'); end; FStack^.obj.Delete(xmlchildren); end; if FStack^.prev <> nil then AddProperty(FStack^.prev^.obj, FStack^.obj, FStack^.obj.AsObject.S[xmlname]); FStack^.obj.Delete(xmlname); end; end; var c: SOChar; read: Integer; p: PSOChar; anobject: ISuperObject; label redo, err; begin p := data; read := 0; //Result := 0; repeat if (read = len) then begin if (FStack^.prev = nil) and ((FStack^.state = xsEnd) or ((FStack^.state = xsEatSpaces) and (FStack^.savedstate = xsEnd))) then begin if FPack then packend; FError := xeSuccess; end else FError := xeContinue; Result := read; exit; end; c := p^; redo: case FStack^.state of xsEatSpaces: if {$IFDEF UNICODE}(c < #256) and {$ENDIF} (AnsiChar(c) in spaces) then {nop} else begin FStack^.state := FStack^.savedstate; goto redo; end; xsStart: case c of '<': FStack^.state := xsElement; else goto err; end; xsElement: begin case c of '?': begin FStack^.savedstate := xsStart; FStack^.state := xsEatSpaces; StackUp; FStr.Reset; FStack^.state := xsElementPI; FStack^.clazz := xcProcessInst; end; '!': begin FPosition := 0; FStack^.state := xsElementComment; FStack^.clazz := xcComment; end; else if ((c < #256) and (AnsiChar(c) in alphas)) or (c >= #256) then begin FStr.Reset; FStack^.state := xsElementName; FStack^.clazz := xcElement; goto redo; end else goto err; end; end; xsElementPI: begin if ((c < #256) and (AnsiChar(c) in alphanums)) or (c >= #256) then FStr.Append(@c, 1) else begin FStack^.obj := TSuperObject.Create(stObject); FStack^.obj.AsObject.S[xmlname] := FStr.Data; FStack^.state := xsEatSpaces; if FStr.Data = 'xml' then FStack^.savedstate := xsAttributes else begin FValue.Reset; FStack^.savedstate := xsElementDataPI; end; goto redo; end; end; xsElementDataPI: begin case c of '?': begin FStack^.obj.AsObject.S['data'] := FValue.Data; FStack^.state := xsCloseElementPI; end; else FValue.Append(@c, 1); end; end; xsCloseElementPI: begin if (c <> '>') then goto err; PI := FStack^.obj; StackDown; PIParent := FStack^.obj; FError := xeProcessInst; Result := read + 1; Exit; end; xsElementName: begin if ((c < #256) and (AnsiChar(c) in alphanums)) or (c >= #256) then FStr.Append(@c, 1) else begin FStack^.obj := TSuperObject.Create(stObject); FStack^.obj.AsObject.S[xmlname] := FStr.Data; FStack^.state := xsEatSpaces; FStack^.savedstate := xsAttributes; goto redo; end; end; xsChildren: begin case c of '<': FStack^.state := xsTryCloseElement; else FValue.Reset; FStack^.state := xsElementString; FStack^.clazz := xcString; goto redo; end; end; xsCloseEmptyElement: begin case c of '>': begin FStack^.state := xsEatSpaces; FStack^.savedstate := xsEnd; end else goto err; end; end; xsTryCloseElement: begin case c of '/': begin FStack^.state := xsCloseElementName; FPosition := 0; FStr.Reset; FStr.Append(PSoChar(FStack^.obj.AsObject.S[xmlname])); end; '!': begin FPosition := 0; FStack^.state := xsElementComment; FStack^.clazz := xcComment; end; '?': begin FStack^.savedstate := xsChildren; FStack^.state := xsEatSpaces; StackUp; FStr.Reset; FStack^.state := xsElementPI; FStack^.clazz := xcProcessInst; end else FStack^.state := xsChildren; StackUp; if ((c < #256) and (AnsiChar(c) in alphas)) or (c >= #256) then begin FStr.Reset; FStack^.state := xsElementName; FStack^.clazz := xcElement; goto redo; end else goto err; end; end; xsCloseElementName: begin if FStr.Position = FPosition then begin FStack^.savedstate := xsCloseEmptyElement; FStack^.state := xsEatSpaces; goto redo; end else begin if (c <> FStr.Data[FPosition]) then goto err; inc(FPosition); end; end; xsAttributes: begin case c of '?': begin if FStack^.clazz <> xcProcessInst then goto err; FStack^.state := xsCloseElementPI; end; '/': begin FStack^.state := xsCloseEmptyElement; end; '>': begin FStack^.state := xsEatSpaces; FStack^.savedstate := xsChildren; end else if ((c < #256) and (AnsiChar(c) in alphas)) or (c >= #256) then begin FStr.Reset; FStr.Append(@c, 1); FStack^.state := xsAttributeName; end else goto err; end; end; xsAttributeName: begin if ((c < #256) and (AnsiChar(c) in alphanums)) or (c >= #256) then FStr.Append(@c, 1) else begin // no duplicate attribute if FPack then begin if FStack^.obj.AsObject[FStr.Data] <> nil then goto err; end else begin anobject := FStack^.obj.AsObject[xmlattributes]; if (anobject <> nil) and (anobject.AsObject[FStr.Data] <> nil) then goto err; end; FStack^.state := xsEatSpaces; FStack^.savedstate := xsEqual; goto redo; end; end; xsEqual: begin if c <> '=' then goto err; FStack^.state := xsEatSpaces; FStack^.savedstate := xsAttributeValue; FValue.Reset; FPosition := 0; FAChar := #0; end; xsAttributeValue: begin if FAChar <> #0 then begin if (c = FAChar) then begin if FPack then begin FStack^.obj.AsObject[FStr.Data] := TSuperObject.Create(Fvalue.Data); end else begin anobject := FStack^.obj.AsObject[xmlattributes]; if anobject = nil then begin anobject := TSuperObject.Create(stObject); FStack^.obj.AsObject[xmlattributes] := anobject; end; anobject.AsObject[FStr.Data] := TSuperObject.Create(Fvalue.Data); end; FStack^.savedstate := xsAttributes; FStack^.state := xsEatSpaces; end else case c of '&': begin FStack^.state := xsEscape; FStack^.savedstate := xsAttributeValue; end; #13, #10: begin FValue.TrimRight; FValue.Append(XML_SPACE, 1); FStack^.state := xsEatSpaces; FStack^.savedstate := xsAttributeValue; end; else FValue.Append(@c, 1); end; end else begin if (c < #256) and (AnsiChar(c) in ['"', '''']) then begin FAChar := c; inc(FPosition); end else goto err; end; end; xsElementString: begin case c of '<': begin FValue.TrimRight; putchildrenstr; FStack^.state := xsTryCloseElement; end; #13, #10: begin FValue.TrimRight; FValue.Append(XML_SPACE, 1); FStack^.state := xsEatSpaces; FStack^.savedstate := xsElementString; end; '&': begin FStack^.state := xsEscape; FStack^.savedstate := xsElementString; end else FValue.Append(@c, 1); end; end; xsElementComment: begin case FPosition of 0: begin case c of '-': Inc(FPosition); '[': begin FValue.Reset; FPosition := 0; FStack^.state := xsElementCDATA; FStack^.clazz := xcCdata; end; 'D': begin if (FStack^.prev = nil) and (FDocType = nil) then begin FStack^.state := xsElementDocType; FPosition := 0; FStack^.clazz := xcDocType; end else goto err; end; else goto err; end; end; 1: begin if c <> '-' then goto err; Inc(FPosition); end; else if c = '-' then begin FPosition := 0; FStack^.state := xsCloseElementComment; end; end; end; xsCloseElementComment: begin case FPosition of 0: begin if c <> '-' then begin FPosition := 2; FStack^.state := xsElementComment; end else Inc(FPosition); end; 1: begin if c <> '>' then goto err; FStack^.state := xsEatSpaces; if FStack^.obj <> nil then FStack^.savedstate := xsChildren else FStack^.savedstate := xsStart; end; end; end; xsElementCDATA: begin case FPosition of 0: if (c = 'C') then inc(FPosition) else goto err; 1: if (c = 'D') then inc(FPosition) else goto err; 2: if (c = 'A') then inc(FPosition) else goto err; 3: if (c = 'T') then inc(FPosition) else goto err; 4: if (c = 'A') then inc(FPosition) else goto err; 5: if (c = '[') then inc(FPosition) else goto err; else case c of ']': begin FPosition := 0; FStack^.state := xsClodeElementCDATA; end; else FValue.Append(@c, 1); end; end; end; xsClodeElementCDATA: begin case FPosition of 0: if (c = ']') then inc(FPosition) else begin FValue.Append(XML_ARR, 1); FValue.Append(@c, 1); FPosition := 6; FStack^.state := xsElementCDATA; end; 1: case c of '>': begin putchildrenstr; FStack^.state := xsEatSpaces; FStack^.savedstate := xsChildren; end; ']': begin FValue.Append(@c, 1); end; else FValue.Append(@c, 1); FStack^.state := xsElementCDATA; end; end; end; xsElementDocType: begin case FPosition of 0: if (c = 'O') then inc(FPosition) else goto err; 1: if (c = 'C') then inc(FPosition) else goto err; 2: if (c = 'T') then inc(FPosition) else goto err; 3: if (c = 'Y') then inc(FPosition) else goto err; 4: if (c = 'P') then inc(FPosition) else goto err; 5: if (c = 'E') then inc(FPosition) else goto err; else if (c < #256) and (AnsiChar(c) in spaces) then begin FStack^.state := xsEatSpaces; FStack^.savedstate := xsElementDocTypeName; FStr.Reset; end else goto err; end; end; xsElementDocTypeName: begin case FStr.Position of 0: begin case c of '>': begin FStack^.state := xsEatSpaces; FStack^.state := xsStart; FStack^.clazz := xcNone; end else if ((c < #256) and (AnsiChar(c) in alphas)) or (c > #256) then FStr.Append(@c, 1) else goto err; end; end; else if ((c < #256) and (AnsiChar(c) in alphanums)) or (c > #256) then FStr.Append(@c, 1) else if (c < #256) and (AnsiChar(c) in spaces) then begin FDocType := TSuperObject.Create(stObject); FDocType.AsObject.S[xmlname] := FStr.Data; FStack^.state := xsEatSpaces; FStack^.savedstate := xsElementDocTypeExternId; end else goto err; end; end; xsElementDocTypeExternId: begin case c of 'P': begin FPosition := 0; FStack^.state := xsElementDocTypeExternIdPublic; end; 'S': begin FPosition := 0; FStack^.state := xsElementDocTypeExternIdSystem; end; '[': begin FStack^.savedstate := xsElementDocTypeIntSubset; FStack^.state := xsEatSpaces; end; '>': begin FStack^.savedstate := xsStart; FStack^.state := xsEatSpaces end else goto err; end; end; xsElementDocTypeExternIdPublic: begin case FPosition of 0: if (c = 'U') then inc(FPosition) else goto err; 1: if (c = 'B') then inc(FPosition) else goto err; 2: if (c = 'L') then inc(FPosition) else goto err; 3: if (c = 'I') then inc(FPosition) else goto err; 4: if (c = 'C') then inc(FPosition) else goto err; else if (c < #256) and (AnsiChar(c) in spaces) then begin FStr.Reset; FPosition := 0; FStack^.savedstate := xsElementDocTypePubIdLiteral; FStack^.state := xsEatSpaces; end else goto err; end; end; xsElementDocTypeExternIdSystem: begin case FPosition of 0: if (c = 'Y') then inc(FPosition) else goto err; 1: if (c = 'S') then inc(FPosition) else goto err; 2: if (c = 'T') then inc(FPosition) else goto err; 3: if (c = 'E') then inc(FPosition) else goto err; 4: if (c = 'M') then inc(FPosition) else goto err; else if (c < #256) and (AnsiChar(c) in spaces) then begin FStr.Reset; FPosition := 0; FStack^.savedstate := xsElementDocTypeSystemLiteral; FStack^.state := xsEatSpaces; end else goto err; end; end; xsElementDocTypePubIdLiteral: begin if FPosition = 0 then case c of '"', '''': begin FAChar := c; FPosition := 1; end else goto err; end else if c = FAChar then begin FDocType.AsObject.S[dtdPubidLiteral] := FStr.Data; FStr.Reset; FPosition := 0; FStack^.state := xsEatSpaces; FStack^.savedstate := xsElementDocTypeSystemLiteral; end else if (c < #256) and (AnsiChar(c) in publitteral) then FStr.Append(@c, 1); end; xsElementDocTypeSystemLiteral: begin if FPosition = 0 then case c of '"', '''': begin FAChar := c; FPosition := 1; end else goto err; end else if c = FAChar then begin FDocType.AsObject.S[dtdSystemLiteral] := FStr.Data; FStack^.state := xsEatSpaces; FStack^.savedstate := xsElementDocTypeTryIntSubset; end else FStr.Append(@c, 1); end; xsElementDocTypeTryIntSubset: begin case c of '>': begin FStack^.state := xsEatSpaces; FStack^.savedstate := xsStart; FStack^.clazz := xcNone; end; '[': begin FStack^.state := xsEatSpaces; FStack^.savedstate := xsElementDocTypeIntSubset; end; end; end; xsElementDocTypeIntSubset: begin case c of ']': begin FStack^.state := xsEatSpaces; FStack^.savedstate := xsElementDocTypeTryClose; end; end; end; xsElementDocTypeTryClose: begin if c = '>' then begin FStack^.state := xsEatSpaces; FStack^.savedstate := xsStart; FStack^.clazz := xcNone; end else goto err; end; xsEscape: begin FPosition := 0; case c of 'l': FStack^.state := xsEscape_lt; 'g': FStack^.state := xsEscape_gt; 'a': FStack^.state := xsEscape_amp; 'q': FStack^.state := xsEscape_quot; '#': FStack^.state := xsEscape_char; else goto err; end; end; xsEscape_lt: begin case FPosition of 0: begin if c <> 't' then goto err; Inc(FPosition); end; 1: begin if c <> ';' then goto err; FValue.Append(XML_LOW, 1); FStack^.state := FStack^.savedstate; end; end; end; xsEscape_gt: begin case FPosition of 0: begin if c <> 't' then goto err; Inc(FPosition); end; 1: begin if c <> ';' then goto err; FValue.Append(XML_BIG, 1); FStack^.state := FStack^.savedstate; end; end; end; xsEscape_amp: begin case FPosition of 0: begin case c of 'm': Inc(FPosition); 'p': begin FStack^.state := xsEscape_apos; Inc(FPosition); end; else goto err; end; end; 1: begin if c <> 'p' then goto err; Inc(FPosition); end; 2: begin if c <> ';' then goto err; FValue.Append(XML_AMP, 1); FStack^.state := FStack^.savedstate; end; end; end; xsEscape_apos: begin case FPosition of 0: begin case c of 'p': Inc(FPosition); 'm': begin FStack^.state := xsEscape_amp; Inc(FPosition); end; else goto err; end; end; 1: begin if c <> 'o' then goto err; Inc(FPosition); end; 2: begin if c <> 's' then goto err; Inc(FPosition); end; 3: begin if c <> ';' then goto err; FValue.Append(XML_SQU, 1); FStack^.state := FStack^.savedstate; end; end; end; xsEscape_quot: begin case FPosition of 0: begin if c <> 'u' then goto err; Inc(FPosition); end; 1: begin if c <> 'o' then goto err; Inc(FPosition); end; 2: begin if c <> 't' then goto err; Inc(FPosition); end; 3: begin if c <> ';' then goto err; FValue.Append(XML_DQU, 1); FStack^.state := FStack^.savedstate; end; end; end; xsEscape_char: begin if (SOIChar(c) >= 256) then goto err; case AnsiChar(c) of '0'..'9': begin FPosition := SOIChar(c) - 48; FStack^.state := xsEscape_char_num; end; 'x': begin FStack^.state := xsEscape_char_hex; end else goto err; end; end; xsEscape_char_num: begin if (SOIChar(c) >= 256) then goto err; case AnsiChar(c) of '0'..'9':FPosition := (FPosition * 10) + (SOIChar(c) - 48); ';': begin FValue.Append(@FPosition, 1); FStack^.state := FStack^.savedstate; end; else goto err; end; end; xsEscape_char_hex: begin if (c >= #256) then goto err; if (AnsiChar(c) in hex) then begin FPosition := (FPosition * 16) + SOIChar(hexdigit(c)); end else if c = ';' then begin FValue.Append(@FPosition, 1); FStack^.state := FStack^.savedstate; end else goto err; end; xsEnd: begin if(FStack^.prev = nil) then Break; if FStack^.obj <> nil then begin if FPack then packend else begin anobject := FStack^.prev^.obj.AsObject[xmlchildren]; if anobject = nil then begin anobject := TSuperObject.Create(stArray); FStack^.prev^.obj.AsObject[xmlchildren] := anobject; end; anobject.AsArray.Add(FStack^.obj); end; end; StackDown; goto redo; end; end; inc(p); inc(read); until (c = #0); if FStack^.state = xsEnd then begin if FPack then packend; FError := xeSuccess; end else FError := xeError; Result := read; exit; err: FError := xeError; Result := read; end; function XMLParseFile(const FileName: string; pack: Boolean; onpi: TOnProcessingInstruction): ISuperObject; var stream: TFileStream; begin stream := TFileStream.Create(FileName, fmOpenRead, fmShareDenyWrite); try Result := XMLParseStream(stream, pack, onpi); finally stream.Free; end; end; procedure TSuperXMLParser.StackDown; var prev: PSuperXMLStack; begin if FStack <> nil then begin prev := FStack^.prev; FStack^.obj := nil; FreeMem(FStack); FStack := prev; if FStack <> nil then FStack^.next := nil; end; end; procedure TSuperXMLParser.StackUp; var st: PSuperXMLStack; begin {$IFDEF FPC} st := nil; {$ENDIF} GetMem(st, SizeOf(st^)); FillChar(st^, SizeOf(st^), 0); st^.state := xsEatSpaces; st^.savedstate := xsStart; st^.prev := FStack; if st^.prev <> nil then st^.prev^.next := st; st^.next := nil; st^.obj := nil; FStack := st; end; function utf8toucs2(src: PAnsiChar; srclen: Integer; dst: PWideChar; unused: PInteger): Integer; var ch: Byte; ret: Word; min: Cardinal; rem, com: integer; label redo; begin Result := 0; ret := 0; rem := 0; min := 0; if unused <> nil then unused^ := 0; if(src = nil) or (srclen = 0) then begin dst^ := #0; Exit; end; while srclen > 0 do begin ch := Byte(src^); inc(src); dec(srclen); redo: if (ch and $80) = 0 then begin dst^ := WideChar(ch); inc(Result); end else begin if((ch and $E0) = $C0) then begin min := $80; rem := 1; ret := ch and $1F; end else if((ch and $F0) = $E0) then begin min := $800; rem := 2; ret := ch and $0F; end else // too large utf8 bloc // ignore and continue continue; com := rem; while(rem <> 0) do begin dec(rem); if(srclen = 0) then begin if unused <> nil then unused^ := com; Exit; end; ch := Byte(src^); inc(src); dec(srclen); if((ch and $C0) = $80) then begin ret := ret shl 6; ret := ret or (ch and $3F); end else begin // unterminated utf8 bloc :/ // try next one goto redo; end; end; if (ch >= min) then begin dst^ := WideChar(ret); inc(Result); end else begin // too small utf8 bloc // ignore and continue Continue; end; end; inc(dst); end; end; function XMLParseStream(stream: TStream; pack: Boolean; onpi: TOnProcessingInstruction): ISuperObject; const CP_UTF8 = 65001; var wbuffer: array[0..1023] of SOChar; abuffer: array[0..1023] of AnsiChar; len, read, cursor: Integer; PI, PIParent: ISuperObject; bom: array[0..2] of byte; encoding: TSuperXMLEncoding; encodingstr: string; cp: Integer; ecp: ISuperObject; function getbuffer: Integer; var size, unusued: Integer; begin case encoding of {$IFNDEF UNIX} xnANSI: begin size := stream.Read(abuffer, sizeof(abuffer)); result := MultiByteToWideChar(cp, 0, @abuffer, size, @wbuffer, sizeof(wbuffer)); end; {$ENDIF} xnUTF8: begin size := stream.Read(abuffer, sizeof(abuffer)); result := utf8toucs2(@abuffer, size, @wbuffer, @unusued); if unusued > 0 then stream.Seek(-unusued, soFromCurrent); end; xnUnicode: Result := stream.Read(wbuffer, sizeof(wbuffer)) div sizeof(SOChar); else Result := 0; end; end; label redo, retry; begin // init knowned code pages ecp := so('{iso-8859-1: 28591,'+ 'iso-8859-2: 28592,'+ 'iso-8859-3: 28593,'+ 'iso-8859-4: 28594,'+ 'iso-8859-5: 28595,'+ 'iso-8859-6: 28596,'+ 'iso-8859-7: 28597,'+ 'iso-8859-8: 28598,'+ 'iso-8859-9: 28599,'+ 'iso 8859-15: 28605,'+ 'iso-2022-jp: 50220,'+ 'shift_jis: 932,'+ 'euc-jp: 20932,'+ 'ascii: 20127,'+ 'windows-1251: 1251,'+ 'windows-1252: 1252}'); // detect bom stream.Seek(0, soFromBeginning); len := stream.Read(bom, sizeof(bom)); if (len >= 2) and (bom[0] = $FF) and (bom[1] = $FE) then begin encoding := xnUnicode; stream.Seek(2, soFromBeginning); end else if (len = 3) and (bom[0] = $EF) and (bom[1] = $BB) and (bom[2] = $BF) then begin encoding := xnUTF8; cp := CP_UTF8; end else begin encoding := xnUTF8; cp := 0; stream.Seek(0, soFromBeginning); end; with TSuperXMLParser.Create(pack) do try len := getbuffer; while len > 0 do begin retry: read := ParseBuffer(@wbuffer, PI, PIParent, len); cursor := 0; redo: case FError of xeContinue: len := getbuffer; xeSuccess, xeError: Break; xeProcessInst: begin if (PIParent = nil) and (PI.AsObject.S[xmlname] = 'xml') then begin if pack then encodingstr := LowerCase(trim(PI.S['encoding'])) else encodingstr := LowerCase(trim(PI.S[xmlattributes + '.encoding'])); if (encodingstr <> '') then case encoding of xnUTF8: if(cp = CP_UTF8) then begin if (encodingstr <> 'utf-8') then begin FError := xeError; Break; end; end else begin cp := ecp.I[encodingstr]; if cp > 0 then begin {$IFNDEF UNIX} encoding := xnANSI; Reset; stream.Seek(0, soFromBeginning); len := getbuffer; goto retry; {$ELSE} raise Exception.Create('charset not implemented'); {$ENDIF} end; end; xnUnicode: if (encodingstr <> 'utf-16') and (encodingstr <> 'unicode') then begin FError := xeError; Break; end; end; end else if Assigned(onpi) then onpi(PI, PIParent); inc(cursor, read); if cursor >= len then begin len := getbuffer; continue; end; read := ParseBuffer(@wbuffer[cursor], PI, PIParent, len - cursor); goto redo; end; end; end; if FError = xeSuccess then Result := FStack^.obj else Result := nil; finally Free; end; end; function XMLParseString(const data: SOString; pack: Boolean; onpi: TOnProcessingInstruction): ISuperObject; var PI, PIParent: ISuperObject; cursor, read: Integer; label redo; begin with TSuperXMLParser.Create(pack) do try cursor := 0; read := ParseBuffer(PSOChar(data), PI, PIParent); redo: case FError of xeSuccess: Result := FStack^.obj; xeError: Result := nil; xeProcessInst: begin if Assigned(onpi) then onpi(PI, PIParent); inc(cursor, read); read := ParseBuffer(@data[cursor+1], PI, PIParent); goto redo; end; end; finally Free; end; end; end.
28.885776
132
0.459449
83cc243524126ff091ff63deda37928af9641e98
1,313
pas
Pascal
Core/DW.SysUtils.Helpers.pas
barlone/Kastri
fb12d9eba242e67efd87eb1cb7acd123601a58ed
[ "MIT" ]
259
2020-05-27T03:15:19.000Z
2022-03-24T16:35:02.000Z
Core/DW.SysUtils.Helpers.pas
talentedexpert0057/Kastri
aacc0db96957ea850abb7b407be5a0722462eb5a
[ "MIT" ]
95
2020-06-16T09:46:06.000Z
2022-03-28T00:27:07.000Z
Core/DW.SysUtils.Helpers.pas
talentedexpert0057/Kastri
aacc0db96957ea850abb7b407be5a0722462eb5a
[ "MIT" ]
56
2020-06-04T19:32:40.000Z
2022-03-26T15:32:47.000Z
unit DW.SysUtils.Helpers; {*******************************************************} { } { Kastri } { } { Delphi Worlds Cross-Platform Library } { } { Copyright 2020-2021 Dave Nottage under MIT license } { which is located in the root folder of this library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses // RTL System.SysUtils; type TOSVersionHelper = record helper for TOSVersion public class function IsIOSSimulator: Boolean; static; class function IsWindows: Boolean; static; end; implementation { TOSVersionHelper } class function TOSVersionHelper.IsIOSSimulator: Boolean; begin Result := (TOSVersion.Platform = TOSVersion.TPlatform.pfiOS) and (TOSVersion.Architecture in [TOSVersion.TArchitecture.arIntelX86, TOSVersion.TArchitecture.arIntelX64]); end; class function TOSVersionHelper.IsWindows: Boolean; begin Result := TOSVersion.Platform = TOSVersion.TPlatform.pfWindows; end; end.
29.177778
109
0.501904
477d7339fd4143b445279bf30149eb7b4074c99d
1,802
pas
Pascal
src/p2c/src/string.pas
rpuntaie/dpic
307bfbd243ea90bd4f4656e16eed8e15ebfbb5ec
[ "CC-BY-3.0", "Unlicense" ]
14
2015-12-22T03:17:48.000Z
2021-07-31T00:02:26.000Z
p2c/src/string.pas
tex-other/TeX--
48a3652e6111e670fd86b8dae147eb8dd85c2515
[ "Unlicense" ]
3
2016-01-19T05:24:47.000Z
2018-01-21T19:41:53.000Z
p2c/src/string.pas
tex-other/TeX--
48a3652e6111e670fd86b8dae147eb8dd85c2515
[ "Unlicense" ]
6
2016-01-19T05:07:17.000Z
2022-01-12T03:25:39.000Z
{ Oregon Software Pascal dynamic string package. } {*VarFiles=0} {INTF-ONLY} function Len(var s : array [lo..hi:integer] of char) : integer; external; {FuncMacro Len(lo,hi,s) = strlen(s)} procedure Clear(var s : array [lo..hi:integer] of char); external; {FuncMacro Clear(lo,hi,s) = (s[lo] = 0)} procedure ReadString(var f : text; var s : array [lo..hi:integer] of char); external; {FuncMacro ReadString(f,lo,hi,s) = fgets(s, hi-lo+1, f)} procedure WriteString(var f : text; var s : array [lo..hi:integer] of char); external; {FuncMacro WriteString(f,lo,hi,s) = fprintf(f, "%s", s)} procedure Concatenate(var d : array [lod..hid:integer] of char; var s : array [los..his:integer] of char); external; {FuncMacro Concatenate(lod,hid,d,los,his,s) = strcat(d, s)} function Search(var s : array [lo..hi:integer] of char; var s2 : array [lo2..hi2:integer] of char; i : integer) : integer; external; {FuncMacro Search(lo,hi,s,lo2,hi2,s2,i) = strpos2(s,s2,i-lo)+lo} procedure Insert(var d : array [lod..hid:integer] of char; var s : array [los..his:integer] of char; i : integer); external; {FuncMacro Insert(lod,hid,d,los,his,s,i) = strinsert(s,d,i-lod)} procedure Assign(var d : array [lo..hi:integer] of char; var s : array [los..his:integer] of char); external; {FuncMacro Assign(lo,hi,d,los,his,s) = strcpy(d,s)} procedure AssChar(var d : array [lo..hi:integer] of char; c : char); external; {FuncMacro AssChar(lo,hi,d,c) = sprintf(d, "%c", c)} function Equal(var s1 : array [lo1..hi1:integer] of char; var s2 : array [lo2..hi2:integer] of char) : boolean; external; {FuncMacro Equal(lo1,hi1,s1,lo2,hi2,s2) = !strcmp(s1,s2)} procedure DelString(var s; i, j : integer); external; procedure SubString(var d; var s; i, j : integer); external;
35.333333
73
0.666482
f13a517955ad1ef585adfe2735ae23b2d980a592
4,041
pas
Pascal
sys/vfs.pas
Laksen/jpaskernel2
4d6aca54406d506d520c3897881bd299188ec609
[ "MIT" ]
null
null
null
sys/vfs.pas
Laksen/jpaskernel2
4d6aca54406d506d520c3897881bd299188ec609
[ "MIT" ]
null
null
null
sys/vfs.pas
Laksen/jpaskernel2
4d6aca54406d506d520c3897881bd299188ec609
[ "MIT" ]
null
null
null
unit vfs; interface uses handles, services, cclasses, sysutils, filesystem, storagedev; const fmOpenRead = 1; fmOpenWrite = 2; fmCreate = 4; soFromBeginning = 1; soFromCurrent = 2; soFromEnd = 4; type TVFS = class(TServiceObject) private fPartitions: TStringList; function FindFile(handle: THandle): TFile; protected procedure RegisterFunctions; override; public procedure RegisterStorage(D: TStorageDevice); procedure AddFilesystem(FsLabel: pchar; fs: TFilesystem); procedure RemoveFilesystem(FsLabel: pchar); function OpenFile(Filename: pchar; FileFlags: PtrUInt): THandle; procedure CloseFile(Handle: THandle); function ReadFile(Handle: THandle; Data: Pointer; DataLen: PtrInt): PtrInt; function WriteFile(Handle: THandle; Data: Pointer; DataLen: PtrInt): PtrInt; function SeekFile(Handle: THandle; Position, PositionHigh, Offset: PtrUInt): PtrInt; function FileSize(Handle: THandle; FsLow, FsHigh: PPtrUInt): PtrInt; function FilePosition(Handle: THandle; FPLow, FPHigh: PPtrUInt): PtrInt; constructor Create; end; var VFSManager: TVFS = nil; implementation uses fsutils; constructor TVFS.Create; begin inherited Create('VFS'); fPartitions := TStringList.Create(nil); end; function TVFS.FindFile(handle: THandle): TFile; begin result := TFile(FindObject(handle)); if not assigned(result) then raise exception.Create('Object not found'); if not result.InheritsFrom(TFile) then raise exception.Create('Object is not a file'); end; procedure TVFS.AddFilesystem(FsLabel: pchar; fs: TFilesystem); begin fPartitions.Add(FsLabel, fs); end; procedure TVFS.RemoveFilesystem(FsLabel: pchar); begin fPartitions.remove(fslabel); end; function TVFS.OpenFile(Filename: pchar; FileFlags: PtrUInt): THandle; var fn: TFilenameInfo; part: TFileSystem; begin result := InvalidHandle; fn := ExplodeFilename(filename); try part := TFileSystem(fPartitions[fn.Drive]); if assigned(part) then result := part.openfile(fn, fileflags).Handle; except end; FreeFilenameInfo(fn); end; function TVFS.ReadFile(Handle: THandle; Data: Pointer; DataLen: PtrInt): PtrInt; var x: TFile; begin try x := FindFile(Handle); result := x.ReadFile(Data, DataLen); except result := -1; end; end; function TVFS.WriteFile(Handle: THandle; Data: Pointer; DataLen: PtrInt): PtrInt; var x: TFile; begin try x := FindFile(Handle); result := x.WriteFile(Data, DataLen); except result := -1; end; end; function TVFS.SeekFile(Handle: THandle; Position, PositionHigh, Offset: PtrUInt): PtrInt; var x: TFile; begin try x := FindFile(Handle); result := x.Seek(Position, Offset); except result := -1; end; end; function TVFS.FileSize(Handle: THandle; FsLow, FsHigh: PPtrUInt): PtrInt; var x: TFile; t: int64; begin try x := FindFile(Handle); t := x.GetFileSize; if assigned(fslow) then fslow^ := t and $FFFFFFFF; if assigned(FsHigh) then FsHigh^ := (t shr 32) and $FFFFFFFF; result := 0; except result := -1; end; end; function TVFS.FilePosition(Handle: THandle; FPLow, FPHigh: PPtrUInt): PtrInt; var x: TFile; t: int64; begin try x := FindFile(Handle); t := x.FilePosition; if assigned(FPLow) then FPLow^ := t and $FFFFFFFF; if assigned(FPHigh) then FPHigh^ := (t shr 32) and $FFFFFFFF; result := 0; except result := -1; end; end; procedure TVFS.CloseFile(Handle: THandle); begin CloseHandle(Handle); end; procedure TVFS.RegisterStorage(D: TStorageDevice); begin end; procedure TVFS.RegisterFunctions; begin RegisterFunction('OpenFile', GetMethod(@TVFS.OpenFile, self), 2); RegisterFunction('CloseFile', GetMethod(@TVFS.WriteFile, self), 1); RegisterFunction('ReadFile', GetMethod(@TVFS.ReadFile, self), 3); RegisterFunction('WriteFile', GetMethod(@TVFS.WriteFile, self), 3); RegisterFunction('SeekFile', GetMethod(@TVFS.SeekFile, self), 4); RegisterFunction('FileSize', GetMethod(@TVFS.FileSize, self), 3); end; initialization if not assigned(VFSManager) then VFSManager := TVFS.Create; end.
22.203297
89
0.723831
47ea0ab21f0d537260156e13e144ae12dea9ad71
881
dfm
Pascal
Samples/BCB/SpikeTrainer/MainFormUnit.dfm
VI10604/nmsdk
065b9e60f6716b3a01275647937a7dd4dcff14d3
[ "BSD-3-Clause" ]
1
2020-04-05T20:14:26.000Z
2020-04-05T20:14:26.000Z
Samples/BCB/SpikeTrainer/MainFormUnit.dfm
VI10604/nmsdk
065b9e60f6716b3a01275647937a7dd4dcff14d3
[ "BSD-3-Clause" ]
null
null
null
Samples/BCB/SpikeTrainer/MainFormUnit.dfm
VI10604/nmsdk
065b9e60f6716b3a01275647937a7dd4dcff14d3
[ "BSD-3-Clause" ]
null
null
null
object MainForm: TMainForm Left = 800 Top = 0 Caption = 'MainForm' ClientHeight = 75 ClientWidth = 182 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False Position = poDesigned Visible = True OnShow = FormShow PixelsPerInch = 96 TextHeight = 13 object Panel1: TPanel Left = -3 Top = 0 Width = 185 Height = 75 Align = alRight TabOrder = 0 ExplicitLeft = 342 ExplicitHeight = 266 object Button2: TButton Left = 8 Top = 23 Width = 169 Height = 25 Caption = 'Manipulator Control' TabOrder = 0 OnClick = Button2Click end end object Timer: TTimer Enabled = False Interval = 1 Left = 24 Top = 8 end end
19.577778
38
0.586833
f19d25604bf8693026abf00c3fb5411b3d588140
127,472
pas
Pascal
source/synacrypt.pas
tanktinker/SourceRepository
540fcdbde95f2640baa8cf0d12191e4e4b13bfbd
[ "BSD-3-Clause" ]
198
2018-12-12T04:32:15.000Z
2022-03-10T03:37:09.000Z
synapse/synacrypt.pas
LicenseChekerWin32/Open-Sitemap-Builder
0aad398c190e3528013477145cb5a32c17d576f5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
425
2018-11-13T12:53:45.000Z
2022-03-29T14:39:59.000Z
synapse/synacrypt.pas
LicenseChekerWin32/Open-Sitemap-Builder
0aad398c190e3528013477145cb5a32c17d576f5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
55
2018-11-20T12:03:11.000Z
2022-03-28T06:34:08.000Z
{==============================================================================| | Project : Ararat Synapse | 001.001.000 | |==============================================================================| | Content: Encryption support | |==============================================================================| | Copyright (c)2007-2011, Lukas Gebauer | | 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 Lukas Gebauer 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR | | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT | | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY | | OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH | | DAMAGE. | |==============================================================================| | The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).| | Portions created by Lukas Gebauer are Copyright (c)2007-2011. | | All Rights Reserved. | | Based on work of David Barton and Eric Young | |==============================================================================| | Contributor(s): | |==============================================================================| | History: see HISTORY.HTM from distribution package | | (Found at URL: http://www.ararat.cz/synapse/) | |==============================================================================} {:@abstract(Encryption support) Implemented are DES and 3DES encryption/decryption by ECB, CBC, CFB-8bit, CFB-block, OFB and CTR methods. } {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} {$Q-} {$R-} {$H+} {$IFDEF UNICODE} {$WARN IMPLICIT_STRING_CAST OFF} {$WARN IMPLICIT_STRING_CAST_LOSS OFF} {$ENDIF} unit synacrypt; interface uses SysUtils, Classes, synautil, synafpc; type {:@abstract(Implementation of common routines block ciphers (dafault size is 64-bits)) Do not use this class directly, use descendants only!} TSynaBlockCipher= class(TObject) protected procedure InitKey(Key: AnsiString); virtual; function GetSize: byte; virtual; private IV, CV: AnsiString; procedure IncCounter; public {:Sets the IV to Value and performs a reset} procedure SetIV(const Value: AnsiString); virtual; {:Returns the current chaining information, not the actual IV} function GetIV: AnsiString; virtual; {:Reset any stored chaining information} procedure Reset; virtual; {:Encrypt a 64-bit block of data using the ECB method of encryption} function EncryptECB(const InData: AnsiString): AnsiString; virtual; {:Decrypt a 64-bit block of data using the ECB method of decryption} function DecryptECB(const InData: AnsiString): AnsiString; virtual; {:Encrypt data using the CBC method of encryption} function EncryptCBC(const Indata: AnsiString): AnsiString; virtual; {:Decrypt data using the CBC method of decryption} function DecryptCBC(const Indata: AnsiString): AnsiString; virtual; {:Encrypt data using the CFB (8 bit) method of encryption} function EncryptCFB8bit(const Indata: AnsiString): AnsiString; virtual; {:Decrypt data using the CFB (8 bit) method of decryption} function DecryptCFB8bit(const Indata: AnsiString): AnsiString; virtual; {:Encrypt data using the CFB (block) method of encryption} function EncryptCFBblock(const Indata: AnsiString): AnsiString; virtual; {:Decrypt data using the CFB (block) method of decryption} function DecryptCFBblock(const Indata: AnsiString): AnsiString; virtual; {:Encrypt data using the OFB method of encryption} function EncryptOFB(const Indata: AnsiString): AnsiString; virtual; {:Decrypt data using the OFB method of decryption} function DecryptOFB(const Indata: AnsiString): AnsiString; virtual; {:Encrypt data using the CTR method of encryption} function EncryptCTR(const Indata: AnsiString): AnsiString; virtual; {:Decrypt data using the CTR method of decryption} function DecryptCTR(const Indata: AnsiString): AnsiString; virtual; {:Create a encryptor/decryptor instance and initialize it by the Key.} constructor Create(Key: AnsiString); end; {:@abstract(Datatype for holding one DES key data) This data type is used internally.} TDesKeyData = array[0..31] of integer; {:@abstract(Implementation of common routines for DES encryption) Do not use this class directly, use descendants only!} TSynaCustomDes = class(TSynaBlockcipher) protected procedure DoInit(KeyB: AnsiString; var KeyData: TDesKeyData); function EncryptBlock(const InData: AnsiString; var KeyData: TDesKeyData): AnsiString; function DecryptBlock(const InData: AnsiString; var KeyData: TDesKeyData): AnsiString; end; {:@abstract(Implementation of DES encryption)} TSynaDes= class(TSynaCustomDes) protected KeyData: TDesKeyData; procedure InitKey(Key: AnsiString); override; public {:Encrypt a 64-bit block of data using the ECB method of encryption} function EncryptECB(const InData: AnsiString): AnsiString; override; {:Decrypt a 64-bit block of data using the ECB method of decryption} function DecryptECB(const InData: AnsiString): AnsiString; override; end; {:@abstract(Implementation of 3DES encryption)} TSyna3Des= class(TSynaCustomDes) protected KeyData: array[0..2] of TDesKeyData; procedure InitKey(Key: AnsiString); override; public {:Encrypt a 64-bit block of data using the ECB method of encryption} function EncryptECB(const InData: AnsiString): AnsiString; override; {:Decrypt a 64-bit block of data using the ECB method of decryption} function DecryptECB(const InData: AnsiString): AnsiString; override; end; const BC = 4; MAXROUNDS = 14; type {:@abstract(Implementation of AES encryption)} TSynaAes= class(TSynaBlockcipher) protected numrounds: longword; rk, drk: array[0..MAXROUNDS,0..7] of longword; procedure InitKey(Key: AnsiString); override; function GetSize: byte; override; public {:Encrypt a 128-bit block of data using the ECB method of encryption} function EncryptECB(const InData: AnsiString): AnsiString; override; {:Decrypt a 128-bit block of data using the ECB method of decryption} function DecryptECB(const InData: AnsiString): AnsiString; override; end; {:Call internal test of all DES encryptions. Returns @true if all is OK.} function TestDes: boolean; {:Call internal test of all 3DES encryptions. Returns @true if all is OK.} function Test3Des: boolean; {:Call internal test of all AES encryptions. Returns @true if all is OK.} function TestAes: boolean; {==============================================================================} implementation //DES consts const shifts2: array[0..15]of byte= (0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0); des_skb: array[0..7,0..63]of integer=( ( (* for C bits (numbered as per FIPS 46) 1 2 3 4 5 6 *) integer($00000000),integer($00000010),integer($20000000),integer($20000010), integer($00010000),integer($00010010),integer($20010000),integer($20010010), integer($00000800),integer($00000810),integer($20000800),integer($20000810), integer($00010800),integer($00010810),integer($20010800),integer($20010810), integer($00000020),integer($00000030),integer($20000020),integer($20000030), integer($00010020),integer($00010030),integer($20010020),integer($20010030), integer($00000820),integer($00000830),integer($20000820),integer($20000830), integer($00010820),integer($00010830),integer($20010820),integer($20010830), integer($00080000),integer($00080010),integer($20080000),integer($20080010), integer($00090000),integer($00090010),integer($20090000),integer($20090010), integer($00080800),integer($00080810),integer($20080800),integer($20080810), integer($00090800),integer($00090810),integer($20090800),integer($20090810), integer($00080020),integer($00080030),integer($20080020),integer($20080030), integer($00090020),integer($00090030),integer($20090020),integer($20090030), integer($00080820),integer($00080830),integer($20080820),integer($20080830), integer($00090820),integer($00090830),integer($20090820),integer($20090830) ),( (* for C bits (numbered as per FIPS 46) 7 8 10 11 12 13 *) integer($00000000),integer($02000000),integer($00002000),integer($02002000), integer($00200000),integer($02200000),integer($00202000),integer($02202000), integer($00000004),integer($02000004),integer($00002004),integer($02002004), integer($00200004),integer($02200004),integer($00202004),integer($02202004), integer($00000400),integer($02000400),integer($00002400),integer($02002400), integer($00200400),integer($02200400),integer($00202400),integer($02202400), integer($00000404),integer($02000404),integer($00002404),integer($02002404), integer($00200404),integer($02200404),integer($00202404),integer($02202404), integer($10000000),integer($12000000),integer($10002000),integer($12002000), integer($10200000),integer($12200000),integer($10202000),integer($12202000), integer($10000004),integer($12000004),integer($10002004),integer($12002004), integer($10200004),integer($12200004),integer($10202004),integer($12202004), integer($10000400),integer($12000400),integer($10002400),integer($12002400), integer($10200400),integer($12200400),integer($10202400),integer($12202400), integer($10000404),integer($12000404),integer($10002404),integer($12002404), integer($10200404),integer($12200404),integer($10202404),integer($12202404) ),( (* for C bits (numbered as per FIPS 46) 14 15 16 17 19 20 *) integer($00000000),integer($00000001),integer($00040000),integer($00040001), integer($01000000),integer($01000001),integer($01040000),integer($01040001), integer($00000002),integer($00000003),integer($00040002),integer($00040003), integer($01000002),integer($01000003),integer($01040002),integer($01040003), integer($00000200),integer($00000201),integer($00040200),integer($00040201), integer($01000200),integer($01000201),integer($01040200),integer($01040201), integer($00000202),integer($00000203),integer($00040202),integer($00040203), integer($01000202),integer($01000203),integer($01040202),integer($01040203), integer($08000000),integer($08000001),integer($08040000),integer($08040001), integer($09000000),integer($09000001),integer($09040000),integer($09040001), integer($08000002),integer($08000003),integer($08040002),integer($08040003), integer($09000002),integer($09000003),integer($09040002),integer($09040003), integer($08000200),integer($08000201),integer($08040200),integer($08040201), integer($09000200),integer($09000201),integer($09040200),integer($09040201), integer($08000202),integer($08000203),integer($08040202),integer($08040203), integer($09000202),integer($09000203),integer($09040202),integer($09040203) ),( (* for C bits (numbered as per FIPS 46) 21 23 24 26 27 28 *) integer($00000000),integer($00100000),integer($00000100),integer($00100100), integer($00000008),integer($00100008),integer($00000108),integer($00100108), integer($00001000),integer($00101000),integer($00001100),integer($00101100), integer($00001008),integer($00101008),integer($00001108),integer($00101108), integer($04000000),integer($04100000),integer($04000100),integer($04100100), integer($04000008),integer($04100008),integer($04000108),integer($04100108), integer($04001000),integer($04101000),integer($04001100),integer($04101100), integer($04001008),integer($04101008),integer($04001108),integer($04101108), integer($00020000),integer($00120000),integer($00020100),integer($00120100), integer($00020008),integer($00120008),integer($00020108),integer($00120108), integer($00021000),integer($00121000),integer($00021100),integer($00121100), integer($00021008),integer($00121008),integer($00021108),integer($00121108), integer($04020000),integer($04120000),integer($04020100),integer($04120100), integer($04020008),integer($04120008),integer($04020108),integer($04120108), integer($04021000),integer($04121000),integer($04021100),integer($04121100), integer($04021008),integer($04121008),integer($04021108),integer($04121108) ),( (* for D bits (numbered as per FIPS 46) 1 2 3 4 5 6 *) integer($00000000),integer($10000000),integer($00010000),integer($10010000), integer($00000004),integer($10000004),integer($00010004),integer($10010004), integer($20000000),integer($30000000),integer($20010000),integer($30010000), integer($20000004),integer($30000004),integer($20010004),integer($30010004), integer($00100000),integer($10100000),integer($00110000),integer($10110000), integer($00100004),integer($10100004),integer($00110004),integer($10110004), integer($20100000),integer($30100000),integer($20110000),integer($30110000), integer($20100004),integer($30100004),integer($20110004),integer($30110004), integer($00001000),integer($10001000),integer($00011000),integer($10011000), integer($00001004),integer($10001004),integer($00011004),integer($10011004), integer($20001000),integer($30001000),integer($20011000),integer($30011000), integer($20001004),integer($30001004),integer($20011004),integer($30011004), integer($00101000),integer($10101000),integer($00111000),integer($10111000), integer($00101004),integer($10101004),integer($00111004),integer($10111004), integer($20101000),integer($30101000),integer($20111000),integer($30111000), integer($20101004),integer($30101004),integer($20111004),integer($30111004) ),( (* for D bits (numbered as per FIPS 46) 8 9 11 12 13 14 *) integer($00000000),integer($08000000),integer($00000008),integer($08000008), integer($00000400),integer($08000400),integer($00000408),integer($08000408), integer($00020000),integer($08020000),integer($00020008),integer($08020008), integer($00020400),integer($08020400),integer($00020408),integer($08020408), integer($00000001),integer($08000001),integer($00000009),integer($08000009), integer($00000401),integer($08000401),integer($00000409),integer($08000409), integer($00020001),integer($08020001),integer($00020009),integer($08020009), integer($00020401),integer($08020401),integer($00020409),integer($08020409), integer($02000000),integer($0A000000),integer($02000008),integer($0A000008), integer($02000400),integer($0A000400),integer($02000408),integer($0A000408), integer($02020000),integer($0A020000),integer($02020008),integer($0A020008), integer($02020400),integer($0A020400),integer($02020408),integer($0A020408), integer($02000001),integer($0A000001),integer($02000009),integer($0A000009), integer($02000401),integer($0A000401),integer($02000409),integer($0A000409), integer($02020001),integer($0A020001),integer($02020009),integer($0A020009), integer($02020401),integer($0A020401),integer($02020409),integer($0A020409) ),( (* for D bits (numbered as per FIPS 46) 16 17 18 19 20 21 *) integer($00000000),integer($00000100),integer($00080000),integer($00080100), integer($01000000),integer($01000100),integer($01080000),integer($01080100), integer($00000010),integer($00000110),integer($00080010),integer($00080110), integer($01000010),integer($01000110),integer($01080010),integer($01080110), integer($00200000),integer($00200100),integer($00280000),integer($00280100), integer($01200000),integer($01200100),integer($01280000),integer($01280100), integer($00200010),integer($00200110),integer($00280010),integer($00280110), integer($01200010),integer($01200110),integer($01280010),integer($01280110), integer($00000200),integer($00000300),integer($00080200),integer($00080300), integer($01000200),integer($01000300),integer($01080200),integer($01080300), integer($00000210),integer($00000310),integer($00080210),integer($00080310), integer($01000210),integer($01000310),integer($01080210),integer($01080310), integer($00200200),integer($00200300),integer($00280200),integer($00280300), integer($01200200),integer($01200300),integer($01280200),integer($01280300), integer($00200210),integer($00200310),integer($00280210),integer($00280310), integer($01200210),integer($01200310),integer($01280210),integer($01280310) ),( (* for D bits (numbered as per FIPS 46) 22 23 24 25 27 28 *) integer($00000000),integer($04000000),integer($00040000),integer($04040000), integer($00000002),integer($04000002),integer($00040002),integer($04040002), integer($00002000),integer($04002000),integer($00042000),integer($04042000), integer($00002002),integer($04002002),integer($00042002),integer($04042002), integer($00000020),integer($04000020),integer($00040020),integer($04040020), integer($00000022),integer($04000022),integer($00040022),integer($04040022), integer($00002020),integer($04002020),integer($00042020),integer($04042020), integer($00002022),integer($04002022),integer($00042022),integer($04042022), integer($00000800),integer($04000800),integer($00040800),integer($04040800), integer($00000802),integer($04000802),integer($00040802),integer($04040802), integer($00002800),integer($04002800),integer($00042800),integer($04042800), integer($00002802),integer($04002802),integer($00042802),integer($04042802), integer($00000820),integer($04000820),integer($00040820),integer($04040820), integer($00000822),integer($04000822),integer($00040822),integer($04040822), integer($00002820),integer($04002820),integer($00042820),integer($04042820), integer($00002822),integer($04002822),integer($00042822),integer($04042822) )); des_sptrans: array[0..7,0..63] of integer=( ( (* nibble 0 *) integer($02080800), integer($00080000), integer($02000002), integer($02080802), integer($02000000), integer($00080802), integer($00080002), integer($02000002), integer($00080802), integer($02080800), integer($02080000), integer($00000802), integer($02000802), integer($02000000), integer($00000000), integer($00080002), integer($00080000), integer($00000002), integer($02000800), integer($00080800), integer($02080802), integer($02080000), integer($00000802), integer($02000800), integer($00000002), integer($00000800), integer($00080800), integer($02080002), integer($00000800), integer($02000802), integer($02080002), integer($00000000), integer($00000000), integer($02080802), integer($02000800), integer($00080002), integer($02080800), integer($00080000), integer($00000802), integer($02000800), integer($02080002), integer($00000800), integer($00080800), integer($02000002), integer($00080802), integer($00000002), integer($02000002), integer($02080000), integer($02080802), integer($00080800), integer($02080000), integer($02000802), integer($02000000), integer($00000802), integer($00080002), integer($00000000), integer($00080000), integer($02000000), integer($02000802), integer($02080800), integer($00000002), integer($02080002), integer($00000800), integer($00080802) ),( (* nibble 1 *) integer($40108010), integer($00000000), integer($00108000), integer($40100000), integer($40000010), integer($00008010), integer($40008000), integer($00108000), integer($00008000), integer($40100010), integer($00000010), integer($40008000), integer($00100010), integer($40108000), integer($40100000), integer($00000010), integer($00100000), integer($40008010), integer($40100010), integer($00008000), integer($00108010), integer($40000000), integer($00000000), integer($00100010), integer($40008010), integer($00108010), integer($40108000), integer($40000010), integer($40000000), integer($00100000), integer($00008010), integer($40108010), integer($00100010), integer($40108000), integer($40008000), integer($00108010), integer($40108010), integer($00100010), integer($40000010), integer($00000000), integer($40000000), integer($00008010), integer($00100000), integer($40100010), integer($00008000), integer($40000000), integer($00108010), integer($40008010), integer($40108000), integer($00008000), integer($00000000), integer($40000010), integer($00000010), integer($40108010), integer($00108000), integer($40100000), integer($40100010), integer($00100000), integer($00008010), integer($40008000), integer($40008010), integer($00000010), integer($40100000), integer($00108000) ),( (* nibble 2 *) integer($04000001), integer($04040100), integer($00000100), integer($04000101), integer($00040001), integer($04000000), integer($04000101), integer($00040100), integer($04000100), integer($00040000), integer($04040000), integer($00000001), integer($04040101), integer($00000101), integer($00000001), integer($04040001), integer($00000000), integer($00040001), integer($04040100), integer($00000100), integer($00000101), integer($04040101), integer($00040000), integer($04000001), integer($04040001), integer($04000100), integer($00040101), integer($04040000), integer($00040100), integer($00000000), integer($04000000), integer($00040101), integer($04040100), integer($00000100), integer($00000001), integer($00040000), integer($00000101), integer($00040001), integer($04040000), integer($04000101), integer($00000000), integer($04040100), integer($00040100), integer($04040001), integer($00040001), integer($04000000), integer($04040101), integer($00000001), integer($00040101), integer($04000001), integer($04000000), integer($04040101), integer($00040000), integer($04000100), integer($04000101), integer($00040100), integer($04000100), integer($00000000), integer($04040001), integer($00000101), integer($04000001), integer($00040101), integer($00000100), integer($04040000) ),( (* nibble 3 *) integer($00401008), integer($10001000), integer($00000008), integer($10401008), integer($00000000), integer($10400000), integer($10001008), integer($00400008), integer($10401000), integer($10000008), integer($10000000), integer($00001008), integer($10000008), integer($00401008), integer($00400000), integer($10000000), integer($10400008), integer($00401000), integer($00001000), integer($00000008), integer($00401000), integer($10001008), integer($10400000), integer($00001000), integer($00001008), integer($00000000), integer($00400008), integer($10401000), integer($10001000), integer($10400008), integer($10401008), integer($00400000), integer($10400008), integer($00001008), integer($00400000), integer($10000008), integer($00401000), integer($10001000), integer($00000008), integer($10400000), integer($10001008), integer($00000000), integer($00001000), integer($00400008), integer($00000000), integer($10400008), integer($10401000), integer($00001000), integer($10000000), integer($10401008), integer($00401008), integer($00400000), integer($10401008), integer($00000008), integer($10001000), integer($00401008), integer($00400008), integer($00401000), integer($10400000), integer($10001008), integer($00001008), integer($10000000), integer($10000008), integer($10401000) ),( (* nibble 4 *) integer($08000000), integer($00010000), integer($00000400), integer($08010420), integer($08010020), integer($08000400), integer($00010420), integer($08010000), integer($00010000), integer($00000020), integer($08000020), integer($00010400), integer($08000420), integer($08010020), integer($08010400), integer($00000000), integer($00010400), integer($08000000), integer($00010020), integer($00000420), integer($08000400), integer($00010420), integer($00000000), integer($08000020), integer($00000020), integer($08000420), integer($08010420), integer($00010020), integer($08010000), integer($00000400), integer($00000420), integer($08010400), integer($08010400), integer($08000420), integer($00010020), integer($08010000), integer($00010000), integer($00000020), integer($08000020), integer($08000400), integer($08000000), integer($00010400), integer($08010420), integer($00000000), integer($00010420), integer($08000000), integer($00000400), integer($00010020), integer($08000420), integer($00000400), integer($00000000), integer($08010420), integer($08010020), integer($08010400), integer($00000420), integer($00010000), integer($00010400), integer($08010020), integer($08000400), integer($00000420), integer($00000020), integer($00010420), integer($08010000), integer($08000020) ),( (* nibble 5 *) integer($80000040), integer($00200040), integer($00000000), integer($80202000), integer($00200040), integer($00002000), integer($80002040), integer($00200000), integer($00002040), integer($80202040), integer($00202000), integer($80000000), integer($80002000), integer($80000040), integer($80200000), integer($00202040), integer($00200000), integer($80002040), integer($80200040), integer($00000000), integer($00002000), integer($00000040), integer($80202000), integer($80200040), integer($80202040), integer($80200000), integer($80000000), integer($00002040), integer($00000040), integer($00202000), integer($00202040), integer($80002000), integer($00002040), integer($80000000), integer($80002000), integer($00202040), integer($80202000), integer($00200040), integer($00000000), integer($80002000), integer($80000000), integer($00002000), integer($80200040), integer($00200000), integer($00200040), integer($80202040), integer($00202000), integer($00000040), integer($80202040), integer($00202000), integer($00200000), integer($80002040), integer($80000040), integer($80200000), integer($00202040), integer($00000000), integer($00002000), integer($80000040), integer($80002040), integer($80202000), integer($80200000), integer($00002040), integer($00000040), integer($80200040) ),( (* nibble 6 *) integer($00004000), integer($00000200), integer($01000200), integer($01000004), integer($01004204), integer($00004004), integer($00004200), integer($00000000), integer($01000000), integer($01000204), integer($00000204), integer($01004000), integer($00000004), integer($01004200), integer($01004000), integer($00000204), integer($01000204), integer($00004000), integer($00004004), integer($01004204), integer($00000000), integer($01000200), integer($01000004), integer($00004200), integer($01004004), integer($00004204), integer($01004200), integer($00000004), integer($00004204), integer($01004004), integer($00000200), integer($01000000), integer($00004204), integer($01004000), integer($01004004), integer($00000204), integer($00004000), integer($00000200), integer($01000000), integer($01004004), integer($01000204), integer($00004204), integer($00004200), integer($00000000), integer($00000200), integer($01000004), integer($00000004), integer($01000200), integer($00000000), integer($01000204), integer($01000200), integer($00004200), integer($00000204), integer($00004000), integer($01004204), integer($01000000), integer($01004200), integer($00000004), integer($00004004), integer($01004204), integer($01000004), integer($01004200), integer($01004000), integer($00004004) ),( (* nibble 7 *) integer($20800080), integer($20820000), integer($00020080), integer($00000000), integer($20020000), integer($00800080), integer($20800000), integer($20820080), integer($00000080), integer($20000000), integer($00820000), integer($00020080), integer($00820080), integer($20020080), integer($20000080), integer($20800000), integer($00020000), integer($00820080), integer($00800080), integer($20020000), integer($20820080), integer($20000080), integer($00000000), integer($00820000), integer($20000000), integer($00800000), integer($20020080), integer($20800080), integer($00800000), integer($00020000), integer($20820000), integer($00000080), integer($00800000), integer($00020000), integer($20000080), integer($20820080), integer($00020080), integer($20000000), integer($00000000), integer($00820000), integer($20800080), integer($20020080), integer($20020000), integer($00800080), integer($20820000), integer($00000080), integer($00800080), integer($20020000), integer($20820080), integer($00800000), integer($20800000), integer($20000080), integer($00820000), integer($00020080), integer($20020080), integer($20800000), integer($00000080), integer($20820000), integer($00820080), integer($00000000), integer($20000000), integer($20800080), integer($00020000), integer($00820080) )); //AES consts const MAXBC= 8; MAXKC= 8; S: array[0..255] of byte= ( 99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22); T1: array[0..255,0..3] of byte= ( ($c6,$63,$63,$a5), ($f8,$7c,$7c,$84), ($ee,$77,$77,$99), ($f6,$7b,$7b,$8d), ($ff,$f2,$f2,$0d), ($d6,$6b,$6b,$bd), ($de,$6f,$6f,$b1), ($91,$c5,$c5,$54), ($60,$30,$30,$50), ($02,$01,$01,$03), ($ce,$67,$67,$a9), ($56,$2b,$2b,$7d), ($e7,$fe,$fe,$19), ($b5,$d7,$d7,$62), ($4d,$ab,$ab,$e6), ($ec,$76,$76,$9a), ($8f,$ca,$ca,$45), ($1f,$82,$82,$9d), ($89,$c9,$c9,$40), ($fa,$7d,$7d,$87), ($ef,$fa,$fa,$15), ($b2,$59,$59,$eb), ($8e,$47,$47,$c9), ($fb,$f0,$f0,$0b), ($41,$ad,$ad,$ec), ($b3,$d4,$d4,$67), ($5f,$a2,$a2,$fd), ($45,$af,$af,$ea), ($23,$9c,$9c,$bf), ($53,$a4,$a4,$f7), ($e4,$72,$72,$96), ($9b,$c0,$c0,$5b), ($75,$b7,$b7,$c2), ($e1,$fd,$fd,$1c), ($3d,$93,$93,$ae), ($4c,$26,$26,$6a), ($6c,$36,$36,$5a), ($7e,$3f,$3f,$41), ($f5,$f7,$f7,$02), ($83,$cc,$cc,$4f), ($68,$34,$34,$5c), ($51,$a5,$a5,$f4), ($d1,$e5,$e5,$34), ($f9,$f1,$f1,$08), ($e2,$71,$71,$93), ($ab,$d8,$d8,$73), ($62,$31,$31,$53), ($2a,$15,$15,$3f), ($08,$04,$04,$0c), ($95,$c7,$c7,$52), ($46,$23,$23,$65), ($9d,$c3,$c3,$5e), ($30,$18,$18,$28), ($37,$96,$96,$a1), ($0a,$05,$05,$0f), ($2f,$9a,$9a,$b5), ($0e,$07,$07,$09), ($24,$12,$12,$36), ($1b,$80,$80,$9b), ($df,$e2,$e2,$3d), ($cd,$eb,$eb,$26), ($4e,$27,$27,$69), ($7f,$b2,$b2,$cd), ($ea,$75,$75,$9f), ($12,$09,$09,$1b), ($1d,$83,$83,$9e), ($58,$2c,$2c,$74), ($34,$1a,$1a,$2e), ($36,$1b,$1b,$2d), ($dc,$6e,$6e,$b2), ($b4,$5a,$5a,$ee), ($5b,$a0,$a0,$fb), ($a4,$52,$52,$f6), ($76,$3b,$3b,$4d), ($b7,$d6,$d6,$61), ($7d,$b3,$b3,$ce), ($52,$29,$29,$7b), ($dd,$e3,$e3,$3e), ($5e,$2f,$2f,$71), ($13,$84,$84,$97), ($a6,$53,$53,$f5), ($b9,$d1,$d1,$68), ($00,$00,$00,$00), ($c1,$ed,$ed,$2c), ($40,$20,$20,$60), ($e3,$fc,$fc,$1f), ($79,$b1,$b1,$c8), ($b6,$5b,$5b,$ed), ($d4,$6a,$6a,$be), ($8d,$cb,$cb,$46), ($67,$be,$be,$d9), ($72,$39,$39,$4b), ($94,$4a,$4a,$de), ($98,$4c,$4c,$d4), ($b0,$58,$58,$e8), ($85,$cf,$cf,$4a), ($bb,$d0,$d0,$6b), ($c5,$ef,$ef,$2a), ($4f,$aa,$aa,$e5), ($ed,$fb,$fb,$16), ($86,$43,$43,$c5), ($9a,$4d,$4d,$d7), ($66,$33,$33,$55), ($11,$85,$85,$94), ($8a,$45,$45,$cf), ($e9,$f9,$f9,$10), ($04,$02,$02,$06), ($fe,$7f,$7f,$81), ($a0,$50,$50,$f0), ($78,$3c,$3c,$44), ($25,$9f,$9f,$ba), ($4b,$a8,$a8,$e3), ($a2,$51,$51,$f3), ($5d,$a3,$a3,$fe), ($80,$40,$40,$c0), ($05,$8f,$8f,$8a), ($3f,$92,$92,$ad), ($21,$9d,$9d,$bc), ($70,$38,$38,$48), ($f1,$f5,$f5,$04), ($63,$bc,$bc,$df), ($77,$b6,$b6,$c1), ($af,$da,$da,$75), ($42,$21,$21,$63), ($20,$10,$10,$30), ($e5,$ff,$ff,$1a), ($fd,$f3,$f3,$0e), ($bf,$d2,$d2,$6d), ($81,$cd,$cd,$4c), ($18,$0c,$0c,$14), ($26,$13,$13,$35), ($c3,$ec,$ec,$2f), ($be,$5f,$5f,$e1), ($35,$97,$97,$a2), ($88,$44,$44,$cc), ($2e,$17,$17,$39), ($93,$c4,$c4,$57), ($55,$a7,$a7,$f2), ($fc,$7e,$7e,$82), ($7a,$3d,$3d,$47), ($c8,$64,$64,$ac), ($ba,$5d,$5d,$e7), ($32,$19,$19,$2b), ($e6,$73,$73,$95), ($c0,$60,$60,$a0), ($19,$81,$81,$98), ($9e,$4f,$4f,$d1), ($a3,$dc,$dc,$7f), ($44,$22,$22,$66), ($54,$2a,$2a,$7e), ($3b,$90,$90,$ab), ($0b,$88,$88,$83), ($8c,$46,$46,$ca), ($c7,$ee,$ee,$29), ($6b,$b8,$b8,$d3), ($28,$14,$14,$3c), ($a7,$de,$de,$79), ($bc,$5e,$5e,$e2), ($16,$0b,$0b,$1d), ($ad,$db,$db,$76), ($db,$e0,$e0,$3b), ($64,$32,$32,$56), ($74,$3a,$3a,$4e), ($14,$0a,$0a,$1e), ($92,$49,$49,$db), ($0c,$06,$06,$0a), ($48,$24,$24,$6c), ($b8,$5c,$5c,$e4), ($9f,$c2,$c2,$5d), ($bd,$d3,$d3,$6e), ($43,$ac,$ac,$ef), ($c4,$62,$62,$a6), ($39,$91,$91,$a8), ($31,$95,$95,$a4), ($d3,$e4,$e4,$37), ($f2,$79,$79,$8b), ($d5,$e7,$e7,$32), ($8b,$c8,$c8,$43), ($6e,$37,$37,$59), ($da,$6d,$6d,$b7), ($01,$8d,$8d,$8c), ($b1,$d5,$d5,$64), ($9c,$4e,$4e,$d2), ($49,$a9,$a9,$e0), ($d8,$6c,$6c,$b4), ($ac,$56,$56,$fa), ($f3,$f4,$f4,$07), ($cf,$ea,$ea,$25), ($ca,$65,$65,$af), ($f4,$7a,$7a,$8e), ($47,$ae,$ae,$e9), ($10,$08,$08,$18), ($6f,$ba,$ba,$d5), ($f0,$78,$78,$88), ($4a,$25,$25,$6f), ($5c,$2e,$2e,$72), ($38,$1c,$1c,$24), ($57,$a6,$a6,$f1), ($73,$b4,$b4,$c7), ($97,$c6,$c6,$51), ($cb,$e8,$e8,$23), ($a1,$dd,$dd,$7c), ($e8,$74,$74,$9c), ($3e,$1f,$1f,$21), ($96,$4b,$4b,$dd), ($61,$bd,$bd,$dc), ($0d,$8b,$8b,$86), ($0f,$8a,$8a,$85), ($e0,$70,$70,$90), ($7c,$3e,$3e,$42), ($71,$b5,$b5,$c4), ($cc,$66,$66,$aa), ($90,$48,$48,$d8), ($06,$03,$03,$05), ($f7,$f6,$f6,$01), ($1c,$0e,$0e,$12), ($c2,$61,$61,$a3), ($6a,$35,$35,$5f), ($ae,$57,$57,$f9), ($69,$b9,$b9,$d0), ($17,$86,$86,$91), ($99,$c1,$c1,$58), ($3a,$1d,$1d,$27), ($27,$9e,$9e,$b9), ($d9,$e1,$e1,$38), ($eb,$f8,$f8,$13), ($2b,$98,$98,$b3), ($22,$11,$11,$33), ($d2,$69,$69,$bb), ($a9,$d9,$d9,$70), ($07,$8e,$8e,$89), ($33,$94,$94,$a7), ($2d,$9b,$9b,$b6), ($3c,$1e,$1e,$22), ($15,$87,$87,$92), ($c9,$e9,$e9,$20), ($87,$ce,$ce,$49), ($aa,$55,$55,$ff), ($50,$28,$28,$78), ($a5,$df,$df,$7a), ($03,$8c,$8c,$8f), ($59,$a1,$a1,$f8), ($09,$89,$89,$80), ($1a,$0d,$0d,$17), ($65,$bf,$bf,$da), ($d7,$e6,$e6,$31), ($84,$42,$42,$c6), ($d0,$68,$68,$b8), ($82,$41,$41,$c3), ($29,$99,$99,$b0), ($5a,$2d,$2d,$77), ($1e,$0f,$0f,$11), ($7b,$b0,$b0,$cb), ($a8,$54,$54,$fc), ($6d,$bb,$bb,$d6), ($2c,$16,$16,$3a)); T2: array[0..255,0..3] of byte= ( ($a5,$c6,$63,$63), ($84,$f8,$7c,$7c), ($99,$ee,$77,$77), ($8d,$f6,$7b,$7b), ($0d,$ff,$f2,$f2), ($bd,$d6,$6b,$6b), ($b1,$de,$6f,$6f), ($54,$91,$c5,$c5), ($50,$60,$30,$30), ($03,$02,$01,$01), ($a9,$ce,$67,$67), ($7d,$56,$2b,$2b), ($19,$e7,$fe,$fe), ($62,$b5,$d7,$d7), ($e6,$4d,$ab,$ab), ($9a,$ec,$76,$76), ($45,$8f,$ca,$ca), ($9d,$1f,$82,$82), ($40,$89,$c9,$c9), ($87,$fa,$7d,$7d), ($15,$ef,$fa,$fa), ($eb,$b2,$59,$59), ($c9,$8e,$47,$47), ($0b,$fb,$f0,$f0), ($ec,$41,$ad,$ad), ($67,$b3,$d4,$d4), ($fd,$5f,$a2,$a2), ($ea,$45,$af,$af), ($bf,$23,$9c,$9c), ($f7,$53,$a4,$a4), ($96,$e4,$72,$72), ($5b,$9b,$c0,$c0), ($c2,$75,$b7,$b7), ($1c,$e1,$fd,$fd), ($ae,$3d,$93,$93), ($6a,$4c,$26,$26), ($5a,$6c,$36,$36), ($41,$7e,$3f,$3f), ($02,$f5,$f7,$f7), ($4f,$83,$cc,$cc), ($5c,$68,$34,$34), ($f4,$51,$a5,$a5), ($34,$d1,$e5,$e5), ($08,$f9,$f1,$f1), ($93,$e2,$71,$71), ($73,$ab,$d8,$d8), ($53,$62,$31,$31), ($3f,$2a,$15,$15), ($0c,$08,$04,$04), ($52,$95,$c7,$c7), ($65,$46,$23,$23), ($5e,$9d,$c3,$c3), ($28,$30,$18,$18), ($a1,$37,$96,$96), ($0f,$0a,$05,$05), ($b5,$2f,$9a,$9a), ($09,$0e,$07,$07), ($36,$24,$12,$12), ($9b,$1b,$80,$80), ($3d,$df,$e2,$e2), ($26,$cd,$eb,$eb), ($69,$4e,$27,$27), ($cd,$7f,$b2,$b2), ($9f,$ea,$75,$75), ($1b,$12,$09,$09), ($9e,$1d,$83,$83), ($74,$58,$2c,$2c), ($2e,$34,$1a,$1a), ($2d,$36,$1b,$1b), ($b2,$dc,$6e,$6e), ($ee,$b4,$5a,$5a), ($fb,$5b,$a0,$a0), ($f6,$a4,$52,$52), ($4d,$76,$3b,$3b), ($61,$b7,$d6,$d6), ($ce,$7d,$b3,$b3), ($7b,$52,$29,$29), ($3e,$dd,$e3,$e3), ($71,$5e,$2f,$2f), ($97,$13,$84,$84), ($f5,$a6,$53,$53), ($68,$b9,$d1,$d1), ($00,$00,$00,$00), ($2c,$c1,$ed,$ed), ($60,$40,$20,$20), ($1f,$e3,$fc,$fc), ($c8,$79,$b1,$b1), ($ed,$b6,$5b,$5b), ($be,$d4,$6a,$6a), ($46,$8d,$cb,$cb), ($d9,$67,$be,$be), ($4b,$72,$39,$39), ($de,$94,$4a,$4a), ($d4,$98,$4c,$4c), ($e8,$b0,$58,$58), ($4a,$85,$cf,$cf), ($6b,$bb,$d0,$d0), ($2a,$c5,$ef,$ef), ($e5,$4f,$aa,$aa), ($16,$ed,$fb,$fb), ($c5,$86,$43,$43), ($d7,$9a,$4d,$4d), ($55,$66,$33,$33), ($94,$11,$85,$85), ($cf,$8a,$45,$45), ($10,$e9,$f9,$f9), ($06,$04,$02,$02), ($81,$fe,$7f,$7f), ($f0,$a0,$50,$50), ($44,$78,$3c,$3c), ($ba,$25,$9f,$9f), ($e3,$4b,$a8,$a8), ($f3,$a2,$51,$51), ($fe,$5d,$a3,$a3), ($c0,$80,$40,$40), ($8a,$05,$8f,$8f), ($ad,$3f,$92,$92), ($bc,$21,$9d,$9d), ($48,$70,$38,$38), ($04,$f1,$f5,$f5), ($df,$63,$bc,$bc), ($c1,$77,$b6,$b6), ($75,$af,$da,$da), ($63,$42,$21,$21), ($30,$20,$10,$10), ($1a,$e5,$ff,$ff), ($0e,$fd,$f3,$f3), ($6d,$bf,$d2,$d2), ($4c,$81,$cd,$cd), ($14,$18,$0c,$0c), ($35,$26,$13,$13), ($2f,$c3,$ec,$ec), ($e1,$be,$5f,$5f), ($a2,$35,$97,$97), ($cc,$88,$44,$44), ($39,$2e,$17,$17), ($57,$93,$c4,$c4), ($f2,$55,$a7,$a7), ($82,$fc,$7e,$7e), ($47,$7a,$3d,$3d), ($ac,$c8,$64,$64), ($e7,$ba,$5d,$5d), ($2b,$32,$19,$19), ($95,$e6,$73,$73), ($a0,$c0,$60,$60), ($98,$19,$81,$81), ($d1,$9e,$4f,$4f), ($7f,$a3,$dc,$dc), ($66,$44,$22,$22), ($7e,$54,$2a,$2a), ($ab,$3b,$90,$90), ($83,$0b,$88,$88), ($ca,$8c,$46,$46), ($29,$c7,$ee,$ee), ($d3,$6b,$b8,$b8), ($3c,$28,$14,$14), ($79,$a7,$de,$de), ($e2,$bc,$5e,$5e), ($1d,$16,$0b,$0b), ($76,$ad,$db,$db), ($3b,$db,$e0,$e0), ($56,$64,$32,$32), ($4e,$74,$3a,$3a), ($1e,$14,$0a,$0a), ($db,$92,$49,$49), ($0a,$0c,$06,$06), ($6c,$48,$24,$24), ($e4,$b8,$5c,$5c), ($5d,$9f,$c2,$c2), ($6e,$bd,$d3,$d3), ($ef,$43,$ac,$ac), ($a6,$c4,$62,$62), ($a8,$39,$91,$91), ($a4,$31,$95,$95), ($37,$d3,$e4,$e4), ($8b,$f2,$79,$79), ($32,$d5,$e7,$e7), ($43,$8b,$c8,$c8), ($59,$6e,$37,$37), ($b7,$da,$6d,$6d), ($8c,$01,$8d,$8d), ($64,$b1,$d5,$d5), ($d2,$9c,$4e,$4e), ($e0,$49,$a9,$a9), ($b4,$d8,$6c,$6c), ($fa,$ac,$56,$56), ($07,$f3,$f4,$f4), ($25,$cf,$ea,$ea), ($af,$ca,$65,$65), ($8e,$f4,$7a,$7a), ($e9,$47,$ae,$ae), ($18,$10,$08,$08), ($d5,$6f,$ba,$ba), ($88,$f0,$78,$78), ($6f,$4a,$25,$25), ($72,$5c,$2e,$2e), ($24,$38,$1c,$1c), ($f1,$57,$a6,$a6), ($c7,$73,$b4,$b4), ($51,$97,$c6,$c6), ($23,$cb,$e8,$e8), ($7c,$a1,$dd,$dd), ($9c,$e8,$74,$74), ($21,$3e,$1f,$1f), ($dd,$96,$4b,$4b), ($dc,$61,$bd,$bd), ($86,$0d,$8b,$8b), ($85,$0f,$8a,$8a), ($90,$e0,$70,$70), ($42,$7c,$3e,$3e), ($c4,$71,$b5,$b5), ($aa,$cc,$66,$66), ($d8,$90,$48,$48), ($05,$06,$03,$03), ($01,$f7,$f6,$f6), ($12,$1c,$0e,$0e), ($a3,$c2,$61,$61), ($5f,$6a,$35,$35), ($f9,$ae,$57,$57), ($d0,$69,$b9,$b9), ($91,$17,$86,$86), ($58,$99,$c1,$c1), ($27,$3a,$1d,$1d), ($b9,$27,$9e,$9e), ($38,$d9,$e1,$e1), ($13,$eb,$f8,$f8), ($b3,$2b,$98,$98), ($33,$22,$11,$11), ($bb,$d2,$69,$69), ($70,$a9,$d9,$d9), ($89,$07,$8e,$8e), ($a7,$33,$94,$94), ($b6,$2d,$9b,$9b), ($22,$3c,$1e,$1e), ($92,$15,$87,$87), ($20,$c9,$e9,$e9), ($49,$87,$ce,$ce), ($ff,$aa,$55,$55), ($78,$50,$28,$28), ($7a,$a5,$df,$df), ($8f,$03,$8c,$8c), ($f8,$59,$a1,$a1), ($80,$09,$89,$89), ($17,$1a,$0d,$0d), ($da,$65,$bf,$bf), ($31,$d7,$e6,$e6), ($c6,$84,$42,$42), ($b8,$d0,$68,$68), ($c3,$82,$41,$41), ($b0,$29,$99,$99), ($77,$5a,$2d,$2d), ($11,$1e,$0f,$0f), ($cb,$7b,$b0,$b0), ($fc,$a8,$54,$54), ($d6,$6d,$bb,$bb), ($3a,$2c,$16,$16)); T3: array[0..255,0..3] of byte= ( ($63,$a5,$c6,$63), ($7c,$84,$f8,$7c), ($77,$99,$ee,$77), ($7b,$8d,$f6,$7b), ($f2,$0d,$ff,$f2), ($6b,$bd,$d6,$6b), ($6f,$b1,$de,$6f), ($c5,$54,$91,$c5), ($30,$50,$60,$30), ($01,$03,$02,$01), ($67,$a9,$ce,$67), ($2b,$7d,$56,$2b), ($fe,$19,$e7,$fe), ($d7,$62,$b5,$d7), ($ab,$e6,$4d,$ab), ($76,$9a,$ec,$76), ($ca,$45,$8f,$ca), ($82,$9d,$1f,$82), ($c9,$40,$89,$c9), ($7d,$87,$fa,$7d), ($fa,$15,$ef,$fa), ($59,$eb,$b2,$59), ($47,$c9,$8e,$47), ($f0,$0b,$fb,$f0), ($ad,$ec,$41,$ad), ($d4,$67,$b3,$d4), ($a2,$fd,$5f,$a2), ($af,$ea,$45,$af), ($9c,$bf,$23,$9c), ($a4,$f7,$53,$a4), ($72,$96,$e4,$72), ($c0,$5b,$9b,$c0), ($b7,$c2,$75,$b7), ($fd,$1c,$e1,$fd), ($93,$ae,$3d,$93), ($26,$6a,$4c,$26), ($36,$5a,$6c,$36), ($3f,$41,$7e,$3f), ($f7,$02,$f5,$f7), ($cc,$4f,$83,$cc), ($34,$5c,$68,$34), ($a5,$f4,$51,$a5), ($e5,$34,$d1,$e5), ($f1,$08,$f9,$f1), ($71,$93,$e2,$71), ($d8,$73,$ab,$d8), ($31,$53,$62,$31), ($15,$3f,$2a,$15), ($04,$0c,$08,$04), ($c7,$52,$95,$c7), ($23,$65,$46,$23), ($c3,$5e,$9d,$c3), ($18,$28,$30,$18), ($96,$a1,$37,$96), ($05,$0f,$0a,$05), ($9a,$b5,$2f,$9a), ($07,$09,$0e,$07), ($12,$36,$24,$12), ($80,$9b,$1b,$80), ($e2,$3d,$df,$e2), ($eb,$26,$cd,$eb), ($27,$69,$4e,$27), ($b2,$cd,$7f,$b2), ($75,$9f,$ea,$75), ($09,$1b,$12,$09), ($83,$9e,$1d,$83), ($2c,$74,$58,$2c), ($1a,$2e,$34,$1a), ($1b,$2d,$36,$1b), ($6e,$b2,$dc,$6e), ($5a,$ee,$b4,$5a), ($a0,$fb,$5b,$a0), ($52,$f6,$a4,$52), ($3b,$4d,$76,$3b), ($d6,$61,$b7,$d6), ($b3,$ce,$7d,$b3), ($29,$7b,$52,$29), ($e3,$3e,$dd,$e3), ($2f,$71,$5e,$2f), ($84,$97,$13,$84), ($53,$f5,$a6,$53), ($d1,$68,$b9,$d1), ($00,$00,$00,$00), ($ed,$2c,$c1,$ed), ($20,$60,$40,$20), ($fc,$1f,$e3,$fc), ($b1,$c8,$79,$b1), ($5b,$ed,$b6,$5b), ($6a,$be,$d4,$6a), ($cb,$46,$8d,$cb), ($be,$d9,$67,$be), ($39,$4b,$72,$39), ($4a,$de,$94,$4a), ($4c,$d4,$98,$4c), ($58,$e8,$b0,$58), ($cf,$4a,$85,$cf), ($d0,$6b,$bb,$d0), ($ef,$2a,$c5,$ef), ($aa,$e5,$4f,$aa), ($fb,$16,$ed,$fb), ($43,$c5,$86,$43), ($4d,$d7,$9a,$4d), ($33,$55,$66,$33), ($85,$94,$11,$85), ($45,$cf,$8a,$45), ($f9,$10,$e9,$f9), ($02,$06,$04,$02), ($7f,$81,$fe,$7f), ($50,$f0,$a0,$50), ($3c,$44,$78,$3c), ($9f,$ba,$25,$9f), ($a8,$e3,$4b,$a8), ($51,$f3,$a2,$51), ($a3,$fe,$5d,$a3), ($40,$c0,$80,$40), ($8f,$8a,$05,$8f), ($92,$ad,$3f,$92), ($9d,$bc,$21,$9d), ($38,$48,$70,$38), ($f5,$04,$f1,$f5), ($bc,$df,$63,$bc), ($b6,$c1,$77,$b6), ($da,$75,$af,$da), ($21,$63,$42,$21), ($10,$30,$20,$10), ($ff,$1a,$e5,$ff), ($f3,$0e,$fd,$f3), ($d2,$6d,$bf,$d2), ($cd,$4c,$81,$cd), ($0c,$14,$18,$0c), ($13,$35,$26,$13), ($ec,$2f,$c3,$ec), ($5f,$e1,$be,$5f), ($97,$a2,$35,$97), ($44,$cc,$88,$44), ($17,$39,$2e,$17), ($c4,$57,$93,$c4), ($a7,$f2,$55,$a7), ($7e,$82,$fc,$7e), ($3d,$47,$7a,$3d), ($64,$ac,$c8,$64), ($5d,$e7,$ba,$5d), ($19,$2b,$32,$19), ($73,$95,$e6,$73), ($60,$a0,$c0,$60), ($81,$98,$19,$81), ($4f,$d1,$9e,$4f), ($dc,$7f,$a3,$dc), ($22,$66,$44,$22), ($2a,$7e,$54,$2a), ($90,$ab,$3b,$90), ($88,$83,$0b,$88), ($46,$ca,$8c,$46), ($ee,$29,$c7,$ee), ($b8,$d3,$6b,$b8), ($14,$3c,$28,$14), ($de,$79,$a7,$de), ($5e,$e2,$bc,$5e), ($0b,$1d,$16,$0b), ($db,$76,$ad,$db), ($e0,$3b,$db,$e0), ($32,$56,$64,$32), ($3a,$4e,$74,$3a), ($0a,$1e,$14,$0a), ($49,$db,$92,$49), ($06,$0a,$0c,$06), ($24,$6c,$48,$24), ($5c,$e4,$b8,$5c), ($c2,$5d,$9f,$c2), ($d3,$6e,$bd,$d3), ($ac,$ef,$43,$ac), ($62,$a6,$c4,$62), ($91,$a8,$39,$91), ($95,$a4,$31,$95), ($e4,$37,$d3,$e4), ($79,$8b,$f2,$79), ($e7,$32,$d5,$e7), ($c8,$43,$8b,$c8), ($37,$59,$6e,$37), ($6d,$b7,$da,$6d), ($8d,$8c,$01,$8d), ($d5,$64,$b1,$d5), ($4e,$d2,$9c,$4e), ($a9,$e0,$49,$a9), ($6c,$b4,$d8,$6c), ($56,$fa,$ac,$56), ($f4,$07,$f3,$f4), ($ea,$25,$cf,$ea), ($65,$af,$ca,$65), ($7a,$8e,$f4,$7a), ($ae,$e9,$47,$ae), ($08,$18,$10,$08), ($ba,$d5,$6f,$ba), ($78,$88,$f0,$78), ($25,$6f,$4a,$25), ($2e,$72,$5c,$2e), ($1c,$24,$38,$1c), ($a6,$f1,$57,$a6), ($b4,$c7,$73,$b4), ($c6,$51,$97,$c6), ($e8,$23,$cb,$e8), ($dd,$7c,$a1,$dd), ($74,$9c,$e8,$74), ($1f,$21,$3e,$1f), ($4b,$dd,$96,$4b), ($bd,$dc,$61,$bd), ($8b,$86,$0d,$8b), ($8a,$85,$0f,$8a), ($70,$90,$e0,$70), ($3e,$42,$7c,$3e), ($b5,$c4,$71,$b5), ($66,$aa,$cc,$66), ($48,$d8,$90,$48), ($03,$05,$06,$03), ($f6,$01,$f7,$f6), ($0e,$12,$1c,$0e), ($61,$a3,$c2,$61), ($35,$5f,$6a,$35), ($57,$f9,$ae,$57), ($b9,$d0,$69,$b9), ($86,$91,$17,$86), ($c1,$58,$99,$c1), ($1d,$27,$3a,$1d), ($9e,$b9,$27,$9e), ($e1,$38,$d9,$e1), ($f8,$13,$eb,$f8), ($98,$b3,$2b,$98), ($11,$33,$22,$11), ($69,$bb,$d2,$69), ($d9,$70,$a9,$d9), ($8e,$89,$07,$8e), ($94,$a7,$33,$94), ($9b,$b6,$2d,$9b), ($1e,$22,$3c,$1e), ($87,$92,$15,$87), ($e9,$20,$c9,$e9), ($ce,$49,$87,$ce), ($55,$ff,$aa,$55), ($28,$78,$50,$28), ($df,$7a,$a5,$df), ($8c,$8f,$03,$8c), ($a1,$f8,$59,$a1), ($89,$80,$09,$89), ($0d,$17,$1a,$0d), ($bf,$da,$65,$bf), ($e6,$31,$d7,$e6), ($42,$c6,$84,$42), ($68,$b8,$d0,$68), ($41,$c3,$82,$41), ($99,$b0,$29,$99), ($2d,$77,$5a,$2d), ($0f,$11,$1e,$0f), ($b0,$cb,$7b,$b0), ($54,$fc,$a8,$54), ($bb,$d6,$6d,$bb), ($16,$3a,$2c,$16)); T4: array[0..255,0..3] of byte= ( ($63,$63,$a5,$c6), ($7c,$7c,$84,$f8), ($77,$77,$99,$ee), ($7b,$7b,$8d,$f6), ($f2,$f2,$0d,$ff), ($6b,$6b,$bd,$d6), ($6f,$6f,$b1,$de), ($c5,$c5,$54,$91), ($30,$30,$50,$60), ($01,$01,$03,$02), ($67,$67,$a9,$ce), ($2b,$2b,$7d,$56), ($fe,$fe,$19,$e7), ($d7,$d7,$62,$b5), ($ab,$ab,$e6,$4d), ($76,$76,$9a,$ec), ($ca,$ca,$45,$8f), ($82,$82,$9d,$1f), ($c9,$c9,$40,$89), ($7d,$7d,$87,$fa), ($fa,$fa,$15,$ef), ($59,$59,$eb,$b2), ($47,$47,$c9,$8e), ($f0,$f0,$0b,$fb), ($ad,$ad,$ec,$41), ($d4,$d4,$67,$b3), ($a2,$a2,$fd,$5f), ($af,$af,$ea,$45), ($9c,$9c,$bf,$23), ($a4,$a4,$f7,$53), ($72,$72,$96,$e4), ($c0,$c0,$5b,$9b), ($b7,$b7,$c2,$75), ($fd,$fd,$1c,$e1), ($93,$93,$ae,$3d), ($26,$26,$6a,$4c), ($36,$36,$5a,$6c), ($3f,$3f,$41,$7e), ($f7,$f7,$02,$f5), ($cc,$cc,$4f,$83), ($34,$34,$5c,$68), ($a5,$a5,$f4,$51), ($e5,$e5,$34,$d1), ($f1,$f1,$08,$f9), ($71,$71,$93,$e2), ($d8,$d8,$73,$ab), ($31,$31,$53,$62), ($15,$15,$3f,$2a), ($04,$04,$0c,$08), ($c7,$c7,$52,$95), ($23,$23,$65,$46), ($c3,$c3,$5e,$9d), ($18,$18,$28,$30), ($96,$96,$a1,$37), ($05,$05,$0f,$0a), ($9a,$9a,$b5,$2f), ($07,$07,$09,$0e), ($12,$12,$36,$24), ($80,$80,$9b,$1b), ($e2,$e2,$3d,$df), ($eb,$eb,$26,$cd), ($27,$27,$69,$4e), ($b2,$b2,$cd,$7f), ($75,$75,$9f,$ea), ($09,$09,$1b,$12), ($83,$83,$9e,$1d), ($2c,$2c,$74,$58), ($1a,$1a,$2e,$34), ($1b,$1b,$2d,$36), ($6e,$6e,$b2,$dc), ($5a,$5a,$ee,$b4), ($a0,$a0,$fb,$5b), ($52,$52,$f6,$a4), ($3b,$3b,$4d,$76), ($d6,$d6,$61,$b7), ($b3,$b3,$ce,$7d), ($29,$29,$7b,$52), ($e3,$e3,$3e,$dd), ($2f,$2f,$71,$5e), ($84,$84,$97,$13), ($53,$53,$f5,$a6), ($d1,$d1,$68,$b9), ($00,$00,$00,$00), ($ed,$ed,$2c,$c1), ($20,$20,$60,$40), ($fc,$fc,$1f,$e3), ($b1,$b1,$c8,$79), ($5b,$5b,$ed,$b6), ($6a,$6a,$be,$d4), ($cb,$cb,$46,$8d), ($be,$be,$d9,$67), ($39,$39,$4b,$72), ($4a,$4a,$de,$94), ($4c,$4c,$d4,$98), ($58,$58,$e8,$b0), ($cf,$cf,$4a,$85), ($d0,$d0,$6b,$bb), ($ef,$ef,$2a,$c5), ($aa,$aa,$e5,$4f), ($fb,$fb,$16,$ed), ($43,$43,$c5,$86), ($4d,$4d,$d7,$9a), ($33,$33,$55,$66), ($85,$85,$94,$11), ($45,$45,$cf,$8a), ($f9,$f9,$10,$e9), ($02,$02,$06,$04), ($7f,$7f,$81,$fe), ($50,$50,$f0,$a0), ($3c,$3c,$44,$78), ($9f,$9f,$ba,$25), ($a8,$a8,$e3,$4b), ($51,$51,$f3,$a2), ($a3,$a3,$fe,$5d), ($40,$40,$c0,$80), ($8f,$8f,$8a,$05), ($92,$92,$ad,$3f), ($9d,$9d,$bc,$21), ($38,$38,$48,$70), ($f5,$f5,$04,$f1), ($bc,$bc,$df,$63), ($b6,$b6,$c1,$77), ($da,$da,$75,$af), ($21,$21,$63,$42), ($10,$10,$30,$20), ($ff,$ff,$1a,$e5), ($f3,$f3,$0e,$fd), ($d2,$d2,$6d,$bf), ($cd,$cd,$4c,$81), ($0c,$0c,$14,$18), ($13,$13,$35,$26), ($ec,$ec,$2f,$c3), ($5f,$5f,$e1,$be), ($97,$97,$a2,$35), ($44,$44,$cc,$88), ($17,$17,$39,$2e), ($c4,$c4,$57,$93), ($a7,$a7,$f2,$55), ($7e,$7e,$82,$fc), ($3d,$3d,$47,$7a), ($64,$64,$ac,$c8), ($5d,$5d,$e7,$ba), ($19,$19,$2b,$32), ($73,$73,$95,$e6), ($60,$60,$a0,$c0), ($81,$81,$98,$19), ($4f,$4f,$d1,$9e), ($dc,$dc,$7f,$a3), ($22,$22,$66,$44), ($2a,$2a,$7e,$54), ($90,$90,$ab,$3b), ($88,$88,$83,$0b), ($46,$46,$ca,$8c), ($ee,$ee,$29,$c7), ($b8,$b8,$d3,$6b), ($14,$14,$3c,$28), ($de,$de,$79,$a7), ($5e,$5e,$e2,$bc), ($0b,$0b,$1d,$16), ($db,$db,$76,$ad), ($e0,$e0,$3b,$db), ($32,$32,$56,$64), ($3a,$3a,$4e,$74), ($0a,$0a,$1e,$14), ($49,$49,$db,$92), ($06,$06,$0a,$0c), ($24,$24,$6c,$48), ($5c,$5c,$e4,$b8), ($c2,$c2,$5d,$9f), ($d3,$d3,$6e,$bd), ($ac,$ac,$ef,$43), ($62,$62,$a6,$c4), ($91,$91,$a8,$39), ($95,$95,$a4,$31), ($e4,$e4,$37,$d3), ($79,$79,$8b,$f2), ($e7,$e7,$32,$d5), ($c8,$c8,$43,$8b), ($37,$37,$59,$6e), ($6d,$6d,$b7,$da), ($8d,$8d,$8c,$01), ($d5,$d5,$64,$b1), ($4e,$4e,$d2,$9c), ($a9,$a9,$e0,$49), ($6c,$6c,$b4,$d8), ($56,$56,$fa,$ac), ($f4,$f4,$07,$f3), ($ea,$ea,$25,$cf), ($65,$65,$af,$ca), ($7a,$7a,$8e,$f4), ($ae,$ae,$e9,$47), ($08,$08,$18,$10), ($ba,$ba,$d5,$6f), ($78,$78,$88,$f0), ($25,$25,$6f,$4a), ($2e,$2e,$72,$5c), ($1c,$1c,$24,$38), ($a6,$a6,$f1,$57), ($b4,$b4,$c7,$73), ($c6,$c6,$51,$97), ($e8,$e8,$23,$cb), ($dd,$dd,$7c,$a1), ($74,$74,$9c,$e8), ($1f,$1f,$21,$3e), ($4b,$4b,$dd,$96), ($bd,$bd,$dc,$61), ($8b,$8b,$86,$0d), ($8a,$8a,$85,$0f), ($70,$70,$90,$e0), ($3e,$3e,$42,$7c), ($b5,$b5,$c4,$71), ($66,$66,$aa,$cc), ($48,$48,$d8,$90), ($03,$03,$05,$06), ($f6,$f6,$01,$f7), ($0e,$0e,$12,$1c), ($61,$61,$a3,$c2), ($35,$35,$5f,$6a), ($57,$57,$f9,$ae), ($b9,$b9,$d0,$69), ($86,$86,$91,$17), ($c1,$c1,$58,$99), ($1d,$1d,$27,$3a), ($9e,$9e,$b9,$27), ($e1,$e1,$38,$d9), ($f8,$f8,$13,$eb), ($98,$98,$b3,$2b), ($11,$11,$33,$22), ($69,$69,$bb,$d2), ($d9,$d9,$70,$a9), ($8e,$8e,$89,$07), ($94,$94,$a7,$33), ($9b,$9b,$b6,$2d), ($1e,$1e,$22,$3c), ($87,$87,$92,$15), ($e9,$e9,$20,$c9), ($ce,$ce,$49,$87), ($55,$55,$ff,$aa), ($28,$28,$78,$50), ($df,$df,$7a,$a5), ($8c,$8c,$8f,$03), ($a1,$a1,$f8,$59), ($89,$89,$80,$09), ($0d,$0d,$17,$1a), ($bf,$bf,$da,$65), ($e6,$e6,$31,$d7), ($42,$42,$c6,$84), ($68,$68,$b8,$d0), ($41,$41,$c3,$82), ($99,$99,$b0,$29), ($2d,$2d,$77,$5a), ($0f,$0f,$11,$1e), ($b0,$b0,$cb,$7b), ($54,$54,$fc,$a8), ($bb,$bb,$d6,$6d), ($16,$16,$3a,$2c)); T5: array[0..255,0..3] of byte= ( ($51,$f4,$a7,$50), ($7e,$41,$65,$53), ($1a,$17,$a4,$c3), ($3a,$27,$5e,$96), ($3b,$ab,$6b,$cb), ($1f,$9d,$45,$f1), ($ac,$fa,$58,$ab), ($4b,$e3,$03,$93), ($20,$30,$fa,$55), ($ad,$76,$6d,$f6), ($88,$cc,$76,$91), ($f5,$02,$4c,$25), ($4f,$e5,$d7,$fc), ($c5,$2a,$cb,$d7), ($26,$35,$44,$80), ($b5,$62,$a3,$8f), ($de,$b1,$5a,$49), ($25,$ba,$1b,$67), ($45,$ea,$0e,$98), ($5d,$fe,$c0,$e1), ($c3,$2f,$75,$02), ($81,$4c,$f0,$12), ($8d,$46,$97,$a3), ($6b,$d3,$f9,$c6), ($03,$8f,$5f,$e7), ($15,$92,$9c,$95), ($bf,$6d,$7a,$eb), ($95,$52,$59,$da), ($d4,$be,$83,$2d), ($58,$74,$21,$d3), ($49,$e0,$69,$29), ($8e,$c9,$c8,$44), ($75,$c2,$89,$6a), ($f4,$8e,$79,$78), ($99,$58,$3e,$6b), ($27,$b9,$71,$dd), ($be,$e1,$4f,$b6), ($f0,$88,$ad,$17), ($c9,$20,$ac,$66), ($7d,$ce,$3a,$b4), ($63,$df,$4a,$18), ($e5,$1a,$31,$82), ($97,$51,$33,$60), ($62,$53,$7f,$45), ($b1,$64,$77,$e0), ($bb,$6b,$ae,$84), ($fe,$81,$a0,$1c), ($f9,$08,$2b,$94), ($70,$48,$68,$58), ($8f,$45,$fd,$19), ($94,$de,$6c,$87), ($52,$7b,$f8,$b7), ($ab,$73,$d3,$23), ($72,$4b,$02,$e2), ($e3,$1f,$8f,$57), ($66,$55,$ab,$2a), ($b2,$eb,$28,$07), ($2f,$b5,$c2,$03), ($86,$c5,$7b,$9a), ($d3,$37,$08,$a5), ($30,$28,$87,$f2), ($23,$bf,$a5,$b2), ($02,$03,$6a,$ba), ($ed,$16,$82,$5c), ($8a,$cf,$1c,$2b), ($a7,$79,$b4,$92), ($f3,$07,$f2,$f0), ($4e,$69,$e2,$a1), ($65,$da,$f4,$cd), ($06,$05,$be,$d5), ($d1,$34,$62,$1f), ($c4,$a6,$fe,$8a), ($34,$2e,$53,$9d), ($a2,$f3,$55,$a0), ($05,$8a,$e1,$32), ($a4,$f6,$eb,$75), ($0b,$83,$ec,$39), ($40,$60,$ef,$aa), ($5e,$71,$9f,$06), ($bd,$6e,$10,$51), ($3e,$21,$8a,$f9), ($96,$dd,$06,$3d), ($dd,$3e,$05,$ae), ($4d,$e6,$bd,$46), ($91,$54,$8d,$b5), ($71,$c4,$5d,$05), ($04,$06,$d4,$6f), ($60,$50,$15,$ff), ($19,$98,$fb,$24), ($d6,$bd,$e9,$97), ($89,$40,$43,$cc), ($67,$d9,$9e,$77), ($b0,$e8,$42,$bd), ($07,$89,$8b,$88), ($e7,$19,$5b,$38), ($79,$c8,$ee,$db), ($a1,$7c,$0a,$47), ($7c,$42,$0f,$e9), ($f8,$84,$1e,$c9), ($00,$00,$00,$00), ($09,$80,$86,$83), ($32,$2b,$ed,$48), ($1e,$11,$70,$ac), ($6c,$5a,$72,$4e), ($fd,$0e,$ff,$fb), ($0f,$85,$38,$56), ($3d,$ae,$d5,$1e), ($36,$2d,$39,$27), ($0a,$0f,$d9,$64), ($68,$5c,$a6,$21), ($9b,$5b,$54,$d1), ($24,$36,$2e,$3a), ($0c,$0a,$67,$b1), ($93,$57,$e7,$0f), ($b4,$ee,$96,$d2), ($1b,$9b,$91,$9e), ($80,$c0,$c5,$4f), ($61,$dc,$20,$a2), ($5a,$77,$4b,$69), ($1c,$12,$1a,$16), ($e2,$93,$ba,$0a), ($c0,$a0,$2a,$e5), ($3c,$22,$e0,$43), ($12,$1b,$17,$1d), ($0e,$09,$0d,$0b), ($f2,$8b,$c7,$ad), ($2d,$b6,$a8,$b9), ($14,$1e,$a9,$c8), ($57,$f1,$19,$85), ($af,$75,$07,$4c), ($ee,$99,$dd,$bb), ($a3,$7f,$60,$fd), ($f7,$01,$26,$9f), ($5c,$72,$f5,$bc), ($44,$66,$3b,$c5), ($5b,$fb,$7e,$34), ($8b,$43,$29,$76), ($cb,$23,$c6,$dc), ($b6,$ed,$fc,$68), ($b8,$e4,$f1,$63), ($d7,$31,$dc,$ca), ($42,$63,$85,$10), ($13,$97,$22,$40), ($84,$c6,$11,$20), ($85,$4a,$24,$7d), ($d2,$bb,$3d,$f8), ($ae,$f9,$32,$11), ($c7,$29,$a1,$6d), ($1d,$9e,$2f,$4b), ($dc,$b2,$30,$f3), ($0d,$86,$52,$ec), ($77,$c1,$e3,$d0), ($2b,$b3,$16,$6c), ($a9,$70,$b9,$99), ($11,$94,$48,$fa), ($47,$e9,$64,$22), ($a8,$fc,$8c,$c4), ($a0,$f0,$3f,$1a), ($56,$7d,$2c,$d8), ($22,$33,$90,$ef), ($87,$49,$4e,$c7), ($d9,$38,$d1,$c1), ($8c,$ca,$a2,$fe), ($98,$d4,$0b,$36), ($a6,$f5,$81,$cf), ($a5,$7a,$de,$28), ($da,$b7,$8e,$26), ($3f,$ad,$bf,$a4), ($2c,$3a,$9d,$e4), ($50,$78,$92,$0d), ($6a,$5f,$cc,$9b), ($54,$7e,$46,$62), ($f6,$8d,$13,$c2), ($90,$d8,$b8,$e8), ($2e,$39,$f7,$5e), ($82,$c3,$af,$f5), ($9f,$5d,$80,$be), ($69,$d0,$93,$7c), ($6f,$d5,$2d,$a9), ($cf,$25,$12,$b3), ($c8,$ac,$99,$3b), ($10,$18,$7d,$a7), ($e8,$9c,$63,$6e), ($db,$3b,$bb,$7b), ($cd,$26,$78,$09), ($6e,$59,$18,$f4), ($ec,$9a,$b7,$01), ($83,$4f,$9a,$a8), ($e6,$95,$6e,$65), ($aa,$ff,$e6,$7e), ($21,$bc,$cf,$08), ($ef,$15,$e8,$e6), ($ba,$e7,$9b,$d9), ($4a,$6f,$36,$ce), ($ea,$9f,$09,$d4), ($29,$b0,$7c,$d6), ($31,$a4,$b2,$af), ($2a,$3f,$23,$31), ($c6,$a5,$94,$30), ($35,$a2,$66,$c0), ($74,$4e,$bc,$37), ($fc,$82,$ca,$a6), ($e0,$90,$d0,$b0), ($33,$a7,$d8,$15), ($f1,$04,$98,$4a), ($41,$ec,$da,$f7), ($7f,$cd,$50,$0e), ($17,$91,$f6,$2f), ($76,$4d,$d6,$8d), ($43,$ef,$b0,$4d), ($cc,$aa,$4d,$54), ($e4,$96,$04,$df), ($9e,$d1,$b5,$e3), ($4c,$6a,$88,$1b), ($c1,$2c,$1f,$b8), ($46,$65,$51,$7f), ($9d,$5e,$ea,$04), ($01,$8c,$35,$5d), ($fa,$87,$74,$73), ($fb,$0b,$41,$2e), ($b3,$67,$1d,$5a), ($92,$db,$d2,$52), ($e9,$10,$56,$33), ($6d,$d6,$47,$13), ($9a,$d7,$61,$8c), ($37,$a1,$0c,$7a), ($59,$f8,$14,$8e), ($eb,$13,$3c,$89), ($ce,$a9,$27,$ee), ($b7,$61,$c9,$35), ($e1,$1c,$e5,$ed), ($7a,$47,$b1,$3c), ($9c,$d2,$df,$59), ($55,$f2,$73,$3f), ($18,$14,$ce,$79), ($73,$c7,$37,$bf), ($53,$f7,$cd,$ea), ($5f,$fd,$aa,$5b), ($df,$3d,$6f,$14), ($78,$44,$db,$86), ($ca,$af,$f3,$81), ($b9,$68,$c4,$3e), ($38,$24,$34,$2c), ($c2,$a3,$40,$5f), ($16,$1d,$c3,$72), ($bc,$e2,$25,$0c), ($28,$3c,$49,$8b), ($ff,$0d,$95,$41), ($39,$a8,$01,$71), ($08,$0c,$b3,$de), ($d8,$b4,$e4,$9c), ($64,$56,$c1,$90), ($7b,$cb,$84,$61), ($d5,$32,$b6,$70), ($48,$6c,$5c,$74), ($d0,$b8,$57,$42)); T6: array[0..255,0..3] of byte= ( ($50,$51,$f4,$a7), ($53,$7e,$41,$65), ($c3,$1a,$17,$a4), ($96,$3a,$27,$5e), ($cb,$3b,$ab,$6b), ($f1,$1f,$9d,$45), ($ab,$ac,$fa,$58), ($93,$4b,$e3,$03), ($55,$20,$30,$fa), ($f6,$ad,$76,$6d), ($91,$88,$cc,$76), ($25,$f5,$02,$4c), ($fc,$4f,$e5,$d7), ($d7,$c5,$2a,$cb), ($80,$26,$35,$44), ($8f,$b5,$62,$a3), ($49,$de,$b1,$5a), ($67,$25,$ba,$1b), ($98,$45,$ea,$0e), ($e1,$5d,$fe,$c0), ($02,$c3,$2f,$75), ($12,$81,$4c,$f0), ($a3,$8d,$46,$97), ($c6,$6b,$d3,$f9), ($e7,$03,$8f,$5f), ($95,$15,$92,$9c), ($eb,$bf,$6d,$7a), ($da,$95,$52,$59), ($2d,$d4,$be,$83), ($d3,$58,$74,$21), ($29,$49,$e0,$69), ($44,$8e,$c9,$c8), ($6a,$75,$c2,$89), ($78,$f4,$8e,$79), ($6b,$99,$58,$3e), ($dd,$27,$b9,$71), ($b6,$be,$e1,$4f), ($17,$f0,$88,$ad), ($66,$c9,$20,$ac), ($b4,$7d,$ce,$3a), ($18,$63,$df,$4a), ($82,$e5,$1a,$31), ($60,$97,$51,$33), ($45,$62,$53,$7f), ($e0,$b1,$64,$77), ($84,$bb,$6b,$ae), ($1c,$fe,$81,$a0), ($94,$f9,$08,$2b), ($58,$70,$48,$68), ($19,$8f,$45,$fd), ($87,$94,$de,$6c), ($b7,$52,$7b,$f8), ($23,$ab,$73,$d3), ($e2,$72,$4b,$02), ($57,$e3,$1f,$8f), ($2a,$66,$55,$ab), ($07,$b2,$eb,$28), ($03,$2f,$b5,$c2), ($9a,$86,$c5,$7b), ($a5,$d3,$37,$08), ($f2,$30,$28,$87), ($b2,$23,$bf,$a5), ($ba,$02,$03,$6a), ($5c,$ed,$16,$82), ($2b,$8a,$cf,$1c), ($92,$a7,$79,$b4), ($f0,$f3,$07,$f2), ($a1,$4e,$69,$e2), ($cd,$65,$da,$f4), ($d5,$06,$05,$be), ($1f,$d1,$34,$62), ($8a,$c4,$a6,$fe), ($9d,$34,$2e,$53), ($a0,$a2,$f3,$55), ($32,$05,$8a,$e1), ($75,$a4,$f6,$eb), ($39,$0b,$83,$ec), ($aa,$40,$60,$ef), ($06,$5e,$71,$9f), ($51,$bd,$6e,$10), ($f9,$3e,$21,$8a), ($3d,$96,$dd,$06), ($ae,$dd,$3e,$05), ($46,$4d,$e6,$bd), ($b5,$91,$54,$8d), ($05,$71,$c4,$5d), ($6f,$04,$06,$d4), ($ff,$60,$50,$15), ($24,$19,$98,$fb), ($97,$d6,$bd,$e9), ($cc,$89,$40,$43), ($77,$67,$d9,$9e), ($bd,$b0,$e8,$42), ($88,$07,$89,$8b), ($38,$e7,$19,$5b), ($db,$79,$c8,$ee), ($47,$a1,$7c,$0a), ($e9,$7c,$42,$0f), ($c9,$f8,$84,$1e), ($00,$00,$00,$00), ($83,$09,$80,$86), ($48,$32,$2b,$ed), ($ac,$1e,$11,$70), ($4e,$6c,$5a,$72), ($fb,$fd,$0e,$ff), ($56,$0f,$85,$38), ($1e,$3d,$ae,$d5), ($27,$36,$2d,$39), ($64,$0a,$0f,$d9), ($21,$68,$5c,$a6), ($d1,$9b,$5b,$54), ($3a,$24,$36,$2e), ($b1,$0c,$0a,$67), ($0f,$93,$57,$e7), ($d2,$b4,$ee,$96), ($9e,$1b,$9b,$91), ($4f,$80,$c0,$c5), ($a2,$61,$dc,$20), ($69,$5a,$77,$4b), ($16,$1c,$12,$1a), ($0a,$e2,$93,$ba), ($e5,$c0,$a0,$2a), ($43,$3c,$22,$e0), ($1d,$12,$1b,$17), ($0b,$0e,$09,$0d), ($ad,$f2,$8b,$c7), ($b9,$2d,$b6,$a8), ($c8,$14,$1e,$a9), ($85,$57,$f1,$19), ($4c,$af,$75,$07), ($bb,$ee,$99,$dd), ($fd,$a3,$7f,$60), ($9f,$f7,$01,$26), ($bc,$5c,$72,$f5), ($c5,$44,$66,$3b), ($34,$5b,$fb,$7e), ($76,$8b,$43,$29), ($dc,$cb,$23,$c6), ($68,$b6,$ed,$fc), ($63,$b8,$e4,$f1), ($ca,$d7,$31,$dc), ($10,$42,$63,$85), ($40,$13,$97,$22), ($20,$84,$c6,$11), ($7d,$85,$4a,$24), ($f8,$d2,$bb,$3d), ($11,$ae,$f9,$32), ($6d,$c7,$29,$a1), ($4b,$1d,$9e,$2f), ($f3,$dc,$b2,$30), ($ec,$0d,$86,$52), ($d0,$77,$c1,$e3), ($6c,$2b,$b3,$16), ($99,$a9,$70,$b9), ($fa,$11,$94,$48), ($22,$47,$e9,$64), ($c4,$a8,$fc,$8c), ($1a,$a0,$f0,$3f), ($d8,$56,$7d,$2c), ($ef,$22,$33,$90), ($c7,$87,$49,$4e), ($c1,$d9,$38,$d1), ($fe,$8c,$ca,$a2), ($36,$98,$d4,$0b), ($cf,$a6,$f5,$81), ($28,$a5,$7a,$de), ($26,$da,$b7,$8e), ($a4,$3f,$ad,$bf), ($e4,$2c,$3a,$9d), ($0d,$50,$78,$92), ($9b,$6a,$5f,$cc), ($62,$54,$7e,$46), ($c2,$f6,$8d,$13), ($e8,$90,$d8,$b8), ($5e,$2e,$39,$f7), ($f5,$82,$c3,$af), ($be,$9f,$5d,$80), ($7c,$69,$d0,$93), ($a9,$6f,$d5,$2d), ($b3,$cf,$25,$12), ($3b,$c8,$ac,$99), ($a7,$10,$18,$7d), ($6e,$e8,$9c,$63), ($7b,$db,$3b,$bb), ($09,$cd,$26,$78), ($f4,$6e,$59,$18), ($01,$ec,$9a,$b7), ($a8,$83,$4f,$9a), ($65,$e6,$95,$6e), ($7e,$aa,$ff,$e6), ($08,$21,$bc,$cf), ($e6,$ef,$15,$e8), ($d9,$ba,$e7,$9b), ($ce,$4a,$6f,$36), ($d4,$ea,$9f,$09), ($d6,$29,$b0,$7c), ($af,$31,$a4,$b2), ($31,$2a,$3f,$23), ($30,$c6,$a5,$94), ($c0,$35,$a2,$66), ($37,$74,$4e,$bc), ($a6,$fc,$82,$ca), ($b0,$e0,$90,$d0), ($15,$33,$a7,$d8), ($4a,$f1,$04,$98), ($f7,$41,$ec,$da), ($0e,$7f,$cd,$50), ($2f,$17,$91,$f6), ($8d,$76,$4d,$d6), ($4d,$43,$ef,$b0), ($54,$cc,$aa,$4d), ($df,$e4,$96,$04), ($e3,$9e,$d1,$b5), ($1b,$4c,$6a,$88), ($b8,$c1,$2c,$1f), ($7f,$46,$65,$51), ($04,$9d,$5e,$ea), ($5d,$01,$8c,$35), ($73,$fa,$87,$74), ($2e,$fb,$0b,$41), ($5a,$b3,$67,$1d), ($52,$92,$db,$d2), ($33,$e9,$10,$56), ($13,$6d,$d6,$47), ($8c,$9a,$d7,$61), ($7a,$37,$a1,$0c), ($8e,$59,$f8,$14), ($89,$eb,$13,$3c), ($ee,$ce,$a9,$27), ($35,$b7,$61,$c9), ($ed,$e1,$1c,$e5), ($3c,$7a,$47,$b1), ($59,$9c,$d2,$df), ($3f,$55,$f2,$73), ($79,$18,$14,$ce), ($bf,$73,$c7,$37), ($ea,$53,$f7,$cd), ($5b,$5f,$fd,$aa), ($14,$df,$3d,$6f), ($86,$78,$44,$db), ($81,$ca,$af,$f3), ($3e,$b9,$68,$c4), ($2c,$38,$24,$34), ($5f,$c2,$a3,$40), ($72,$16,$1d,$c3), ($0c,$bc,$e2,$25), ($8b,$28,$3c,$49), ($41,$ff,$0d,$95), ($71,$39,$a8,$01), ($de,$08,$0c,$b3), ($9c,$d8,$b4,$e4), ($90,$64,$56,$c1), ($61,$7b,$cb,$84), ($70,$d5,$32,$b6), ($74,$48,$6c,$5c), ($42,$d0,$b8,$57)); T7: array[0..255,0..3] of byte= ( ($a7,$50,$51,$f4), ($65,$53,$7e,$41), ($a4,$c3,$1a,$17), ($5e,$96,$3a,$27), ($6b,$cb,$3b,$ab), ($45,$f1,$1f,$9d), ($58,$ab,$ac,$fa), ($03,$93,$4b,$e3), ($fa,$55,$20,$30), ($6d,$f6,$ad,$76), ($76,$91,$88,$cc), ($4c,$25,$f5,$02), ($d7,$fc,$4f,$e5), ($cb,$d7,$c5,$2a), ($44,$80,$26,$35), ($a3,$8f,$b5,$62), ($5a,$49,$de,$b1), ($1b,$67,$25,$ba), ($0e,$98,$45,$ea), ($c0,$e1,$5d,$fe), ($75,$02,$c3,$2f), ($f0,$12,$81,$4c), ($97,$a3,$8d,$46), ($f9,$c6,$6b,$d3), ($5f,$e7,$03,$8f), ($9c,$95,$15,$92), ($7a,$eb,$bf,$6d), ($59,$da,$95,$52), ($83,$2d,$d4,$be), ($21,$d3,$58,$74), ($69,$29,$49,$e0), ($c8,$44,$8e,$c9), ($89,$6a,$75,$c2), ($79,$78,$f4,$8e), ($3e,$6b,$99,$58), ($71,$dd,$27,$b9), ($4f,$b6,$be,$e1), ($ad,$17,$f0,$88), ($ac,$66,$c9,$20), ($3a,$b4,$7d,$ce), ($4a,$18,$63,$df), ($31,$82,$e5,$1a), ($33,$60,$97,$51), ($7f,$45,$62,$53), ($77,$e0,$b1,$64), ($ae,$84,$bb,$6b), ($a0,$1c,$fe,$81), ($2b,$94,$f9,$08), ($68,$58,$70,$48), ($fd,$19,$8f,$45), ($6c,$87,$94,$de), ($f8,$b7,$52,$7b), ($d3,$23,$ab,$73), ($02,$e2,$72,$4b), ($8f,$57,$e3,$1f), ($ab,$2a,$66,$55), ($28,$07,$b2,$eb), ($c2,$03,$2f,$b5), ($7b,$9a,$86,$c5), ($08,$a5,$d3,$37), ($87,$f2,$30,$28), ($a5,$b2,$23,$bf), ($6a,$ba,$02,$03), ($82,$5c,$ed,$16), ($1c,$2b,$8a,$cf), ($b4,$92,$a7,$79), ($f2,$f0,$f3,$07), ($e2,$a1,$4e,$69), ($f4,$cd,$65,$da), ($be,$d5,$06,$05), ($62,$1f,$d1,$34), ($fe,$8a,$c4,$a6), ($53,$9d,$34,$2e), ($55,$a0,$a2,$f3), ($e1,$32,$05,$8a), ($eb,$75,$a4,$f6), ($ec,$39,$0b,$83), ($ef,$aa,$40,$60), ($9f,$06,$5e,$71), ($10,$51,$bd,$6e), ($8a,$f9,$3e,$21), ($06,$3d,$96,$dd), ($05,$ae,$dd,$3e), ($bd,$46,$4d,$e6), ($8d,$b5,$91,$54), ($5d,$05,$71,$c4), ($d4,$6f,$04,$06), ($15,$ff,$60,$50), ($fb,$24,$19,$98), ($e9,$97,$d6,$bd), ($43,$cc,$89,$40), ($9e,$77,$67,$d9), ($42,$bd,$b0,$e8), ($8b,$88,$07,$89), ($5b,$38,$e7,$19), ($ee,$db,$79,$c8), ($0a,$47,$a1,$7c), ($0f,$e9,$7c,$42), ($1e,$c9,$f8,$84), ($00,$00,$00,$00), ($86,$83,$09,$80), ($ed,$48,$32,$2b), ($70,$ac,$1e,$11), ($72,$4e,$6c,$5a), ($ff,$fb,$fd,$0e), ($38,$56,$0f,$85), ($d5,$1e,$3d,$ae), ($39,$27,$36,$2d), ($d9,$64,$0a,$0f), ($a6,$21,$68,$5c), ($54,$d1,$9b,$5b), ($2e,$3a,$24,$36), ($67,$b1,$0c,$0a), ($e7,$0f,$93,$57), ($96,$d2,$b4,$ee), ($91,$9e,$1b,$9b), ($c5,$4f,$80,$c0), ($20,$a2,$61,$dc), ($4b,$69,$5a,$77), ($1a,$16,$1c,$12), ($ba,$0a,$e2,$93), ($2a,$e5,$c0,$a0), ($e0,$43,$3c,$22), ($17,$1d,$12,$1b), ($0d,$0b,$0e,$09), ($c7,$ad,$f2,$8b), ($a8,$b9,$2d,$b6), ($a9,$c8,$14,$1e), ($19,$85,$57,$f1), ($07,$4c,$af,$75), ($dd,$bb,$ee,$99), ($60,$fd,$a3,$7f), ($26,$9f,$f7,$01), ($f5,$bc,$5c,$72), ($3b,$c5,$44,$66), ($7e,$34,$5b,$fb), ($29,$76,$8b,$43), ($c6,$dc,$cb,$23), ($fc,$68,$b6,$ed), ($f1,$63,$b8,$e4), ($dc,$ca,$d7,$31), ($85,$10,$42,$63), ($22,$40,$13,$97), ($11,$20,$84,$c6), ($24,$7d,$85,$4a), ($3d,$f8,$d2,$bb), ($32,$11,$ae,$f9), ($a1,$6d,$c7,$29), ($2f,$4b,$1d,$9e), ($30,$f3,$dc,$b2), ($52,$ec,$0d,$86), ($e3,$d0,$77,$c1), ($16,$6c,$2b,$b3), ($b9,$99,$a9,$70), ($48,$fa,$11,$94), ($64,$22,$47,$e9), ($8c,$c4,$a8,$fc), ($3f,$1a,$a0,$f0), ($2c,$d8,$56,$7d), ($90,$ef,$22,$33), ($4e,$c7,$87,$49), ($d1,$c1,$d9,$38), ($a2,$fe,$8c,$ca), ($0b,$36,$98,$d4), ($81,$cf,$a6,$f5), ($de,$28,$a5,$7a), ($8e,$26,$da,$b7), ($bf,$a4,$3f,$ad), ($9d,$e4,$2c,$3a), ($92,$0d,$50,$78), ($cc,$9b,$6a,$5f), ($46,$62,$54,$7e), ($13,$c2,$f6,$8d), ($b8,$e8,$90,$d8), ($f7,$5e,$2e,$39), ($af,$f5,$82,$c3), ($80,$be,$9f,$5d), ($93,$7c,$69,$d0), ($2d,$a9,$6f,$d5), ($12,$b3,$cf,$25), ($99,$3b,$c8,$ac), ($7d,$a7,$10,$18), ($63,$6e,$e8,$9c), ($bb,$7b,$db,$3b), ($78,$09,$cd,$26), ($18,$f4,$6e,$59), ($b7,$01,$ec,$9a), ($9a,$a8,$83,$4f), ($6e,$65,$e6,$95), ($e6,$7e,$aa,$ff), ($cf,$08,$21,$bc), ($e8,$e6,$ef,$15), ($9b,$d9,$ba,$e7), ($36,$ce,$4a,$6f), ($09,$d4,$ea,$9f), ($7c,$d6,$29,$b0), ($b2,$af,$31,$a4), ($23,$31,$2a,$3f), ($94,$30,$c6,$a5), ($66,$c0,$35,$a2), ($bc,$37,$74,$4e), ($ca,$a6,$fc,$82), ($d0,$b0,$e0,$90), ($d8,$15,$33,$a7), ($98,$4a,$f1,$04), ($da,$f7,$41,$ec), ($50,$0e,$7f,$cd), ($f6,$2f,$17,$91), ($d6,$8d,$76,$4d), ($b0,$4d,$43,$ef), ($4d,$54,$cc,$aa), ($04,$df,$e4,$96), ($b5,$e3,$9e,$d1), ($88,$1b,$4c,$6a), ($1f,$b8,$c1,$2c), ($51,$7f,$46,$65), ($ea,$04,$9d,$5e), ($35,$5d,$01,$8c), ($74,$73,$fa,$87), ($41,$2e,$fb,$0b), ($1d,$5a,$b3,$67), ($d2,$52,$92,$db), ($56,$33,$e9,$10), ($47,$13,$6d,$d6), ($61,$8c,$9a,$d7), ($0c,$7a,$37,$a1), ($14,$8e,$59,$f8), ($3c,$89,$eb,$13), ($27,$ee,$ce,$a9), ($c9,$35,$b7,$61), ($e5,$ed,$e1,$1c), ($b1,$3c,$7a,$47), ($df,$59,$9c,$d2), ($73,$3f,$55,$f2), ($ce,$79,$18,$14), ($37,$bf,$73,$c7), ($cd,$ea,$53,$f7), ($aa,$5b,$5f,$fd), ($6f,$14,$df,$3d), ($db,$86,$78,$44), ($f3,$81,$ca,$af), ($c4,$3e,$b9,$68), ($34,$2c,$38,$24), ($40,$5f,$c2,$a3), ($c3,$72,$16,$1d), ($25,$0c,$bc,$e2), ($49,$8b,$28,$3c), ($95,$41,$ff,$0d), ($01,$71,$39,$a8), ($b3,$de,$08,$0c), ($e4,$9c,$d8,$b4), ($c1,$90,$64,$56), ($84,$61,$7b,$cb), ($b6,$70,$d5,$32), ($5c,$74,$48,$6c), ($57,$42,$d0,$b8)); T8: array[0..255,0..3] of byte= ( ($f4,$a7,$50,$51), ($41,$65,$53,$7e), ($17,$a4,$c3,$1a), ($27,$5e,$96,$3a), ($ab,$6b,$cb,$3b), ($9d,$45,$f1,$1f), ($fa,$58,$ab,$ac), ($e3,$03,$93,$4b), ($30,$fa,$55,$20), ($76,$6d,$f6,$ad), ($cc,$76,$91,$88), ($02,$4c,$25,$f5), ($e5,$d7,$fc,$4f), ($2a,$cb,$d7,$c5), ($35,$44,$80,$26), ($62,$a3,$8f,$b5), ($b1,$5a,$49,$de), ($ba,$1b,$67,$25), ($ea,$0e,$98,$45), ($fe,$c0,$e1,$5d), ($2f,$75,$02,$c3), ($4c,$f0,$12,$81), ($46,$97,$a3,$8d), ($d3,$f9,$c6,$6b), ($8f,$5f,$e7,$03), ($92,$9c,$95,$15), ($6d,$7a,$eb,$bf), ($52,$59,$da,$95), ($be,$83,$2d,$d4), ($74,$21,$d3,$58), ($e0,$69,$29,$49), ($c9,$c8,$44,$8e), ($c2,$89,$6a,$75), ($8e,$79,$78,$f4), ($58,$3e,$6b,$99), ($b9,$71,$dd,$27), ($e1,$4f,$b6,$be), ($88,$ad,$17,$f0), ($20,$ac,$66,$c9), ($ce,$3a,$b4,$7d), ($df,$4a,$18,$63), ($1a,$31,$82,$e5), ($51,$33,$60,$97), ($53,$7f,$45,$62), ($64,$77,$e0,$b1), ($6b,$ae,$84,$bb), ($81,$a0,$1c,$fe), ($08,$2b,$94,$f9), ($48,$68,$58,$70), ($45,$fd,$19,$8f), ($de,$6c,$87,$94), ($7b,$f8,$b7,$52), ($73,$d3,$23,$ab), ($4b,$02,$e2,$72), ($1f,$8f,$57,$e3), ($55,$ab,$2a,$66), ($eb,$28,$07,$b2), ($b5,$c2,$03,$2f), ($c5,$7b,$9a,$86), ($37,$08,$a5,$d3), ($28,$87,$f2,$30), ($bf,$a5,$b2,$23), ($03,$6a,$ba,$02), ($16,$82,$5c,$ed), ($cf,$1c,$2b,$8a), ($79,$b4,$92,$a7), ($07,$f2,$f0,$f3), ($69,$e2,$a1,$4e), ($da,$f4,$cd,$65), ($05,$be,$d5,$06), ($34,$62,$1f,$d1), ($a6,$fe,$8a,$c4), ($2e,$53,$9d,$34), ($f3,$55,$a0,$a2), ($8a,$e1,$32,$05), ($f6,$eb,$75,$a4), ($83,$ec,$39,$0b), ($60,$ef,$aa,$40), ($71,$9f,$06,$5e), ($6e,$10,$51,$bd), ($21,$8a,$f9,$3e), ($dd,$06,$3d,$96), ($3e,$05,$ae,$dd), ($e6,$bd,$46,$4d), ($54,$8d,$b5,$91), ($c4,$5d,$05,$71), ($06,$d4,$6f,$04), ($50,$15,$ff,$60), ($98,$fb,$24,$19), ($bd,$e9,$97,$d6), ($40,$43,$cc,$89), ($d9,$9e,$77,$67), ($e8,$42,$bd,$b0), ($89,$8b,$88,$07), ($19,$5b,$38,$e7), ($c8,$ee,$db,$79), ($7c,$0a,$47,$a1), ($42,$0f,$e9,$7c), ($84,$1e,$c9,$f8), ($00,$00,$00,$00), ($80,$86,$83,$09), ($2b,$ed,$48,$32), ($11,$70,$ac,$1e), ($5a,$72,$4e,$6c), ($0e,$ff,$fb,$fd), ($85,$38,$56,$0f), ($ae,$d5,$1e,$3d), ($2d,$39,$27,$36), ($0f,$d9,$64,$0a), ($5c,$a6,$21,$68), ($5b,$54,$d1,$9b), ($36,$2e,$3a,$24), ($0a,$67,$b1,$0c), ($57,$e7,$0f,$93), ($ee,$96,$d2,$b4), ($9b,$91,$9e,$1b), ($c0,$c5,$4f,$80), ($dc,$20,$a2,$61), ($77,$4b,$69,$5a), ($12,$1a,$16,$1c), ($93,$ba,$0a,$e2), ($a0,$2a,$e5,$c0), ($22,$e0,$43,$3c), ($1b,$17,$1d,$12), ($09,$0d,$0b,$0e), ($8b,$c7,$ad,$f2), ($b6,$a8,$b9,$2d), ($1e,$a9,$c8,$14), ($f1,$19,$85,$57), ($75,$07,$4c,$af), ($99,$dd,$bb,$ee), ($7f,$60,$fd,$a3), ($01,$26,$9f,$f7), ($72,$f5,$bc,$5c), ($66,$3b,$c5,$44), ($fb,$7e,$34,$5b), ($43,$29,$76,$8b), ($23,$c6,$dc,$cb), ($ed,$fc,$68,$b6), ($e4,$f1,$63,$b8), ($31,$dc,$ca,$d7), ($63,$85,$10,$42), ($97,$22,$40,$13), ($c6,$11,$20,$84), ($4a,$24,$7d,$85), ($bb,$3d,$f8,$d2), ($f9,$32,$11,$ae), ($29,$a1,$6d,$c7), ($9e,$2f,$4b,$1d), ($b2,$30,$f3,$dc), ($86,$52,$ec,$0d), ($c1,$e3,$d0,$77), ($b3,$16,$6c,$2b), ($70,$b9,$99,$a9), ($94,$48,$fa,$11), ($e9,$64,$22,$47), ($fc,$8c,$c4,$a8), ($f0,$3f,$1a,$a0), ($7d,$2c,$d8,$56), ($33,$90,$ef,$22), ($49,$4e,$c7,$87), ($38,$d1,$c1,$d9), ($ca,$a2,$fe,$8c), ($d4,$0b,$36,$98), ($f5,$81,$cf,$a6), ($7a,$de,$28,$a5), ($b7,$8e,$26,$da), ($ad,$bf,$a4,$3f), ($3a,$9d,$e4,$2c), ($78,$92,$0d,$50), ($5f,$cc,$9b,$6a), ($7e,$46,$62,$54), ($8d,$13,$c2,$f6), ($d8,$b8,$e8,$90), ($39,$f7,$5e,$2e), ($c3,$af,$f5,$82), ($5d,$80,$be,$9f), ($d0,$93,$7c,$69), ($d5,$2d,$a9,$6f), ($25,$12,$b3,$cf), ($ac,$99,$3b,$c8), ($18,$7d,$a7,$10), ($9c,$63,$6e,$e8), ($3b,$bb,$7b,$db), ($26,$78,$09,$cd), ($59,$18,$f4,$6e), ($9a,$b7,$01,$ec), ($4f,$9a,$a8,$83), ($95,$6e,$65,$e6), ($ff,$e6,$7e,$aa), ($bc,$cf,$08,$21), ($15,$e8,$e6,$ef), ($e7,$9b,$d9,$ba), ($6f,$36,$ce,$4a), ($9f,$09,$d4,$ea), ($b0,$7c,$d6,$29), ($a4,$b2,$af,$31), ($3f,$23,$31,$2a), ($a5,$94,$30,$c6), ($a2,$66,$c0,$35), ($4e,$bc,$37,$74), ($82,$ca,$a6,$fc), ($90,$d0,$b0,$e0), ($a7,$d8,$15,$33), ($04,$98,$4a,$f1), ($ec,$da,$f7,$41), ($cd,$50,$0e,$7f), ($91,$f6,$2f,$17), ($4d,$d6,$8d,$76), ($ef,$b0,$4d,$43), ($aa,$4d,$54,$cc), ($96,$04,$df,$e4), ($d1,$b5,$e3,$9e), ($6a,$88,$1b,$4c), ($2c,$1f,$b8,$c1), ($65,$51,$7f,$46), ($5e,$ea,$04,$9d), ($8c,$35,$5d,$01), ($87,$74,$73,$fa), ($0b,$41,$2e,$fb), ($67,$1d,$5a,$b3), ($db,$d2,$52,$92), ($10,$56,$33,$e9), ($d6,$47,$13,$6d), ($d7,$61,$8c,$9a), ($a1,$0c,$7a,$37), ($f8,$14,$8e,$59), ($13,$3c,$89,$eb), ($a9,$27,$ee,$ce), ($61,$c9,$35,$b7), ($1c,$e5,$ed,$e1), ($47,$b1,$3c,$7a), ($d2,$df,$59,$9c), ($f2,$73,$3f,$55), ($14,$ce,$79,$18), ($c7,$37,$bf,$73), ($f7,$cd,$ea,$53), ($fd,$aa,$5b,$5f), ($3d,$6f,$14,$df), ($44,$db,$86,$78), ($af,$f3,$81,$ca), ($68,$c4,$3e,$b9), ($24,$34,$2c,$38), ($a3,$40,$5f,$c2), ($1d,$c3,$72,$16), ($e2,$25,$0c,$bc), ($3c,$49,$8b,$28), ($0d,$95,$41,$ff), ($a8,$01,$71,$39), ($0c,$b3,$de,$08), ($b4,$e4,$9c,$d8), ($56,$c1,$90,$64), ($cb,$84,$61,$7b), ($32,$b6,$70,$d5), ($6c,$5c,$74,$48), ($b8,$57,$42,$d0)); S5: array[0..255] of byte= ( $52,$09,$6a,$d5, $30,$36,$a5,$38, $bf,$40,$a3,$9e, $81,$f3,$d7,$fb, $7c,$e3,$39,$82, $9b,$2f,$ff,$87, $34,$8e,$43,$44, $c4,$de,$e9,$cb, $54,$7b,$94,$32, $a6,$c2,$23,$3d, $ee,$4c,$95,$0b, $42,$fa,$c3,$4e, $08,$2e,$a1,$66, $28,$d9,$24,$b2, $76,$5b,$a2,$49, $6d,$8b,$d1,$25, $72,$f8,$f6,$64, $86,$68,$98,$16, $d4,$a4,$5c,$cc, $5d,$65,$b6,$92, $6c,$70,$48,$50, $fd,$ed,$b9,$da, $5e,$15,$46,$57, $a7,$8d,$9d,$84, $90,$d8,$ab,$00, $8c,$bc,$d3,$0a, $f7,$e4,$58,$05, $b8,$b3,$45,$06, $d0,$2c,$1e,$8f, $ca,$3f,$0f,$02, $c1,$af,$bd,$03, $01,$13,$8a,$6b, $3a,$91,$11,$41, $4f,$67,$dc,$ea, $97,$f2,$cf,$ce, $f0,$b4,$e6,$73, $96,$ac,$74,$22, $e7,$ad,$35,$85, $e2,$f9,$37,$e8, $1c,$75,$df,$6e, $47,$f1,$1a,$71, $1d,$29,$c5,$89, $6f,$b7,$62,$0e, $aa,$18,$be,$1b, $fc,$56,$3e,$4b, $c6,$d2,$79,$20, $9a,$db,$c0,$fe, $78,$cd,$5a,$f4, $1f,$dd,$a8,$33, $88,$07,$c7,$31, $b1,$12,$10,$59, $27,$80,$ec,$5f, $60,$51,$7f,$a9, $19,$b5,$4a,$0d, $2d,$e5,$7a,$9f, $93,$c9,$9c,$ef, $a0,$e0,$3b,$4d, $ae,$2a,$f5,$b0, $c8,$eb,$bb,$3c, $83,$53,$99,$61, $17,$2b,$04,$7e, $ba,$77,$d6,$26, $e1,$69,$14,$63, $55,$21,$0c,$7d); U1: array[0..255,0..3] of byte= ( ($00,$00,$00,$00), ($0e,$09,$0d,$0b), ($1c,$12,$1a,$16), ($12,$1b,$17,$1d), ($38,$24,$34,$2c), ($36,$2d,$39,$27), ($24,$36,$2e,$3a), ($2a,$3f,$23,$31), ($70,$48,$68,$58), ($7e,$41,$65,$53), ($6c,$5a,$72,$4e), ($62,$53,$7f,$45), ($48,$6c,$5c,$74), ($46,$65,$51,$7f), ($54,$7e,$46,$62), ($5a,$77,$4b,$69), ($e0,$90,$d0,$b0), ($ee,$99,$dd,$bb), ($fc,$82,$ca,$a6), ($f2,$8b,$c7,$ad), ($d8,$b4,$e4,$9c), ($d6,$bd,$e9,$97), ($c4,$a6,$fe,$8a), ($ca,$af,$f3,$81), ($90,$d8,$b8,$e8), ($9e,$d1,$b5,$e3), ($8c,$ca,$a2,$fe), ($82,$c3,$af,$f5), ($a8,$fc,$8c,$c4), ($a6,$f5,$81,$cf), ($b4,$ee,$96,$d2), ($ba,$e7,$9b,$d9), ($db,$3b,$bb,$7b), ($d5,$32,$b6,$70), ($c7,$29,$a1,$6d), ($c9,$20,$ac,$66), ($e3,$1f,$8f,$57), ($ed,$16,$82,$5c), ($ff,$0d,$95,$41), ($f1,$04,$98,$4a), ($ab,$73,$d3,$23), ($a5,$7a,$de,$28), ($b7,$61,$c9,$35), ($b9,$68,$c4,$3e), ($93,$57,$e7,$0f), ($9d,$5e,$ea,$04), ($8f,$45,$fd,$19), ($81,$4c,$f0,$12), ($3b,$ab,$6b,$cb), ($35,$a2,$66,$c0), ($27,$b9,$71,$dd), ($29,$b0,$7c,$d6), ($03,$8f,$5f,$e7), ($0d,$86,$52,$ec), ($1f,$9d,$45,$f1), ($11,$94,$48,$fa), ($4b,$e3,$03,$93), ($45,$ea,$0e,$98), ($57,$f1,$19,$85), ($59,$f8,$14,$8e), ($73,$c7,$37,$bf), ($7d,$ce,$3a,$b4), ($6f,$d5,$2d,$a9), ($61,$dc,$20,$a2), ($ad,$76,$6d,$f6), ($a3,$7f,$60,$fd), ($b1,$64,$77,$e0), ($bf,$6d,$7a,$eb), ($95,$52,$59,$da), ($9b,$5b,$54,$d1), ($89,$40,$43,$cc), ($87,$49,$4e,$c7), ($dd,$3e,$05,$ae), ($d3,$37,$08,$a5), ($c1,$2c,$1f,$b8), ($cf,$25,$12,$b3), ($e5,$1a,$31,$82), ($eb,$13,$3c,$89), ($f9,$08,$2b,$94), ($f7,$01,$26,$9f), ($4d,$e6,$bd,$46), ($43,$ef,$b0,$4d), ($51,$f4,$a7,$50), ($5f,$fd,$aa,$5b), ($75,$c2,$89,$6a), ($7b,$cb,$84,$61), ($69,$d0,$93,$7c), ($67,$d9,$9e,$77), ($3d,$ae,$d5,$1e), ($33,$a7,$d8,$15), ($21,$bc,$cf,$08), ($2f,$b5,$c2,$03), ($05,$8a,$e1,$32), ($0b,$83,$ec,$39), ($19,$98,$fb,$24), ($17,$91,$f6,$2f), ($76,$4d,$d6,$8d), ($78,$44,$db,$86), ($6a,$5f,$cc,$9b), ($64,$56,$c1,$90), ($4e,$69,$e2,$a1), ($40,$60,$ef,$aa), ($52,$7b,$f8,$b7), ($5c,$72,$f5,$bc), ($06,$05,$be,$d5), ($08,$0c,$b3,$de), ($1a,$17,$a4,$c3), ($14,$1e,$a9,$c8), ($3e,$21,$8a,$f9), ($30,$28,$87,$f2), ($22,$33,$90,$ef), ($2c,$3a,$9d,$e4), ($96,$dd,$06,$3d), ($98,$d4,$0b,$36), ($8a,$cf,$1c,$2b), ($84,$c6,$11,$20), ($ae,$f9,$32,$11), ($a0,$f0,$3f,$1a), ($b2,$eb,$28,$07), ($bc,$e2,$25,$0c), ($e6,$95,$6e,$65), ($e8,$9c,$63,$6e), ($fa,$87,$74,$73), ($f4,$8e,$79,$78), ($de,$b1,$5a,$49), ($d0,$b8,$57,$42), ($c2,$a3,$40,$5f), ($cc,$aa,$4d,$54), ($41,$ec,$da,$f7), ($4f,$e5,$d7,$fc), ($5d,$fe,$c0,$e1), ($53,$f7,$cd,$ea), ($79,$c8,$ee,$db), ($77,$c1,$e3,$d0), ($65,$da,$f4,$cd), ($6b,$d3,$f9,$c6), ($31,$a4,$b2,$af), ($3f,$ad,$bf,$a4), ($2d,$b6,$a8,$b9), ($23,$bf,$a5,$b2), ($09,$80,$86,$83), ($07,$89,$8b,$88), ($15,$92,$9c,$95), ($1b,$9b,$91,$9e), ($a1,$7c,$0a,$47), ($af,$75,$07,$4c), ($bd,$6e,$10,$51), ($b3,$67,$1d,$5a), ($99,$58,$3e,$6b), ($97,$51,$33,$60), ($85,$4a,$24,$7d), ($8b,$43,$29,$76), ($d1,$34,$62,$1f), ($df,$3d,$6f,$14), ($cd,$26,$78,$09), ($c3,$2f,$75,$02), ($e9,$10,$56,$33), ($e7,$19,$5b,$38), ($f5,$02,$4c,$25), ($fb,$0b,$41,$2e), ($9a,$d7,$61,$8c), ($94,$de,$6c,$87), ($86,$c5,$7b,$9a), ($88,$cc,$76,$91), ($a2,$f3,$55,$a0), ($ac,$fa,$58,$ab), ($be,$e1,$4f,$b6), ($b0,$e8,$42,$bd), ($ea,$9f,$09,$d4), ($e4,$96,$04,$df), ($f6,$8d,$13,$c2), ($f8,$84,$1e,$c9), ($d2,$bb,$3d,$f8), ($dc,$b2,$30,$f3), ($ce,$a9,$27,$ee), ($c0,$a0,$2a,$e5), ($7a,$47,$b1,$3c), ($74,$4e,$bc,$37), ($66,$55,$ab,$2a), ($68,$5c,$a6,$21), ($42,$63,$85,$10), ($4c,$6a,$88,$1b), ($5e,$71,$9f,$06), ($50,$78,$92,$0d), ($0a,$0f,$d9,$64), ($04,$06,$d4,$6f), ($16,$1d,$c3,$72), ($18,$14,$ce,$79), ($32,$2b,$ed,$48), ($3c,$22,$e0,$43), ($2e,$39,$f7,$5e), ($20,$30,$fa,$55), ($ec,$9a,$b7,$01), ($e2,$93,$ba,$0a), ($f0,$88,$ad,$17), ($fe,$81,$a0,$1c), ($d4,$be,$83,$2d), ($da,$b7,$8e,$26), ($c8,$ac,$99,$3b), ($c6,$a5,$94,$30), ($9c,$d2,$df,$59), ($92,$db,$d2,$52), ($80,$c0,$c5,$4f), ($8e,$c9,$c8,$44), ($a4,$f6,$eb,$75), ($aa,$ff,$e6,$7e), ($b8,$e4,$f1,$63), ($b6,$ed,$fc,$68), ($0c,$0a,$67,$b1), ($02,$03,$6a,$ba), ($10,$18,$7d,$a7), ($1e,$11,$70,$ac), ($34,$2e,$53,$9d), ($3a,$27,$5e,$96), ($28,$3c,$49,$8b), ($26,$35,$44,$80), ($7c,$42,$0f,$e9), ($72,$4b,$02,$e2), ($60,$50,$15,$ff), ($6e,$59,$18,$f4), ($44,$66,$3b,$c5), ($4a,$6f,$36,$ce), ($58,$74,$21,$d3), ($56,$7d,$2c,$d8), ($37,$a1,$0c,$7a), ($39,$a8,$01,$71), ($2b,$b3,$16,$6c), ($25,$ba,$1b,$67), ($0f,$85,$38,$56), ($01,$8c,$35,$5d), ($13,$97,$22,$40), ($1d,$9e,$2f,$4b), ($47,$e9,$64,$22), ($49,$e0,$69,$29), ($5b,$fb,$7e,$34), ($55,$f2,$73,$3f), ($7f,$cd,$50,$0e), ($71,$c4,$5d,$05), ($63,$df,$4a,$18), ($6d,$d6,$47,$13), ($d7,$31,$dc,$ca), ($d9,$38,$d1,$c1), ($cb,$23,$c6,$dc), ($c5,$2a,$cb,$d7), ($ef,$15,$e8,$e6), ($e1,$1c,$e5,$ed), ($f3,$07,$f2,$f0), ($fd,$0e,$ff,$fb), ($a7,$79,$b4,$92), ($a9,$70,$b9,$99), ($bb,$6b,$ae,$84), ($b5,$62,$a3,$8f), ($9f,$5d,$80,$be), ($91,$54,$8d,$b5), ($83,$4f,$9a,$a8), ($8d,$46,$97,$a3)); U2: array[0..255,0..3] of byte= ( ($00,$00,$00,$00), ($0b,$0e,$09,$0d), ($16,$1c,$12,$1a), ($1d,$12,$1b,$17), ($2c,$38,$24,$34), ($27,$36,$2d,$39), ($3a,$24,$36,$2e), ($31,$2a,$3f,$23), ($58,$70,$48,$68), ($53,$7e,$41,$65), ($4e,$6c,$5a,$72), ($45,$62,$53,$7f), ($74,$48,$6c,$5c), ($7f,$46,$65,$51), ($62,$54,$7e,$46), ($69,$5a,$77,$4b), ($b0,$e0,$90,$d0), ($bb,$ee,$99,$dd), ($a6,$fc,$82,$ca), ($ad,$f2,$8b,$c7), ($9c,$d8,$b4,$e4), ($97,$d6,$bd,$e9), ($8a,$c4,$a6,$fe), ($81,$ca,$af,$f3), ($e8,$90,$d8,$b8), ($e3,$9e,$d1,$b5), ($fe,$8c,$ca,$a2), ($f5,$82,$c3,$af), ($c4,$a8,$fc,$8c), ($cf,$a6,$f5,$81), ($d2,$b4,$ee,$96), ($d9,$ba,$e7,$9b), ($7b,$db,$3b,$bb), ($70,$d5,$32,$b6), ($6d,$c7,$29,$a1), ($66,$c9,$20,$ac), ($57,$e3,$1f,$8f), ($5c,$ed,$16,$82), ($41,$ff,$0d,$95), ($4a,$f1,$04,$98), ($23,$ab,$73,$d3), ($28,$a5,$7a,$de), ($35,$b7,$61,$c9), ($3e,$b9,$68,$c4), ($0f,$93,$57,$e7), ($04,$9d,$5e,$ea), ($19,$8f,$45,$fd), ($12,$81,$4c,$f0), ($cb,$3b,$ab,$6b), ($c0,$35,$a2,$66), ($dd,$27,$b9,$71), ($d6,$29,$b0,$7c), ($e7,$03,$8f,$5f), ($ec,$0d,$86,$52), ($f1,$1f,$9d,$45), ($fa,$11,$94,$48), ($93,$4b,$e3,$03), ($98,$45,$ea,$0e), ($85,$57,$f1,$19), ($8e,$59,$f8,$14), ($bf,$73,$c7,$37), ($b4,$7d,$ce,$3a), ($a9,$6f,$d5,$2d), ($a2,$61,$dc,$20), ($f6,$ad,$76,$6d), ($fd,$a3,$7f,$60), ($e0,$b1,$64,$77), ($eb,$bf,$6d,$7a), ($da,$95,$52,$59), ($d1,$9b,$5b,$54), ($cc,$89,$40,$43), ($c7,$87,$49,$4e), ($ae,$dd,$3e,$05), ($a5,$d3,$37,$08), ($b8,$c1,$2c,$1f), ($b3,$cf,$25,$12), ($82,$e5,$1a,$31), ($89,$eb,$13,$3c), ($94,$f9,$08,$2b), ($9f,$f7,$01,$26), ($46,$4d,$e6,$bd), ($4d,$43,$ef,$b0), ($50,$51,$f4,$a7), ($5b,$5f,$fd,$aa), ($6a,$75,$c2,$89), ($61,$7b,$cb,$84), ($7c,$69,$d0,$93), ($77,$67,$d9,$9e), ($1e,$3d,$ae,$d5), ($15,$33,$a7,$d8), ($08,$21,$bc,$cf), ($03,$2f,$b5,$c2), ($32,$05,$8a,$e1), ($39,$0b,$83,$ec), ($24,$19,$98,$fb), ($2f,$17,$91,$f6), ($8d,$76,$4d,$d6), ($86,$78,$44,$db), ($9b,$6a,$5f,$cc), ($90,$64,$56,$c1), ($a1,$4e,$69,$e2), ($aa,$40,$60,$ef), ($b7,$52,$7b,$f8), ($bc,$5c,$72,$f5), ($d5,$06,$05,$be), ($de,$08,$0c,$b3), ($c3,$1a,$17,$a4), ($c8,$14,$1e,$a9), ($f9,$3e,$21,$8a), ($f2,$30,$28,$87), ($ef,$22,$33,$90), ($e4,$2c,$3a,$9d), ($3d,$96,$dd,$06), ($36,$98,$d4,$0b), ($2b,$8a,$cf,$1c), ($20,$84,$c6,$11), ($11,$ae,$f9,$32), ($1a,$a0,$f0,$3f), ($07,$b2,$eb,$28), ($0c,$bc,$e2,$25), ($65,$e6,$95,$6e), ($6e,$e8,$9c,$63), ($73,$fa,$87,$74), ($78,$f4,$8e,$79), ($49,$de,$b1,$5a), ($42,$d0,$b8,$57), ($5f,$c2,$a3,$40), ($54,$cc,$aa,$4d), ($f7,$41,$ec,$da), ($fc,$4f,$e5,$d7), ($e1,$5d,$fe,$c0), ($ea,$53,$f7,$cd), ($db,$79,$c8,$ee), ($d0,$77,$c1,$e3), ($cd,$65,$da,$f4), ($c6,$6b,$d3,$f9), ($af,$31,$a4,$b2), ($a4,$3f,$ad,$bf), ($b9,$2d,$b6,$a8), ($b2,$23,$bf,$a5), ($83,$09,$80,$86), ($88,$07,$89,$8b), ($95,$15,$92,$9c), ($9e,$1b,$9b,$91), ($47,$a1,$7c,$0a), ($4c,$af,$75,$07), ($51,$bd,$6e,$10), ($5a,$b3,$67,$1d), ($6b,$99,$58,$3e), ($60,$97,$51,$33), ($7d,$85,$4a,$24), ($76,$8b,$43,$29), ($1f,$d1,$34,$62), ($14,$df,$3d,$6f), ($09,$cd,$26,$78), ($02,$c3,$2f,$75), ($33,$e9,$10,$56), ($38,$e7,$19,$5b), ($25,$f5,$02,$4c), ($2e,$fb,$0b,$41), ($8c,$9a,$d7,$61), ($87,$94,$de,$6c), ($9a,$86,$c5,$7b), ($91,$88,$cc,$76), ($a0,$a2,$f3,$55), ($ab,$ac,$fa,$58), ($b6,$be,$e1,$4f), ($bd,$b0,$e8,$42), ($d4,$ea,$9f,$09), ($df,$e4,$96,$04), ($c2,$f6,$8d,$13), ($c9,$f8,$84,$1e), ($f8,$d2,$bb,$3d), ($f3,$dc,$b2,$30), ($ee,$ce,$a9,$27), ($e5,$c0,$a0,$2a), ($3c,$7a,$47,$b1), ($37,$74,$4e,$bc), ($2a,$66,$55,$ab), ($21,$68,$5c,$a6), ($10,$42,$63,$85), ($1b,$4c,$6a,$88), ($06,$5e,$71,$9f), ($0d,$50,$78,$92), ($64,$0a,$0f,$d9), ($6f,$04,$06,$d4), ($72,$16,$1d,$c3), ($79,$18,$14,$ce), ($48,$32,$2b,$ed), ($43,$3c,$22,$e0), ($5e,$2e,$39,$f7), ($55,$20,$30,$fa), ($01,$ec,$9a,$b7), ($0a,$e2,$93,$ba), ($17,$f0,$88,$ad), ($1c,$fe,$81,$a0), ($2d,$d4,$be,$83), ($26,$da,$b7,$8e), ($3b,$c8,$ac,$99), ($30,$c6,$a5,$94), ($59,$9c,$d2,$df), ($52,$92,$db,$d2), ($4f,$80,$c0,$c5), ($44,$8e,$c9,$c8), ($75,$a4,$f6,$eb), ($7e,$aa,$ff,$e6), ($63,$b8,$e4,$f1), ($68,$b6,$ed,$fc), ($b1,$0c,$0a,$67), ($ba,$02,$03,$6a), ($a7,$10,$18,$7d), ($ac,$1e,$11,$70), ($9d,$34,$2e,$53), ($96,$3a,$27,$5e), ($8b,$28,$3c,$49), ($80,$26,$35,$44), ($e9,$7c,$42,$0f), ($e2,$72,$4b,$02), ($ff,$60,$50,$15), ($f4,$6e,$59,$18), ($c5,$44,$66,$3b), ($ce,$4a,$6f,$36), ($d3,$58,$74,$21), ($d8,$56,$7d,$2c), ($7a,$37,$a1,$0c), ($71,$39,$a8,$01), ($6c,$2b,$b3,$16), ($67,$25,$ba,$1b), ($56,$0f,$85,$38), ($5d,$01,$8c,$35), ($40,$13,$97,$22), ($4b,$1d,$9e,$2f), ($22,$47,$e9,$64), ($29,$49,$e0,$69), ($34,$5b,$fb,$7e), ($3f,$55,$f2,$73), ($0e,$7f,$cd,$50), ($05,$71,$c4,$5d), ($18,$63,$df,$4a), ($13,$6d,$d6,$47), ($ca,$d7,$31,$dc), ($c1,$d9,$38,$d1), ($dc,$cb,$23,$c6), ($d7,$c5,$2a,$cb), ($e6,$ef,$15,$e8), ($ed,$e1,$1c,$e5), ($f0,$f3,$07,$f2), ($fb,$fd,$0e,$ff), ($92,$a7,$79,$b4), ($99,$a9,$70,$b9), ($84,$bb,$6b,$ae), ($8f,$b5,$62,$a3), ($be,$9f,$5d,$80), ($b5,$91,$54,$8d), ($a8,$83,$4f,$9a), ($a3,$8d,$46,$97)); U3: array[0..255,0..3] of byte= ( ($00,$00,$00,$00), ($0d,$0b,$0e,$09), ($1a,$16,$1c,$12), ($17,$1d,$12,$1b), ($34,$2c,$38,$24), ($39,$27,$36,$2d), ($2e,$3a,$24,$36), ($23,$31,$2a,$3f), ($68,$58,$70,$48), ($65,$53,$7e,$41), ($72,$4e,$6c,$5a), ($7f,$45,$62,$53), ($5c,$74,$48,$6c), ($51,$7f,$46,$65), ($46,$62,$54,$7e), ($4b,$69,$5a,$77), ($d0,$b0,$e0,$90), ($dd,$bb,$ee,$99), ($ca,$a6,$fc,$82), ($c7,$ad,$f2,$8b), ($e4,$9c,$d8,$b4), ($e9,$97,$d6,$bd), ($fe,$8a,$c4,$a6), ($f3,$81,$ca,$af), ($b8,$e8,$90,$d8), ($b5,$e3,$9e,$d1), ($a2,$fe,$8c,$ca), ($af,$f5,$82,$c3), ($8c,$c4,$a8,$fc), ($81,$cf,$a6,$f5), ($96,$d2,$b4,$ee), ($9b,$d9,$ba,$e7), ($bb,$7b,$db,$3b), ($b6,$70,$d5,$32), ($a1,$6d,$c7,$29), ($ac,$66,$c9,$20), ($8f,$57,$e3,$1f), ($82,$5c,$ed,$16), ($95,$41,$ff,$0d), ($98,$4a,$f1,$04), ($d3,$23,$ab,$73), ($de,$28,$a5,$7a), ($c9,$35,$b7,$61), ($c4,$3e,$b9,$68), ($e7,$0f,$93,$57), ($ea,$04,$9d,$5e), ($fd,$19,$8f,$45), ($f0,$12,$81,$4c), ($6b,$cb,$3b,$ab), ($66,$c0,$35,$a2), ($71,$dd,$27,$b9), ($7c,$d6,$29,$b0), ($5f,$e7,$03,$8f), ($52,$ec,$0d,$86), ($45,$f1,$1f,$9d), ($48,$fa,$11,$94), ($03,$93,$4b,$e3), ($0e,$98,$45,$ea), ($19,$85,$57,$f1), ($14,$8e,$59,$f8), ($37,$bf,$73,$c7), ($3a,$b4,$7d,$ce), ($2d,$a9,$6f,$d5), ($20,$a2,$61,$dc), ($6d,$f6,$ad,$76), ($60,$fd,$a3,$7f), ($77,$e0,$b1,$64), ($7a,$eb,$bf,$6d), ($59,$da,$95,$52), ($54,$d1,$9b,$5b), ($43,$cc,$89,$40), ($4e,$c7,$87,$49), ($05,$ae,$dd,$3e), ($08,$a5,$d3,$37), ($1f,$b8,$c1,$2c), ($12,$b3,$cf,$25), ($31,$82,$e5,$1a), ($3c,$89,$eb,$13), ($2b,$94,$f9,$08), ($26,$9f,$f7,$01), ($bd,$46,$4d,$e6), ($b0,$4d,$43,$ef), ($a7,$50,$51,$f4), ($aa,$5b,$5f,$fd), ($89,$6a,$75,$c2), ($84,$61,$7b,$cb), ($93,$7c,$69,$d0), ($9e,$77,$67,$d9), ($d5,$1e,$3d,$ae), ($d8,$15,$33,$a7), ($cf,$08,$21,$bc), ($c2,$03,$2f,$b5), ($e1,$32,$05,$8a), ($ec,$39,$0b,$83), ($fb,$24,$19,$98), ($f6,$2f,$17,$91), ($d6,$8d,$76,$4d), ($db,$86,$78,$44), ($cc,$9b,$6a,$5f), ($c1,$90,$64,$56), ($e2,$a1,$4e,$69), ($ef,$aa,$40,$60), ($f8,$b7,$52,$7b), ($f5,$bc,$5c,$72), ($be,$d5,$06,$05), ($b3,$de,$08,$0c), ($a4,$c3,$1a,$17), ($a9,$c8,$14,$1e), ($8a,$f9,$3e,$21), ($87,$f2,$30,$28), ($90,$ef,$22,$33), ($9d,$e4,$2c,$3a), ($06,$3d,$96,$dd), ($0b,$36,$98,$d4), ($1c,$2b,$8a,$cf), ($11,$20,$84,$c6), ($32,$11,$ae,$f9), ($3f,$1a,$a0,$f0), ($28,$07,$b2,$eb), ($25,$0c,$bc,$e2), ($6e,$65,$e6,$95), ($63,$6e,$e8,$9c), ($74,$73,$fa,$87), ($79,$78,$f4,$8e), ($5a,$49,$de,$b1), ($57,$42,$d0,$b8), ($40,$5f,$c2,$a3), ($4d,$54,$cc,$aa), ($da,$f7,$41,$ec), ($d7,$fc,$4f,$e5), ($c0,$e1,$5d,$fe), ($cd,$ea,$53,$f7), ($ee,$db,$79,$c8), ($e3,$d0,$77,$c1), ($f4,$cd,$65,$da), ($f9,$c6,$6b,$d3), ($b2,$af,$31,$a4), ($bf,$a4,$3f,$ad), ($a8,$b9,$2d,$b6), ($a5,$b2,$23,$bf), ($86,$83,$09,$80), ($8b,$88,$07,$89), ($9c,$95,$15,$92), ($91,$9e,$1b,$9b), ($0a,$47,$a1,$7c), ($07,$4c,$af,$75), ($10,$51,$bd,$6e), ($1d,$5a,$b3,$67), ($3e,$6b,$99,$58), ($33,$60,$97,$51), ($24,$7d,$85,$4a), ($29,$76,$8b,$43), ($62,$1f,$d1,$34), ($6f,$14,$df,$3d), ($78,$09,$cd,$26), ($75,$02,$c3,$2f), ($56,$33,$e9,$10), ($5b,$38,$e7,$19), ($4c,$25,$f5,$02), ($41,$2e,$fb,$0b), ($61,$8c,$9a,$d7), ($6c,$87,$94,$de), ($7b,$9a,$86,$c5), ($76,$91,$88,$cc), ($55,$a0,$a2,$f3), ($58,$ab,$ac,$fa), ($4f,$b6,$be,$e1), ($42,$bd,$b0,$e8), ($09,$d4,$ea,$9f), ($04,$df,$e4,$96), ($13,$c2,$f6,$8d), ($1e,$c9,$f8,$84), ($3d,$f8,$d2,$bb), ($30,$f3,$dc,$b2), ($27,$ee,$ce,$a9), ($2a,$e5,$c0,$a0), ($b1,$3c,$7a,$47), ($bc,$37,$74,$4e), ($ab,$2a,$66,$55), ($a6,$21,$68,$5c), ($85,$10,$42,$63), ($88,$1b,$4c,$6a), ($9f,$06,$5e,$71), ($92,$0d,$50,$78), ($d9,$64,$0a,$0f), ($d4,$6f,$04,$06), ($c3,$72,$16,$1d), ($ce,$79,$18,$14), ($ed,$48,$32,$2b), ($e0,$43,$3c,$22), ($f7,$5e,$2e,$39), ($fa,$55,$20,$30), ($b7,$01,$ec,$9a), ($ba,$0a,$e2,$93), ($ad,$17,$f0,$88), ($a0,$1c,$fe,$81), ($83,$2d,$d4,$be), ($8e,$26,$da,$b7), ($99,$3b,$c8,$ac), ($94,$30,$c6,$a5), ($df,$59,$9c,$d2), ($d2,$52,$92,$db), ($c5,$4f,$80,$c0), ($c8,$44,$8e,$c9), ($eb,$75,$a4,$f6), ($e6,$7e,$aa,$ff), ($f1,$63,$b8,$e4), ($fc,$68,$b6,$ed), ($67,$b1,$0c,$0a), ($6a,$ba,$02,$03), ($7d,$a7,$10,$18), ($70,$ac,$1e,$11), ($53,$9d,$34,$2e), ($5e,$96,$3a,$27), ($49,$8b,$28,$3c), ($44,$80,$26,$35), ($0f,$e9,$7c,$42), ($02,$e2,$72,$4b), ($15,$ff,$60,$50), ($18,$f4,$6e,$59), ($3b,$c5,$44,$66), ($36,$ce,$4a,$6f), ($21,$d3,$58,$74), ($2c,$d8,$56,$7d), ($0c,$7a,$37,$a1), ($01,$71,$39,$a8), ($16,$6c,$2b,$b3), ($1b,$67,$25,$ba), ($38,$56,$0f,$85), ($35,$5d,$01,$8c), ($22,$40,$13,$97), ($2f,$4b,$1d,$9e), ($64,$22,$47,$e9), ($69,$29,$49,$e0), ($7e,$34,$5b,$fb), ($73,$3f,$55,$f2), ($50,$0e,$7f,$cd), ($5d,$05,$71,$c4), ($4a,$18,$63,$df), ($47,$13,$6d,$d6), ($dc,$ca,$d7,$31), ($d1,$c1,$d9,$38), ($c6,$dc,$cb,$23), ($cb,$d7,$c5,$2a), ($e8,$e6,$ef,$15), ($e5,$ed,$e1,$1c), ($f2,$f0,$f3,$07), ($ff,$fb,$fd,$0e), ($b4,$92,$a7,$79), ($b9,$99,$a9,$70), ($ae,$84,$bb,$6b), ($a3,$8f,$b5,$62), ($80,$be,$9f,$5d), ($8d,$b5,$91,$54), ($9a,$a8,$83,$4f), ($97,$a3,$8d,$46)); U4: array[0..255,0..3] of byte= ( ($00,$00,$00,$00), ($09,$0d,$0b,$0e), ($12,$1a,$16,$1c), ($1b,$17,$1d,$12), ($24,$34,$2c,$38), ($2d,$39,$27,$36), ($36,$2e,$3a,$24), ($3f,$23,$31,$2a), ($48,$68,$58,$70), ($41,$65,$53,$7e), ($5a,$72,$4e,$6c), ($53,$7f,$45,$62), ($6c,$5c,$74,$48), ($65,$51,$7f,$46), ($7e,$46,$62,$54), ($77,$4b,$69,$5a), ($90,$d0,$b0,$e0), ($99,$dd,$bb,$ee), ($82,$ca,$a6,$fc), ($8b,$c7,$ad,$f2), ($b4,$e4,$9c,$d8), ($bd,$e9,$97,$d6), ($a6,$fe,$8a,$c4), ($af,$f3,$81,$ca), ($d8,$b8,$e8,$90), ($d1,$b5,$e3,$9e), ($ca,$a2,$fe,$8c), ($c3,$af,$f5,$82), ($fc,$8c,$c4,$a8), ($f5,$81,$cf,$a6), ($ee,$96,$d2,$b4), ($e7,$9b,$d9,$ba), ($3b,$bb,$7b,$db), ($32,$b6,$70,$d5), ($29,$a1,$6d,$c7), ($20,$ac,$66,$c9), ($1f,$8f,$57,$e3), ($16,$82,$5c,$ed), ($0d,$95,$41,$ff), ($04,$98,$4a,$f1), ($73,$d3,$23,$ab), ($7a,$de,$28,$a5), ($61,$c9,$35,$b7), ($68,$c4,$3e,$b9), ($57,$e7,$0f,$93), ($5e,$ea,$04,$9d), ($45,$fd,$19,$8f), ($4c,$f0,$12,$81), ($ab,$6b,$cb,$3b), ($a2,$66,$c0,$35), ($b9,$71,$dd,$27), ($b0,$7c,$d6,$29), ($8f,$5f,$e7,$03), ($86,$52,$ec,$0d), ($9d,$45,$f1,$1f), ($94,$48,$fa,$11), ($e3,$03,$93,$4b), ($ea,$0e,$98,$45), ($f1,$19,$85,$57), ($f8,$14,$8e,$59), ($c7,$37,$bf,$73), ($ce,$3a,$b4,$7d), ($d5,$2d,$a9,$6f), ($dc,$20,$a2,$61), ($76,$6d,$f6,$ad), ($7f,$60,$fd,$a3), ($64,$77,$e0,$b1), ($6d,$7a,$eb,$bf), ($52,$59,$da,$95), ($5b,$54,$d1,$9b), ($40,$43,$cc,$89), ($49,$4e,$c7,$87), ($3e,$05,$ae,$dd), ($37,$08,$a5,$d3), ($2c,$1f,$b8,$c1), ($25,$12,$b3,$cf), ($1a,$31,$82,$e5), ($13,$3c,$89,$eb), ($08,$2b,$94,$f9), ($01,$26,$9f,$f7), ($e6,$bd,$46,$4d), ($ef,$b0,$4d,$43), ($f4,$a7,$50,$51), ($fd,$aa,$5b,$5f), ($c2,$89,$6a,$75), ($cb,$84,$61,$7b), ($d0,$93,$7c,$69), ($d9,$9e,$77,$67), ($ae,$d5,$1e,$3d), ($a7,$d8,$15,$33), ($bc,$cf,$08,$21), ($b5,$c2,$03,$2f), ($8a,$e1,$32,$05), ($83,$ec,$39,$0b), ($98,$fb,$24,$19), ($91,$f6,$2f,$17), ($4d,$d6,$8d,$76), ($44,$db,$86,$78), ($5f,$cc,$9b,$6a), ($56,$c1,$90,$64), ($69,$e2,$a1,$4e), ($60,$ef,$aa,$40), ($7b,$f8,$b7,$52), ($72,$f5,$bc,$5c), ($05,$be,$d5,$06), ($0c,$b3,$de,$08), ($17,$a4,$c3,$1a), ($1e,$a9,$c8,$14), ($21,$8a,$f9,$3e), ($28,$87,$f2,$30), ($33,$90,$ef,$22), ($3a,$9d,$e4,$2c), ($dd,$06,$3d,$96), ($d4,$0b,$36,$98), ($cf,$1c,$2b,$8a), ($c6,$11,$20,$84), ($f9,$32,$11,$ae), ($f0,$3f,$1a,$a0), ($eb,$28,$07,$b2), ($e2,$25,$0c,$bc), ($95,$6e,$65,$e6), ($9c,$63,$6e,$e8), ($87,$74,$73,$fa), ($8e,$79,$78,$f4), ($b1,$5a,$49,$de), ($b8,$57,$42,$d0), ($a3,$40,$5f,$c2), ($aa,$4d,$54,$cc), ($ec,$da,$f7,$41), ($e5,$d7,$fc,$4f), ($fe,$c0,$e1,$5d), ($f7,$cd,$ea,$53), ($c8,$ee,$db,$79), ($c1,$e3,$d0,$77), ($da,$f4,$cd,$65), ($d3,$f9,$c6,$6b), ($a4,$b2,$af,$31), ($ad,$bf,$a4,$3f), ($b6,$a8,$b9,$2d), ($bf,$a5,$b2,$23), ($80,$86,$83,$09), ($89,$8b,$88,$07), ($92,$9c,$95,$15), ($9b,$91,$9e,$1b), ($7c,$0a,$47,$a1), ($75,$07,$4c,$af), ($6e,$10,$51,$bd), ($67,$1d,$5a,$b3), ($58,$3e,$6b,$99), ($51,$33,$60,$97), ($4a,$24,$7d,$85), ($43,$29,$76,$8b), ($34,$62,$1f,$d1), ($3d,$6f,$14,$df), ($26,$78,$09,$cd), ($2f,$75,$02,$c3), ($10,$56,$33,$e9), ($19,$5b,$38,$e7), ($02,$4c,$25,$f5), ($0b,$41,$2e,$fb), ($d7,$61,$8c,$9a), ($de,$6c,$87,$94), ($c5,$7b,$9a,$86), ($cc,$76,$91,$88), ($f3,$55,$a0,$a2), ($fa,$58,$ab,$ac), ($e1,$4f,$b6,$be), ($e8,$42,$bd,$b0), ($9f,$09,$d4,$ea), ($96,$04,$df,$e4), ($8d,$13,$c2,$f6), ($84,$1e,$c9,$f8), ($bb,$3d,$f8,$d2), ($b2,$30,$f3,$dc), ($a9,$27,$ee,$ce), ($a0,$2a,$e5,$c0), ($47,$b1,$3c,$7a), ($4e,$bc,$37,$74), ($55,$ab,$2a,$66), ($5c,$a6,$21,$68), ($63,$85,$10,$42), ($6a,$88,$1b,$4c), ($71,$9f,$06,$5e), ($78,$92,$0d,$50), ($0f,$d9,$64,$0a), ($06,$d4,$6f,$04), ($1d,$c3,$72,$16), ($14,$ce,$79,$18), ($2b,$ed,$48,$32), ($22,$e0,$43,$3c), ($39,$f7,$5e,$2e), ($30,$fa,$55,$20), ($9a,$b7,$01,$ec), ($93,$ba,$0a,$e2), ($88,$ad,$17,$f0), ($81,$a0,$1c,$fe), ($be,$83,$2d,$d4), ($b7,$8e,$26,$da), ($ac,$99,$3b,$c8), ($a5,$94,$30,$c6), ($d2,$df,$59,$9c), ($db,$d2,$52,$92), ($c0,$c5,$4f,$80), ($c9,$c8,$44,$8e), ($f6,$eb,$75,$a4), ($ff,$e6,$7e,$aa), ($e4,$f1,$63,$b8), ($ed,$fc,$68,$b6), ($0a,$67,$b1,$0c), ($03,$6a,$ba,$02), ($18,$7d,$a7,$10), ($11,$70,$ac,$1e), ($2e,$53,$9d,$34), ($27,$5e,$96,$3a), ($3c,$49,$8b,$28), ($35,$44,$80,$26), ($42,$0f,$e9,$7c), ($4b,$02,$e2,$72), ($50,$15,$ff,$60), ($59,$18,$f4,$6e), ($66,$3b,$c5,$44), ($6f,$36,$ce,$4a), ($74,$21,$d3,$58), ($7d,$2c,$d8,$56), ($a1,$0c,$7a,$37), ($a8,$01,$71,$39), ($b3,$16,$6c,$2b), ($ba,$1b,$67,$25), ($85,$38,$56,$0f), ($8c,$35,$5d,$01), ($97,$22,$40,$13), ($9e,$2f,$4b,$1d), ($e9,$64,$22,$47), ($e0,$69,$29,$49), ($fb,$7e,$34,$5b), ($f2,$73,$3f,$55), ($cd,$50,$0e,$7f), ($c4,$5d,$05,$71), ($df,$4a,$18,$63), ($d6,$47,$13,$6d), ($31,$dc,$ca,$d7), ($38,$d1,$c1,$d9), ($23,$c6,$dc,$cb), ($2a,$cb,$d7,$c5), ($15,$e8,$e6,$ef), ($1c,$e5,$ed,$e1), ($07,$f2,$f0,$f3), ($0e,$ff,$fb,$fd), ($79,$b4,$92,$a7), ($70,$b9,$99,$a9), ($6b,$ae,$84,$bb), ($62,$a3,$8f,$b5), ($5d,$80,$be,$9f), ($54,$8d,$b5,$91), ($4f,$9a,$a8,$83), ($46,$97,$a3,$8d)); rcon: array[0..29] of cardinal= ( $01, $02, $04, $08, $10, $20, $40, $80, $1b, $36, $6c, $d8, $ab, $4d, $9a, $2f, $5e, $bc, $63, $c6, $97, $35, $6a, $d4, $b3, $7d, $fa, $ef, $c5, $91); {==============================================================================} type PDWord = ^LongWord; procedure hperm_op(var a, t: integer; n, m: integer); begin t:= ((a shl (16 - n)) xor a) and m; a:= a xor t xor (t shr (16 - n)); end; procedure perm_op(var a, b, t: integer; n, m: integer); begin t:= ((a shr n) xor b) and m; b:= b xor t; a:= a xor (t shl n); end; {==============================================================================} function TSynaBlockCipher.GetSize: byte; begin Result := 8; end; procedure TSynaBlockCipher.IncCounter; var i: integer; begin Inc(CV[GetSize]); i:= GetSize -1; while (i> 0) and (CV[i + 1] = #0) do begin Inc(CV[i]); Dec(i); end; end; procedure TSynaBlockCipher.Reset; begin CV := IV; end; procedure TSynaBlockCipher.InitKey(Key: AnsiString); begin end; procedure TSynaBlockCipher.SetIV(const Value: AnsiString); begin IV := PadString(Value, GetSize, #0); Reset; end; function TSynaBlockCipher.GetIV: AnsiString; begin Result := CV; end; function TSynaBlockCipher.EncryptECB(const InData: AnsiString): AnsiString; begin Result := InData; end; function TSynaBlockCipher.DecryptECB(const InData: AnsiString): AnsiString; begin Result := InData; end; function TSynaBlockCipher.EncryptCBC(const Indata: AnsiString): AnsiString; var i: integer; s: ansistring; l: integer; bs: byte; begin Result := ''; l := Length(InData); bs := GetSize; for i:= 1 to (l div bs) do begin s := copy(Indata, (i - 1) * bs + 1, bs); s := XorString(s, CV); s := EncryptECB(s); CV := s; Result := Result + s; end; if (l mod bs)<> 0 then begin CV := EncryptECB(CV); s := copy(Indata, (l div bs) * bs + 1, l mod bs); s := XorString(s, CV); Result := Result + s; end; end; function TSynaBlockCipher.DecryptCBC(const Indata: AnsiString): AnsiString; var i: integer; s, temp: ansistring; l: integer; bs: byte; begin Result := ''; l := Length(InData); bs := GetSize; for i:= 1 to (l div bs) do begin s := copy(Indata, (i - 1) * bs + 1, bs); temp := s; s := DecryptECB(s); s := XorString(s, CV); Result := Result + s; CV := Temp; end; if (l mod bs)<> 0 then begin CV := EncryptECB(CV); s := copy(Indata, (l div bs) * bs + 1, l mod bs); s := XorString(s, CV); Result := Result + s; end; end; function TSynaBlockCipher.EncryptCFB8bit(const Indata: AnsiString): AnsiString; var i: integer; Temp: AnsiString; c: AnsiChar; begin Result := ''; for i:= 1 to Length(Indata) do begin Temp := EncryptECB(CV); c := AnsiChar(ord(InData[i]) xor ord(temp[1])); Result := Result + c; Delete(CV, 1, 1); CV := CV + c; end; end; function TSynaBlockCipher.DecryptCFB8bit(const Indata: AnsiString): AnsiString; var i: integer; Temp: AnsiString; c: AnsiChar; begin Result := ''; for i:= 1 to length(Indata) do begin c:= Indata[i]; Temp := EncryptECB(CV); Result := Result + AnsiChar(ord(InData[i]) xor ord(temp[1])); Delete(CV, 1, 1); CV := CV + c; end; end; function TSynaBlockCipher.EncryptCFBblock(const Indata: AnsiString): AnsiString; var i: integer; s: AnsiString; l: integer; bs: byte; begin Result := ''; l := Length(InData); bs := GetSize; for i:= 1 to (l div bs) do begin CV := EncryptECB(CV); s := copy(Indata, (i - 1) * bs + 1, bs); s := XorString(s, CV); Result := Result + s; CV := s; end; if (l mod bs)<> 0 then begin CV := EncryptECB(CV); s := copy(Indata, (l div bs) * bs + 1, l mod bs); s := XorString(s, CV); Result := Result + s; end; end; function TSynaBlockCipher.DecryptCFBblock(const Indata: AnsiString): AnsiString; var i: integer; S, Temp: AnsiString; l: integer; bs: byte; begin Result := ''; l := Length(InData); bs := GetSize; for i:= 1 to (l div bs) do begin s := copy(Indata, (i - 1) * bs + 1, bs); Temp := s; CV := EncryptECB(CV); s := XorString(s, CV); Result := result + s; CV := temp; end; if (l mod bs)<> 0 then begin CV := EncryptECB(CV); s := copy(Indata, (l div bs) * bs + 1, l mod bs); s := XorString(s, CV); Result := Result + s; end; end; function TSynaBlockCipher.EncryptOFB(const Indata: AnsiString): AnsiString; var i: integer; s: AnsiString; l: integer; bs: byte; begin Result := ''; l := Length(InData); bs := GetSize; for i:= 1 to (l div bs) do begin CV := EncryptECB(CV); s := copy(Indata, (i - 1) * bs + 1, bs); s := XorString(s, CV); Result := Result + s; end; if (l mod bs)<> 0 then begin CV := EncryptECB(CV); s := copy(Indata, (l div bs) * bs + 1, l mod bs); s := XorString(s, CV); Result := Result + s; end; end; function TSynaBlockCipher.DecryptOFB(const Indata: AnsiString): AnsiString; var i: integer; s: AnsiString; l: integer; bs: byte; begin Result := ''; l := Length(InData); bs := GetSize; for i:= 1 to (l div bs) do begin Cv := EncryptECB(CV); s := copy(Indata, (i - 1) * bs + 1, bs); s := XorString(s, CV); Result := Result + s; end; if (l mod bs)<> 0 then begin CV := EncryptECB(CV); s := copy(Indata, (l div bs) * bs + 1, l mod bs); s := XorString(s, CV); Result := Result + s; end; end; function TSynaBlockCipher.EncryptCTR(const Indata: AnsiString): AnsiString; var temp: AnsiString; i: integer; s: AnsiString; l: integer; bs: byte; begin Result := ''; l := Length(InData); bs := GetSize; for i:= 1 to (l div bs) do begin temp := EncryptECB(CV); IncCounter; s := copy(Indata, (i - 1) * bs + 1, bs); s := XorString(s, temp); Result := Result + s; end; if (l mod bs)<> 0 then begin temp := EncryptECB(CV); IncCounter; s := copy(Indata, (l div bs) * bs + 1, l mod bs); s := XorString(s, temp); Result := Result + s; end; end; function TSynaBlockCipher.DecryptCTR(const Indata: AnsiString): AnsiString; var temp: AnsiString; s: AnsiString; i: integer; l: integer; bs: byte; begin Result := ''; l := Length(InData); bs := GetSize; for i:= 1 to (l div bs) do begin temp := EncryptECB(CV); IncCounter; s := copy(Indata, (i - 1) * bs + 1, bs); s := XorString(s, temp); Result := Result + s; end; if (l mod bs)<> 0 then begin temp := EncryptECB(CV); IncCounter; s := copy(Indata, (l div bs) * bs + 1, l mod bs); s := XorString(s, temp); Result := Result + s; end; end; constructor TSynaBlockCipher.Create(Key: AnsiString); begin inherited Create; InitKey(Key); IV := StringOfChar(#0, GetSize); IV := EncryptECB(IV); Reset; end; {==============================================================================} procedure TSynaCustomDes.DoInit(KeyB: AnsiString; var KeyData: TDesKeyData); var c, d, t, s, t2, i: integer; begin KeyB := PadString(KeyB, 8, #0); c:= ord(KeyB[1]) or (ord(KeyB[2]) shl 8) or (ord(KeyB[3]) shl 16) or (ord(KeyB[4]) shl 24); d:= ord(KeyB[5]) or (ord(KeyB[6]) shl 8) or (ord(KeyB[7]) shl 16) or (ord(KeyB[8]) shl 24); perm_op(d,c,t,4,integer($0f0f0f0f)); hperm_op(c,t,integer(-2),integer($cccc0000)); hperm_op(d,t,integer(-2),integer($cccc0000)); perm_op(d,c,t,1,integer($55555555)); perm_op(c,d,t,8,integer($00ff00ff)); perm_op(d,c,t,1,integer($55555555)); d:= ((d and $ff) shl 16) or (d and $ff00) or ((d and $ff0000) shr 16) or ((c and integer($f0000000)) shr 4); c:= c and $fffffff; for i:= 0 to 15 do begin if shifts2[i]<> 0 then begin c:= ((c shr 2) or (c shl 26)); d:= ((d shr 2) or (d shl 26)); end else begin c:= ((c shr 1) or (c shl 27)); d:= ((d shr 1) or (d shl 27)); end; c:= c and $fffffff; d:= d and $fffffff; s:= des_skb[0,c and $3f] or des_skb[1,((c shr 6) and $03) or ((c shr 7) and $3c)] or des_skb[2,((c shr 13) and $0f) or ((c shr 14) and $30)] or des_skb[3,((c shr 20) and $01) or ((c shr 21) and $06) or ((c shr 22) and $38)]; t:= des_skb[4,d and $3f] or des_skb[5,((d shr 7) and $03) or ((d shr 8) and $3c)] or des_skb[6, (d shr 15) and $3f ] or des_skb[7,((d shr 21) and $0f) or ((d shr 22) and $30)]; t2:= ((t shl 16) or (s and $ffff)); KeyData[(i shl 1)]:= ((t2 shl 2) or (t2 shr 30)); t2:= ((s shr 16) or (t and integer($ffff0000))); KeyData[(i shl 1)+1]:= ((t2 shl 6) or (t2 shr 26)); end; end; function TSynaCustomDes.EncryptBlock(const InData: AnsiString; var KeyData: TDesKeyData): AnsiString; var l, r, t, u: integer; i: longint; begin r := Swapbytes(DecodeLongint(Indata, 1)); l := swapbytes(DecodeLongint(Indata, 5)); t:= ((l shr 4) xor r) and $0f0f0f0f; r:= r xor t; l:= l xor (t shl 4); t:= ((r shr 16) xor l) and $0000ffff; l:= l xor t; r:= r xor (t shl 16); t:= ((l shr 2) xor r) and $33333333; r:= r xor t; l:= l xor (t shl 2); t:= ((r shr 8) xor l) and $00ff00ff; l:= l xor t; r:= r xor (t shl 8); t:= ((l shr 1) xor r) and $55555555; r:= r xor t; l:= l xor (t shl 1); r:= (r shr 29) or (r shl 3); l:= (l shr 29) or (l shl 3); i:= 0; while i< 32 do begin u:= r xor KeyData[i ]; t:= r xor KeyData[i+1]; t:= (t shr 4) or (t shl 28); l:= l xor des_SPtrans[0,(u shr 2) and $3f] xor des_SPtrans[2,(u shr 10) and $3f] xor des_SPtrans[4,(u shr 18) and $3f] xor des_SPtrans[6,(u shr 26) and $3f] xor des_SPtrans[1,(t shr 2) and $3f] xor des_SPtrans[3,(t shr 10) and $3f] xor des_SPtrans[5,(t shr 18) and $3f] xor des_SPtrans[7,(t shr 26) and $3f]; u:= l xor KeyData[i+2]; t:= l xor KeyData[i+3]; t:= (t shr 4) or (t shl 28); r:= r xor des_SPtrans[0,(u shr 2) and $3f] xor des_SPtrans[2,(u shr 10) and $3f] xor des_SPtrans[4,(u shr 18) and $3f] xor des_SPtrans[6,(u shr 26) and $3f] xor des_SPtrans[1,(t shr 2) and $3f] xor des_SPtrans[3,(t shr 10) and $3f] xor des_SPtrans[5,(t shr 18) and $3f] xor des_SPtrans[7,(t shr 26) and $3f]; u:= r xor KeyData[i+4]; t:= r xor KeyData[i+5]; t:= (t shr 4) or (t shl 28); l:= l xor des_SPtrans[0,(u shr 2) and $3f] xor des_SPtrans[2,(u shr 10) and $3f] xor des_SPtrans[4,(u shr 18) and $3f] xor des_SPtrans[6,(u shr 26) and $3f] xor des_SPtrans[1,(t shr 2) and $3f] xor des_SPtrans[3,(t shr 10) and $3f] xor des_SPtrans[5,(t shr 18) and $3f] xor des_SPtrans[7,(t shr 26) and $3f]; u:= l xor KeyData[i+6]; t:= l xor KeyData[i+7]; t:= (t shr 4) or (t shl 28); r:= r xor des_SPtrans[0,(u shr 2) and $3f] xor des_SPtrans[2,(u shr 10) and $3f] xor des_SPtrans[4,(u shr 18) and $3f] xor des_SPtrans[6,(u shr 26) and $3f] xor des_SPtrans[1,(t shr 2) and $3f] xor des_SPtrans[3,(t shr 10) and $3f] xor des_SPtrans[5,(t shr 18) and $3f] xor des_SPtrans[7,(t shr 26) and $3f]; Inc(i,8); end; r:= (r shr 3) or (r shl 29); l:= (l shr 3) or (l shl 29); t:= ((r shr 1) xor l) and $55555555; l:= l xor t; r:= r xor (t shl 1); t:= ((l shr 8) xor r) and $00ff00ff; r:= r xor t; l:= l xor (t shl 8); t:= ((r shr 2) xor l) and $33333333; l:= l xor t; r:= r xor (t shl 2); t:= ((l shr 16) xor r) and $0000ffff; r:= r xor t; l:= l xor (t shl 16); t:= ((r shr 4) xor l) and $0f0f0f0f; l:= l xor t; r:= r xor (t shl 4); Result := CodeLongInt(Swapbytes(l)) + CodeLongInt(Swapbytes(r)); end; function TSynaCustomDes.DecryptBlock(const InData: AnsiString; var KeyData: TDesKeyData): AnsiString; var l, r, t, u: integer; i: longint; begin r := Swapbytes(DecodeLongint(Indata, 1)); l := Swapbytes(DecodeLongint(Indata, 5)); t:= ((l shr 4) xor r) and $0f0f0f0f; r:= r xor t; l:= l xor (t shl 4); t:= ((r shr 16) xor l) and $0000ffff; l:= l xor t; r:= r xor (t shl 16); t:= ((l shr 2) xor r) and $33333333; r:= r xor t; l:= l xor (t shl 2); t:= ((r shr 8) xor l) and $00ff00ff; l:= l xor t; r:= r xor (t shl 8); t:= ((l shr 1) xor r) and $55555555; r:= r xor t; l:= l xor (t shl 1); r:= (r shr 29) or (r shl 3); l:= (l shr 29) or (l shl 3); i:= 30; while i> 0 do begin u:= r xor KeyData[i ]; t:= r xor KeyData[i+1]; t:= (t shr 4) or (t shl 28); l:= l xor des_SPtrans[0,(u shr 2) and $3f] xor des_SPtrans[2,(u shr 10) and $3f] xor des_SPtrans[4,(u shr 18) and $3f] xor des_SPtrans[6,(u shr 26) and $3f] xor des_SPtrans[1,(t shr 2) and $3f] xor des_SPtrans[3,(t shr 10) and $3f] xor des_SPtrans[5,(t shr 18) and $3f] xor des_SPtrans[7,(t shr 26) and $3f]; u:= l xor KeyData[i-2]; t:= l xor KeyData[i-1]; t:= (t shr 4) or (t shl 28); r:= r xor des_SPtrans[0,(u shr 2) and $3f] xor des_SPtrans[2,(u shr 10) and $3f] xor des_SPtrans[4,(u shr 18) and $3f] xor des_SPtrans[6,(u shr 26) and $3f] xor des_SPtrans[1,(t shr 2) and $3f] xor des_SPtrans[3,(t shr 10) and $3f] xor des_SPtrans[5,(t shr 18) and $3f] xor des_SPtrans[7,(t shr 26) and $3f]; u:= r xor KeyData[i-4]; t:= r xor KeyData[i-3]; t:= (t shr 4) or (t shl 28); l:= l xor des_SPtrans[0,(u shr 2) and $3f] xor des_SPtrans[2,(u shr 10) and $3f] xor des_SPtrans[4,(u shr 18) and $3f] xor des_SPtrans[6,(u shr 26) and $3f] xor des_SPtrans[1,(t shr 2) and $3f] xor des_SPtrans[3,(t shr 10) and $3f] xor des_SPtrans[5,(t shr 18) and $3f] xor des_SPtrans[7,(t shr 26) and $3f]; u:= l xor KeyData[i-6]; t:= l xor KeyData[i-5]; t:= (t shr 4) or (t shl 28); r:= r xor des_SPtrans[0,(u shr 2) and $3f] xor des_SPtrans[2,(u shr 10) and $3f] xor des_SPtrans[4,(u shr 18) and $3f] xor des_SPtrans[6,(u shr 26) and $3f] xor des_SPtrans[1,(t shr 2) and $3f] xor des_SPtrans[3,(t shr 10) and $3f] xor des_SPtrans[5,(t shr 18) and $3f] xor des_SPtrans[7,(t shr 26) and $3f]; Dec(i,8); end; r:= (r shr 3) or (r shl 29); l:= (l shr 3) or (l shl 29); t:= ((r shr 1) xor l) and $55555555; l:= l xor t; r:= r xor (t shl 1); t:= ((l shr 8) xor r) and $00ff00ff; r:= r xor t; l:= l xor (t shl 8); t:= ((r shr 2) xor l) and $33333333; l:= l xor t; r:= r xor (t shl 2); t:= ((l shr 16) xor r) and $0000ffff; r:= r xor t; l:= l xor (t shl 16); t:= ((r shr 4) xor l) and $0f0f0f0f; l:= l xor t; r:= r xor (t shl 4); Result := CodeLongInt(Swapbytes(l)) + CodeLongInt(Swapbytes(r)); end; {==============================================================================} procedure TSynaDes.InitKey(Key: AnsiString); begin Key := PadString(Key, 8, #0); DoInit(Key,KeyData); end; function TSynaDes.EncryptECB(const InData: AnsiString): AnsiString; begin Result := EncryptBlock(InData,KeyData); end; function TSynaDes.DecryptECB(const InData: AnsiString): AnsiString; begin Result := DecryptBlock(Indata,KeyData); end; {==============================================================================} procedure TSyna3Des.InitKey(Key: AnsiString); var Size: integer; n: integer; begin Size := length(Key); key := PadString(key, 3 * 8, #0); DoInit(Copy(key, 1, 8),KeyData[0]); DoInit(Copy(key, 9, 8),KeyData[1]); if Size > 16 then DoInit(Copy(key, 17, 8),KeyData[2]) else for n := 0 to high(KeyData[0]) do KeyData[2][n] := Keydata[0][n]; end; function TSyna3Des.EncryptECB(const InData: AnsiString): AnsiString; begin Result := EncryptBlock(Indata,KeyData[0]); Result := DecryptBlock(Result,KeyData[1]); Result := EncryptBlock(Result,KeyData[2]); end; function TSyna3Des.DecryptECB(const InData: AnsiString): AnsiString; begin Result := DecryptBlock(InData,KeyData[2]); Result := EncryptBlock(Result,KeyData[1]); Result := DecryptBlock(Result,KeyData[0]); end; {==============================================================================} procedure InvMixColumn(a: PByteArray; BC: byte); var j: longword; begin for j:= 0 to (BC-1) do PDWord(@(a^[j*4]))^:= PDWord(@U1[a^[j*4+0]])^ xor PDWord(@U2[a^[j*4+1]])^ xor PDWord(@U3[a^[j*4+2]])^ xor PDWord(@U4[a^[j*4+3]])^; end; {==============================================================================} function TSynaAes.GetSize: byte; begin Result := 16; end; procedure TSynaAes.InitKey(Key: AnsiString); var Size: integer; KC, ROUNDS, j, r, t, rconpointer: longword; tk: array[0..MAXKC-1,0..3] of byte; n: integer; begin FillChar(tk,Sizeof(tk),0); //key must have at least 128 bits and max 256 bits if length(key) < 16 then key := PadString(key, 16, #0); if length(key) > 32 then delete(key, 33, maxint); Size := length(Key); Move(PAnsiChar(Key)^, tk, Size); if Size<= 16 then begin KC:= 4; Rounds:= 10; end else if Size<= 24 then begin KC:= 6; Rounds:= 12; end else begin KC:= 8; Rounds:= 14; end; numrounds:= rounds; r:= 0; t:= 0; j:= 0; while (j< KC) and (r< (rounds+1)) do begin while (j< KC) and (t< BC) do begin rk[r,t]:= PDWord(@tk[j])^; Inc(j); Inc(t); end; if t= BC then begin t:= 0; Inc(r); end; end; rconpointer:= 0; while (r< (rounds+1)) do begin tk[0,0]:= tk[0,0] xor S[tk[KC-1,1]]; tk[0,1]:= tk[0,1] xor S[tk[KC-1,2]]; tk[0,2]:= tk[0,2] xor S[tk[KC-1,3]]; tk[0,3]:= tk[0,3] xor S[tk[KC-1,0]]; tk[0,0]:= tk[0,0] xor rcon[rconpointer]; Inc(rconpointer); if KC<> 8 then begin for j:= 1 to (KC-1) do PDWord(@tk[j])^:= PDWord(@tk[j])^ xor PDWord(@tk[j-1])^; end else begin for j:= 1 to ((KC div 2)-1) do PDWord(@tk[j])^:= PDWord(@tk[j])^ xor PDWord(@tk[j-1])^; tk[KC div 2,0]:= tk[KC div 2,0] xor S[tk[KC div 2 - 1,0]]; tk[KC div 2,1]:= tk[KC div 2,1] xor S[tk[KC div 2 - 1,1]]; tk[KC div 2,2]:= tk[KC div 2,2] xor S[tk[KC div 2 - 1,2]]; tk[KC div 2,3]:= tk[KC div 2,3] xor S[tk[KC div 2 - 1,3]]; for j:= ((KC div 2) + 1) to (KC-1) do PDWord(@tk[j])^:= PDWord(@tk[j])^ xor PDWord(@tk[j-1])^; end; j:= 0; while (j< KC) and (r< (rounds+1)) do begin while (j< KC) and (t< BC) do begin rk[r,t]:= PDWord(@tk[j])^; Inc(j); Inc(t); end; if t= BC then begin Inc(r); t:= 0; end; end; end; Move(rk,drk,Sizeof(rk)); for r:= 1 to (numrounds-1) do InvMixColumn(@drk[r],BC); end; function TSynaAes.EncryptECB(const InData: AnsiString): AnsiString; var r: longword; tempb: array[0..MAXBC-1,0..3] of byte; a: array[0..MAXBC,0..3] of byte; p: pointer; begin p := @a[0,0]; move(pointer(InData)^, p^, 16); for r:= 0 to (numrounds-2) do begin PDWord(@tempb[0])^:= PDWord(@a[0])^ xor rk[r,0]; PDWord(@tempb[1])^:= PDWord(@a[1])^ xor rk[r,1]; PDWord(@tempb[2])^:= PDWord(@a[2])^ xor rk[r,2]; PDWord(@tempb[3])^:= PDWord(@a[3])^ xor rk[r,3]; PDWord(@a[0])^:= PDWord(@T1[tempb[0,0]])^ xor PDWord(@T2[tempb[1,1]])^ xor PDWord(@T3[tempb[2,2]])^ xor PDWord(@T4[tempb[3,3]])^; PDWord(@a[1])^:= PDWord(@T1[tempb[1,0]])^ xor PDWord(@T2[tempb[2,1]])^ xor PDWord(@T3[tempb[3,2]])^ xor PDWord(@T4[tempb[0,3]])^; PDWord(@a[2])^:= PDWord(@T1[tempb[2,0]])^ xor PDWord(@T2[tempb[3,1]])^ xor PDWord(@T3[tempb[0,2]])^ xor PDWord(@T4[tempb[1,3]])^; PDWord(@a[3])^:= PDWord(@T1[tempb[3,0]])^ xor PDWord(@T2[tempb[0,1]])^ xor PDWord(@T3[tempb[1,2]])^ xor PDWord(@T4[tempb[2,3]])^; end; PDWord(@tempb[0])^:= PDWord(@a[0])^ xor rk[numrounds-1,0]; PDWord(@tempb[1])^:= PDWord(@a[1])^ xor rk[numrounds-1,1]; PDWord(@tempb[2])^:= PDWord(@a[2])^ xor rk[numrounds-1,2]; PDWord(@tempb[3])^:= PDWord(@a[3])^ xor rk[numrounds-1,3]; a[0,0]:= T1[tempb[0,0],1]; a[0,1]:= T1[tempb[1,1],1]; a[0,2]:= T1[tempb[2,2],1]; a[0,3]:= T1[tempb[3,3],1]; a[1,0]:= T1[tempb[1,0],1]; a[1,1]:= T1[tempb[2,1],1]; a[1,2]:= T1[tempb[3,2],1]; a[1,3]:= T1[tempb[0,3],1]; a[2,0]:= T1[tempb[2,0],1]; a[2,1]:= T1[tempb[3,1],1]; a[2,2]:= T1[tempb[0,2],1]; a[2,3]:= T1[tempb[1,3],1]; a[3,0]:= T1[tempb[3,0],1]; a[3,1]:= T1[tempb[0,1],1]; a[3,2]:= T1[tempb[1,2],1]; a[3,3]:= T1[tempb[2,3],1]; PDWord(@a[0])^:= PDWord(@a[0])^ xor rk[numrounds,0]; PDWord(@a[1])^:= PDWord(@a[1])^ xor rk[numrounds,1]; PDWord(@a[2])^:= PDWord(@a[2])^ xor rk[numrounds,2]; PDWord(@a[3])^:= PDWord(@a[3])^ xor rk[numrounds,3]; Result := StringOfChar(#0, 16); move(p^, pointer(Result)^, 16); end; function TSynaAes.DecryptECB(const InData: AnsiString): AnsiString; var r: longword; tempb: array[0..MAXBC-1,0..3] of byte; a: array[0..MAXBC,0..3] of byte; p: pointer; begin p := @a[0,0]; move(pointer(InData)^, p^, 16); for r:= NumRounds downto 2 do begin PDWord(@tempb[0])^:= PDWord(@a[0])^ xor drk[r,0]; PDWord(@tempb[1])^:= PDWord(@a[1])^ xor drk[r,1]; PDWord(@tempb[2])^:= PDWord(@a[2])^ xor drk[r,2]; PDWord(@tempb[3])^:= PDWord(@a[3])^ xor drk[r,3]; PDWord(@a[0])^:= PDWord(@T5[tempb[0,0]])^ xor PDWord(@T6[tempb[3,1]])^ xor PDWord(@T7[tempb[2,2]])^ xor PDWord(@T8[tempb[1,3]])^; PDWord(@a[1])^:= PDWord(@T5[tempb[1,0]])^ xor PDWord(@T6[tempb[0,1]])^ xor PDWord(@T7[tempb[3,2]])^ xor PDWord(@T8[tempb[2,3]])^; PDWord(@a[2])^:= PDWord(@T5[tempb[2,0]])^ xor PDWord(@T6[tempb[1,1]])^ xor PDWord(@T7[tempb[0,2]])^ xor PDWord(@T8[tempb[3,3]])^; PDWord(@a[3])^:= PDWord(@T5[tempb[3,0]])^ xor PDWord(@T6[tempb[2,1]])^ xor PDWord(@T7[tempb[1,2]])^ xor PDWord(@T8[tempb[0,3]])^; end; PDWord(@tempb[0])^:= PDWord(@a[0])^ xor drk[1,0]; PDWord(@tempb[1])^:= PDWord(@a[1])^ xor drk[1,1]; PDWord(@tempb[2])^:= PDWord(@a[2])^ xor drk[1,2]; PDWord(@tempb[3])^:= PDWord(@a[3])^ xor drk[1,3]; a[0,0]:= S5[tempb[0,0]]; a[0,1]:= S5[tempb[3,1]]; a[0,2]:= S5[tempb[2,2]]; a[0,3]:= S5[tempb[1,3]]; a[1,0]:= S5[tempb[1,0]]; a[1,1]:= S5[tempb[0,1]]; a[1,2]:= S5[tempb[3,2]]; a[1,3]:= S5[tempb[2,3]]; a[2,0]:= S5[tempb[2,0]]; a[2,1]:= S5[tempb[1,1]]; a[2,2]:= S5[tempb[0,2]]; a[2,3]:= S5[tempb[3,3]]; a[3,0]:= S5[tempb[3,0]]; a[3,1]:= S5[tempb[2,1]]; a[3,2]:= S5[tempb[1,2]]; a[3,3]:= S5[tempb[0,3]]; PDWord(@a[0])^:= PDWord(@a[0])^ xor drk[0,0]; PDWord(@a[1])^:= PDWord(@a[1])^ xor drk[0,1]; PDWord(@a[2])^:= PDWord(@a[2])^ xor drk[0,2]; PDWord(@a[3])^:= PDWord(@a[3])^ xor drk[0,3]; Result := StringOfChar(#0, 16); move(p^, pointer(Result)^, 16); end; {==============================================================================} function TestDes: boolean; var des: TSynaDes; s, t: string; const key = '01234567'; data1= '01234567'; data2= '0123456789abcdefghij'; begin //ECB des := TSynaDes.Create(key); try s := des.EncryptECB(data1); t := strtohex(s); result := t = 'c50ad028c6da9800'; s := des.DecryptECB(s); result := result and (data1 = s); finally des.free; end; //CBC des := TSynaDes.Create(key); try s := des.EncryptCBC(data2); t := strtohex(s); result := result and (t = 'eec50f6353115ad6dee90a22ed1b6a88a0926e35'); des.Reset; s := des.DecryptCBC(s); result := result and (data2 = s); finally des.free; end; //CFB-8bit des := TSynaDes.Create(key); try s := des.EncryptCFB8bit(data2); t := strtohex(s); result := result and (t = 'eb6aa12c2f0ff634b4dfb6da6cb2af8f9c5c1452'); des.Reset; s := des.DecryptCFB8bit(s); result := result and (data2 = s); finally des.free; end; //CFB-block des := TSynaDes.Create(key); try s := des.EncryptCFBblock(data2); t := strtohex(s); result := result and (t = 'ebdbbaa7f9286cdec28605e07f9b7f3be1053257'); des.Reset; s := des.DecryptCFBblock(s); result := result and (data2 = s); finally des.free; end; //OFB des := TSynaDes.Create(key); try s := des.EncryptOFB(data2); t := strtohex(s); result := result and (t = 'ebdbbaa7f9286cdee0b8b3798c4c34baac87dbdc'); des.Reset; s := des.DecryptOFB(s); result := result and (data2 = s); finally des.free; end; //CTR des := TSynaDes.Create(key); try s := des.EncryptCTR(data2); t := strtohex(s); result := result and (t = 'ebdbbaa7f9286cde0dd20b45f3afd9aa1b91b87e'); des.Reset; s := des.DecryptCTR(s); result := result and (data2 = s); finally des.free; end; end; function Test3Des: boolean; var des: TSyna3Des; s, t: string; const key = '0123456789abcdefghijklmn'; data1= '01234567'; data2= '0123456789abcdefghij'; begin //ECB des := TSyna3Des.Create(key); try s := des.EncryptECB(data1); t := strtohex(s); result := t = 'e0dee91008dc460c'; s := des.DecryptECB(s); result := result and (data1 = s); finally des.free; end; //CBC des := TSyna3Des.Create(key); try s := des.EncryptCBC(data2); t := strtohex(s); result := result and (t = 'ee844a2a4f49c01b91a1599b8eba29128c1ad87a'); des.Reset; s := des.DecryptCBC(s); result := result and (data2 = s); finally des.free; end; //CFB-8bit des := TSyna3Des.Create(key); try s := des.EncryptCFB8bit(data2); t := strtohex(s); result := result and (t = '935bbf5210c32cfa1faf61f91e8dc02dfa0ff1e8'); des.Reset; s := des.DecryptCFB8bit(s); result := result and (data2 = s); finally des.free; end; //CFB-block des := TSyna3Des.Create(key); try s := des.EncryptCFBblock(data2); t := strtohex(s); result := result and (t = '93754e3d54828fbf4bd81f1739419e8d2cfe1671'); des.Reset; s := des.DecryptCFBblock(s); result := result and (data2 = s); finally des.free; end; //OFB des := TSyna3Des.Create(key); try s := des.EncryptOFB(data2); t := strtohex(s); result := result and (t = '93754e3d54828fbf04ef0a5efc926ebdf2d95f20'); des.Reset; s := des.DecryptOFB(s); result := result and (data2 = s); finally des.free; end; //CTR des := TSyna3Des.Create(key); try s := des.EncryptCTR(data2); t := strtohex(s); result := result and (t = '93754e3d54828fbf1c51a121d2c93f989e70b3ad'); des.Reset; s := des.DecryptCTR(s); result := result and (data2 = s); finally des.free; end; end; function TestAes: boolean; var aes: TSynaAes; s, t: string; const key1 = #$00#$01#$02#$03#$05#$06#$07#$08#$0A#$0B#$0C#$0D#$0F#$10#$11#$12; data1= #$50#$68#$12#$A4#$5F#$08#$C8#$89#$B9#$7F#$59#$80#$03#$8B#$83#$59; key2 = #$A0#$A1#$A2#$A3#$A5#$A6#$A7#$A8#$AA#$AB#$AC#$AD#$AF#$B0#$B1#$B2#$B4#$B5#$B6#$B7#$B9#$BA#$BB#$BC; data2= #$4F#$1C#$76#$9D#$1E#$5B#$05#$52#$C7#$EC#$A8#$4D#$EA#$26#$A5#$49; key3 = #$00#$01#$02#$03#$05#$06#$07#$08#$0A#$0B#$0C#$0D#$0F#$10#$11#$12#$14#$15#$16#$17#$19#$1A#$1B#$1C#$1E#$1F#$20#$21#$23#$24#$25#$26; data3= #$5E#$25#$CA#$78#$F0#$DE#$55#$80#$25#$24#$D3#$8D#$A3#$FE#$44#$56; begin //ECB aes := TSynaAes.Create(key1); try t := aes.EncryptECB(data1); result := t = #$D8#$F5#$32#$53#$82#$89#$EF#$7D#$06#$B5#$06#$A4#$FD#$5B#$E9#$C9; s := aes.DecryptECB(t); result := result and (data1 = s); finally aes.free; end; aes := TSynaAes.Create(key2); try t := aes.EncryptECB(data2); result := result and (t = #$F3#$84#$72#$10#$D5#$39#$1E#$23#$60#$60#$8E#$5A#$CB#$56#$05#$81); s := aes.DecryptECB(t); result := result and (data2 = s); finally aes.free; end; aes := TSynaAes.Create(key3); try t := aes.EncryptECB(data3); result := result and (t = #$E8#$B7#$2B#$4E#$8B#$E2#$43#$43#$8C#$9F#$FF#$1F#$0E#$20#$58#$72); s := aes.DecryptECB(t); result := result and (data3 = s); finally aes.free; end; end; {==============================================================================} end.
52.827186
139
0.492202
85ce5dec04269f4db25f6265fac2307c5a44007d
4,271
pas
Pascal
Scripts/Delphiscript Scripts/SCH/modelsofacomponent.pas
spoilsport/Yazgac-Libraries
276edeca757c524f7b6c04495d07bd41f6a2f691
[ "MIT" ]
null
null
null
Scripts/Delphiscript Scripts/SCH/modelsofacomponent.pas
spoilsport/Yazgac-Libraries
276edeca757c524f7b6c04495d07bd41f6a2f691
[ "MIT" ]
null
null
null
Scripts/Delphiscript Scripts/SCH/modelsofacomponent.pas
spoilsport/Yazgac-Libraries
276edeca757c524f7b6c04495d07bd41f6a2f691
[ "MIT" ]
null
null
null
{..............................................................................} { Summary Obtain models for each component and generate a report. } { Copyright (c) 2004 by Altium Limited } {..............................................................................} {..............................................................................} Procedure GenerateModelsReport (ModelsList : TStringList); Var S : TString; ReportDocument : IServerDocument; Begin ModelsList.Insert(0,'Schematic Components and their models Report...'); ModelsList.Insert(1,'==============================================='); ModelsList.Insert(2,''); ModelsList.Insert(3,''); S := 'C:\ComponentModels.Txt'; ModelsList.SaveToFile(S); ReportDocument := Client.OpenDocument('Text', S); If ReportDocument <> Nil Then Client.ShowDocument(ReportDocument); End; {..............................................................................} {..............................................................................} Procedure ExtractModelsFromComponents; Var CurrentSheet : ISch_Document; Iterator : ISch_Iterator; Component : ISch_Component; j : Integer; ImplIterator : ISch_Iterator; SchImplementation : ISch_Implementation; Modelslist : TStringList; ModelDataFile : ISch_ModelDatafileLink; Begin If SchServer = Nil Then Exit; CurrentSheet := SchServer.GetCurrentSchDocument; If CurrentSheet = Nil Then Exit; Iterator := CurrentSheet.SchIterator_Create; Iterator.AddFilter_ObjectSet(MkSet(eSchComponent)); Modelslist := TStringList.Create; Try Component := Iterator.FirstSchObject; While Component <> Nil Do Begin ModelsList.Add('Designator: ' + Component.Designator.Text); ModelsList.Add(' Library Reference: ' + Component.LibReference); ModelsList.Add(' Library Path: ' + Component.LibraryPath); ImplIterator := Component.SchIterator_Create; ImplIterator.AddFilter_ObjectSet(MkSet(eImplementation)); Try SchImplementation := ImplIterator.FirstSchObject; While SchImplementation <> Nil Do Begin ModelsList.Add(' Implementation Model details:'); ModelsList.Add(' ModelName: ' + SchImplementation.ModelName + ' ModelType: ' + SchImplementation.ModelType + ' Description: ' + SchImplementation.Description); ModelsList.Add(' Map: ' + SchImplementation.MapAsString); For j := 0 To SchImplementation.DatafileLinkCount - 1 Do Begin ModelDataFile := SchImplementation.DatafileLink[j]; If ModelDataFile <> Nil Then Begin ModelsList.Add(' Implemenation Data File Link Details:'); ModelsList.Add(' Data File Location: ' + ModelDataFile.Location + ', Entity Name: ' + ModelDataFile.EntityName + ', FileKind: ' + ModelDataFile.FileKind); ModelsList.Add(''); End; End; SchImplementation := ImplIterator.NextSchObject; End; Finally Component.SchIterator_Destroy(ImplIterator); End; ModelsList.Add(''); ModelsList.Add(''); Component := Iterator.NextSchObject; End; Finally CurrentSheet.SchIterator_Destroy(Iterator); End; GenerateModelsReport(ModelsList); Modelslist.Free; End; {..............................................................................} {..............................................................................}
42.71
98
0.461953
f1b743c146890a50850d243d60a1a9f9b1b0c329
53,728
pas
Pascal
gr32/GR32_MicroTiles.pas
mickyvac/fc-measure
0b6db36af01f25479a956138cfceddd02a88d14d
[ "MIT" ]
null
null
null
gr32/GR32_MicroTiles.pas
mickyvac/fc-measure
0b6db36af01f25479a956138cfceddd02a88d14d
[ "MIT" ]
null
null
null
gr32/GR32_MicroTiles.pas
mickyvac/fc-measure
0b6db36af01f25479a956138cfceddd02a88d14d
[ "MIT" ]
null
null
null
unit GR32_MicroTiles; (* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 or LGPL 2.1 with linking exception * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Alternatively, the contents of this file may be used under the terms of the * Free Pascal modified version of the GNU Lesser General Public License * Version 2.1 (the "FPC modified LGPL License"), in which case the provisions * of this license are applicable instead of those above. * Please see the file LICENSE.txt for additional information concerning this * license. * * The Original Code is MicroTiles Repaint Optimizer Extension for Graphics32 * * The Initial Developer of the Original Code is * Andre Beckedorf - metaException * Andre@metaException.de * * Portions created by the Initial Developer are Copyright (C) 2005-2009 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) interface {$I GR32.inc} {-$DEFINE CODESITE} {-$DEFINE CODESITE_HIGH} {-$DEFINE PROFILINGDRYRUN} {-$DEFINE MICROTILES_DEBUGDRAW} {-$DEFINE MICROTILES_DEBUGDRAW_RANDOM_COLORS} {-$DEFINE MICROTILES_DEBUGDRAW_UNOPTIMIZED} {-$DEFINE MICROTILES_NO_ADAPTION} {-$DEFINE MICROTILES_NO_ADAPTION_FORCE_WHOLETILES} uses {$IFDEF FPC} Types, {$IFDEF Windows} Windows, {$ENDIF} {$ELSE} Windows, {$ENDIF} {$IFDEF CODESITE} CSIntf, CSAux, {$ENDIF} {$IFDEF COMPILER2005_UP} Types, {$ENDIF} SysUtils, Classes, GR32, GR32_System, GR32_Containers, GR32_Layers, GR32_RepaintOpt; const MICROTILE_SHIFT = 5; MICROTILE_SIZE = 1 shl MICROTILE_SHIFT; MICROTILE_EMPTY = 0; // MICROTILE_EMPTY -> Left: 0, Top: 0, Right: 0, Bottom: 0 MICROTILE_FULL = MICROTILE_SIZE shl 8 or MICROTILE_SIZE; // MICROTILE_FULL -> Left: 0, Top: 0, Right: MICROTILE_SIZE, Bottom: MICROTILE_SIZE MicroTileSize = MaxInt div 16; {$IFDEF MICROTILES_DEBUGDRAW} clDebugDrawFill = TColor32($30FF0000); clDebugDrawFrame = TColor32($90FF0000); {$ENDIF} type PMicroTile = ^TMicroTile; TMicroTile = type Integer; PMicroTileArray = ^TMicroTileArray; TMicroTileArray = array[0..MicroTileSize - 1] of TMicroTile; PPMicroTiles = ^PMicroTiles; PMicroTiles = ^TMicroTiles; TMicroTiles = record BoundsRect: TRect; Columns, Rows: Integer; BoundsUsedTiles: TRect; Count: Integer; Tiles: PMicroTileArray; end; // MicroTile auxiliary routines function MakeMicroTile(const Left, Top, Right, Bottom: Integer): TMicroTile; {$IFDEF USEINLINING} inline; {$ENDIF} function MicroTileHeight(const Tile: TMicroTile): Integer; {$IFDEF USEINLINING} inline; {$ENDIF} function MicroTileWidth(const Tile: TMicroTile): Integer; {$IFDEF USEINLINING} inline; {$ENDIF} var MicroTileUnion: procedure(var DstTile: TMicroTile; const SrcTile: TMicroTile); // MicroTiles auxiliary routines function MakeEmptyMicroTiles: TMicroTiles; {$IFDEF USEINLINING} inline; {$ENDIF} procedure MicroTilesCreate(var MicroTiles: TMicroTiles); {$IFDEF USEINLINING} inline; {$ENDIF} procedure MicroTilesDestroy(var MicroTiles: TMicroTiles); {$IFDEF USEINLINING} inline; {$ENDIF} procedure MicroTilesSetSize(var MicroTiles: TMicroTiles; const DstRect: TRect); procedure MicroTilesClear(var MicroTiles: TMicroTiles; const Value: TMicroTile = MICROTILE_EMPTY); {$IFDEF USEINLINING} inline; {$ENDIF} procedure MicroTilesClearUsed(var MicroTiles: TMicroTiles; const Value: TMicroTile = MICROTILE_EMPTY); procedure MicroTilesCopy(var DstTiles: TMicroTiles; SrcTiles: TMicroTiles); procedure MicroTilesAddLine(var MicroTiles: TMicroTiles; X1, Y1, X2, Y2: Integer; LineWidth: Integer; RoundToWholeTiles: Boolean = False); procedure MicroTilesAddRect(var MicroTiles: TMicroTiles; Rect: TRect; RoundToWholeTiles: Boolean = False); procedure MicroTilesUnion(var DstTiles: TMicroTiles; const SrcTiles: TMicroTiles; RoundToWholeTiles: Boolean = False); function MicroTilesCalcRects(const MicroTiles: TMicroTiles; DstRects: TRectList; CountOnly: Boolean = False; RoundToWholeTiles: Boolean = False): Integer; overload; function MicroTilesCalcRects(const MicroTiles: TMicroTiles; DstRects: TRectList; const Clip: TRect; CountOnly: Boolean = False; RoundToWholeTiles: Boolean = False): Integer; overload; function MicroTilesCountEmptyTiles(const MicroTiles: TMicroTiles): Integer; type { TMicroTilesMap } { associative array that is used to map Layers to their MicroTiles } TMicroTilesMap = class(TPointerMap) private function GetData(Item: Pointer): PMicroTiles; procedure SetData(Item: Pointer; const Data: PMicroTiles); protected function Delete(BucketIndex: Integer; ItemIndex: Integer): Pointer; override; public function Add(Item: Pointer): PPMicroTiles; property Data[Item: Pointer]: PMicroTiles read GetData write SetData; default; end; type { TMicroTilesRepaintOptimizer } { Repaint manager that optimizes the repaint process using MicroTiles } TMicroTilesRepaintOptimizer = class(TCustomRepaintOptimizer) private // working tiles FBufferBounds: TRect; FWorkMicroTiles: PMicroTiles; // used by DrawLayerToMicroTiles FTempTiles: TMicroTiles; FInvalidTiles: TMicroTiles; FForcedInvalidTiles: TMicroTiles; // list of invalid layers FInvalidLayers: TList; // association that maps layers to their old invalid tiles FOldInvalidTilesMap: TMicroTilesMap; FWorkingTilesValid: Boolean; FOldInvalidTilesValid: Boolean; FUseInvalidTiles: Boolean; // adaptive stuff... FAdaptiveMode: Boolean; FPerfTimer: TPerfTimer; FPerformanceLevel: Integer; FElapsedTimeForLastRepaint: Int64; FElapsedTimeForFullSceneRepaint: Int64; FAdaptionFailed: Boolean; // vars for time based approach FTimedCheck: Boolean; FTimeDelta: Integer; FNextCheck: Integer; FElapsedTimeOnLastPenalty: Int64; // vars for invalid rect difference approach FOldInvalidRectsCount: Integer; {$IFDEF MICROTILES_DEBUGDRAW} FDebugWholeTiles: Boolean; FDebugMicroTiles: TMicroTiles; FDebugInvalidRects: TRectList; {$ENDIF} procedure DrawLayerToMicroTiles(var DstTiles: TMicroTiles; Layer: TCustomLayer); procedure DrawMeasuringHandler(Sender: TObject; const Area: TRect; const Info: Cardinal); procedure ValidateWorkingTiles; procedure UpdateOldInvalidTiles; procedure SetAdaptiveMode(const Value: Boolean); procedure ResetAdaptiveMode; procedure BeginAdaption; procedure EndAdaption; procedure AddArea(var Tiles: TMicroTiles; const Area: TRect; const Info: Cardinal); protected procedure SetEnabled(const Value: Boolean); override; // LayerCollection handler procedure LayerCollectionNotifyHandler(Sender: TLayerCollection; Action: TLayerListNotification; Layer: TCustomLayer; Index: Integer); override; public constructor Create(Buffer: TBitmap32; InvalidRects: TRectList); override; destructor Destroy; override; procedure RegisterLayerCollection(Layers: TLayerCollection); override; procedure UnregisterLayerCollection(Layers: TLayerCollection); override; procedure Reset; override; function UpdatesAvailable: Boolean; override; procedure PerformOptimization; override; procedure BeginPaintBuffer; override; procedure EndPaintBuffer; override; // handlers procedure AreaUpdateHandler(Sender: TObject; const Area: TRect; const Info: Cardinal); override; procedure LayerUpdateHandler(Sender: TObject; Layer: TCustomLayer); override; procedure BufferResizedHandler(const NewWidth, NewHeight: Integer); override; // custom settings: property AdaptiveMode: Boolean read FAdaptiveMode write SetAdaptiveMode; end; {$IFDEF CODESITE} TDebugMicroTilesRepaintOptimizer = class(TMicroTilesRepaintOptimizer) public procedure Reset; override; function UpdatesAvailable: Boolean; override; procedure PerformOptimization; override; procedure BeginPaintBuffer; override; procedure EndPaintBuffer; override; procedure AreaUpdateHandler(Sender: TObject; const Area: TRect; const Info: Cardinal); override; procedure LayerUpdateHandler(Sender: TObject; Layer: TCustomLayer); override; procedure BufferResizedHandler(const NewWidth, NewHeight: Integer); override; end; {$ENDIF} implementation uses GR32_Bindings, GR32_LowLevel, GR32_Math, Math; var MicroTilesU: procedure(var DstTiles: TMicroTiles; const SrcTiles: TMicroTiles); { MicroTile auxiliary routines } function MakeMicroTile(const Left, Top, Right, Bottom: Integer): TMicroTile; begin Result := Left shl 24 or Top shl 16 or Right shl 8 or Bottom; end; function MicroTileHeight(const Tile: TMicroTile): Integer; begin Result := (Tile and $FF) - (Tile shr 16 and $FF); end; function MicroTileWidth(const Tile: TMicroTile): Integer; begin Result := (Tile shr 8 and $FF) - (Tile shr 24); end; procedure MicroTileUnion_Pas(var DstTile: TMicroTile; const SrcTile: TMicroTile); var SrcLeft, SrcTop, SrcRight, SrcBottom: Integer; begin SrcLeft := SrcTile shr 24; SrcTop := (SrcTile and $FF0000) shr 16; SrcRight := (SrcTile and $FF00) shr 8; SrcBottom := SrcTile and $FF; if (DstTile <> MICROTILE_FULL) and (SrcTile <> MICROTILE_EMPTY) and (SrcRight - SrcLeft <> 0) and (SrcBottom - SrcTop <> 0) then begin if (DstTile = MICROTILE_EMPTY) or (SrcTile = MICROTILE_FULL) then DstTile := SrcTile else begin DstTile := Min(DstTile shr 24, SrcLeft) shl 24 or Min(DstTile shr 16 and $FF, SrcTop) shl 16 or Max(DstTile shr 8 and $FF, SrcRight) shl 8 or Max(DstTile and $FF, SrcBottom); end; end; end; {$IFDEF TARGET_x86} procedure MicroTileUnion_EMMX(var DstTile: TMicroTile; const SrcTile: TMicroTile); var SrcLeft, SrcTop, SrcRight, SrcBottom: Integer; begin SrcLeft := SrcTile shr 24; SrcTop := (SrcTile and $FF0000) shr 16; SrcRight := (SrcTile and $FF00) shr 8; SrcBottom := SrcTile and $FF; if (DstTile <> MICROTILE_FULL) and (SrcTile <> MICROTILE_EMPTY) and (SrcRight - SrcLeft <> 0) and (SrcBottom - SrcTop <> 0) then begin if (DstTile = MICROTILE_EMPTY) or (SrcTile = MICROTILE_FULL) then DstTile := SrcTile else asm MOVD MM1,[SrcTile] MOV EAX,[DstTile] MOVD MM2, [EAX] MOVQ MM3, MM1 MOV ECX,$FFFF0000 // Mask MOVD MM0, ECX PMINUB MM1, MM2 PAND MM1, MM0 PSRLD MM0, 16 // shift mask right by 16 bits PMAXUB MM2, MM3 PAND MM2, MM0 POR MM1, MM2 MOVD [EAX], MM1 EMMS end; end; end; {$ENDIF} { MicroTiles auxiliary routines } function MakeEmptyMicroTiles: TMicroTiles; begin FillChar(Result, SizeOf(TMicroTiles), 0); ReallocMem(Result.Tiles, 0); end; procedure MicroTilesCreate(var MicroTiles: TMicroTiles); begin FillChar(MicroTiles, SizeOf(TMicroTiles), 0); ReallocMem(MicroTiles.Tiles, 0); end; procedure MicroTilesDestroy(var MicroTiles: TMicroTiles); begin ReallocMem(MicroTiles.Tiles, 0); end; procedure MicroTilesSetSize(var MicroTiles: TMicroTiles; const DstRect: TRect); begin MicroTiles.BoundsRect := DstRect; MicroTiles.Columns := ((DstRect.Right - DstRect.Left) shr MICROTILE_SHIFT) + 1; MicroTiles.Rows := ((DstRect.Bottom - DstRect.Top) shr MICROTILE_SHIFT) + 1; MicroTiles.Count := (MicroTiles.Columns + 1) * (MicroTiles.Rows + 1); ReallocMem(MicroTiles.Tiles, MicroTiles.Count * SizeOf(TMicroTile)); MicroTilesClear(MicroTiles) end; procedure MicroTilesClear(var MicroTiles: TMicroTiles; const Value: TMicroTile); begin MicroTiles.BoundsUsedTiles := MakeRect(MicroTiles.Columns, MicroTiles.Rows, 0, 0); FillLongword(MicroTiles.Tiles^[0], MicroTiles.Count, Value); end; procedure MicroTilesClearUsed(var MicroTiles: TMicroTiles; const Value: TMicroTile); var I: Integer; begin for I := MicroTiles.BoundsUsedTiles.Top to MicroTiles.BoundsUsedTiles.Bottom do FillLongword(MicroTiles.Tiles^[I * MicroTiles.Columns + MicroTiles.BoundsUsedTiles.Left], MicroTiles.BoundsUsedTiles.Right - MicroTiles.BoundsUsedTiles.Left + 1, Value); MicroTiles.BoundsUsedTiles := MakeRect(MicroTiles.Columns, MicroTiles.Rows, 0, 0); end; procedure MicroTilesCopy(var DstTiles: TMicroTiles; SrcTiles: TMicroTiles); var CurRow, Width: Integer; SrcTilePtr, DstTilePtr: PMicroTile; begin if Assigned(DstTiles.Tiles) and (DstTiles.Count > 0) then MicroTilesClearUsed(DstTiles); DstTiles.BoundsRect := SrcTiles.BoundsRect; DstTiles.Columns := SrcTiles.Columns; DstTiles.Rows := SrcTiles.Rows; DstTiles.BoundsUsedTiles := SrcTiles.BoundsUsedTiles; ReallocMem(DstTiles.Tiles, SrcTiles.Count * SizeOf(TMicroTile)); if DstTiles.Count < SrcTiles.Count then FillLongword(DstTiles.Tiles^[DstTiles.Count], SrcTiles.Count - DstTiles.Count, MICROTILE_EMPTY); DstTiles.Count := SrcTiles.Count; SrcTilePtr := @SrcTiles.Tiles^[SrcTiles.BoundsUsedTiles.Top * SrcTiles.Columns + SrcTiles.BoundsUsedTiles.Left]; DstTilePtr := @DstTiles.Tiles^[SrcTiles.BoundsUsedTiles.Top * DstTiles.Columns + SrcTiles.BoundsUsedTiles.Left]; Width := SrcTiles.BoundsUsedTiles.Right - SrcTiles.BoundsUsedTiles.Left + 1; for CurRow := SrcTiles.BoundsUsedTiles.Top to SrcTiles.BoundsUsedTiles.Bottom do begin MoveLongword(SrcTilePtr^, DstTilePtr^, Width); Inc(DstTilePtr, DstTiles.Columns); Inc(SrcTilePtr, SrcTiles.Columns); end end; procedure MicroTilesAddLine(var MicroTiles: TMicroTiles; X1, Y1, X2, Y2: Integer; LineWidth: Integer; RoundToWholeTiles: Boolean = False); var I: Integer; Dx, Dy: Integer; Sx, Sy: Integer; DeltaX, DeltaY: Integer; Rects: Integer; NewX, NewY: Integer; TempRect: TRect; Swapped: Boolean; begin Dx := X2 - X1; Dy := Y2 - Y1; LineWidth := LineWidth shl 1; if Dx > 0 then Sx := 1 else if Dx < 0 then begin Dx := -Dx; Sx := -1; end else // Dx = 0 begin TempRect := MakeRect(X1, Y1, X2, Y2); InflateArea(TempRect, LineWidth, LineWidth); MicroTilesAddRect(MicroTiles, TempRect, RoundToWholeTiles); Exit; end; if Dy > 0 then Sy := 1 else if Dy < 0 then begin Dy := -Dy; Sy := -1; end else // Dy = 0 begin TempRect := MakeRect(X1, Y1, X2, Y2); InflateArea(TempRect, LineWidth, LineWidth); MicroTilesAddRect(MicroTiles, TempRect, RoundToWholeTiles); Exit; end; X1 := X1 * FixedOne; Y1 := Y1 * FixedOne; Dx := Dx * FixedOne; Dy := Dy * FixedOne; if Dx < Dy then begin Swapped := True; Swap(Dx, Dy); end else Swapped := False; Rects := Dx div MICROTILE_SIZE; DeltaX := MICROTILE_SIZE * FixedOne; DeltaY := FixedDiv(Dy, Rects); if Swapped then Swap(DeltaX, DeltaY); DeltaX := Sx * DeltaX; DeltaY := Sy * DeltaY; for I := 1 to FixedCeil(Rects) do begin NewX := X1 + DeltaX; NewY := Y1 + DeltaY; TempRect := MakeRect(FixedRect(X1, Y1, NewX, NewY)); InflateArea(TempRect, LineWidth, LineWidth); MicroTilesAddRect(MicroTiles, TempRect, RoundToWholeTiles); X1 := NewX; Y1 := NewY; end; end; procedure MicroTilesAddRect(var MicroTiles: TMicroTiles; Rect: TRect; RoundToWholeTiles: Boolean); var ModLeft, ModRight, ModTop, ModBottom, Temp: Integer; LeftTile, TopTile, RightTile, BottomTile, ColSpread, RowSpread: Integer; CurRow, CurCol: Integer; TilePtr, TilePtr2: PMicroTile; begin if MicroTiles.Count = 0 then Exit; with Rect do begin TestSwap(Left, Right); TestSwap(Top, Bottom); if Left < 0 then Left := 0; if Top < 0 then Top := 0; Temp := MicroTiles.Columns shl MICROTILE_SHIFT; if Right > Temp then Right := Temp; Temp := MicroTiles.Rows shl MICROTILE_SHIFT; if Bottom > Temp then Bottom := Temp; if (Left > Right) or (Top > Bottom) then Exit; end; LeftTile := Rect.Left shr MICROTILE_SHIFT; TopTile := Rect.Top shr MICROTILE_SHIFT; RightTile := Rect.Right shr MICROTILE_SHIFT; BottomTile := Rect.Bottom shr MICROTILE_SHIFT; TilePtr := @MicroTiles.Tiles^[TopTile * MicroTiles.Columns + LeftTile]; if RoundToWholeTiles then begin for CurRow := TopTile to BottomTile do begin FillLongword(TilePtr^, RightTile - LeftTile + 1, MICROTILE_FULL); Inc(TilePtr, MicroTiles.Columns); end; end else begin // calculate number of tiles needed in columns and rows ColSpread := ((Rect.Right + MICROTILE_SIZE) shr MICROTILE_SHIFT) - (Rect.Left shr MICROTILE_SHIFT); RowSpread := ((Rect.Bottom + MICROTILE_SIZE) shr MICROTILE_SHIFT) - (Rect.Top shr MICROTILE_SHIFT); ModLeft := Rect.Left mod MICROTILE_SIZE; ModTop := Rect.Top mod MICROTILE_SIZE; ModRight := Rect.Right mod MICROTILE_SIZE; ModBottom := Rect.Bottom mod MICROTILE_SIZE; if (ColSpread = 1) and (RowSpread = 1) then MicroTileUnion(TilePtr^, MakeMicroTile(ModLeft, ModTop, ModRight, ModBottom)) else if ColSpread = 1 then begin MicroTileUnion(TilePtr^, MakeMicroTile(ModLeft, ModTop, ModRight, MICROTILE_SIZE)); Inc(TilePtr, MicroTiles.Columns); if RowSpread > 2 then for CurCol := TopTile + 1 to BottomTile - 1 do begin MicroTileUnion(TilePtr^, MakeMicroTile(ModLeft, 0, ModRight, MICROTILE_SIZE)); Inc(TilePtr, MicroTiles.Columns); end; MicroTileUnion(TilePtr^, MakeMicroTile(ModLeft, 0, ModRight, ModBottom)); end else if RowSpread = 1 then begin MicroTileUnion(TilePtr^, MakeMicroTile(ModLeft, ModTop, MICROTILE_SIZE, ModBottom)); Inc(TilePtr); if ColSpread > 2 then for CurRow := LeftTile + 1 to RightTile - 1 do begin MicroTileUnion(TilePtr^, MakeMicroTile(0, ModTop, MICROTILE_SIZE, ModBottom)); Inc(TilePtr); end; MicroTileUnion(TilePtr^, MakeMicroTile(0, ModTop, ModRight, ModBottom)); end else begin TilePtr2 := TilePtr; // TOP: // render top-left corner MicroTileUnion(TilePtr2^, MakeMicroTile(ModLeft, ModTop, MICROTILE_SIZE, MICROTILE_SIZE)); Inc(TilePtr2); // render top edge if ColSpread > 2 then for CurRow := LeftTile + 1 to RightTile - 1 do begin MicroTileUnion(TilePtr2^, MakeMicroTile(0, ModTop, MICROTILE_SIZE, MICROTILE_SIZE)); Inc(TilePtr2); end; // render top-right corner MicroTileUnion(TilePtr2^, MakeMicroTile(0, ModTop, ModRight, MICROTILE_SIZE)); Inc(TilePtr, MicroTiles.Columns); // INTERMEDIATE AREA: if RowSpread > 2 then for CurCol := TopTile + 1 to BottomTile - 1 do begin TilePtr2 := TilePtr; // render left edge MicroTileUnion(TilePtr2^, MakeMicroTile(ModLeft, 0, MICROTILE_SIZE, MICROTILE_SIZE)); Inc(TilePtr2); // render content if ColSpread > 2 then begin FillLongword(TilePtr2^, RightTile - LeftTile - 1, MICROTILE_FULL); Inc(TilePtr2, RightTile - LeftTile - 1); end; // render right edge MicroTileUnion(TilePtr2^, MakeMicroTile(0, 0, ModRight, MICROTILE_SIZE)); Inc(TilePtr, MicroTiles.Columns); end; TilePtr2 := TilePtr; // BOTTOM: // render bottom-left corner MicroTileUnion(TilePtr2^, MakeMicroTile(ModLeft, 0, MICROTILE_SIZE, ModBottom)); Inc(TilePtr2); // render bottom edge if ColSpread > 2 then for CurRow := LeftTile + 1 to RightTile - 1 do begin MicroTileUnion(TilePtr2^, MakeMicroTile(0, 0, MICROTILE_SIZE, ModBottom)); Inc(TilePtr2); end; // render bottom-right corner MicroTileUnion(TilePtr2^, MakeMicroTile(0, 0, ModRight, ModBottom)); end; end; with MicroTiles.BoundsUsedTiles do begin if LeftTile < Left then Left := LeftTile; if TopTile < Top then Top := TopTile; if RightTile > Right then Right := RightTile; if BottomTile > Bottom then Bottom := BottomTile; end; end; procedure MicroTilesUnion_Pas(var DstTiles: TMicroTiles; const SrcTiles: TMicroTiles); var SrcTilePtr, DstTilePtr: PMicroTile; SrcTilePtr2, DstTilePtr2: PMicroTile; X, Y: Integer; SrcLeft, SrcTop, SrcRight, SrcBottom: Integer; SrcTile: TMicroTile; begin SrcTilePtr := @SrcTiles.Tiles^[SrcTiles.BoundsUsedTiles.Top * SrcTiles.Columns + SrcTiles.BoundsUsedTiles.Left]; DstTilePtr := @DstTiles.Tiles^[SrcTiles.BoundsUsedTiles.Top * DstTiles.Columns + SrcTiles.BoundsUsedTiles.Left]; for Y := SrcTiles.BoundsUsedTiles.Top to SrcTiles.BoundsUsedTiles.Bottom do begin SrcTilePtr2 := SrcTilePtr; DstTilePtr2 := DstTilePtr; for X := SrcTiles.BoundsUsedTiles.Left to SrcTiles.BoundsUsedTiles.Right do begin SrcTile := SrcTilePtr2^; SrcLeft := SrcTile shr 24; SrcTop := (SrcTile and $FF0000) shr 16; SrcRight := (SrcTile and $FF00) shr 8; SrcBottom := SrcTile and $FF; if (DstTilePtr2^ <> MICROTILE_FULL) and (SrcTilePtr2^ <> MICROTILE_EMPTY) and (SrcRight - SrcLeft <> 0) and (SrcBottom - SrcTop <> 0) then begin if (DstTilePtr2^ = MICROTILE_EMPTY) or (SrcTilePtr2^ = MICROTILE_FULL) then DstTilePtr2^ := SrcTilePtr2^ else DstTilePtr2^ := Min(DstTilePtr2^ shr 24, SrcLeft) shl 24 or Min(DstTilePtr2^ shr 16 and $FF, SrcTop) shl 16 or Max(DstTilePtr2^ shr 8 and $FF, SrcRight) shl 8 or Max(DstTilePtr2^ and $FF, SrcBottom); end; Inc(DstTilePtr2); Inc(SrcTilePtr2); end; Inc(DstTilePtr, DstTiles.Columns); Inc(SrcTilePtr, SrcTiles.Columns); end; end; {$IFDEF TARGET_x86} procedure MicroTilesUnion_EMMX(var DstTiles: TMicroTiles; const SrcTiles: TMicroTiles); var SrcTilePtr, DstTilePtr: PMicroTile; SrcTilePtr2, DstTilePtr2: PMicroTile; X, Y: Integer; SrcLeft, SrcTop, SrcRight, SrcBottom: Integer; begin SrcTilePtr := @SrcTiles.Tiles^[SrcTiles.BoundsUsedTiles.Top * SrcTiles.Columns + SrcTiles.BoundsUsedTiles.Left]; DstTilePtr := @DstTiles.Tiles^[SrcTiles.BoundsUsedTiles.Top * DstTiles.Columns + SrcTiles.BoundsUsedTiles.Left]; asm MOV ECX, $FFFF // Mask MOVD MM0, ECX MOVQ MM4, MM0 PSLLD MM4, 16 // shift mask left by 16 bits end; for Y := SrcTiles.BoundsUsedTiles.Top to SrcTiles.BoundsUsedTiles.Bottom do begin SrcTilePtr2 := SrcTilePtr; DstTilePtr2 := DstTilePtr; for X := SrcTiles.BoundsUsedTiles.Left to SrcTiles.BoundsUsedTiles.Right do begin SrcLeft := SrcTilePtr2^ shr 24; SrcTop := (SrcTilePtr2^ and $FF0000) shr 16; SrcRight := (SrcTilePtr2^ and $FF00) shr 8; SrcBottom := SrcTilePtr2^ and $FF; if (DstTilePtr2^ <> MICROTILE_FULL) and (SrcTilePtr2^ <> MICROTILE_EMPTY) and (SrcRight - SrcLeft <> 0) and (SrcBottom - SrcTop <> 0) then begin if (DstTilePtr2^ = MICROTILE_EMPTY) or (SrcTilePtr2^ = MICROTILE_FULL) then DstTilePtr2^ := SrcTilePtr2^ else asm MOV EAX, [DstTilePtr2] MOVD MM2, [EAX] MOV ECX, [SrcTilePtr2] MOVD MM1, [ECX] MOVQ MM3, MM1 PMINUB MM1, MM2 PAND MM1, MM4 PMAXUB MM2, MM3 PAND MM2, MM0 POR MM1, MM2 MOVD [EAX], MM1 end; end; Inc(DstTilePtr2); Inc(SrcTilePtr2); end; Inc(DstTilePtr, DstTiles.Columns); Inc(SrcTilePtr, SrcTiles.Columns); end; asm db $0F,$77 /// EMMS end; end; {$ENDIF} procedure MicroTilesUnion(var DstTiles: TMicroTiles; const SrcTiles: TMicroTiles; RoundToWholeTiles: Boolean); var SrcTilePtr, DstTilePtr: PMicroTile; SrcTilePtr2, DstTilePtr2: PMicroTile; X, Y: Integer; SrcLeft, SrcTop, SrcRight, SrcBottom: Integer; begin if SrcTiles.Count = 0 then Exit; if RoundToWholeTiles then begin SrcTilePtr := @SrcTiles.Tiles^[SrcTiles.BoundsUsedTiles.Top * SrcTiles.Columns + SrcTiles.BoundsUsedTiles.Left]; DstTilePtr := @DstTiles.Tiles^[SrcTiles.BoundsUsedTiles.Top * DstTiles.Columns + SrcTiles.BoundsUsedTiles.Left]; for Y := SrcTiles.BoundsUsedTiles.Top to SrcTiles.BoundsUsedTiles.Bottom do begin SrcTilePtr2 := SrcTilePtr; DstTilePtr2 := DstTilePtr; for X := SrcTiles.BoundsUsedTiles.Left to SrcTiles.BoundsUsedTiles.Right do begin SrcLeft := SrcTilePtr2^ shr 24; SrcTop := (SrcTilePtr2^ and $FF0000) shr 16; SrcRight := (SrcTilePtr2^ and $FF00) shr 8; SrcBottom := SrcTilePtr2^ and $FF; if (DstTilePtr2^ <> MICROTILE_FULL) and (SrcTilePtr2^ <> MICROTILE_EMPTY) and (SrcRight - SrcLeft <> 0) and (SrcBottom - SrcTop <> 0) then DstTilePtr2^ := MICROTILE_FULL; Inc(DstTilePtr2); Inc(SrcTilePtr2); end; Inc(DstTilePtr, DstTiles.Columns); Inc(SrcTilePtr, SrcTiles.Columns); end end else MicroTilesU(DstTiles, SrcTiles); with DstTiles.BoundsUsedTiles do begin if SrcTiles.BoundsUsedTiles.Left < Left then Left := SrcTiles.BoundsUsedTiles.Left; if SrcTiles.BoundsUsedTiles.Top < Top then Top := SrcTiles.BoundsUsedTiles.Top; if SrcTiles.BoundsUsedTiles.Right > Right then Right := SrcTiles.BoundsUsedTiles.Right; if SrcTiles.BoundsUsedTiles.Bottom > Bottom then Bottom := SrcTiles.BoundsUsedTiles.Bottom; end; end; function MicroTilesCalcRects(const MicroTiles: TMicroTiles; DstRects: TRectList; CountOnly, RoundToWholeTiles: Boolean): Integer; begin Result := MicroTilesCalcRects(MicroTiles, DstRects, MicroTiles.BoundsRect, CountOnly); end; function MicroTilesCalcRects(const MicroTiles: TMicroTiles; DstRects: TRectList; const Clip: TRect; CountOnly, RoundToWholeTiles: Boolean): Integer; var Rects: Array Of TRect; Rect: PRect; CombLUT: Array Of Integer; StartIndex: Integer; CurTile, TempTile: TMicroTile; Temp: Integer; NewLeft, NewTop, NewRight, NewBottom: Integer; CurCol, CurRow, I, RectsCount: Integer; begin Result := 0; if (MicroTiles.Count = 0) or (MicroTiles.BoundsUsedTiles.Right - MicroTiles.BoundsUsedTiles.Left < 0) or (MicroTiles.BoundsUsedTiles.Bottom - MicroTiles.BoundsUsedTiles.Top < 0) then Exit; SetLength(Rects, MicroTiles.Columns * MicroTiles.Rows); SetLength(CombLUT, MicroTiles.Columns * MicroTiles.Rows); FillLongword(CombLUT[0], Length(CombLUT), Cardinal(-1)); I := 0; RectsCount := 0; if not RoundToWholeTiles then for CurRow := 0 to MicroTiles.Rows - 1 do begin CurCol := 0; while CurCol < MicroTiles.Columns do begin CurTile := MicroTiles.Tiles[I]; if CurTile <> MICROTILE_EMPTY then begin Temp := CurRow shl MICROTILE_SHIFT; NewTop := Constrain(Temp + CurTile shr 16 and $FF, Clip.Top, Clip.Bottom); NewBottom := Constrain(Temp + CurTile and $FF, Clip.Top, Clip.Bottom); NewLeft := Constrain(CurCol shl MICROTILE_SHIFT + CurTile shr 24, Clip.Left, Clip.Right); StartIndex := I; if (CurTile shr 8 and $FF = MICROTILE_SIZE) and (CurCol <> MicroTiles.Columns - 1) then begin while True do begin Inc(CurCol); Inc(I); TempTile := MicroTiles.Tiles[I]; if (CurCol = MicroTiles.Columns) or (TempTile shr 16 and $FF <> CurTile shr 16 and $FF) or (TempTile and $FF <> CurTile and $FF) or (TempTile shr 24 <> 0) then begin Dec(CurCol); Dec(I); Break; end; end; end; NewRight := Constrain(CurCol shl MICROTILE_SHIFT + MicroTiles.Tiles[I] shr 8 and $FF, Clip.Left, Clip.Right); Temp := CombLUT[StartIndex]; Rect := nil; if Temp <> -1 then Rect := @Rects[Temp]; if Assigned(Rect) and (Rect.Left = NewLeft) and (Rect.Right = NewRight) and (Rect.Bottom = NewTop) then begin Rect.Bottom := NewBottom; if CurRow <> MicroTiles.Rows - 1 then CombLUT[StartIndex + MicroTiles.Columns] := Temp; end else with Rects[RectsCount] do begin Left := NewLeft; Top := NewTop; Right := NewRight; Bottom := NewBottom; if CurRow <> MicroTiles.Rows - 1 then CombLUT[StartIndex + MicroTiles.Columns] := RectsCount; Inc(RectsCount); end; end; Inc(I); Inc(CurCol); end; end else for CurRow := 0 to MicroTiles.Rows - 1 do begin CurCol := 0; while CurCol < MicroTiles.Columns do begin CurTile := MicroTiles.Tiles[I]; if CurTile <> MICROTILE_EMPTY then begin Temp := CurRow shl MICROTILE_SHIFT; NewTop := Constrain(Temp, Clip.Top, Clip.Bottom); NewBottom := Constrain(Temp + MICROTILE_SIZE, Clip.Top, Clip.Bottom); NewLeft := Constrain(CurCol shl MICROTILE_SHIFT, Clip.Left, Clip.Right); StartIndex := I; if CurCol <> MicroTiles.Columns - 1 then begin while True do begin Inc(CurCol); Inc(I); TempTile := MicroTiles.Tiles[I]; if (CurCol = MicroTiles.Columns) or (TempTile = MICROTILE_EMPTY) then begin Dec(CurCol); Dec(I); Break; end; end; end; NewRight := Constrain(CurCol shl MICROTILE_SHIFT + MICROTILE_SIZE, Clip.Left, Clip.Right); Temp := CombLUT[StartIndex]; Rect := nil; if Temp <> -1 then Rect := @Rects[Temp]; if Assigned(Rect) and (Rect.Left = NewLeft) and (Rect.Right = NewRight) and (Rect.Bottom = NewTop) then begin Rect.Bottom := NewBottom; if CurRow <> MicroTiles.Rows - 1 then CombLUT[StartIndex + MicroTiles.Columns] := Temp; end else with Rects[RectsCount] do begin Left := NewLeft; Top := NewTop; Right := NewRight; Bottom := NewBottom; if CurRow <> MicroTiles.Rows - 1 then CombLUT[StartIndex + MicroTiles.Columns] := RectsCount; Inc(RectsCount); end; end; Inc(I); Inc(CurCol); end; end; Result := RectsCount; if not CountOnly then for I := 0 to RectsCount - 1 do DstRects.Add(Rects[I]); end; function MicroTilesCountEmptyTiles(const MicroTiles: TMicroTiles): Integer; var CurRow, CurCol: Integer; TilePtr: PMicroTile; begin Result := 0; if MicroTiles.Count > 0 then begin TilePtr := @MicroTiles.Tiles^[0]; for CurRow := 0 to MicroTiles.Rows - 1 do for CurCol := 0 to MicroTiles.Columns - 1 do begin if TilePtr^ = MICROTILE_EMPTY then Inc(Result); Inc(TilePtr); end; end; end; {$IFDEF MICROTILES_DEBUGDRAW} procedure MicroTilesDebugDraw(const MicroTiles: TMicroTiles; DstBitmap: TBitmap32; DrawOptimized, RoundToWholeTiles: Boolean); var I: Integer; TempRect: TRect; Rects: TRectList; C1, C2: TColor32; begin {$IFDEF MICROTILES_DEBUGDRAW_RANDOM_COLORS} C1 := Random(MaxInt) AND $00FFFFFF; C2 := C1 OR $90000000; C1 := C1 OR $30000000; {$ELSE} C1 := clDebugDrawFill; C2 := clDebugDrawFrame; {$ENDIF} if DrawOptimized then begin Rects := TRectList.Create; MicroTilesCalcRects(MicroTiles, Rects, False, RoundToWholeTiles); try if Rects.Count > 0 then begin for I := 0 to Rects.Count - 1 do begin DstBitmap.FillRectTS(Rects[I]^, C1); DstBitmap.FrameRectTS(Rects[I]^, C2); end; end finally Rects.Free; end; end else for I := 0 to MicroTiles.Count - 1 do begin if MicroTiles.Tiles^[i] <> MICROTILE_EMPTY then begin TempRect.Left := ((I mod MicroTiles.Columns) shl MICROTILE_SHIFT) + (MicroTiles.Tiles[i] shr 24); TempRect.Top := ((I div MicroTiles.Columns) shl MICROTILE_SHIFT) + (MicroTiles.Tiles[i] shr 16 and $FF); TempRect.Right := ((I mod MicroTiles.Columns) shl MICROTILE_SHIFT) + (MicroTiles.Tiles[i] shr 8 and $FF); TempRect.Bottom := ((I div MicroTiles.Columns) shl MICROTILE_SHIFT) + (MicroTiles.Tiles[i] and $FF); DstBitmap.FillRectTS(TempRect, C1); DstBitmap.FrameRectTS(TempRect, C2); end; end; end; {$ENDIF} { TMicroTilesMap } function TMicroTilesMap.Add(Item: Pointer): PPMicroTiles; var TilesPtr: PMicroTiles; IsNew: Boolean; begin Result := PPMicroTiles(inherited Add(Item, IsNew)); if IsNew then begin New(TilesPtr); MicroTilesCreate(TilesPtr^); Result^ := TilesPtr; end; end; function TMicroTilesMap.Delete(BucketIndex, ItemIndex: Integer): Pointer; var TilesPtr: PMicroTiles; begin TilesPtr := inherited Delete(BucketIndex, ItemIndex); MicroTilesDestroy(TilesPtr^); Dispose(TilesPtr); Result := nil; end; procedure TMicroTilesMap.SetData(Item: Pointer; const Data: PMicroTiles); begin inherited SetData(Item, Data); end; function TMicroTilesMap.GetData(Item: Pointer): PMicroTiles; begin Result := inherited GetData(Item); end; { TMicroTilesRepaintManager } type TLayerCollectionAccess = class(TLayerCollection); TCustomLayerAccess = class(TCustomLayer); const PL_MICROTILES = 0; PL_WHOLETILES = 1; PL_FULLSCENE = 2; TIMER_PENALTY = 250; TIMER_LOWLIMIT = 1000; TIMER_HIGHLIMIT = 5000; INVALIDRECTS_DELTA = 10; constructor TMicroTilesRepaintOptimizer.Create(Buffer: TBitmap32; InvalidRects: TRectList); begin inherited; FOldInvalidTilesMap := TMicroTilesMap.Create; FInvalidLayers := TList.Create; FPerfTimer := TPerfTimer.Create; {$IFNDEF MICROTILES_DEBUGDRAW} {$IFNDEF MICROTILES_NO_ADAPTION} FAdaptiveMode := True; {$ENDIF} {$ENDIF} MicroTilesCreate(FInvalidTiles); MicroTilesCreate(FTempTiles); MicroTilesCreate(FForcedInvalidTiles); {$IFDEF MICROTILES_DEBUGDRAW} MicroTilesCreate(FDebugMicroTiles); FDebugInvalidRects := TRectList.Create; {$ENDIF} end; destructor TMicroTilesRepaintOptimizer.Destroy; begin MicroTilesDestroy(FForcedInvalidTiles); MicroTilesDestroy(FTempTiles); MicroTilesDestroy(FInvalidTiles); FPerfTimer.Free; FInvalidLayers.Free; FOldInvalidTilesMap.Free; {$IFDEF MICROTILES_DEBUGDRAW} FDebugInvalidRects.Free; MicroTilesDestroy(FDebugMicroTiles); {$ENDIF} inherited; end; procedure TMicroTilesRepaintOptimizer.AreaUpdateHandler(Sender: TObject; const Area: TRect; const Info: Cardinal); begin ValidateWorkingTiles; AddArea(FForcedInvalidTiles, Area, Info); FUseInvalidTiles := True; end; procedure TMicroTilesRepaintOptimizer.AddArea(var Tiles: TMicroTiles; const Area: TRect; const Info: Cardinal); var LineWidth: Integer; TempRect: TRect; begin if Info and AREAINFO_LINE <> 0 then begin LineWidth := Info and $00FFFFFF; TempRect := Area; InflateArea(TempRect, LineWidth, LineWidth); with TempRect do MicroTilesAddLine(Tiles, Left, Top, Right, Bottom, LineWidth, FPerformanceLevel > PL_MICROTILES); end else MicroTilesAddRect(Tiles, Area, FPerformanceLevel > PL_MICROTILES); end; procedure TMicroTilesRepaintOptimizer.LayerUpdateHandler(Sender: TObject; Layer: TCustomLayer); begin if FOldInvalidTilesValid and not TCustomLayerAccess(Layer).Invalid then begin FInvalidLayers.Add(Layer); TCustomLayerAccess(Layer).Invalid := True; FUseInvalidTiles := True; end; end; procedure TMicroTilesRepaintOptimizer.LayerCollectionNotifyHandler(Sender: TLayerCollection; Action: TLayerListNotification; Layer: TCustomLayer; Index: Integer); var TilesPtr: PMicroTiles; begin case Action of lnLayerAdded, lnLayerInserted: begin TilesPtr := FOldInvalidTilesMap.Add(Layer)^; MicroTilesSetSize(TilesPtr^, Buffer.BoundsRect); FOldInvalidTilesValid := True; end; lnLayerDeleted: begin if FOldInvalidTilesValid then begin // force repaint of tiles that the layer did previously allocate MicroTilesUnion(FInvalidTiles, FOldInvalidTilesMap[Layer]^); FUseInvalidTiles := True; end; FInvalidLayers.Remove(Layer); FOldInvalidTilesMap.Remove(Layer); end; lnCleared: begin if FOldInvalidTilesValid then begin with TPointerMapIterator.Create(FOldInvalidTilesMap) do try while Next do MicroTilesUnion(FInvalidTiles, PMicroTiles(Data)^); finally Free; end; FUseInvalidTiles := True; ResetAdaptiveMode; end; FOldInvalidTilesMap.Clear; FOldInvalidTilesValid := True; end; end; end; procedure TMicroTilesRepaintOptimizer.ValidateWorkingTiles; begin if not FWorkingTilesValid then // check if working microtiles need resize... begin MicroTilesSetSize(FTempTiles, FBufferBounds); MicroTilesSetSize(FInvalidTiles, FBufferBounds); MicroTilesSetSize(FForcedInvalidTiles, FBufferBounds); FWorkingTilesValid := True; end; end; procedure TMicroTilesRepaintOptimizer.BufferResizedHandler(const NewWidth, NewHeight: Integer); begin FBufferBounds := MakeRect(0, 0, NewWidth, NewHeight); Reset; end; procedure TMicroTilesRepaintOptimizer.Reset; begin FWorkingTilesValid := False; // force resizing of working microtiles FOldInvalidTilesValid := False; // force resizing and rerendering of invalid tiles UpdateOldInvalidTiles; // mark whole buffer area invalid... MicroTilesClear(FForcedInvalidTiles, MICROTILE_FULL); FForcedInvalidTiles.BoundsUsedTiles := MakeRect(0, 0, FForcedInvalidTiles.Columns, FForcedInvalidTiles.Rows); FUseInvalidTiles := True; end; function TMicroTilesRepaintOptimizer.UpdatesAvailable: Boolean; begin UpdateOldInvalidTiles; Result := FUseInvalidTiles; end; procedure TMicroTilesRepaintOptimizer.UpdateOldInvalidTiles; var I, J: Integer; TilesPtr: PMicroTiles; Layer: TCustomLayer; begin if not FOldInvalidTilesValid then // check if old Invalid tiles need resize and rerendering... begin ValidateWorkingTiles; for I := 0 to LayerCollections.Count - 1 do with TLayerCollection(LayerCollections[I]) do for J := 0 to Count - 1 do begin Layer := Items[J]; TilesPtr := FOldInvalidTilesMap.Add(Layer)^; MicroTilesSetSize(TilesPtr^, FBufferBounds); DrawLayerToMicroTiles(TilesPtr^, Layer); TCustomLayerAccess(Layer).Invalid := False; end; FInvalidLayers.Clear; FOldInvalidTilesValid := True; FUseInvalidTiles := False; end; end; procedure TMicroTilesRepaintOptimizer.RegisterLayerCollection(Layers: TLayerCollection); begin inherited; if Enabled then with TLayerCollectionAccess(Layers) do begin OnLayerUpdated := LayerUpdateHandler; OnAreaUpdated := AreaUpdateHandler; OnListNotify := LayerCollectionNotifyHandler; end; end; procedure TMicroTilesRepaintOptimizer.UnregisterLayerCollection(Layers: TLayerCollection); begin with TLayerCollectionAccess(Layers) do begin OnLayerUpdated := nil; OnAreaUpdated := nil; OnListNotify := nil; end; inherited; end; procedure TMicroTilesRepaintOptimizer.SetEnabled(const Value: Boolean); var I: Integer; begin if Value <> Enabled then begin if Value then begin // initialize: for I := 0 to LayerCollections.Count - 1 do with TLayerCollectionAccess(LayerCollections[I]) do begin OnLayerUpdated := LayerUpdateHandler; OnAreaUpdated := AreaUpdateHandler; OnListNotify := LayerCollectionNotifyHandler; end; BufferResizedHandler(Buffer.Width, Buffer.Height); end else begin // clean up: for I := 0 to LayerCollections.Count - 1 do with TLayerCollectionAccess(LayerCollections[I]) do begin OnLayerUpdated := nil; OnAreaUpdated := nil; OnListNotify := nil; end; MicroTilesDestroy(FInvalidTiles); MicroTilesDestroy(FTempTiles); MicroTilesDestroy(FForcedInvalidTiles); FUseInvalidTiles := False; FOldInvalidTilesValid := False; FOldInvalidTilesMap.Clear; FInvalidLayers.Clear; end; inherited; end; end; procedure TMicroTilesRepaintOptimizer.SetAdaptiveMode(const Value: Boolean); begin if FAdaptiveMode <> Value then begin FAdaptiveMode := Value; ResetAdaptiveMode; end; end; procedure TMicroTilesRepaintOptimizer.ResetAdaptiveMode; begin FTimeDelta := TIMER_LOWLIMIT; FAdaptionFailed := False; FPerformanceLevel := PL_MICROTILES; end; procedure TMicroTilesRepaintOptimizer.BeginPaintBuffer; begin if AdaptiveMode then FPerfTimer.Start; end; procedure TMicroTilesRepaintOptimizer.EndPaintBuffer; begin FUseInvalidTiles := False; {$IFDEF MICROTILES_DEBUGDRAW} {$IFDEF MICROTILES_DEBUGDRAW_UNOPTIMIZED} MicroTilesDebugDraw(FDebugMicroTiles, Buffer, False, FDebugWholeTiles); {$ELSE} MicroTilesDebugDraw(FDebugMicroTiles, Buffer, True, FDebugWholeTiles); {$ENDIF} MicroTilesClear(FDebugMicroTiles); {$ENDIF} {$IFNDEF MICROTILES_NO_ADAPTION} EndAdaption; {$ENDIF} end; procedure TMicroTilesRepaintOptimizer.DrawLayerToMicroTiles(var DstTiles: TMicroTiles; Layer: TCustomLayer); begin Buffer.BeginMeasuring(DrawMeasuringHandler); FWorkMicroTiles := @DstTiles; TCustomLayerAccess(Layer).DoPaint(Buffer); Buffer.EndMeasuring; end; procedure TMicroTilesRepaintOptimizer.DrawMeasuringHandler(Sender: TObject; const Area: TRect; const Info: Cardinal); begin AddArea(FWorkMicroTiles^, Area, Info); end; procedure TMicroTilesRepaintOptimizer.PerformOptimization; var I: Integer; Layer: TCustomLayer; UseWholeTiles: Boolean; LayerTilesPtr: PMicroTiles; begin if FUseInvalidTiles then begin ValidateWorkingTiles; // Determine if the use of whole tiles is better for current performance level {$IFNDEF MICROTILES_NO_ADAPTION} UseWholeTiles := FPerformanceLevel > PL_MICROTILES; {$ELSE} {$IFDEF MICROTILES_NO_ADAPTION_FORCE_WHOLETILES} UseWholeTiles := True; {$ELSE} UseWholeTiles := False; {$ENDIF} {$ENDIF} if FInvalidLayers.Count > 0 then begin for I := 0 to FInvalidLayers.Count - 1 do begin Layer := FInvalidLayers[I]; // Clear temporary tiles MicroTilesClearUsed(FTempTiles); // Draw layer to temporary tiles DrawLayerToMicroTiles(FTempTiles, Layer); // Combine temporary tiles with the global invalid tiles MicroTilesUnion(FInvalidTiles, FTempTiles, UseWholeTiles); // Retrieve old invalid tiles for the current layer LayerTilesPtr := FOldInvalidTilesMap[Layer]; // Combine old invalid tiles with the global invalid tiles MicroTilesUnion(FInvalidTiles, LayerTilesPtr^, UseWholeTiles); // Copy temporary (current) invalid tiles to the layer MicroTilesCopy(LayerTilesPtr^, FTempTiles); // Unmark layer as invalid TCustomLayerAccess(Layer).Invalid := False; end; FInvalidLayers.Clear; end; {$IFDEF MICROTILES_DEBUGDRAW} MicroTilesCalcRects(FInvalidTiles, InvalidRects, False, UseWholeTiles); MicroTilesCalcRects(FForcedInvalidTiles, InvalidRects, False, UseWholeTiles); MicroTilesCopy(FDebugMicroTiles, FInvalidTiles); MicroTilesUnion(FDebugMicroTiles, FForcedInvalidTiles); FDebugWholeTiles := UseWholeTiles; {$ELSE} // Calculate optimized rectangles from global invalid tiles MicroTilesCalcRects(FInvalidTiles, InvalidRects, False, UseWholeTiles); // Calculate optimized rectangles from forced invalid tiles MicroTilesCalcRects(FForcedInvalidTiles, InvalidRects, False, UseWholeTiles); {$ENDIF} end; {$IFNDEF MICROTILES_NO_ADAPTION} BeginAdaption; {$ENDIF} {$IFDEF MICROTILES_DEBUGDRAW} if InvalidRects.Count > 0 then begin FDebugInvalidRects.Count := InvalidRects.Count; Move(InvalidRects[0]^, FDebugInvalidRects[0]^, InvalidRects.Count * SizeOf(TRect)); InvalidRects.Clear; end; {$ENDIF} // Rects have been created, so we don't need the tiles any longer, clear them. MicroTilesClearUsed(FInvalidTiles); MicroTilesClearUsed(FForcedInvalidTiles); end; procedure TMicroTilesRepaintOptimizer.BeginAdaption; begin if AdaptiveMode and (FPerformanceLevel > PL_MICROTILES) then begin if Integer(GetTickCount) > FNextCheck then begin FPerformanceLevel := Constrain(FPerformanceLevel - 1, PL_MICROTILES, PL_FULLSCENE); {$IFDEF CODESITE} CodeSite.SendInteger('PrepareInvalidRects(Timed): FPerformanceLevel', FPerformanceLevel); {$ENDIF} FTimedCheck := True; end else if not FAdaptionFailed and (InvalidRects.Count < FOldInvalidRectsCount - INVALIDRECTS_DELTA) then begin FPerformanceLevel := Constrain(FPerformanceLevel - 1, PL_MICROTILES, PL_FULLSCENE); {$IFDEF CODESITE} CodeSite.SendInteger('PrepareInvalidRects: FPerformanceLevel', FPerformanceLevel); {$ENDIF} end else if FPerformanceLevel = PL_FULLSCENE then // we need a full scene rendition, so clear the invalid rects InvalidRects.Clear; end; end; procedure TMicroTilesRepaintOptimizer.EndAdaption; var TimeElapsed: Int64; Level: Integer; begin // our KISS(TM) repaint mode balancing starts here... TimeElapsed := FPerfTimer.ReadValue; {$IFDEF MICROTILES_DEBUGDRAW} if FDebugInvalidRects.Count = 0 then {$ELSE} if InvalidRects.Count = 0 then {$ENDIF} FElapsedTimeForFullSceneRepaint := TimeElapsed else if AdaptiveMode then begin if TimeElapsed > FElapsedTimeForFullSceneRepaint then begin Level := Constrain(FPerformanceLevel + 1, PL_MICROTILES, PL_FULLSCENE); // did performance level change from previous level? if Level <> FPerformanceLevel then begin {$IFDEF MICROTILES_DEBUGDRAW} FOldInvalidRectsCount := FDebugInvalidRects.Count; {$ELSE} // save count of old invalid rects so we can use it in PrepareInvalidRects // the next time... FOldInvalidRectsCount := InvalidRects.Count; {$ENDIF} FPerformanceLevel := Level; {$IFDEF CODESITE} CodeSite.SendInteger('EndPaintBuffer: FPerformanceLevel', FPerformanceLevel); {$ENDIF} // was this a timed check? if FTimedCheck then begin // time based approach failed, so add penalty FTimeDelta := Constrain(Integer(FTimeDelta + TIMER_PENALTY), TIMER_LOWLIMIT, TIMER_HIGHLIMIT); // schedule next check FNextCheck := Integer(GetTickCount) + FTimeDelta; FElapsedTimeOnLastPenalty := TimeElapsed; FTimedCheck := False; {$IFDEF CODESITE} CodeSite.SendInteger('timed check failed, new delta', FTimeDelta); {$ENDIF} end; {$IFDEF CODESITE} CodeSite.AddSeparator; {$ENDIF} FAdaptionFailed := True; end; end else if TimeElapsed < FElapsedTimeForFullSceneRepaint then begin if FTimedCheck then begin // time based approach had success!! // reset time delta back to lower limit, ie. remove penalties FTimeDelta := TIMER_LOWLIMIT; // schedule next check FNextCheck := Integer(GetTickCount) + FTimeDelta; FTimedCheck := False; {$IFDEF CODESITE} CodeSite.SendInteger('timed check succeeded, new delta', FTimeDelta); CodeSite.AddSeparator; {$ENDIF} FAdaptionFailed := False; end else begin // invalid rect count approach had success!! // shorten time for next check to benefit nonetheless in case we have a fallback... if FTimeDelta > TIMER_LOWLIMIT then begin // remove the penalty value 4 times from the current time delta FTimeDelta := Constrain(FTimeDelta - 4 * TIMER_PENALTY, TIMER_LOWLIMIT, TIMER_HIGHLIMIT); // schedule next check FNextCheck := Integer(GetTickCount) + FTimeDelta; {$IFDEF CODESITE} CodeSite.SendInteger('invalid rect count approach succeeded, new timer delta', FTimeDelta); CodeSite.AddSeparator; {$ENDIF} end; FAdaptionFailed := False; end; end else if (TimeElapsed < FElapsedTimeOnLastPenalty) and FTimedCheck then begin // time approach had success optimizing the situation, so shorten time until next check FTimeDelta := Constrain(FTimeDelta - TIMER_PENALTY, TIMER_LOWLIMIT, TIMER_HIGHLIMIT); // schedule next check FNextCheck := Integer(GetTickCount) + FTimeDelta; FTimedCheck := False; {$IFDEF CODESITE} CodeSite.SendInteger('timed check succeeded, new delta', FTimeDelta); CodeSite.AddSeparator; {$ENDIF} end; end; FElapsedTimeForLastRepaint := TimeElapsed; end; {$IFDEF CODESITE} { TDebugMicroTilesRepaintOptimizer } procedure TDebugMicroTilesRepaintOptimizer.AreaUpdateHandler(Sender: TObject; const Area: TRect; const Info: Cardinal); begin DumpCallStack('TDebugMicroTilesRepaintOptimizer.AreaUpdateHandler'); inherited; end; procedure TDebugMicroTilesRepaintOptimizer.BeginPaintBuffer; begin DumpCallStack('TDebugMicroTilesRepaintOptimizer.BeginPaintBuffer'); inherited; end; procedure TDebugMicroTilesRepaintOptimizer.BufferResizedHandler(const NewWidth, NewHeight: Integer); begin DumpCallStack('TDebugMicroTilesRepaintOptimizer.BufferResizedHandler'); inherited; end; procedure TDebugMicroTilesRepaintOptimizer.EndPaintBuffer; begin DumpCallStack('TDebugMicroTilesRepaintOptimizer.EndPaintBuffer'); inherited; CodeSite.AddSeparator; end; procedure TDebugMicroTilesRepaintOptimizer.LayerUpdateHandler(Sender: TObject; Layer: TCustomLayer); begin DumpCallStack('TDebugMicroTilesRepaintOptimizer.LayerUpdateHandler'); inherited; end; procedure TDebugMicroTilesRepaintOptimizer.PerformOptimization; begin DumpCallStack('TDebugMicroTilesRepaintOptimizer.PerformOptimization'); inherited; end; procedure TDebugMicroTilesRepaintOptimizer.Reset; begin DumpCallStack('TDebugMicroTilesRepaintOptimizer.Reset'); inherited; CodeSite.AddSeparator; end; function TDebugMicroTilesRepaintOptimizer.UpdatesAvailable: Boolean; begin DumpCallStack('TDebugMicroTilesRepaintOptimizer.UpdatesAvailable'); Result := inherited UpdatesAvailable; end; {$ENDIF} const FID_MICROTILEUNION = 0; FID_MICROTILESUNION = 1; var Registry: TFunctionRegistry; procedure RegisterBindings; begin Registry := NewRegistry('GR32_MicroTiles bindings'); Registry.RegisterBinding(FID_MICROTILEUNION, @@MicroTileUnion); Registry.RegisterBinding(FID_MICROTILESUNION, @@MicroTilesU); Registry.Add(FID_MICROTILEUNION, @MicroTileUnion_Pas); Registry.Add(FID_MICROTILESUNION, @MicroTilesUnion_Pas); {$IFNDEF PUREPASCAL} {$IFDEF TARGET_x86} Registry.Add(FID_MICROTILEUNION, @MicroTileUnion_EMMX, [ciEMMX]); Registry.Add(FID_MICROTILESUNION, @MicroTilesUnion_EMMX, [ciEMMX]); {$ENDIF} {$ENDIF} Registry.RebindAll; end; initialization RegisterBindings; end.
31.200929
184
0.672629
f1fcf8cfaa5e59ddf1bb482427fb917e58c4411f
9,334
pas
Pascal
ThirdParty/Spring4D/Source/Persistence/Adapters/Spring.Persistence.Adapters.FireDAC.pas
Gronfi/DPN
a21706737f6eca7378e31511d15768a36f93a72a
[ "Apache-2.0" ]
3
2020-11-06T15:46:18.000Z
2021-06-24T09:23:29.000Z
ThirdParty/Spring4D/Source/Persistence/Adapters/Spring.Persistence.Adapters.FireDAC.pas
Gronfi/DPN
a21706737f6eca7378e31511d15768a36f93a72a
[ "Apache-2.0" ]
null
null
null
ThirdParty/Spring4D/Source/Persistence/Adapters/Spring.Persistence.Adapters.FireDAC.pas
Gronfi/DPN
a21706737f6eca7378e31511d15768a36f93a72a
[ "Apache-2.0" ]
3
2020-10-31T00:46:34.000Z
2021-06-23T15:23:27.000Z
{***************************************************************************} { } { Spring Framework for Delphi } { } { Copyright (c) 2009-2020 Spring4D Team } { } { http://www.spring4d.org } { } {***************************************************************************} { } { 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. } { } {***************************************************************************} {$I Spring.inc} unit Spring.Persistence.Adapters.FireDAC; interface uses FireDAC.Comp.Client, SysUtils, Spring.Collections, Spring.Persistence.Core.Base, Spring.Persistence.Core.Exceptions, Spring.Persistence.Core.Interfaces, Spring.Persistence.SQL.Params; type EFireDACAdapterException = class(EORMAdapterException); TFireDACResultSetAdapter = class(TDriverResultSetAdapter<TFDQuery>); TFireDACStatementAdapter = class(TDriverStatementAdapter<TFDQuery>) public destructor Destroy; override; procedure SetSQLCommand(const commandText: string); override; procedure SetParam(const param: TDBParam); virtual; procedure SetParams(const params: IEnumerable<TDBParam>); override; function Execute: NativeUInt; override; function ExecuteQuery(serverSideCursor: Boolean = True): IDBResultSet; override; end; TFireDACConnectionAdapter = class(TDriverConnectionAdapter<TFDConnection>) protected constructor Create(const connection: TFDConnection; const exceptionHandler: IORMExceptionHandler); override; public constructor Create(const connection: TFDConnection); override; destructor Destroy; override; procedure Connect; override; procedure Disconnect; override; function IsConnected: Boolean; override; function CreateStatement: IDBStatement; override; function BeginTransaction: IDBTransaction; override; end; TFireDACTransactionAdapter = class(TDriverTransactionAdapter<TFDConnection>, IDBTransaction) private fInTransaction: Boolean; protected function InTransaction: Boolean; override; public constructor Create(const transaction: TFDConnection; const exceptionHandler: IORMExceptionHandler); reintroduce; procedure Commit; override; procedure Rollback; override; end; TFireDACExceptionHandler = class(TORMExceptionHandler) protected function GetAdapterException(const exc: Exception; const defaultMsg: string): Exception; override; end; implementation uses DB, FireDAC.DApt, FireDAC.Stan.Async, FireDAC.Stan.Def, FireDAC.Stan.Error, FireDAC.Stan.Option, FireDAC.Stan.Param, Spring.Persistence.Core.ConnectionFactory, Spring.Persistence.Core.ResourceStrings; {$REGION 'TFireDACStatementAdapter'} destructor TFireDACStatementAdapter.Destroy; begin {$IFNDEF AUTOREFCOUNT} Statement.Free; {$ELSE} Statement.DisposeOf; {$ENDIF} inherited Destroy; end; function TFireDACStatementAdapter.Execute: NativeUInt; begin inherited; try Statement.ExecSQL; Result := Statement.RowsAffected; except raise HandleException; end end; function TFireDACStatementAdapter.ExecuteQuery( serverSideCursor: Boolean): IDBResultSet; var query: TFDQuery; begin inherited; query := TFDQuery.Create(nil); query.Connection := Statement.Connection; query.SQL.Text := Statement.SQL.Text; query.Params.AssignValues(Statement.Params); query.DisableControls; if AllowServerSideCursor and serverSideCursor then query.FetchOptions.CursorKind := ckForwardOnly; try query.OpenOrExecute; Result := TFireDACResultSetAdapter.Create(query, ExceptionHandler); except on E:Exception do begin query.Free; raise HandleException(Format(SCannotOpenQuery, [E.Message])); end; end; end; procedure TFireDACStatementAdapter.SetParam(const param: TDBParam); var paramName: string; parameter: TFDParam; begin paramName := param.GetNormalizedParamName; parameter := Statement.ParamByName(paramName); parameter.DataType := param.ParamType; parameter.Value := param.ToVariant; end; procedure TFireDACStatementAdapter.SetParams(const params: IEnumerable<TDBParam>); begin inherited; params.ForEach(SetParam); end; procedure TFireDACStatementAdapter.SetSQLCommand(const commandText: string); begin inherited; Statement.SQL.Text := commandText; end; {$ENDREGION} {$REGION 'TFireDACConnectionAdapter'} constructor TFireDACConnectionAdapter.Create(const connection: TFDConnection); begin Create(connection, TFireDACExceptionHandler.Create); end; constructor TFireDACConnectionAdapter.Create(const connection: TFDConnection; const exceptionHandler: IORMExceptionHandler); begin inherited Create(connection, exceptionHandler); Connection.LoginPrompt := False; end; function TFireDACConnectionAdapter.BeginTransaction: IDBTransaction; begin if Assigned(Connection) then try Connection.Connected := True; if not Connection.InTransaction or Connection.TxOptions.EnableNested then begin Connection.StartTransaction; Result := TFireDACTransactionAdapter.Create(Connection, ExceptionHandler); end else raise EFireDACAdapterException.Create('Transaction already started, and EnableNested transaction is false'); except raise HandleException; end else Result := nil; end; procedure TFireDACConnectionAdapter.Connect; begin if Assigned(Connection) then try Connection.Connected := True; except raise HandleException; end; end; function TFireDACConnectionAdapter.CreateStatement: IDBStatement; var statement: TFDQuery; adapter: TFireDACStatementAdapter; begin if Assigned(Connection) then begin statement := TFDQuery.Create(nil); statement.Connection := Connection; adapter := TFireDACStatementAdapter.Create(statement, ExceptionHandler); adapter.ExecutionListeners := ExecutionListeners; adapter.AllowServerSideCursor := AllowServerSideCursor; Result := adapter; end else Result := nil; end; destructor TFireDACConnectionAdapter.Destroy; begin {$IFDEF AUTOREFCOUNT} if AutoFreeConnection then Connection.DisposeOf; {$ENDIF} inherited; end; procedure TFireDACConnectionAdapter.Disconnect; begin if Assigned(Connection) then try Connection.Connected := False; except raise HandleException; end; end; function TFireDACConnectionAdapter.IsConnected: Boolean; begin Result := Assigned(Connection) and Connection.Connected; end; {$ENDREGION} {$REGION 'TFireDACTransactionAdapter'} constructor TFireDACTransactionAdapter.Create(const transaction: TFDConnection; const exceptionHandler: IORMExceptionHandler); begin inherited Create(transaction, exceptionHandler); fInTransaction := True; end; procedure TFireDACTransactionAdapter.Commit; begin if InTransaction then try Transaction.Commit; fInTransaction := False; except raise HandleException; end; end; function TFireDACTransactionAdapter.InTransaction: Boolean; begin Result := fInTransaction and Assigned(Transaction) and Transaction.InTransaction; end; procedure TFireDACTransactionAdapter.Rollback; begin if InTransaction then try Transaction.Rollback; fInTransaction := False; except raise HandleException; end; end; {$ENDREGION} {$REGION 'TFireDACExceptionHandler'} function TFireDACExceptionHandler.GetAdapterException(const exc: Exception; const defaultMsg: string): Exception; begin if exc is EFDDBEngineException then with EFDDBEngineException(exc) do begin case Kind of ekUKViolated, ekFKViolated : Result := EORMConstraintException.Create(defaultMsg, ErrorCode); else Result := EFireDACAdapterException.Create(defaultMsg, ErrorCode); end; end else if exc is EDatabaseError then Result := EFireDACAdapterException.Create(defaultMsg) else Result := nil; end; {$ENDREGION} initialization TConnectionFactory.RegisterConnection<TFireDACConnectionAdapter>(dtFireDAC); end.
28.03003
114
0.67613
47d07859e5bf158448ea743a15c547bcf98a3ed7
278,977
pas
Pascal
Libraries/BigIntegersLib/Velthuis.BigIntegers.pas
skolkman/dwscript
b9f99d4b8187defac3f3713e2ae0f7b83b63d516
[ "Condor-1.1" ]
79
2015-03-18T10:46:13.000Z
2022-03-17T18:05:11.000Z
Libraries/BigIntegersLib/Velthuis.BigIntegers.pas
skolkman/dwscript
b9f99d4b8187defac3f3713e2ae0f7b83b63d516
[ "Condor-1.1" ]
6
2016-03-29T14:39:00.000Z
2020-09-14T10:04:14.000Z
Libraries/BigIntegersLib/Velthuis.BigIntegers.pas
skolkman/dwscript
b9f99d4b8187defac3f3713e2ae0f7b83b63d516
[ "Condor-1.1" ]
25
2016-05-04T13:11:38.000Z
2021-09-29T13:34:31.000Z
{---------------------------------------------------------------------------} { } { File: Velthuis.BigIntegers.pas } { Function: A big integer implementation, with critical parts written in } { Win32 or Win64 assembler, or "Pure Pascal" for other } { platforms, or if explicitly specified. } { Language: Delphi version XE2 or later } { Author: Rudy Velthuis } { Copyright: (c) 2015, Rudy Velthuis } { Notes: See http://praxis-velthuis.de/rdc/programs/bigintegers.html } { } { For tests, see BigIntegerDevelopmentTests.dproj. The data } { for these tests are generated by a C# program, in the } { Tests\CSharp\BigIntegerTestGenerator subdirectory. } { } { Credits: } { Thanks to Peter Cordes, Nils Pipenbrinck and Johan for their } { help on StackOverflow: } { - http://stackoverflow.com/a/32298732/95954 } { - http://stackoverflow.com/a/32087095/95954 } { - http://stackoverflow.com/a/32084357/95954 } { } { Thanks to Agner Fog for his excellent optimization guides. } { } { Literature: } { 1. Donald Knuth, "The Art Of Computer Programming", 2nd ed. } { Vol I-III. } { 2. Karl Hasselström, } { "Fast Division of Large Integers - A Comparison of } { Algorithms" } { bioinfo.ict.ac.cn/~dbu/AlgorithmCourses/ } { Lectures/Hasselstrom2003.pdf } { 3. Richard P. Brent and Paul Zimmermann, } { "Modern Computer Arithmetic" } { http://arxiv.org/pdf/1004.4710v1.pdf } { 4. Christoph Burnikel, Joachim Ziegler } { "Fast Recursive Division" } { cr.yp.to/bib/1998/burnikel.ps } { 5. Hacker's Delight, e.g. } { http://www.hackersdelight.org/basics2.pdf } { as well as many Wikipedia articles } { } { ------------------------------------------------------------------------- } { } { License: 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. } { } { Disclaimer: THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "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. } { } {---------------------------------------------------------------------------} {---------------------------------------------------------------------------} { Corrections: } { 2015.11.28: changed calls to System.@GetMem in } { System.AllocMem. GetMem does not clear memory, causing the } { occasional bad result. } {---------------------------------------------------------------------------} unit Velthuis.BigIntegers; interface uses Velthuis.RandomNumbers, Types, SysUtils, Math; // --- User settings --- {$UNDEF DEBUG} // Setting PUREPASCAL forces the use of plain Object Pascal for all routines, i.e. no assembler is used. {$DEFINE PUREPASCAL} // Setting RESETSIZE forces the Compact routine to shrink the dynamic array when that makes sense. // This can slow down code a little. { $DEFINE RESETSIZE} // Experimental is set for code that tries something new without deleting the original code yet. Undefine it to get the original code. {$DEFINE Experimental} // --- Permanent settings --- // For Delphi XE3 and up: {$IF CompilerVersion >= 24.0 } {$LEGACYIFEND ON} {$IFEND} // For Delphi XE and up: {$IF CompilerVersion >= 22.0} {$CODEALIGN 16} {$ALIGN 16} {$IFEND} // Assembler is only supplied for Windows targets. // For other targets, PUREPASCAL must be defined. {$IFNDEF PUREPASCAL} {$IF NOT DEFINED(MSWINDOWS)} {$DEFINE PUREPASCAL} {$IFEND} {$ENDIF} const {$IFDEF PUREPASCAL} PurePascal = True; {$ELSE} PurePascal = False; {$ENDIF} // This assumes an unroll factor of 4. Unrolling more (e.g. 8) does not improve performance anymore. // That was tested and removed again. CUnrollShift = 2; CUnrollIncrement = 1 shl CUnrollShift; CunrollMask = CUnrollIncrement - 1; type BigIntegerException = Exception; TNumberBase = 2..36; PLimb = ^TLimb; // Knuth calls them "limbs". TLimb = type UInt32; TMagnitude = array of TLimb; // These BigIntegers use sign-magnitude format, hence the name. // TBigInteger uses a sign-magnitude representation, i.e. the magnitude is always interpreted as an unsigned big integer, // while the sign bit represents the sign. Currently, the sign bit is stored as the top bit of the FSize member. PBigInteger = ^BigInteger; BigInteger = record public {$REGION 'public constants, types and variables'} type /// <summary>TRoundingMode governs which rounding mode is used to convert from Double to BigInteger.</summary> /// <param name="rmTruncate">Truncates any fraction</param> /// <param name="rmSchool">Rounds any fraction >= 0.5 away from zero</param> /// <param name="rmRound">Rounds any fraction > 0.5 away from zero</param> TRoundingMode = (rmTruncate, rmSchool, rmRound); class var MinusOne: BigInteger; Zero: BigInteger; One: BigInteger; Ten: BigInteger; const CapacityMask = High(Integer) - 3; // Mask ensuring that FData lengths are a multiple of 4, e.g. $7FFFFFFC SizeMask = High(Integer); // Mask to extract size part of FSize member, e.g. $7FFFFFFF SignMask = Low(Integer); // Mask to extract sign bit of FSize member, e.g. $80000000 // TODO: check the values of these constants {$IFDEF PUREPASCAL} {$IFDEF CPUX64} // 64PP = 64 bit, Pure Pascal KaratsubaThreshold = 96; // Checked ToomCook3Threshold = 272; // Checked BurnikelZieglerThreshold = 91; // Checked BurnikelZieglerOffsetThreshold = 5; // Unchecked KaratsubaSqrThreshold = 48; // Unchecked {$ELSE CPUX86} // 32PP = 32 bit, Pure Pascal KaratsubaThreshold = 56; // Checked ToomCook3Threshold = 144; // Checked BurnikelZieglerThreshold = 91; // Checked BurnikelZieglerOffsetThreshold = 5; // Unchecked KaratsubaSqrThreshold = 48; // Unchecked {$ENDIF CPUX64} {$ELSE !PUREPASCAL} {$IFDEF CPUX64} // 64A = 64 bit, Assembler KaratsubaThreshold = 256; // Checked ToomCook3Threshold = 768; // Checked BurnikelZieglerThreshold = 160; // Checked BurnikelZieglerOffsetThreshold = 80; // Unchecked KaratsubaSqrThreshold = 256; // Unchecked {$ELSE CPUX86} // 32A = 32 bit, Assembler KaratsubaThreshold = 96; // Checked ToomCook3Threshold = 256; // Checked BurnikelZieglerThreshold = 80; // Checked BurnikelZieglerOffsetThreshold = 40; // Unchecked KaratsubaSqrThreshold = 128; // Unchecked {$ENDIF CPUX64} {$ENDIF PUREPASCAL} ToomCook3SqrThreshold = 216; // Unchecked {$ENDREGION} {$REGION 'public methods'} // -- Constructors -- /// <summary>Initializes class variables before first use.</summary> class constructor Initialize; /// <summary>Creates a new BigInteger from the data in limbs and the sign specified in Negative.</summary> /// <param name="Limbs">data for the magnitude of the BigInteger. The data is interpreted as unsigned, and comes low limb first.</param> /// <param name="Negative">Indicates if the BigInteger is negative.</param> constructor Create(const Limbs: array of TLimb; Negative: Boolean); overload; /// <summary>Creates a new BigInteger from the data in limbs and the sign specified in Negative.</summary> /// <param name="Data">data for the magnitude of the BigInteger. The data is interpreted as unsigned, and comes low limb first.</param> /// <param name="Negative">Indicates if the BigInteger is negative.</param> constructor Create(const Data: TMagnitude; Negative: Boolean); overload; /// <summary>Creates a new BigInteger with the same value as the specified BigInteger.</summary> constructor Create(const Int: BigInteger); overload; /// <summary>Creates a new BigInteger with the value of the specified Integer.<summary> constructor Create(const Int: Int32); overload; /// <summary>Creates a new BigInteger with the value of the specified Cardinal.<summary> constructor Create(const Int: UInt32); overload; /// <summary>Creates a new BigInteger with the value of the specified 64 bit integer.<summary> constructor Create(const Int: Int64); overload; /// <summary>Creates a new BigInteger with the value of the specified Integer.<summary> constructor Create(const Int: UInt64); overload; /// <summary>Creates a new BigInteger with the integer value of the specified Double.</summary> constructor Create(const ADouble: Double); overload; /// <summary>Creates a new BigInteger from the value in the byte array. /// The byte array is considered to be in two's complement.</summary> /// <remarks>This is the complementary function of ToByteArray</remarks> constructor Create(const Bytes: array of Byte); overload; /// <summary>Creates a new random BigInteger of the given size. Uses the given IRandom to /// generate the random value.</summary> constructor Create(NumBits: Integer; const Random: IRandom); overload; // -- Global numeric base related functions -- /// <summary>Sets the global numeric base for big integers to 10.</summary> /// <remarks>The global numeric base is used for input or output if there is no override in the input string or /// the output function.</remarks> class procedure Decimal; static; /// <summary>Sets the global numeric base for big integers to 16.</summary> /// <remarks>The global numeric base is used for input or output if there is no override in the input string or /// the output function.</remarks> class procedure Hexadecimal; static; /// <summary>Sets the global numeric base for big integers to 16.</summary> /// <remarks>The global numeric base is used for input or output if there is no override in the input string or /// the output function.</remarks> class procedure Hex; static; /// <summary>Sets the global numeric base for big integers to 2.</summary> /// <remarks>The global numeric base is used for input or output if there is no override in the input string or /// the output function.</remarks> class procedure Binary; static; /// <summary>Sets the global numeric base for big integers to 8.</summary> /// <remarks>The global numeric base is used for input or output if there is no override in the input string or /// the output function.</remarks> class procedure Octal; static; // -- String input functions -- /// <summary>Tries to parse the specified string into a valid BigInteger value in the specified numeric base. Returns False if this failed.</summary> /// <param name="S">The string that represents a big integer value in the specified numeric base.</param> /// <param name="Base">The numeric base that is assumed when parsing the string. Valid values are 2..36.</param> /// <param name="Res">The resulting BigInteger, if the parsing succeeds. Res is undefined if the parsing fails.</param> /// <returns>Returns True if S could be parsed into a valid BigInteger in Res. Returns False on failure.</returns> class function TryParse(const S: string; Base: TNumberBase; out Res: BigInteger): Boolean; overload; static; // -------------------------------------------------------------------------------------------------------------// // Note: most of the parse format for BigIntegers was taken from or inspired by Common Lisp (e.g. '%nnR' or // // '_'), some was inspired by other languages, including Delphi (e.g. the '$ 'for hex values), some was // // something I prefer (e.g. '0k' additional to '0o' for octal format). It should be usable in Delphi as well // // as in C++Builder, as it contains the default formats for integer values in these languages too. // // -- Rudy Velthuis. // //--------------------------------------------------------------------------------------------------------------// /// <summary>Tries to parse the specified string into a valid BigInteger value in the default BigInteger numeric base.</summary> /// <param name="S">The string that represents a big integer value in the default numeric base, unless /// specified otherwise. See <see cref="BigInteger.Base" /></param> /// <param name="Res">The resulting BigInteger, if the parsing succeeds. Res is undefined if the parsing fails.</param> /// <returns>Returns True if S could be parsed into a valid BigInteger in Res. Returns False on failure.</returns> /// <remarks> /// <para>To make it easier to increase the legibility of large numbers, any '_' in the numeric string will completely be ignored, so /// '1_000_000_000' is exactly equivalent to '1000000000'.</para> /// <para>The string to be parsed is considered case insensitive, so '$ABC' and '$abc' represent exactly the same value.</para> /// <para>The format of a string to be parsed is as follows:</para> /// <para><c>[sign][base override]digits</c></para> /// <para> /// <param name="sign">This can either be '-' or '+'. It will make the BigInteger negative or positive, respectively. /// If no sign is specified, a positive BigInteger is generated.</param> /// <param name="base override">There are several ways to override the default numeric base.<para>Specifying '0x' or '$' here will cause the /// string to be interpreted as representing a hexadecimal (base 16) value.</para><para>Specifying '0b' will cause it to be interpreted as /// binary (base 2).</para><para>Specifying '0d' will cause it to be interpreted as /// decimal (base 10).</para> /// <para>Specifying '0o' or '0k' will cause it to be interpreted as octal (base 8).</para><para>Finally, to specify any base, /// using an override in the format '%nnR' (R for radix) will cause the number to be interpreted to be in base 'nn', where 'nn' represent one or two /// decimal digits. So '%36rRudyVelthuis' is a valid BigInteger value with base 36.</para></param> /// </para> /// </remarks> class function TryParse(const S: string; out Res: BigInteger; aBase : Integer): Boolean; overload; static; /// <summary>Parses the specified string into a BigInteger, using the default numeric base.</summary> class function Parse(const S: string; aBase : Integer): BigInteger; static; // -- Sign related functions -- /// <summary>Returns True if the BigInteger is zero.</summary> function IsZero: Boolean; inline; /// <summary>Returns True if the BigInteger is negative (&lt; 0).</summary> function IsNegative: Boolean; inline; /// <summary>Returns True if the BigInteger is positive (&gt; 0).</summary> function IsPositive: Boolean; inline; /// <summary>Returns True if the BigInteger is even (0 is considered even too).</summary> function IsEven: Boolean; inline; /// <summary>Returns True if the magnitude of the BigInteger value is exactly a power of two.</summary> function IsPowerOfTwo: Boolean; /// <summary>Returns True if the BigInteger represents a value of 1.</summary> function IsOne: Boolean; // Bit fiddling // TODO: Should have two's complement semantics. function TestBit(Index: Integer): Boolean; function SetBit(Index: Integer): BigInteger; function ClearBit(Index: Integer): BigInteger; function FlipBit(Index: Integer): BigInteger; // String output functions /// <summary>Returns the string interpretation of the specified BigInteger in the default numeric base, see <see cref="BigInteger.Base" />.</summary> function ToString: string; overload; /// <summary>Returns the string interpretation of the specified BigInteger in the specified numeric base.</summary> function ToString(Base: Integer): string; overload; /// <summary>Returns the string interpretation of the specified BigInteger in numeric base 10. Equivalent /// to ToString(10).</summary> function ToDecimalString: string; /// <summary>Returns the string interpretation of the specified BigInteger in numeric base 16. Equivalent /// to ToString(16).</summary> function ToHexString: string; /// <summary>Returns the string interpretation of the specified BigInteger in numeric base 2. Equivalent /// to ToString(2).</summary> function ToBinaryString: string; /// <summary>Returns the string interpretation of the specified BigInteger in numeric base 8. Equivalent /// to ToString(8).</summary> function ToOctalString: string; procedure FromString(const Value: string; aBase : Integer); // -- Arithmetic operators -- /// <summary>Adds two BigIntegers.</summary> class operator Add(const Left, Right: BigInteger): BigInteger; /// <summary>Subtracts the second BigInteger from the first.</summary> class operator Subtract(const Left, Right: BigInteger): BigInteger; /// <summary>Multiplies two BigIntegers.</summary> class operator Multiply(const Left, Right: BigInteger): BigInteger; /// <summary>Multiplies the specified BigInteger with the specified Word value.</summary> class operator Multiply(const Left: BigInteger; Right: Word): BigInteger; inline; /// <summary>multiplies the specified Wirdvalue with the specified BigInteger.</summary> class operator Multiply(Left: Word; const Right: BigInteger): BigInteger; inline; /// <summary>Performs an integer divide of the first BigInteger by the second. class operator IntDivide(const Left, Right: BigInteger): BigInteger; /// <summary>Performs an integer divide of the first BigInteger by the second. class operator IntDivide(const Left: BigInteger; Right: UInt16): BigInteger; /// <summary>Performs an integer divide of the first BigInteger by the second. class operator IntDivide(const Left: BigInteger; Right: UInt32): BigInteger; /// <summary>Returns the remainder of an integer divide of the first BigInteger by the second.</summary> class operator Modulus(const Left, Right: BigInteger): BigInteger; /// <summary>Returns the remainder of an integer divide of the first BigInteger by the second.</summary> class operator Modulus(const Left: BigInteger; Right: UInt32): BigInteger; /// <summary>Returns the remainder of an integer divide of the first BigInteger by the second.</summary> class operator Modulus(const Left: BigInteger; Right: UInt16): BigInteger; /// <summary>Unary minus. Negates the value of the specified BigInteger.</summary> class operator Negative(const Int: BigInteger): BigInteger; /// <summary>Increment. Adds 1 to the value of the specified BigInteger very fast.</summary> class operator Inc(const Int: BigInteger): BigInteger; /// <summary>Decrement. Subtracts 1 from the value of the specified BigInteger very fast.</summary> class operator Dec(const Int: BigInteger): BigInteger; // -- Logical and bitwise operators -- /// <summary>Returns the result of the bitwise AND operation on its BigInteger operands. The result /// has two's complement semantics, e.g. '-1 and 7' returns '7'.</summary> class operator BitwiseAnd(const Left, Right: BigInteger): BigInteger; /// <summary>Returns the result of the bitwise OR operation on its BigInteger operands. The result /// has two's complement semantics, e.g. '-1 or 7' returns '-1'.</summary> class operator BitwiseOr(const Left, Right: BigInteger): BigInteger; /// <summary>Returns the result of the bitwise XOR operation on its BigIntegers operands. The result /// has two's complement semantics, e.g. '-1 xor 7' returns '-8'.</summary> class operator BitwiseXor(const Left, Right: BigInteger): BigInteger; /// <summary>Returns the result of the bitwise NOT operation on its BigInteger operand. The result /// has two's complement semantics, e.g. 'not 1' returns '-2'.</summary> class operator LogicalNot(const Int: BigInteger): BigInteger; // -- Shift operators -- /// <summary>Shifts the specified BigInteger value the specified number of bits to the left (away from 0). /// The size of the BigInteger is adjusted accordingly.</summary> /// <remarks>Note that this is an arithmetic shift, i.e. the sign is preserved. This is unlike normal /// integer shifts in Delphi.</remarks> class operator LeftShift(const Value: BigInteger; Shift: Integer): BigInteger; /// <summary>Shifts the specified BigInteger value the specified number of bits to the right (toward 0). /// The size of the BigInteger is adjusted accordingly.</summary> /// <remarks>Note that this is an arithmetic shift, i.e. the sign is preserved. This is unlike normal /// integer shifts in Delphi. This means that negative values do not finally end up as 0, but /// as -1, since the sign bit is always shifted in.</remarks> class operator RightShift(const Value: BigInteger; Shift: Integer): BigInteger; // -- Comparison operators -- /// <summary>Returns True if the specified BigIntegers have the same value.</summary> class operator Equal(const Left, Right: BigInteger): Boolean; /// <summary>Returns True if the specified BigInteger do not have the same value.</summary> class operator NotEqual(const Left, Right: BigInteger): Boolean; /// <summary>Returns true if the value of Left is mathematically greater than the value of Right.</summary> class operator GreaterThan(const Left, Right: BigInteger): Boolean; /// <summary>Returns true if the value of Left is mathematically greater than or equal to the value of Right.</summary> class operator GreaterThanOrEqual(const Left, Right: BigInteger): Boolean; /// <summary>Returns true if the value of Left is mathematically less than the value of Right.</summary> class operator LessThan(const Left, Right: BigInteger): Boolean; /// <summary>Returns true if the value of Left is mathematically less than or equal to the value of Right.</summary> class operator LessThanOrEqual(const Left, Right: BigInteger): Boolean; // -- Implicit conversion operators -- /// <summary>Implicitly (i.e. without a cast) converts the specified Integer to a BigInteger.</summary> class operator Implicit(const Int: Integer): BigInteger; /// <summary>Implicitly (i.e. without a cast) converts the specified Cardinal to a BigInteger.</summary> class operator Implicit(const Int: Cardinal): BigInteger; /// <summary>Implicitly (i.e. without a cast) converts the specified Int64 to a BigInteger.</summary> class operator Implicit(const Int: Int64): BigInteger; /// <summary>Implicitly (i.e. without a cast) converts the specified UInt64 to a BigInteger.</summary> class operator Implicit(const Int: UInt64): BigInteger; /// <summary>Implicitly (i.e. without a cast) converts the specified string to a BigInteger. The BigInteger is the /// result of a call to Parse(Value).</summary> class operator Implicit(const Value: string): BigInteger; // -- Explicit conversion operators -- /// <summary>Explicitly (i.e. with a cast) converts the specified BigInteger to an Integer. If necessary, the /// value of the BigInteger is truncated or sign-extended to fit in the result.</summary> class operator Explicit(const Int: BigInteger): Integer; /// <summary>Explicitly (i.e. with a cast) converts the specified BigInteger to a Cardinal. If necessary, the /// value of the BigInteger is truncated to fit in the result.</summary> class operator Explicit(const Int: BigInteger): Cardinal; /// <summary>Explicitly (i.e. with a cast) converts the specified BigInteger to an Int64. If necessary, the /// value of the BigInteger is truncated or sign-extended to fit in the result.</summary> class operator Explicit(const Int: BigInteger): Int64; /// <summary>Explicitly (i.e. with a cast) converts the specified BigInteger to an UInt64. If necessary, the /// value of the BigInteger is truncated to fit in the result.</summary> class operator Explicit(const Int: BigInteger): UInt64; /// <summary>Explicitly (i.e. with a cast) converts the specified BigInteger to a Double.</summary> class operator Explicit(const Int: BigInteger): Double; /// <summary>Explicitly (i.e. with a cast) converts the specified Double to a BigInteger.</summary> class operator Explicit(const ADouble: Double): BigInteger; // -- Conversion functions -- /// <summary>Converts the specified BigInteger to a Double, if this is possible. Returns an exception if the /// value of the BigInteger is too large.</summary> function AsDouble: Double; /// <summary>Converts the specified BigInteger to an Integer, if this is possible. Returns an exception if the /// value of the BigInteger is too large.</summary> function AsInteger: Integer; /// <summary>Converts the specified BigInteger to a Cardinal, if this is possible. Returns an exception if the /// value of the BigInteger is too large or is negative.</summary> function AsCardinal: Cardinal; /// <summary>Converts the specified BigInteger to an Int64, if this is possible. Returns an exception if the /// value of the BigInteger is too large.</summary> function AsInt64: Int64; /// <summary>Converts the specified BigInteger to a UInt64, if this is possible. Returns an exception if the /// value of the BigInteger is too large or is negative.</summary> function AsUInt64: UInt64; // -- Operators as functions -- /// <summary>The function equivalent to the operator '+'.</summary> class function Add(const Left, Right: BigInteger): BigInteger; overload; static; /// <summary>The function equivalent to the operator '-'.</summary> class function Subtract(const Left, Right: BigInteger): BigInteger; overload; static; /// <summary>The function equivalent to the operator '*'.</summary> class function Multiply(const Left, Right: BigInteger): BigInteger; overload; static; class function MultiplyThreshold(const Left, Right: BigInteger; Threshold: Integer): BigInteger; static; class function MultiplyBaseCase(const Left, Right: BigInteger): BigInteger; static; /// <summary>The function equivalent to the operators 'div' and 'mod'. Since calculation of the quotient /// automatically leaves a remainder, this function allows you to get both for more or less the "price" /// (performance-wise) of one.</summary> class procedure DivMod(const Dividend, Divisor: BigInteger; var Quotient, Remainder: BigInteger); static; /// <summary>Simple "schoolbook" division according to Knuth, with limb-size digits.</summary> class procedure DivModKnuth(const Left, Right: BigInteger; var Quotient, Remainder: BigInteger); static; /// <summary>Recursive "schoolbook" division, as described by Burnikel and Ziegler. Faster than /// <see cref="DivModBaseCase" />, but with more overhead, so should only be applied for larger BigIntegers.</summary> class procedure DivModBurnikelZiegler(const Left, Right: BigInteger; var Quotient, Remainder: BigInteger); static; /// <summary>The function equivalent to the operator 'div'.</summary> class function Divide(const Left: BigInteger; Right: UInt16): BigInteger; overload; static; /// <summary>The function equivalent to the operator 'div'.</summary> class function Divide(const Left:BigInteger; Right: UInt32): BigInteger; overload; static; /// <summary>The function equivalent to the operator 'div'.</summary> class function Divide(const Left, Right: BigInteger): BigInteger; overload; static; /// <summary>>The function equivalent to the operator 'mod'. Like for integers, the remainder gets /// the sign - if any - of the dividend (i.e. of Left).</summary> class function Remainder(const Left, Right: BigInteger): BigInteger; overload; static; /// <summary>>The function equivalent to the operator 'mod'. Like for integers, the remainder gets /// the sign - if any - of the dividend (i.e. of Left).</summary> class function Remainder(const Left: BigInteger; Right: UInt32): BigInteger; overload; static; /// <summary>>The function equivalent to the operator 'mod'. Like for integers, the remainder gets /// the sign - if any - of the dividend (i.e. of Left).</summary> class function Remainder(const Left: BigInteger; Right: UInt16): BigInteger; overload; static; class function MultiplyKaratsuba(const Left, Right: BigInteger): BigInteger; static; class function MultiplyToomCook3(const Left, Right: BigInteger): BigInteger; static; class function SqrKaratsuba(const Value: BigInteger): BigInteger; static; {$IFDEF Experimental} class function MultiplyKaratsubaThreshold(const Left, Right: BigInteger; Threshold: Integer): BigInteger; static; class function MultiplyToomCook3Threshold(const Left, Right: BigInteger; Threshold: Integer): BigInteger; static; class function SqrKaratsubaThreshold(const Value: BigInteger; Threshold: Integer): BigInteger; static; {$ENDIF Experimental} // -- Self-referential operator functions -- /// <summary> /// <para>The functional equivalent to</para> /// <code> A := A + Other;</code> /// <para>This can be chained, as the function returns a pointer to itself:</para> /// <code> A.Add(First).Add(Second);</code></summary> /// <remarks><para>This was added in the hope to gain speed by avoiding some allocations. /// This is not so, although a longer chain seems to improve performance, compared to normal addition /// using operators, a bit.</para></remarks> function Add(const Other: BigInteger): PBigInteger; overload; /// <summary>The functional equivalent to Self := Self + Other;</summary> function Subtract(const Other: BigInteger): PBigInteger; overload; /// <summary>The functional equivalent to Self := Self div Other;</summary> function Divide(const Other: BigInteger): PBigInteger; overload; /// <summary>The functional equivalent to Self := Self mod Other;</summary> function Remainder(const Other: BigInteger): PBigInteger; overload; /// <summar>The functional equivalent to Self := Self * Other;</summary> function Multiply(const Other: BigInteger): PBigInteger; overload; // -- Math functions -- /// <summary>Returns the absolute value of the value in the BigInteger.</summary> class function Abs(const Int: BigInteger): BigInteger; static; /// <summary>Returns the bit length, the minimum number of bits needed to represent the value, excluding /// the sign bit.</summary> function BitLength: Integer; /// <summary>Returns the number of all bits that are set, assuming two's complement. The sign bit is /// included in the count.</summary> function BitCount: Integer; /// <summary>Returns a copy of the current BigInteger, with a unique copy of the data.</summary> function Clone: BigInteger; /// <summary>Returns +1 if the value in Left is greater than the value in Right, 0 if they are equal and /// 1 if it is lesser.</summary> class function Compare(const Left, Right: BigInteger): TValueSign; static; /// <summary>Returns the (positive) greatest common divisor of the specified BigInteger values.</summary> class function GreatestCommonDivisor(const Left, Right: BigInteger): BigInteger; static; /// <summary>Returns the natural logarithm of the value in Int.</summary> class function Ln(const Int: BigInteger): Double; static; /// <summary>Returns the logarithm to the specified base of the value in Int.</summary> class function Log(const Int: BigInteger; Base: Double): Double; static; /// <summary>Returns the logarithm to base 2 of the value in Int.</summary> class function Log2(const Int: BigInteger): Double; static; /// <summary>Returns the logarithm to base 10 of the value in Int.</summary> class function Log10(const Int: BigInteger): Double; static; /// <summary>Returns the larger of two specified values.</summary> class function Max(const Left, Right: BigInteger): BigInteger; static; /// <summary>Returns the smaller of two specified values.</summary> class function Min(const Left, Right: BigInteger): BigInteger; static; /// <summary>Returns the specified modulus value of the specified value raised to the specified power.</summary> class function ModPow(const ABase, AExponent, AModulus: BigInteger): BigInteger; static; /// <summary>Returns the specified value raised to the specified power.</summary> class function Pow(const ABase: BigInteger; AExponent: Integer): BigInteger; static; /// <summary>Returns the nth root R of a BigInteger such that R^Nth <= Radicand <= (R+1)^Nth.</summary> class function NthRoot(const Radicand: BigInteger; Nth: Integer): BigInteger; static; /// <summary>If R is the nth root of Radicand, returns Radicand - R^Nth.</summary> class procedure NthRootRemainder(const Radicand: BigInteger; Nth: Integer; var Root, Remainder: BigInteger); static; /// <summary> Returns the square root R of Radicand, such that R^2 < Radicand < (R+1)^2</summary> class function Sqrt(const Radicand: BigInteger): BigInteger; static; /// <summary>If R is the square root of Radicand, returns Radicand - R^2.</summary> class procedure SqrtRemainder(const Radicand: BigInteger; var Root, Remainder: BigInteger); static; class function Sqr(const Value: BigInteger): BigInteger; static; // -- Utility functions -- /// <summary>Sets whether partial-flags stall must be avoided with modified routines.</summary> /// <remarks>USING THE WRONG SETTING MAY AFFECT THE TIMING OF CERTAIN ROUTINES CONSIDERABLY, SO USE THIS WITH EXTREME CARE! /// The unit is usually able to determine the right settings automatically.</remarks> class procedure AvoidPartialFlagsStall(Value: Boolean); static; // -- Array function(s) -- /// <summary>Converts a BigInteger value to a byte array.</summary> /// <returns><para>A TArray&lt;Byte&gt;, see remarks.</para></returns> /// <remarks> /// <para>The individual bytes in the array returned by this method appear in little-endian order.</para> /// <para>Negative values are written to the array using two's complement representation in the most compact /// form possible. For example, -1 is represented as a single byte whose value is $FF instead of as an array /// with multiple elements, such as $FF, $FF or $FF, $FF, $FF, $FF.</para> /// <para>Because two's complement representation always interprets the highest-order bit of the last byte in /// the array (the byte at position High(Array)) as the sign bit, the method returns a byte array with /// an extra element whose value is zero to disambiguate positive values that could otherwise be interpreted /// as having their sign bits set. For example, the value 120 or $78 is represented as a single-byte array: /// $78. However, 129, or $81, is represented as a two-byte array: $81, $00. Something similar applies to /// negative values: -179 (or -$B3) must be represented as $4D, $FF.</para> /// </remarks> function ToByteArray: TArray<Byte>; function GetAllocated: Integer; function GetSize: Integer; inline; function Data: PLimb; inline; function GetSign: Integer; inline; procedure SetSign(Value: Integer); inline; {$ENDREGION} private {$REGION 'private constants, types and variables'} type TErrorCode = (ecParse, ecDivbyZero, ecConversion, ecInvalidArg, ecOverflow, ecInvalidArgument); TClearData = (cdClearData, cdKeepData); TDyadicOperator = procedure(Left, Right, Result: PLimb; LSize, RSize: Integer); var FData: TMagnitude; // The limbs of the magnitude, least significant limb at lowest address. FSize: Integer; // The top bit is the sign of the big integer. Rest is the number of valid limbs of the big integer. class var FBase: TNumberBase; FAvoidStall: Boolean; FRoundingMode: TRoundingMode; FInternalAdd: TDyadicOperator; FInternalSubtract: TDyadicOperator; {$ENDREGION} {$REGION 'private functions'} {$IFNDEF PUREPASCAL} class procedure DetectPartialFlagsStall; static; class procedure InternalAddModified(Left, Right, Result: PLimb; LSize, RSize: Integer); static; class procedure InternalAddPlain(Left, Right, Result: PLimb; LSize, RSize: Integer); static; class procedure InternalSubtractModified(Larger, Smaller, Result: PLimb; LSize, SSize: Integer); static; class procedure InternalSubtractPlain(Larger, Smaller, Result: PLimb; LSize, SSize: Integer); static; class procedure InternalDivideBy3(Value, Result: PLimb; ASize: Integer); static; {$ELSE} class procedure InternalAddPurePascal(Left, Right, Result: PLimb; LSize, RSize: Integer); static; class procedure InternalSubtractPurePascal(Larger, Smaller, Result: PLimb; LSize, SSize: Integer); static; {$ENDIF} class function InternalCompare(Left, Right: PLimb; LSize, RSize: Integer): TValueSign; static; class procedure InternalAnd(Left, Right, Result: PLimb; LSize, RSize: Integer); static; class procedure InternalOr(Left, Right, Result: PLimb; LSize, RSize: Integer); static; class procedure InternalXor(Left, Right, Result: PLimb; LSize, RSize: Integer); static; class procedure InternalAndNot(Left, Right, Result: PLimb; LSize, RSize: Integer); static; class procedure InternalNotAnd(Left, Right, Result: PLimb; LSize, RSize: Integer); static; inline; class procedure InternalBitwise(const Left, Right: BigInteger; var Result: BigInteger; PlainOp, OppositeOp, InversionOp: TDyadicOperator); static; class procedure InternalIncrement(Limbs: PLimb; Size: Integer); static; class procedure InternalDecrement(Limbs: PLimb; Size: Integer); static; class procedure InternalShiftLeft(Source, Dest: PLimb; Shift, Size: Integer); static; class procedure InternalShiftRight(Source, Dest: PLimb; Shift, Size: Integer); static; class function InternalDivMod(Dividend, Divisor, Quotient, Remainder: PLimb; LSize, RSize: Integer): Boolean; static; class function InternalDivMod32(Dividend: PLimb; Divisor: UInt32; Quotient, Remainder: PLimb; LSize: Integer): Boolean; static; class function InternalDivMod16(Dividend: PLimb; Divisor: UInt16; Quotient, Remainder: PLimb; LSize: Integer): Boolean; static; class procedure InternalMultiply(Left, Right, Result: PLimb; LSize, RSize: Integer); static; // class function InternalCompareMagnitudes(Left, Right: PLimb; LSize, RSize: Integer): TValueSign; static; class function InternalDivideByBase(Mag: PLimb; Base: Integer; var Size: Integer): UInt32; static; class procedure InternalMultiplyAndAdd(const Multiplicand: TMagnitude; Multiplicator, Addend: Word; const Res: TMagnitude); static; class procedure InternalNegate(Source, Dest: PLimb; Size: Integer); static; class function DivideBy3Exactly(const A: BigInteger): BigInteger; static; class procedure InternalDivModBurnikelZiegler(const Left, Right: BigInteger; var Quotient, Remainder: BigInteger); static; class procedure DivThreeHalvesByTwo(const LeftUpperMid, LeftLower, Right, RightUpper, RightLower: BigInteger; N: Integer; var Quotient, Remainder: BigInteger); static; class procedure DivTwoDigitsByOne(const Left, Right: BigInteger; N: Integer; var Quotient, Remainder: BigInteger); static; procedure AddWithOffset(const Addend: BigInteger; Offset: Integer); function Split(BlockSize, BlockCount: Integer): TArray<BigInteger>; class procedure SetBase(const Value: TNumberBase); static; class procedure Error(ErrorCode: TErrorCode; const ErrorInfo: string = ''); static; procedure Compact; procedure EnsureSize(RequiredSize: Integer); procedure MakeSize(RequiredSize: Integer); {$ENDREGION} public {$REGION 'public properties'} property Size: Integer read GetSize; property Allocated: Integer read GetAllocated; property Negative: Boolean read IsNegative; property Sign: Integer read GetSign write SetSign; property Magnitude: TMagnitude read FData; // -- Global numeric base for BigIntegers -- class property Base: TNumberBase read FBase write SetBase; class property StallAvoided: Boolean read FAvoidStall; class property RoundingMode: TRoundingMode read FRoundingMode write FRoundingMode; {$ENDREGION} end; function SignBitOf(Int: Integer): Integer; inline; function Min(const A, B: BigInteger): BigInteger; overload; inline; function Max(const A, B: BigInteger): BigInteger; overload; inline; //var // DoDebug: Boolean = True; implementation // To switch PUREPASCAL for debug purposes. UNDEF PUREPASCAL before the routine and DEFINE PUREPASCAL after the routine, if PP was defined. {$IFDEF PUREPASCAL} {$DEFINE PP} {$ENDIF} // Copy the following around the routine for which you want to switch off PUREPASCAL {$UNDEF PUREPASCAL} // Routine here. {$IFDEF PP} {$DEFINE PUREPASCAL} {$ENDIF} uses {$IFDEF DEBUG} Windows, {$ENDIF} Velthuis.Sizes, Velthuis.Numerics; {$POINTERMATH ON} {$IFDEF DEBUG} function Join(const Delimiter: string; const Values: array of string): string; var I: Integer; begin if Length(Values) > 0 then begin Result := Values[0]; for I := 1 to High(Values) do Result := Delimiter + Result; end; end; function DumpPLimb(P: PLimb; Size: Integer): string; var SL: TArray<string>; I: Integer; begin Result := ''; SetLength(SL, Size); for I := 0 to Size - 1 do SL[I] := Format('%.8x', [P[Size - I - 1]]); Result := Result + Join(' ', SL); end; procedure Debug(const Msg: string; const Params: array of const); overload; begin if not DoDebug then Exit; if IsConsole then // Write to console. Writeln(System.ErrOutput, Format(Msg, Params)) else // Inside the IDE, this will be displayed in the Event Log. OutputDebugString(PChar(Format(Msg, Params))); end; procedure Debug(const Msg: string); overload; begin Debug(Msg, []); end; {$ELSE} procedure Debug(const Msg: string; const Params: array of const); begin end; {$ENDIF} const CTimingLoops = $40000; {$IFNDEF PUREPASCAL} procedure Timing(var T1, T2, T3: UInt64); stdcall; {$IFDEF WIN32} asm RDTSC MOV ECX,T1 MOV DWORD PTR [ECX],EAX MOV DWORD PTR [ECX+4],EDX XOR EAX,EAX MOV EDX,CTimingLoops @ADCLoop: ADC EAX,[ECX] // Partial-flags stall on some "older" processors causes a measurable timing difference. DEC EDX // DEC only changes one flag, not entire flags register, causing a stall when ADC reads flag register. JNE @ADCLoop RDTSC MOV ECX,T2 MOV [ECX],EAX MOV [ECX+4],EDX XOR EAX,EAX MOV EDX,CTimingLoops NOP @ADDLoop: ADD EAX,[ECX] // ADD does not read carry flag, so no partial-flags stall. DEC EDX JNE @ADDLoop RDTSC MOV ECX,T3 MOV [ECX],EAX MOV [ECX+4],EDX end; {$ELSE} asm MOV R9,RDX RDTSC MOV [RCX],EAX MOV [RCX+4],EDX XOR EAX,EAX MOV EDX,CTimingLoops @ADCLoop: ADC EAX,[RCX] DEC EDX JNE @ADCLoop RDTSC MOV [R9],EAX MOV [R9+4],EDX XOR EAX,EAX MOV EDX,CTimingLoops NOP @ADDLoop: ADD EAX,[RCX] DEC EDX JNE @ADDLoop RDTSC MOV [R8],EAX MOV [R8+4],EDX end; {$ENDIF} class procedure BigInteger.DetectPartialFlagsStall; var T1, T2, T3: UInt64; I1, I2: UInt64; begin Randomize; repeat Timing(T1, T2, T3); I1 := T2 - T1; I2 := T3 - T2; Debug('Timing: %d / %d = %.2f', [I1, I2, I1 / I2]); // Make sure timings are far enough apart. Repeat if in "grey area" inbetween. if I1 / I2 > 4.0 then begin AvoidPartialFlagsStall(True); Exit; end else if I1 / I2 < 2.0 then begin AvoidPartialFlagsStall(False); Exit; end; until False; end; {$ENDIF !PUREPASCAL} procedure DivMod64(Dividend: UInt64; Divisor: UInt64; var Result, Remainder: UInt64); overload; {$IF DEFINED(CPUX64) and NOT DEFINED(PUREPASCAL_X64)} asm MOV R10,RDX MOV RAX,RCX XOR EDX,EDX DIV R10 MOV [R8],RAX MOV [R9],RDX end; {$ELSE} // Merged from system __lludiv and __llumod asm PUSH EBX PUSH ESI PUSH EDI PUSH EAX PUSH EDX // // Now the stack looks something like this: // // 40[esp]: Dividend(high dword) // 36[esp]: Dividend(low dword) // 32[esp]: divisor (high dword) // 28[esp]: divisor (low dword) // 24[esp]: return EIP // 20[esp]: previous EBP // 16[esp]: previous EBX // 12[esp]: previous ESI // 8[esp]: previous EDI // 4[esp]: previous EAX Result ptr // [esp]: previous EDX Remainder ptr // MOV EBX,28[ESP] // get the divisor low word MOV ECX,32[ESP] // get the divisor high word MOV EAX,36[ESP] // get the dividend low word MOV EDX,40[ESP] // get the dividend high word OR ECX,ECX JNZ @DivMod64@slow_ldiv // both high words are zero OR EDX,EDX JZ @DivMod64@quick_ldiv OR EBX,EBX JZ @DivMod64@quick_ldiv // if ecx:ebx == 0 force a zero divide // we don't expect this to actually // work @DivMod64@slow_ldiv: MOV EBP,ECX MOV ECX,64 // shift counter XOR EDI,EDI // fake a 64 bit dividend XOR ESI,ESI // @DivMod64@xloop: SHL EAX,1 // shift dividend left one bit RCL EDX,1 RCL ESI,1 RCL EDI,1 CMP EDI,EBP // dividend larger? JB @DivMod64@nosub JA @DivMod64@subtract CMP ESI,EBX // maybe JB @DivMod64@nosub @DivMod64@subtract: SUB ESI,EBX SBB EDI,EBP // subtract the divisor INC EAX // build quotient @DivMod64@nosub: LOOP @DivMod64@xloop // // When done with the loop the four registers values' look like: // // | edi | esi | edx | eax | // | remainder | quotient | // JMP @DivMod64@finish @DivMod64@quick_ldiv: DIV EBX // unsigned divide MOV ESI,EDX XOR EDX,EDX XOR EDI,EDI @DivMod64@finish: POP EBX POP ECX MOV [EBX],ESI MOV [EBX+4],EDI MOV [ECX],EAX MOV [ECX+4],EDX POP EDI POP ESI POP EBX end; {$ifend} (* begin Result := Dividend div Divisor; Remainder := Dividend mod Divisor; end; *) resourcestring SErrorBigIntegerParsing = '''%s'' is not a valid big integer value'; SDivisionByZero = 'Division by zero'; SInvalidOperation = 'Invalid operation'; SConversionFailed = 'BigInteger value too large for conversion to %s'; SOverflow = 'Double parameter may not be NaN or +/- Infinity'; SInvalidArgumentBase = 'Base parameter must be in the range 2..36.'; SSqrtBigInteger = 'Negative values not allowed for Sqrt'; {$RANGECHECKS OFF} {$OVERFLOWCHECKS OFF} {$POINTERMATH ON} {$STACKFRAMES OFF} type TUInt64 = record Lo, Hi: UInt32; end; const // Size of a single limb, used in e.g. asm blocks. CLimbSize = SizeOf(TLimb); // Double limb, for 64 bit access DLimbSize = 2 * CLimbSize; // Array mapping a digit in a specified base to its textual representation. CBaseChars: array[0..35] of Char = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; CNumBase = Ord('0'); CAlphaBase = Ord('A'); // Array mapping a specified base to the maximum number of digits required to represent one limb in that base. // They map a specified base to Ceil(32 / Log2(base)). CStringMaxLengths: array[TNumberBase] of Integer = ( 32, 21, 16, 14, 13, 12, 11, 11, 10, 10, 9, 9, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 ); CStringMinLengths: array[TNumberBase] of Integer = ( 32, 20, 16, 13, 12, 11, 10, 10, 9, 9, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 ); // Various useful sizes and bitcounts. CLimbBits = CByteBits * CLimbSize; CLimbWords = CLimbSize div SizeOf(Word); CUInt64Limbs = SizeOf(UInt64) div CLimbSize; CInt64Limbs = SizeOf(Int64) div CLimbSize; function IntMax(Left, Right: UInt32): UInt32; {$IFNDEF PUREPASCAL} {$IFDEF WIN32} asm CMP EAX,EDX CMOVB EAX,EDX end; {$ELSE WIN64} asm MOV EAX,ECX CMP EAX,EDX CMOVB EAX,EDX end; {$ENDIF} {$ELSE} begin Result := Left; if Left < Right then Result := Right; end; {$ENDIF} function IntMin(Left, Right: UInt32): UInt32; {$IFNDEF PUREPASCAL} {$IFDEF WIN32} asm CMP EAX,EDX CMOVA EAX,EDX end; {$ELSE WIN64} asm MOV EAX,ECX CMP EAX,EDX CMOVA EAX,EDX end; {$ENDIF} {$ELSE} begin Result := Left; if Left > Right then Result := Right; end; {$ENDIF} function ShouldUseBurnikelZiegler(LSize, RSize: Integer): Boolean; inline; begin // http://mail.openjdk.java.net/pipermail/core-libs-dev/2013-November/023493.html Result := (RSize >= BigInteger.BurnikelZieglerThreshold) and ((LSize - RSize) >= BigInteger.BurnikelZieglerOffsetThreshold); end; function SizeBitsOf(Int: Integer): Integer; inline; begin Result := Int and BigInteger.SizeMask; end; function SignBitOf(Int: Integer): Integer; inline; begin Result := Int and BigInteger.SignMask; end; function Min(const A, B: BigInteger): BigInteger; inline; begin Result := BigInteger.Min(A, B); end; function Max(const A, B: BigInteger): BigInteger; inline; begin Result := BigInteger.Max(A, B); end; function GreaterSize(Left, Right: Integer): Integer; inline; begin Result := IntMax(SizeBitsOf(Left), SizeBitsOf(Right)); end; function LesserSize(Left, Right: Integer): Integer; inline; begin Result := IntMin(SizeBitsOf(Left), SizeBitsOf(Right)); end; function AllocLimbs(Size: Integer): PLimb; inline; begin GetMem(Result, Size * CLimbSize); end; procedure CopyLimbs(Src, Dest: PLimb; Count: Integer); inline; begin Move(Src^, Dest^, Count * CLimbSize); end; { TBigInteger } procedure ShallowCopy(const Value: BigInteger; var Result: BigInteger); inline; begin Result.FSize := Value.FSize; Result.FData := Value.FData; end; procedure DeepCopy(const Value: BigInteger; var Result: BigInteger); inline; begin Result.FSize := Value.FSize; Result.FData := Copy(Value.FData); end; class function BigInteger.Abs(const Int: BigInteger): BigInteger; begin ShallowCopy(Int, Result); Result.SetSign(0); end; class function BigInteger.Add(const Left, Right: BigInteger): BigInteger; var Res: BigInteger; LSize, RSize: Integer; SignBit: Integer; Comparison: TValueSign; begin if Left.FData = nil then begin ShallowCopy(Right, Result); Exit; end else if Right.FData = nil then begin ShallowCopy(Left, Result); Exit; end; LSize := SizeBitsOf(Left.FSize); RSize := SizeBitsOf(Right.FSize); Res.MakeSize(IntMax(LSize, RSize) + 1); if ((Left.FSize xor Right.FSize) and SignMask) = 0 then begin // Same sign: add both magnitudes and transfer sign. FInternalAdd(PLimb(Left.FData), PLimb(Right.FData), PLimb(Res.FData), LSize, RSize); SignBit := SignBitOf(Left.FSize); end else begin Comparison := InternalCompare(PLimb(Left.FData), PLimb(Right.FData), Left.FSize and SizeMask, Right.FSize and SizeMask); case Comparison of -1: // Left < Right begin FInternalSubtract(PLimb(Right.FData), PLimb(Left.FData), PLimb(Res.FData), RSize, LSize); SignBit := SignBitOf(Right.FSize); end; 1: // Left > Right begin FInternalSubtract(PLimb(Left.FData), PLimb(Right.FData), PLimb(Res.FData), LSize, RSize); SignBit := SignBitOf(Left.FSize); end; else // Left = Right begin // Left and Right have equal magnitude but different sign, so return 0. ShallowCopy(Zero, Result); Exit; end; end; end; Res.FSize := (Res.FSize and SizeMask) or SignBit; Res.Compact; ShallowCopy(Res, Result); end; class operator BigInteger.Add(const Left, Right: BigInteger): BigInteger; begin Result := Add(Left, Right); end; class procedure BigInteger.Binary; begin FBase := 2; end; class procedure BigInteger.InternalAnd(Left, Right, Result: PLimb; LSize, RSize: Integer); {$IFDEF PUREPASCAL} var I: Integer; begin if LSize < RSize then RSize := LSize; for I := 0 to RSize - 1 do Result[I] := Left[I] and Right[I]; end; {$ELSE !PUREPASCAL} {$IFDEF WIN32} asm PUSH ESI PUSH EDI PUSH EBX MOV EBX,RSize MOV EDI,LSize CMP EDI,EBX JAE @SkipSwap XCHG EBX,EDI XCHG EAX,EDX @SkipSwap: MOV EDI,EBX AND EDI,CUnrollMask SHR EBX,CUnrollShift JE @MainTail @MainLoop: MOV ESI,[EAX] AND ESI,[EDX] MOV [ECX],ESI MOV ESI,[EAX + CLimbSize] AND ESI,[EDX + CLimbSize] MOV [ECX + CLimbSize],ESI MOV ESI,[EAX + 2*CLimbSize] AND ESI,[EDX + 2*CLimbSize] MOV [ECX + 2*CLimbSize],ESI MOV ESI,[EAX + 3*CLimbSize] AND ESI,[EDX + 3*CLimbSize] MOV [ECX + 3*CLimbSize],ESI LEA EAX,[EAX + 4*CLimbSize] LEA EDX,[EDX + 4*CLimbSize] LEA ECX,[ECX + 4*CLimbSize] DEC EBX JNE @MainLoop @MainTail: LEA EAX,[EAX + EDI*CLimbSize] LEA EDX,[EDX + EDI*CLimbSize] LEA ECX,[ECX + EDI*CLimbSize] LEA EBX,[@JumpsMain] JMP [EBX + EDI*TYPE Pointer] // Align jump tables manually, with NOPs. @JumpsMain: DD @Exit DD @Main1 DD @Main2 DD @Main3 @Main3: MOV ESI,[EAX - 3*CLimbSize] AND ESI,[EDX - 3*CLimbSize] MOV [ECX - 3*CLimbSize],ESI @Main2: MOV ESI,[EAX - 2*CLimbSize] AND ESI,[EDX - 2*CLimbSize] MOV [ECX - 2*CLimbSize],ESI @Main1: MOV ESI,[EAX - CLimbSize] AND ESI,[EDX - CLimbSize] MOV [ECX - CLimbSize],ESI @Exit: POP EBX POP EDI POP ESI end; {$ELSE WIN64} asm MOV R10D,RSize CMP R9D,R10D JAE @SkipSwap XCHG R10D,R9D XCHG RCX,RDX @SkipSwap: MOV R9D,R10D AND R9D,CUnrollMask SHR R10D,CUnrollShift JE @MainTail @MainLoop: MOV RAX,[RCX] AND RAX,[RDX] MOV [R8],RAX MOV RAX,[RCX + DLimbSize] AND RAX,[RDX + DLimbSize] MOV [R8 + DLimbSize],RAX LEA RCX,[RCX + 2*DLimbSize] LEA RDX,[RDX + 2*DLimbSize] LEA R8,[R8 + 2*DLimbSize] DEC R10D JNE @MainLoop @MainTail: LEA RCX,[RCX + R9*CLimbSize] LEA RDX,[RDX + R9*CLimbSize] LEA R8,[R8 + R9*CLimbSize] LEA R10,[@JumpsMain] JMP [R10 + R9*TYPE Pointer] // Align jump table manually, with NOPs NOP NOP NOP @JumpsMain: DQ @Exit DQ @Main1 DQ @Main2 DQ @Main3 @Main3: MOV EAX,[RCX - 3*CLimbSize] AND EAX,[RDX - 3*CLimbSize] MOV [R8 - 3*CLimbSize],EAX @Main2: MOV EAX,[RCX - 2*CLimbSize] AND EAX,[RDX - 2*CLimbSize] MOV [R8 - 2*CLimbSize],EAX @Main1: MOV EAX,[RCX - CLimbSize] AND EAX,[RDX - CLimbSize] MOV [R8 - CLimbSize],EAX @Exit: end; {$ENDIF WIN64} {$ENDIF !PUREPASCAL} class procedure BigInteger.InternalXor(Left, Right, Result: PLimb; LSize, RSize: Integer); {$IFDEF PUREPASCAL} var I: Integer; P: PLimb; begin if LSize < RSize then begin // Swap left and right pointers and sizes. I := LSize; LSize := RSize; RSize := I; P := Left; Left := Right; Right := P; end; for I := 0 to RSize - 1 do Result[I] := Left[I] xor Right[I]; for I := RSize to LSize - 1 do Result[I] := Left[I]; end; {$ELSE !PUREPASCAL} {$IFDEF WIN32} asm PUSH ESI PUSH EDI PUSH EBX MOV EBX,RSize MOV EDI,LSize CMP EDI,EBX JAE @SkipSwap XCHG EBX,EDI XCHG EAX,EDX @SkipSwap: SUB EDI,EBX PUSH EDI // Number of "tail" loops MOV EDI,EBX AND EDI,CUnrollMask SHR EBX,CUnrollShift JE @MainTail @MainLoop: MOV ESI,[EAX] XOR ESI,[EDX] MOV [ECX],ESI MOV ESI,[EAX + CLimbSize] XOR ESI,[EDX + CLimbSize] MOV [ECX + CLimbSize],ESI MOV ESI,[EAX + 2*CLimbSize] XOR ESI,[EDX + 2*CLimbSize] MOV [ECX + 2*CLimbSize],ESI MOV ESI,[EAX + 3*CLimbSize] XOR ESI,[EDX + 3*CLimbSize] MOV [ECX + 3*CLimbSize],ESI LEA EAX,[EAX + 4*CLimbSize] LEA EDX,[EDX + 4*CLimbSize] LEA ECX,[ECX + 4*CLimbSize] DEC EBX JNE @MainLoop @MainTail: LEA EAX,[EAX + EDI*CLimbSize] LEA EDX,[EDX + EDI*CLimbSize] LEA ECX,[ECX + EDI*CLimbSize] LEA EBX,[@JumpsMain] JMP [EBX + EDI*TYPE Pointer] // Align jump table manually, with NOPs NOP @JumpsMain: DD @DoRestLoop DD @Main1 DD @Main2 DD @Main3 @Main3: MOV ESI,[EAX - 3*CLimbSize] XOR ESI,[EDX - 3*CLimbSize] MOV [ECX - 3*CLimbSize],ESI @Main2: MOV ESI,[EAX - 2*CLimbSize] XOR ESI,[EDX - 2*CLimbSize] MOV [ECX - 2*CLimbSize],ESI @Main1: MOV ESI,[EAX - CLimbSize] XOR ESI,[EDX - CLimbSize] MOV [ECX - CLimbSize],ESI @DoRestLoop: XOR EDX,EDX POP EBX MOV EDI,EBX AND EDI,CUnrollMask SHR EBX,CunrollShift JE @RestLast3 @RestLoop: MOV EDX,[EAX] MOV [ECX],EDX MOV EDX,[EAX + CLimbSize] MOV [ECX + CLimbSize],EDX MOV EDX,[EAX + 2*CLimbSize] MOV [ECX + 2*CLimbSize],EDX MOV EDX,[EAX + 3*CLimbSize] MOV [ECX + 3*CLimbSize],EDX LEA EAX,[EAX + 4*CLimbSize] LEA ECX,[ECX + 4*CLimbSize] DEC EBX JNE @RestLoop @RestLast3: LEA EAX,[EAX + EDI*CLimbSize] LEA ECX,[ECX + EDI*CLimbSize] LEA EBX,[@RestJumps] JMP [EBX + EDI*TYPE Pointer] // Align jump table manually, with NOPs. NOP NOP @RestJumps: DD @Exit DD @Rest1 DD @Rest2 DD @Rest3 @Rest3: MOV EDX,[EAX - 3*CLimbSize] MOV [ECX - 3*CLimbSize],EDX @Rest2: MOV EDX,[EAX - 2*CLimbSize] MOV [ECX - 2*CLimbSize],EDX @Rest1: MOV EDX,[EAX - CLimbSize] MOV [ECX - CLimbSize],EDX @Exit: POP EBX POP EDI POP ESI end; {$ELSE WIN64} asm MOV R10D,RSize CMP R9D,R10D JAE @SkipSwap XCHG R10D,R9D XCHG RCX,RDX @SkipSwap: SUB R9D,R10D PUSH R9 MOV R9D,R10D AND R9D,CUnrollMask SHR R10D,CUnrollShift JE @MainTail @MainLoop: MOV RAX,[RCX] XOR RAX,[RDX] MOV [R8],RAX MOV RAX,[RCX + DLimbSize] XOR RAX,[RDX + DLimbSize] MOV [R8 + DLimbSize],RAX LEA RCX,[RCX + 2*DLimbSize] LEA RDX,[RDX + 2*DLimbSize] LEA R8,[R8 + 2*DLimbSize] DEC R10D JNE @MainLoop @MainTail: LEA RCX,[RCX + R9*CLimbSize] LEA RDX,[RDX + R9*CLimbSize] LEA R8,[R8 + R9*CLimbSize] LEA R10,[@JumpsMain] JMP [R10 + R9*TYPE Pointer] @JumpsMain: DQ @DoRestLoop DQ @Main1 DQ @Main2 DQ @Main3 @Main3: MOV EAX,[RCX - 3*CLimbSize] XOR EAX,[RDX - 3*CLimbSize] MOV [R8 - 3*CLimbSize],EAX @Main2: MOV EAX,[RCX - 2*CLimbSize] XOR EAX,[RDX - 2*CLimbSize] MOV [R8 - 2*CLimbSize],EAX @Main1: MOV EAX,[RCX - CLimbSize] XOR EAX,[RDX - CLimbSize] MOV [R8 - CLimbSize],EAX @DoRestLoop: POP R10 TEST R10D,R10D JE @Exit MOV R9D,R10D AND R9D,CUnrollMask SHR R10D,CUnrollShift JE @RestLast3 @RestLoop: MOV RAX,[RCX] MOV [R8],RAX MOV RAX,[RCX + DLimbSize] MOV [R8 + DLimbSize],RAX LEA RCX,[RCX + 2*DLimbSize] LEA R8,[R8 + 2*DLimbSize] DEC R10D JNE @RestLoop @RestLast3: LEA RCX,[RCX + R9*CLimbSize] LEA R8,[R8 + R9*CLimbSize] LEA R10,[@RestJumps] JMP [R10 + R9*TYPE Pointer] @RestJumps: DQ @Exit DQ @Rest1 DQ @Rest2 DQ @Rest3 @Rest3: MOV EAX,[RCX - 3*CLimbSize] MOV [R8 - 3*CLimbSize],EAX @Rest2: MOV EAX,[RCX - 2*CLimbSize] MOV [R8 - 2*CLimbSize],EAX @Rest1: MOV EAX,[RCX - CLimbSize] MOV [R8 - CLimbSize],EAX @Exit: end; {$ENDIF WIN64} {$ENDIF !PUREPASCAL} class procedure BigInteger.InternalOr(Left, Right, Result: PLimb; LSize, RSize: Integer); {$IFDEF PUREPASCAL} var I: Integer; P: PLimb; begin if LSize < RSize then begin // Swap left and right pointers and sizes. I := LSize; LSize := RSize; RSize := I; P := Left; Left := Right; Right := P; end; for I := 0 to RSize - 1 do Result[I] := Left[I] or Right[I]; for I := RSize to LSize - 1 do Result[I] := Left[I]; end; {$ELSE !PUREPASCAL} {$IFDEF WIN32} asm PUSH ESI PUSH EDI PUSH EBX MOV EBX,RSize MOV EDI,LSize CMP EDI,EBX JAE @SkipSwap XCHG EBX,EDI XCHG EAX,EDX @SkipSwap: SUB EDI,EBX PUSH EDI // Number of "rest" loops MOV EDI,EBX AND EDI,CUnrollMask SHR EBX,CUnrollShift JE @MainTail @MainLoop: MOV ESI,[EAX] OR ESI,[EDX] MOV [ECX],ESI MOV ESI,[EAX + CLimbSize] OR ESI,[EDX + CLimbSize] MOV [ECX + CLimbSize],ESI MOV ESI,[EAX + 2*CLimbSize] OR ESI,[EDX + 2*CLimbSize] MOV [ECX + 2*CLimbSize],ESI MOV ESI,[EAX + 3*CLimbSize] OR ESI,[EDX + 3*CLimbSize] MOV [ECX + 3*CLimbSize],ESI LEA EAX,[EAX + 4*CLimbSize] LEA EDX,[EDX + 4*CLimbSize] LEA ECX,[ECX + 4*CLimbSize] DEC EBX JNE @MainLoop @MainTail: LEA EAX,[EAX + EDI*CLimbSize] LEA EDX,[EDX + EDI*CLimbSize] LEA ECX,[ECX + EDI*CLimbSize] LEA EBX,[@JumpsMain] JMP [EBX + EDI*TYPE Pointer] // Align jump table manually, with NOPs NOP @JumpsMain: DD @DoRestLoop DD @Main1 DD @Main2 DD @Main3 @Main3: MOV ESI,[EAX - 3*CLimbSize] OR ESI,[EDX - 3*CLimbSize] MOV [ECX - 3*CLimbSize],ESI @Main2: MOV ESI,[EAX - 2*CLimbSize] OR ESI,[EDX - 2*CLimbSize] MOV [ECX - 2*CLimbSize],ESI @Main1: MOV ESI,[EAX - CLimbSize] OR ESI,[EDX - CLimbSize] MOV [ECX - CLimbSize],ESI @DoRestLoop: XOR EDX,EDX POP EBX MOV EDI,EBX AND EDI,CUnrollMask SHR EBX,CUnrollShift JE @RestLast3 @RestLoop: MOV EDX,[EAX] MOV [ECX],EDX MOV EDX,[EAX + CLimbSize] MOV [ECX + CLimbSize],EDX MOV EDX,[EAX + 2*CLimbSize] MOV [ECX + 2*CLimbSize],EDX MOV EDX,[EAX + 3*CLimbSize] MOV [ECX + 3*CLimbSize],EDX LEA EAX,[EAX + 4*CLimbSize] LEA ECX,[ECX + 4*CLimbSize] DEC EBX JNE @RestLoop @RestLast3: LEA EAX,[EAX + EDI*CLimbSize] LEA ECX,[ECX + EDI*CLimbSize] LEA EBX,[@RestJumps] JMP [EBX + EDI*TYPE Pointer] // Align jump table manually, with NOPs. NOP NOP @RestJumps: DD @Exit DD @Rest1 DD @Rest2 DD @Rest3 @Rest3: MOV EDX,[EAX - 3*CLimbSize] MOV [ECX - 3*CLimbSize],EDX @Rest2: MOV EDX,[EAX - 2*CLimbSize] MOV [ECX - 2*CLimbSize],EDX @Rest1: MOV EDX,[EAX - CLimbSize] MOV [ECX - CLimbSize],EDX @Exit: POP EBX POP EDI POP ESI end; {$ELSE WIN64} asm MOV R10D,RSize CMP R9D,R10D JAE @SkipSwap XCHG R10D,R9D XCHG RCX,RDX @SkipSwap: SUB R9D,R10D PUSH R9 MOV R9D,R10D AND R9D,CUnrollMask SHR R10D,CUnrollShift JE @MainTail @MainLoop: MOV RAX,[RCX] OR RAX,[RDX] MOV [R8],RAX MOV RAX,[RCX + DLimbSize] OR RAX,[RDX + DLimbSize] MOV [R8 + DLimbSize],RAX LEA RCX,[RCX + 2*DLimbSize] LEA RDX,[RDX + 2*DLimbSize] LEA R8,[R8 + 2*DLimbSize] DEC R10D JNE @MainLoop @MainTail: LEA RCX,[RCX + R9*CLimbSize] LEA RDX,[RDX + R9*CLimbSize] LEA R8,[R8 + R9*CLimbSize] LEA R10,[@JumpsMain] JMP [R10 + R9*TYPE Pointer] // Align jump table manually, with NOPs. DB $90,$90,$90,$90,$90,$90 @JumpsMain: DQ @DoRestLoop DQ @Main1 DQ @Main2 DQ @Main3 @Main3: MOV EAX,[RCX - 3*CLimbSize] OR EAX,[RDX - 3*CLimbSize] MOV [R8 - 3*CLimbSize],EAX @Main2: MOV EAX,[RCX - 2*CLimbSize] OR EAX,[RDX - 2*CLimbSize] MOV [R8 - 2*CLimbSize],EAX @Main1: MOV EAX,[RCX - CLimbSize] OR EAX,[RDX - CLimbSize] MOV [R8 - CLimbSize],EAX @DoRestLoop: POP R10 TEST R10D,R10D JE @Exit MOV R9D,R10D AND R9D,CUnrollMask SHR R10D,CUnrollShift JE @RestLast3 @RestLoop: MOV RAX,[RCX] MOV [R8],RAX MOV RAX,[RCX + DLimbSize] MOV [R8 + DLimbSize],RAX LEA RCX,[RCX + 2*DLimbSize] LEA R8,[R8 + 2*DLimbSize] DEC R10D JNE @RestLoop @RestLast3: LEA RCX,[RCX + R9*CLimbSize] LEA R8,[R8 + R9*CLimbSize] LEA R10,[@RestJumps] JMP [R10 + R9*TYPE Pointer] // Align jump table manually, with NOPs. // -- Aligned. @RestJumps: DQ @Exit DQ @Rest1 DQ @Rest2 DQ @Rest3 @Rest3: MOV EAX,[RCX - 3*CLimbSize] MOV [R8 - 3*CLimbSize],EAX @Rest2: MOV EAX,[RCX - 2*CLimbSize] MOV [R8 - 2*CLimbSize],EAX @Rest1: MOV EAX,[RCX - CLimbSize] MOV [R8 - CLimbSize],EAX @Exit: end; {$ENDIF WIN64} {$ENDIF !PUREPASCAL} class procedure BigInteger.InternalAndNot(Left, Right, Result: PLimb; LSize, RSize: Integer); {$IFDEF PUREPASCAL} var I: Integer; begin // Note: AndNot is - of course - not commutative. if LSize < RSize then RSize := LSize; for I := 0 to RSize - 1 do Result[I] := not Right[I] and Left[I]; for I := RSize to LSize - 1 do Result[I] := Left[I]; end; {$ELSE !PUREPASCAL} {$IFDEF WIN32} asm PUSH ESI PUSH EDI PUSH EBX MOV EBX,RSize MOV EDI,LSize CMP EDI,EBX JAE @SkipSwap MOV EBX,EDI @SkipSwap: SUB EDI,EBX PUSH EDI // Number of "rest" loops MOV EDI,EBX AND EDI,CUnrollMask SHR EBX,CUnrollShift JE @MainTail @MainLoop: MOV ESI,[EDX] NOT ESI AND ESI,[EAX] MOV [ECX],ESI MOV ESI,[EDX + CLimbSize] NOT ESI AND ESI,[EAX + CLimbSize] MOV [ECX + CLimbSize],ESI MOV ESI,[EDX + 2*CLimbSize] NOT ESI AND ESI,[EAX + 2*CLimbSize] MOV [ECX + 2*CLimbSize],ESI MOV ESI,[EDX + 3*CLimbSize] NOT ESI AND ESI,[EAX + 3*CLimbSize] MOV [ECX + 3*CLimbSize],ESI LEA EAX,[EAX + 4*CLimbSize] LEA EDX,[EDX + 4*CLimbSize] LEA ECX,[ECX + 4*CLimbSize] DEC EBX JNE @MainLoop @MainTail: LEA EAX,[EAX + EDI*CLimbSize] LEA EDX,[EDX + EDI*CLimbSize] LEA ECX,[ECX + EDI*CLimbSize] LEA EBX,[@JumpsMain] JMP [EBX + EDI*TYPE Pointer] // Align jump table manually, with NOPs NOP NOP @JumpsMain: DD @DoRestLoop DD @Main1 DD @Main2 DD @Main3 @Main3: MOV ESI,[EDX - 3*CLimbSize] NOT ESI AND ESI,[EAX - 3*CLimbSize] MOV [ECX - 3*CLimbSize],ESI @Main2: MOV ESI,[EDX - 2*CLimbSize] NOT ESI AND ESI,[EAX - 2*CLimbSize] MOV [ECX - 2*CLimbSize],ESI @Main1: MOV ESI,[EDX - CLimbSize] NOT ESI AND ESI,[EAX - CLimbSize] MOV [ECX - CLimbSize],ESI @DoRestLoop: XOR EDX,EDX POP EBX MOV EDI,EBX AND EDI,CUnrollMask SHR EBX,CUnrollShift JE @RestLast3 @RestLoop: // X AND NOT 0 = X AND -1 = X MOV EDX,[EAX] MOV [ECX],EDX MOV EDX,[EAX + CLimbSize] MOV [ECX + CLimbSize],EDX MOV EDX,[EAX + 2*CLimbSize] MOV [ECX + 2*CLimbSize],EDX MOV EDX,[EAX + 3*CLimbSize] MOV [ECX + 3*CLimbSize],EDX LEA EAX,[EAX + 4*CLimbSize] LEA ECX,[ECX + 4*CLimbSize] DEC EBX JNE @RestLoop @RestLast3: LEA EAX,[EAX + EDI*CLimbSize] LEA ECX,[ECX + EDI*CLimbSize] LEA EBX,[@RestJumps] JMP [EBX + EDI*TYPE Pointer] // Align jump table manually, with NOPs. @RestJumps: DD @Exit DD @Rest1 DD @Rest2 DD @Rest3 @Rest3: MOV EDX,[EAX - 3*CLimbSize] MOV [ECX - 3*CLimbSize],EDX @Rest2: MOV EDX,[EAX - 2*CLimbSize] MOV [ECX - 2*CLimbSize],EDX @Rest1: MOV EDX,[EAX - CLimbSize] MOV [ECX - CLimbSize],EDX @Exit: POP EBX POP EDI POP ESI end; {$ELSE WIN64} asm MOV R10D,RSize CMP R9D,R10D JAE @SkipSwap MOV R10D,R9D @SkipSwap: SUB R9D,R10D PUSH R9 MOV R9D,R10D AND R9D,CUnrollMask SHR R10D,CUnrollShift JE @MainTail @MainLoop: MOV RAX,[RDX] NOT RAX AND RAX,[RCX] MOV [R8],RAX MOV RAX,[RDX + DLimbSize] NOT RAX AND RAX,[RCX + DLimbSize] MOV [R8 + DLimbSize],RAX LEA RCX,[RCX + 2*DLimbSize] LEA RDX,[RDX + 2*DLimbSize] LEA R8,[R8 + 2*DLimbSize] DEC R10D JNE @MainLoop @MainTail: LEA RCX,[RCX + R9*CLimbSize] LEA RDX,[RDX + R9*CLimbSize] LEA R8,[R8 + R9*CLimbSize] LEA R10,[@JumpsMain] JMP [R10 + R9*TYPE Pointer] // Align jump table manually, with NOPs. DB $90,$90,$90 @JumpsMain: DQ @DoRestLoop DQ @Main1 DQ @Main2 DQ @Main3 @Main3: MOV EAX,[RDX - 3*CLimbSize] NOT EAX AND EAX,[RCX - 3*CLimbSize] MOV [R8 - 3*CLimbSize],EAX @Main2: MOV EAX,[RDX - 2*CLimbSize] NOT EAX AND EAX,[RCX - 2*CLimbSize] MOV [R8 - 2*CLimbSize],EAX @Main1: MOV EAX,[RDX - CLimbSize] NOT EAX AND EAX,[RCX - CLimbSize] MOV [R8 - CLimbSize],EAX @DoRestLoop: POP R10 TEST R10D,R10D JE @Exit MOV R9D,R10D AND R9D,CUnrollMask SHR R10D,CUnrollShift JE @RestLast3 @RestLoop: // X AND NOT 0 = X AND -1 = X MOV RAX,[RCX] MOV RDX,[RCX + DLimbSize] MOV [R8],RAX MOV [R8 + DLimbSize],RDX LEA RCX,[RCX + 2*DLimbSize] LEA R8,[R8 + 2*DLimbSize] DEC R10D JNE @RestLoop @RestLast3: LEA RCX,[RCX + R9*CLimbSize] LEA R8,[R8 + R9*CLimbSize] LEA R10,[@RestJumps] JMP [R10 + R9*TYPE Pointer] // Align jump table manually, with NOPs. DB $90,$90 @RestJumps: DQ @Exit DQ @Rest1 DQ @Rest2 DQ @Rest3 @Rest3: MOV EAX,[RCX - 3*CLimbSize] MOV [R8 - 3*CLimbSize],EAX @Rest2: MOV EAX,[RCX - 2*CLimbSize] MOV [R8 - 2*CLimbSize],EAX @Rest1: MOV EAX,[RCX - CLimbSize] MOV [R8 - CLimbSize],EAX @Exit: end; {$ENDIF WIN64} {$ENDIF !PUREPASCAL} class procedure BigInteger.InternalNotAnd(Left, Right, Result: PLimb; LSize, RSize: Integer); begin InternalAndNot(Right, Left, Result, RSize, LSize); end; class operator BigInteger.BitwiseAnd(const Left, Right: BigInteger): BigInteger; begin // Special handling for 0. if (Left.FData = nil) or (Right.FData = nil) then begin Result.FData := nil; Result.FSize := 0; Exit; end; InternalBitwise(Left, Right, Result, InternalAnd, InternalOr, InternalAndNot); end; class operator BigInteger.BitwiseOr(const Left, Right: BigInteger): BigInteger; begin // Special handling for 0. if Left.FData = nil then begin ShallowCopy(Right, Result); Exit; end else if Right.FData = nil then begin ShallowCopy(Left, Result); Exit; end; InternalBitwise(Left, Right, Result, InternalOr, InternalAnd, InternalNotAnd); end; class operator BigInteger.BitwiseXor(const Left, Right: BigInteger): BigInteger; begin // Special handling for 0. if Left.FData = nil then begin ShallowCopy(Right, Result); Exit; end else if Right.FData = nil then begin ShallowCopy(Left, Result); Exit; end; InternalBitwise(Left, Right, Result, InternalXor, InternalXor, InternalXor); end; function BigInteger.Clone: BigInteger; begin DeepCopy(Self, Result); end; function FindSize(Limb: PLimb; Size: Integer): Integer; {$IFDEF PUREPASCAL} begin while (Size > 0) and (Limb[Size - 1] = 0) do Dec(Size); Result := Size; end; {$ELSE} {$IFDEF WIN32} asm LEA EAX,[EAX + EDX * CLimbSize - CLimbSize] XOR ECX,ECX @Loop: CMP [EAX],ECX JNE @Exit LEA EAX,[EAX - CLimbSize] DEC EDX JNE @Loop @Exit: MOV EAX,EDX end; {$ELSE !WIN32} asm LEA RAX,[RCX + RDX * CLimbSize - CLimbSize] XOR ECX,ECX @Loop: CMP [RAX],ECX JNE @Exit LEA RAX,[RAX - CLimbSize] DEC EDX JNE @Loop @Exit: MOV EAX,EDX end; {$ENDIF !WIN32} {$ENDIF} procedure BigInteger.Compact; var NewSize: Integer; begin if FData = nil then begin FSize := 0; Exit; end; NewSize := FindSize(PLimb(FData), FSize and SizeMask); if NewSize < (FSize and SizeMask) then begin if NewSize = 0 then begin FSize := 0; FData := nil; end else begin FSize := SignBitOf(FSize) or NewSize; {$IFDEF RESETSIZE} SetLength(FData, (NewSize + 4) and CapacityMask); {$ENDIF} end; end; end; class function BigInteger.Compare(const Left, Right: BigInteger): TValueSign; begin Result := InternalCompare(PLimb(Left.FData), PLimb(Right.FData), Left.FSize and SizeMask, Right.FSize and SizeMask); if Left.FSize < 0 then if Right.FSize < 0 then Result := -Result else Result := -1 else if Right.FSize < 0 then Result := 1; end; constructor BigInteger.Create(const Int: Integer); begin Create(Cardinal(System.Abs(Int))); if Int < 0 then FSize := FSize or SignMask; end; constructor BigInteger.Create(const Int: BigInteger); begin Self.FSize := Int.FSize; Self.FData := Int.FData; end; constructor BigInteger.Create(const Data: TMagnitude; Negative: Boolean); begin FSize := Length(Data) or (Ord(Negative) * SignMask); FData := Copy(Data); Compact; end; constructor BigInteger.Create(const Int: UInt64); begin FData := nil; if Int <> 0 then begin if Int > High(UInt32) then FSize := CUInt64Limbs else FSize := 1; SetLength(FData, 4); Move(Int, FData[0], SizeOf(Int)); end else begin FData := nil; FSize := 0; end; end; const CMantissaBits = 52; CMaxShift = 62; function IsDenormal(const ADouble: Double): Boolean; inline; begin Result := (PUInt64(@ADouble)^ and (UInt64($7FF) shl CMantissaBits)) = 0 end; function MantissaOf(const ADouble: Double): UInt64; inline; begin Result := PUInt64(@ADouble)^ and (UInt64(-1) shr (64 - CMantissaBits)); if not IsDenormal(ADouble) then Result := Result or (UInt64(1) shl CMantissaBits); end; function ExponentOf(const ADouble: Double): Integer; begin Result := ((PUInt64(@ADouble)^ shr CMantissaBits) and $7FF) - 1023; if Result = -1023 then Result := -1022; end; function SignOf(const ADouble: Double): Boolean; begin Result := PInt64(@ADouble)^ < 0; end; constructor BigInteger.Create(const ADouble: Double); var Exponent: Integer; Mantissa: UInt64; Sign, Guard, Round, Sticky: Boolean; Shift: Integer; ZeroExponentLimit: Integer; begin FSize := 0; // FData := nil; // Error for special values. if IsNan(ADouble) or IsInfinite(ADouble) then Error(ecOverflow); // Get the required values from TDoubleHelper. Mantissa := MantissaOf(ADouble); Exponent := ExponentOf(ADouble); Sign := SignOf(ADouble); // Make 0 for denormal values and values < 0.5. if FRoundingMode <> rmTruncate then ZeroExponentLimit := -1 else ZeroExponentLimit := 0; // Denormals and values with small exponent convert to 0. if IsDenormal(ADouble) or (Exponent < ZeroExponentLimit) then begin Self := BigInteger.Zero; Exit; end; // Internal shift of the mantissa. Shift := Exponent; if Shift > CMaxShift then Shift := CMaxShift; // Guard, Round and Sticky bits are used to determine rounding, see comments in function AsDouble. Guard := False; Round := False; Sticky := False; if (FRoundingMode <> rmTruncate) and (Exponent < CMantissaBits) then begin // Round anything with a fraction >= 0.5 away from 0. No Round and Sticky bits required. Guard := ((UInt64(1) shl (CMantissaBits - 1 - Exponent)) and Mantissa) <> 0; if FRoundingMode = rmRound then begin // Only if full rounding (like System.Round() performs) is required: Round any fraction > 0.5 away from 0. Round := ((UInt64(1) shl (CMantissaBits - 2 - Exponent)) and Mantissa) <> 0; Sticky := ((Int64(-1) shr (Exponent + (64 - CMantissaBits + 2))) and Mantissa) <> 0; end; end; // Shift mantissa left or right to get the most bits out of it before converting to BigInteger. if Shift > CMantissaBits then Mantissa := Mantissa shl (Shift - CMantissaBits) else Mantissa := Mantissa shr (CMantissaBits - Shift); // Round shifted mantissa. if ((RoundingMode = rmSchool) and Guard) or ((RoundingMode = rmRound) and (Guard and (Round or Sticky))) then Inc(Mantissa); // Turn shifted mantissa (a UInt64) into BigInteger. Self := 0; Self.Create(UInt64(Mantissa)); // Shift left by the restant value of the exponent. if Exponent > Shift then Self := Self shl (Exponent - Shift); if Sign then FSize := FSize or SignMask; end; // Bytes are considered to contain value in two's complement format. constructor BigInteger.Create(const Bytes: array of Byte); var Limbs: TMagnitude; Negative: Boolean; begin Negative := Bytes[High(Bytes)] >= $80; SetLength(Limbs, (Length(Bytes) + 3) div 4); if Negative then Limbs[High(Limbs)] := TLimb(-1); Move((@Bytes[0])^, PLimb(Limbs)^, Length(Bytes)); if Negative then InternalNegate(PLimb(Limbs), PLimb(Limbs), Length(Limbs)); Create(Limbs, Negative); end; // This assumes sign-magnitude format. constructor BigInteger.Create(const Limbs: array of TLimb; Negative: Boolean); var LSize: Integer; begin LSize := Length(Limbs); MakeSize(LSize); FSize := LSize or (Ord(Negative) * SignMask); if LSize > 0 then CopyLimbs(@Limbs[0], PLimb(FData), LSize); Compact; end; constructor BigInteger.Create(const Int: Int64); begin Create(UInt64(System.Abs(Int))); if Int < 0 then FSize := FSize or SignMask; end; constructor BigInteger.Create(const Int: Cardinal); begin if Int <> 0 then begin FSize := 1; SetLength(FData, 4); FData[0] := Int; end else begin FData := nil; FSize := 0; end; end; constructor BigInteger.Create(NumBits: Integer; const Random: IRandom); var Bytes: TArray<Byte>; Bits: Byte; begin if NumBits = 0 then begin ShallowCopy(Zero, Self); Exit; end; SetLength(Bytes, (NumBits + 7) shr 3 + 1); Random.NextBytes(Bytes); // One byte too many was allocated, to get a top byte of 0, i.e. always positive. Bytes[High(Bytes)] := 0; // Set bits above required bit length to 0. Bits := NumBits and $07; Bytes[High(Bytes) - 1] := Bytes[High(Bytes) - 1] and ($7F shr (7 - Bits)); Create(Bytes); Compact; // Assert(BitLength <= Numbits, Format('BitLength (%d) >= NumBits (%d): %s', [BitLength, NumBits, Self.ToString(2)])); end; function BigInteger.GetAllocated: Integer; begin Result := Length(FData); end; function BigInteger.IsEven: Boolean; begin Result := IsZero or ((FData[0] and 1) = 0); end; function BigInteger.IsNegative: Boolean; begin Result := FSize < 0; end; function BigInteger.IsOne: Boolean; begin Result := (FSize = 1) and (FData[0] = 1); end; function BigInteger.IsPositive: Boolean; begin Result := FSize > 0; end; function BigInteger.IsPowerOfTwo: Boolean; var FirstNonZeroIndex: Integer; AHigh: Integer; begin AHigh := (FSize and SizeMask) - 1; if (FData = nil) or not Velthuis.Numerics.IsPowerOfTwo(FData[AHigh]) then Result := False else begin FirstNonZeroIndex := 0; // All limbs below top one must be 0 while FData[FirstNonZeroIndex] = 0 do Inc(FirstNonZeroIndex); // Top limb must be power of two. Result := (FirstNonZeroIndex = AHigh); end; end; function BigInteger.GetSign: Integer; begin if FData = nil then begin FSize := 0; Exit(0); end; if FSize > 0 then Result := 1 else Result := -1 end; function BigInteger.GetSize: Integer; begin if FData = nil then FSize := 0; Result := FSize and SizeMask; end; function BigInteger.Data: PLimb; begin Result := PLimb(FData); end; class operator BigInteger.GreaterThan(const Left, Right: BigInteger): Boolean; begin Result := Compare(Left, Right) > 0; // Result := not (Left <= Right); end; class operator BigInteger.GreaterThanOrEqual(const Left, Right: BigInteger): Boolean; begin Result := Compare(left, Right) >= 0; end; // http://en.wikipedia.org/wiki/Binary_GCD_algorithm class function BigInteger.GreatestCommonDivisor(const Left, Right: BigInteger): BigInteger; var Shift: Integer; ALeft, ARight, Temp: BigInteger; begin // GCD(left, 0) = left; GCD(0, right) = right; GCD(0, 0) = 0 if Left.IsZero then Exit(Abs(Right)); if Right.IsZero then Exit(Abs(Left)); // Let Shift = Log2(K), where K is the greatest power of 2 dividing both ALeft and ARight. ALeft := Abs(Left); ARight := Abs(Right); Shift := 0; while ALeft.IsEven and ARight.IsEven do begin ALeft := ALeft shr 1; ARight := ARight shr 1; Inc(Shift); end; while ALeft.IsEven do ALeft := ALeft shr 1; // Now, ALeft is always odd. repeat // Remove all factors of 2 in ARight, since they are not in common. // ARight is not 0, so the loop will terminate while ARight.IsEven do ARight := ARight shr 1; // ALeft and ARight are both odd. Swap if necessary, so that ALeft <= ARight, // then set ARight to ARight - ALeft (which is even). if ALeft > ARight then begin // Swap ALeft and ALeft. Temp := ALeft; ALeft := ARight; ARight := Temp; end; ARight := ARight - ALeft; until ARight = 0; // Restore common factors of 2. Result := ALeft shl Shift; end; class procedure BigInteger.Hexadecimal; begin FBase := 16; end; class procedure BigInteger.Hex; begin FBase := 16; end; class operator BigInteger.Implicit(const Int: Cardinal): BigInteger; begin Result := BigInteger.Create(Int); end; class operator BigInteger.Implicit(const Int: Integer): BigInteger; begin Result := BigInteger.Create(Int); end; class operator BigInteger.Implicit(const Int: UInt64): BigInteger; begin Result := BigInteger.Create(Int); end; class operator BigInteger.Implicit(const Int: Int64): BigInteger; begin Result := BigInteger.Create(Int); end; class constructor BigInteger.Initialize; begin MinusOne := -1; Zero.FSize := 0; Zero.FData := nil; One := 1; Ten := 10; FBase := 10; FRoundingMode := rmTruncate; {$IFNDEF PUREPASCAL} // See comments in BigInteger.InternalAddEmu. BigInteger.DetectPartialFlagsStall; {$ELSE} FInternalAdd := InternalAddPurePascal; FInternalSubtract := InternalSubtractPurePascal; {$ENDIF} end; class operator BigInteger.IntDivide(const Left, Right: BigInteger): BigInteger; begin Result := Divide(Left, Right); end; class operator BigInteger.IntDivide(const Left: BigInteger; Right: UInt16): BigInteger; begin Result := Divide(Left, Right); end; class operator BigInteger.IntDivide(const Left: BigInteger; Right: UInt32): BigInteger; begin Result := Divide(Left, Right); end; {$IFNDEF PUREPASCAL} class procedure BigInteger.InternalAddModified(Left, Right, Result: PLimb; LSize, RSize: Integer); {$IFDEF WIN32} asm PUSH ESI PUSH EDI PUSH EBX MOV ESI,EAX MOV EDI,EDX MOV EBX,ECX MOV ECX,RSize MOV EDX,LSize CMP EDX,ECX JAE @SkipSwap XCHG ECX,EDX XCHG ESI,EDI @SkipSwap: SUB EDX,ECX PUSH EDX XOR EDX,EDX XOR EAX,EAX MOV EDX,ECX AND EDX,CunrollMask SHR ECX,CunrollShift CLC JE @MainTail @MainLoop: MOV EAX,[ESI] ADC EAX,[EDI] MOV [EBX],EAX MOV EAX,[ESI + CLimbSize] ADC EAX,[EDI + CLimbSize] MOV [EBX + CLimbSize],EAX MOV EAX,[ESI + 2*CLimbSize] ADC EAX,[EDI + 2*CLimbSize] MOV [EBX + 2*CLimbSize],EAX MOV EAX,[ESI + 3*CLimbSize] ADC EAX,[EDI + 3*CLimbSize] MOV [EBX + 3*CLimbSize],EAX LEA ESI,[ESI + CUnrollIncrement*CLimbSize] LEA EDI,[EDI + CUnrollIncrement*CLimbSize] LEA EBX,[EBX + CUnrollIncrement*CLimbSize] LEA ECX,[ECX - 1] JECXZ @Maintail JMP @Mainloop @MainTail: LEA ESI,[ESI + EDX*CLimbSize] LEA EDI,[EDI + EDX*CLimbSize] LEA EBX,[EBX + EDX*CLimbSize] LEA ECX,[@JumpsMain] JMP [ECX + EDX*TYPE Pointer] // Align jump table manually, with NOPs. NOP @JumpsMain: DD @DoRestLoop DD @Main1 DD @Main2 DD @Main3 @Main3: MOV EAX,[ESI - 3*CLimbSize] ADC EAX,[EDI - 3*CLimbSize] MOV [EBX - 3*CLimbSize],EAX @Main2: MOV EAX,[ESI - 2*CLimbSize] ADC EAX,[EDI - 2*CLimbSize] MOV [EBX - 2*CLimbSize],EAX @Main1: MOV EAX,[ESI - CLimbSize] ADC EAX,[EDI - CLimbSize] MOV [EBX - CLimbSize],EAX @DoRestLoop: SETC AL // Save Carry Flag XOR EDI,EDI POP ECX MOV EDX,ECX AND EDX,CUnrollMask SHR ECX,CUnrollShift ADD AL,255 // Restore Carry Flag. JECXZ @RestLastN @RestLoop: MOV EAX,[ESI] ADC EAX,EDI MOV [EBX],EAX MOV EAX,[ESI + CLimbSize] ADC EAX,EDI MOV [EBX + CLimbSize],EAX MOV EAX,[ESI + 2*CLimbSize] ADC EAX,EDI MOV [EBX + 2*CLimbSize],EAX MOV EAX,[ESI + 3*CLimbSize] ADC EAX,EDI MOV [EBX + 3*CLimbSize],EAX LEA ESI,[ESI + CUnrollIncrement*CLimbSize] LEA EBX,[EBX + CUnrollIncrement*CLimbSize] LEA ECX,[ECX - 1] JECXZ @RestLastN JMP @RestLoop @RestLastN: LEA ESI,[ESI + EDX*CLimbSize] LEA EBX,[EBX + EDX*CLimbSize] LEA ECX,[@RestJumps] JMP [ECX + EDX*TYPE Pointer] // Align jump table manually, with NOPs. NOP @RestJumps: DD @LastLimb DD @Rest1 DD @Rest2 DD @Rest3 @Rest3: MOV EAX,[ESI - 3*CLimbSize] ADC EAX,EDI MOV [EBX - 3*CLimbSize],EAX @Rest2: MOV EAX,[ESI - 2*CLimbSize] ADC EAX,EDI MOV [EBX - 2*CLimbSize],EAX @Rest1: MOV EAX,[ESI - CLimbSize] ADC EAX,EDI MOV [EBX - CLimbSize],EAX @LastLimb: ADC EDI,EDI MOV [EBX],EDI @Exit: POP EBX POP EDI POP ESI end; {$ELSE WIN64} asm MOV R10,RCX MOV ECX,RSize CMP R9D,ECX JAE @SkipSwap XCHG ECX,R9D XCHG R10,RDX @SkipSwap: SUB R9D,ECX PUSH R9 MOV R9D,ECX AND R9D,CUnrollMask SHR ECX,CUnrollShift CLC JE @MainTail @MainLoop: MOV RAX,[R10] ADC RAX,[RDX] MOV [R8],RAX MOV RAX,[R10 + DLimbSize] ADC RAX,[RDX + DLimbSize] MOV [R8 + DLimbSize],RAX LEA R10,[R10 + 2*DLimbSize] LEA RDX,[RDX + 2*DLimbSize] LEA R8,[R8 + 2*DLimbSize] LEA RCX,[RCX - 1] JECXZ @MainTail JMP @MainLoop @MainTail: LEA RCX,[@MainJumps] JMP [RCX + R9*TYPE Pointer] // Align jump table manually, with NOPs. DB $90,$90,$90,$90 @MainJumps: DQ @DoRestLoop DQ @Main1 DQ @Main2 DQ @Main3 @Main3: MOV RAX,[R10] ADC RAX,[RDX] MOV [R8],RAX MOV EAX,[R10 + 2*CLimbSize] ADC EAX,[RDX + 2*CLimbSize] MOV [R8 + 2*CLimbSize],EAX LEA R10,[R10 + 3*CLimbSize] LEA RDX,[RDX + 3*CLimbSize] LEA R8,[R8 + 3*CLimbSize] JMP @DoRestLoop @Main2: MOV RAX,[R10] ADC RAX,[RDX] MOV [R8],RAX LEA R10,[R10 + 2*CLimbSize] LEA RDX,[RDX + 2*CLimbSize] LEA R8,[R8 + 2*CLimbSize] JMP @DoRestLoop @Main1: MOV EAX,[R10] ADC EAX,[RDX] MOV [R8],EAX LEA R10,[R10 + CLimbSize] LEA RDX,[RDX + CLimbSize] LEA R8,[R8 + CLimbSize] @DoRestLoop: SETC AL // Save Carry Flag XOR EDX,EDX POP RCX MOV R9D,ECX AND R9D,CUnrollMask SHR ECX,CUnrollShift ADD AL,255 // Restore Carry Flag. JECXZ @RestLast3 @RestLoop: MOV RAX,[R10] ADC RAX,RDX MOV [R8],RAX MOV RAX,[R10 + DLimbSize] ADC RAX,RDX MOV [R8 + DLimbSize],RAX LEA R10,[R10 + 2*DLimbSize] LEA R8,[R8 + 2*DLimbSize] LEA RCX,[RCX - 1] JECXZ @RestLast3 JMP @RestLoop @RestLast3: LEA RCX,[@RestJumps] JMP [RCX + R9*TYPE Pointer] // If necessary, align second jump table with NOPs. DB $90,$90,$90,$90,$90,$90 @RestJumps: DQ @LastLimb DQ @Rest1 DQ @Rest2 DQ @Rest3 @Rest3: MOV RAX,[R10] ADC RAX,RDX MOV [R8],RAX MOV EAX,[R10 + 2*CLimbSize] ADC EAX,EDX MOV [R8 + 2*CLimbSize],EAX LEA R8,[R8 + 3*CLimbSize] JMP @LastLimb @Rest2: MOV RAX,[R10] ADC RAX,RDX MOV [R8],RAX LEA R8,[R8 + 2*CLimbSize] JMP @LastLimb @Rest1: MOV EAX,[R10] ADC EAX,EDX MOV [R8],EAX LEA R8,[R8 + CLimbSize] @LastLimb: ADC EDX,EDX MOV [R8],EDX @Exit: end; {$ENDIF WIN32/WIN64} class procedure BigInteger.InternalAddPlain(Left, Right, Result: PLimb; LSize, RSize: Integer); //==============================================// // // // To understand the code, please read this: // // // // http://stackoverflow.com/q/32084204/95954 // // // // especially Peter Cordes' answer: // // // // http://stackoverflow.com/a/32087095/95954 // // // //==============================================// {$IFDEF WIN32} asm PUSH ESI PUSH EDI PUSH EBX MOV ESI,EAX // Left MOV EDI,EDX // Right MOV EBX,ECX // Result MOV ECX,RSize MOV EDX,LSize CMP EDX,ECX JAE @SkipSwap XCHG ECX,EDX XCHG ESI,EDI @SkipSwap: SUB EDX,ECX PUSH EDX XOR EDX,EDX XOR EAX,EAX MOV EDX,ECX AND EDX,CUnrollMask SHR ECX,CUnrollShift CLC JE @MainTail @MainLoop: MOV EAX,[ESI] ADC EAX,[EDI] MOV [EBX],EAX MOV EAX,[ESI + CLimbSize] ADC EAX,[EDI + CLimbSize] MOV [EBX + CLimbSize],EAX MOV EAX,[ESI + 2*CLimbSize] ADC EAX,[EDI + 2*CLimbSize] MOV [EBX + 2*CLimbSize],EAX MOV EAX,[ESI + 3*CLimbSize] ADC EAX,[EDI + 3*CLimbSize] MOV [EBX + 3*CLimbSize],EAX LEA ESI,[ESI + 4*CLimbSize] LEA EDI,[EDI + 4*CLimbSize] LEA EBX,[EBX + 4*CLimbSize] DEC ECX JNE @MainLoop @MainTail: LEA ESI,[ESI + EDX*CLimbSize] LEA EDI,[EDI + EDX*CLimbSize] LEA EBX,[EBX + EDX*CLimbSize] LEA ECX,[@JumpsMain] JMP [ECX + EDX*TYPE Pointer] // Align jump table manually, with NOPs. Update if necessary. NOP @JumpsMain: DD @DoRestLoop DD @Main1 DD @Main2 DD @Main3 @Main3: MOV EAX,[ESI - 3*CLimbSize] ADC EAX,[EDI - 3*CLimbSize] MOV [EBX - 3*CLimbSize],EAX @Main2: MOV EAX,[ESI - 2*CLimbSize] ADC EAX,[EDI - 2*CLimbSize] MOV [EBX - 2*CLimbSize],EAX @Main1: MOV EAX,[ESI - CLimbSize] ADC EAX,[EDI - CLimbSize] MOV [EBX - CLimbSize],EAX @DoRestLoop: SETC AL // Save Carry Flag XOR EDI,EDI POP ECX MOV EDX,ECX AND EDX,CUnrollMask SHR ECX,CUnrollShift ADD AL,255 // Restore Carry Flag. INC ECX DEC ECX JE @RestLast3 // JECXZ is slower than INC/DEC/JE @RestLoop: MOV EAX,[ESI] ADC EAX,EDI MOV [EBX],EAX MOV EAX,[ESI + CLimbSize] ADC EAX,EDI MOV [EBX + CLimbSize],EAX MOV EAX,[ESI + 2*CLimbSize] ADC EAX,EDI MOV [EBX + 2*CLimbSize],EAX MOV EAX,[ESI + 3*CLimbSize] ADC EAX,EDI MOV [EBX + 3*CLimbSize],EAX LEA ESI,[ESI + 4*CLimbSize] LEA EBX,[EBX + 4*CLimbSize] DEC ECX JNE @RestLoop @RestLast3: LEA ESI,[ESI + EDX*CLimbSize] LEA EBX,[EBX + EDX*CLimbSize] LEA ECX,[@RestJumps] JMP [ECX + EDX*TYPE Pointer] // If necessary, align second jump table with NOPs NOP NOP NOP @RestJumps: DD @LastLimb DD @Rest1 DD @Rest2 DD @Rest3 @Rest3: MOV EAX,[ESI - 3*CLimbSize] ADC EAX,EDI MOV [EBX - 3*CLimbSize],EAX @Rest2: MOV EAX,[ESI - 2*CLimbSize] ADC EAX,EDI MOV [EBX - 2*CLimbSize],EAX @Rest1: MOV EAX,[ESI - CLimbSize] ADC EAX,EDI MOV [EBX - CLimbSize],EAX @LastLimb: ADC EDI,EDI MOV [EBX],EDI @Exit: POP EBX POP EDI POP ESI end; {$ELSE WIN64} asm MOV R10,RCX MOV ECX,RSize CMP R9D,ECX JAE @SkipSwap XCHG ECX,R9D XCHG R10,RDX @SkipSwap: SUB R9D,ECX PUSH R9 MOV R9D,ECX AND R9D,CUnrollMask SHR ECX,CUnrollShift CLC JE @MainTail @MainLoop: MOV RAX,[R10] ADC RAX,[RDX] MOV [R8],RAX MOV RAX,[R10 + DLimbSize] ADC RAX,[RDX + DLimbSize] MOV [R8 + DLimbSize],RAX LEA R10,[R10 + 2*DLimbSize] LEA RDX,[RDX + 2*DLimbSize] LEA R8,[R8 + 2*DLimbSize] DEC ECX JNE @MainLoop @MainTail: LEA RCX,[@MainJumps] JMP [RCX + R9*TYPE Pointer] // Align jump table. Update if necessary! NOP @MainJumps: DQ @DoRestLoop DQ @Main1 DQ @Main2 DQ @Main3 @Main3: MOV RAX,[R10] ADC RAX,[RDX] MOV [R8],RAX MOV EAX,[R10 + 2*CLimbSize] ADC EAX,[RDX + 2*CLimbSize] MOV [R8 + 2*CLimbSize],EAX LEA R10,[R10 + 3*CLimbSize] LEA RDX,[RDX + 3*CLimbSize] LEA R8,[R8 + 3*CLimbSize] JMP @DoRestLoop @Main2: MOV RAX,[R10] ADC RAX,[RDX] MOV [R8],RAX LEA R10,[R10 + 2*CLimbSize] LEA RDX,[RDX + 2*CLimbSize] LEA R8,[R8 + 2*CLimbSize] JMP @DoRestLoop @Main1: MOV EAX,[R10] ADC EAX,[RDX] MOV [R8],EAX LEA R10,[R10 + CLimbSize] LEA RDX,[RDX + CLimbSize] LEA R8,[R8 + CLimbSize] @DoRestLoop: SETC AL // Save Carry Flag XOR EDX,EDX POP RCX MOV R9D,ECX AND R9D,CUnrollMask SHR ECX,CUnrollShift ADD AL,255 // Restore Carry Flag. INC ECX DEC ECX JE @RestLast3 @RestLoop: MOV RAX,[R10] ADC RAX,RDX MOV [R8],RAX MOV RAX,[R10 + DLimbSize] ADC RAX,RDX MOV [R8 + DLimbSize],RAX LEA R10,[R10 + 2*DLimbSize] LEA R8,[R8 + 2*DLimbSize] DEC ECX JNE @RestLoop @RestLast3: LEA RCX,[@RestJumps] JMP [RCX + R9*TYPE Pointer] // If necessary, align second jump table with NOPs // -- Aligned. @RestJumps: DQ @LastLimb DQ @Rest1 DQ @Rest2 DQ @Rest3 @Rest3: MOV RAX,[R10] ADC RAX,RDX MOV [R8],RAX MOV EAX,[R10 + DLimbSize] ADC EAX,EDX MOV [R8 + DLimbSize],EAX LEA R8,[R8 + 3*CLimbSize] JMP @LastLimb @Rest2: MOV RAX,[R10] ADC RAX,RDX MOV [R8],RAX LEA R8,[R8 + DLimbSize] JMP @LastLimb @Rest1: MOV EAX,[R10] ADC EAX,EDX MOV [R8],EAX LEA R8,[R8 + CLimbSize] @LastLimb: ADC EDX,EDX MOV [R8],EDX @Exit: end; {$ENDIF !WIN32} {$ENDIF !PUREPASCAL} {$IFDEF PUREPASCAL} class procedure BigInteger.InternalAddPurePascal(Left, Right, Result: PLimb; LSize, RSize: Integer); var I: Integer; Carry, InterCarry: TLimb; PTemp: PLimb; LCount, LTail: Integer; Sum: TLimb; {$IFDEF CPUX64} Left64, Sum64, Carry64, InterCarry64: UInt64; {$ELSE} Left32: TLimb; {$ENDIF} begin if LSize < RSize then begin PTemp := Left; Left := Right; Right := PTemp; I := LSize; LSize := RSize; RSize := I; end; // From here on, // - Left is larger and LSize is its size, // - Right is smaller and RSize is its size. // Emulate ADC (add with carry) Carry := 0; Dec(LSize, RSize); LTail := RSize and CUnrollMask; LCount := RSize shr CUnrollShift; {$IFDEF CPUX64} Carry64 := 0; {$ENDIF} while LCount > 0 do begin {$IFDEF CPUX64} Left64 := PUInt64(Left)[0]; Sum64 := Left64 + PUInt64(Right)[0]; InterCarry64 := Ord(Sum64 < Left64); Inc(Sum64, Carry64); PUInt64(Result)[0] := Sum64; Carry64 := InterCarry64 or Ord(Sum64 < Carry64); Left64 := PUInt64(Left)[1]; Sum64 := Left64 + PUInt64(Right)[1]; InterCarry64 := Ord(Sum64 < Left64); Inc(Sum64, Carry64); PUInt64(Result)[1] := Sum64; Carry64 := InterCarry64 or Ord(Sum64 < Carry64); {$ELSE !CPUX64} Left32 := Left[0]; Sum := Left32 + Right[0]; InterCarry := TLimb(Sum < Left32); Inc(Sum, Carry); Result[0] := Sum; Carry := InterCarry or TLimb(Sum < Carry); Left32 := Left[1]; Sum := Left32 + Right[1]; InterCarry := TLimb(Sum < Left32); Inc(Sum, Carry); Result[1] := Sum; Carry := InterCarry or TLimb(Sum < Carry); Left32 := Left[2]; Sum := Left32 + Right[2]; InterCarry := TLimb(Sum < Left32); Inc(Sum, Carry); Result[2] := Sum; Carry := InterCarry or TLimb(Sum < Carry); Left32 := Left[3]; Sum := Left32 + Right[3]; InterCarry := TLimb(Sum < Left32); Inc(Sum, Carry); Result[3] := Sum; Carry := InterCarry or TLimb(Sum < Carry); {$ENDIF} Inc(Left, CUnrollIncrement); Inc(Right, CUnrollIncrement); Inc(Result, CUnrollIncrement); Dec(LCount); end; {$IFDEF CPUX64} Carry := Carry64; {$ENDIF} while LTail > 0 do begin Sum := Left[0] + Right[0]; InterCarry := TLimb(Sum < Left[0]); Inc(Sum, Carry); Result[0] := Sum; Carry := TLimb(Sum < Carry) or InterCarry; Inc(Left); Inc(Right); Inc(Result); Dec(LTail); end; LTail := LSize and CUnrollMask; LCount := LSize shr CunrollShift; {$IFDEF CPUX64} Carry64 := Carry; {$ENDIF} while LCount > 0 do begin {$IFDEF CPUX64} Sum64 := PUInt64(Left)[0] + Carry64; PUInt64(Result)[0] := Sum64; Carry64 := Ord(Sum64 < Carry64); Sum64 := PUInt64(Left)[1] + Carry64; PUInt64(Result)[1] := Sum64; Carry64 := Ord(Sum64 < Carry64); {$ELSE} Sum := Left[0] + Carry; Result[0] := Sum; Carry := TLimb(Sum < Carry); Sum := Left[1] + Carry; Result[1] := Sum; Carry := TLimb(Sum < Carry); Sum := Left[2] + Carry; Result[2] := Sum; Carry := TLimb(Sum < Carry); Sum := Left[3] + Carry; Result[3] := Sum; Carry := TLimb(Sum < Carry); {$ENDIF} Inc(Left, CUnrollIncrement); Inc(Result, CUnrollIncrement); Dec(LCount); end; {$IFDEF CPUX64} Carry := Carry64; {$ENDIF} while LTail > 0 do begin Sum := Left[0] + Carry; Result[0] := Sum; Carry := TLimb(Sum < Carry); Inc(Left); Inc(Result); Dec(LTail); end; Result[0] := Carry; end; {$ENDIF} class procedure BigInteger.InternalMultiply(Left, Right, Result: PLimb; LSize, RSize: Integer); {$IFDEF PUREPASCAL} type TUInt64 = packed record Lo, Hi: TLimb; end; var Product: UInt64; LRest, LCount: Integer; CurrentRightLimb: TLimb; PLeft, PDest, PRight, PDestRowStart: PLimb; begin if RSize > LSize then begin PDest := Left; Left := Right; Right := PDest; LRest := LSize; LSize := RSize; RSize := LRest; end; PRight := Right; PDestRowStart := Result; PLeft := Left; PDest := PDestRowStart; Inc(PDestRowStart); CurrentRightLimb := PRight^; Inc(PRight); TUInt64(Product).Hi := 0; Dec(RSize); LCount := LSize; while LCount > 0 do begin Product := UInt64(PLeft^) * CurrentRightLimb + TUInt64(Product).Hi; PDest^ := TUInt64(Product).Lo; Inc(PLeft); Inc(PDest); Dec(LCount); end; PDest^ := TUInt64(Product).Hi; LRest := LSize and CUnrollMask; // Low 2 bits: 0..3. LSize := LSize shr CUnrollShift; // Divide by 4. while RSize > 0 do begin PLeft := Left; PDest := PDestRowStart; Inc(PDestRowStart); CurrentRightLimb := PRight^; Inc(PRight); if CurrentRightLimb <> 0 then begin TUInt64(Product).Hi := 0; LCount := LSize; // Inner loop, unrolled. while LCount > 0 do begin Product := UInt64(PLeft[0]) * CurrentRightLimb + PDest[0] + TUInt64(Product).Hi; PDest[0] := TUInt64(Product).Lo; Product := UInt64(PLeft[1]) * CurrentRightLimb + PDest[1] + TUInt64(Product).Hi; PDest[1] := TUInt64(Product).Lo; Product := UInt64(PLeft[2]) * CurrentRightLimb + PDest[2] + TUInt64(Product).Hi; PDest[2] := TUInt64(Product).Lo; Product := UInt64(PLeft[3]) * CurrentRightLimb + PDest[3] + TUInt64(Product).Hi; PDest[3] := TUInt64(Product).Lo; Inc(PLeft, CUnrollIncrement); Inc(PDest, CunrollIncrement); Dec(LCount); end; // Rest loop. LCount := LRest; while LCount > 0 do begin Product := UInt64(PLeft^) * CurrentRightLimb + PDest^ + TUInt64(Product).Hi; PDest^ := TUInt64(Product).Lo; Inc(PLeft); Inc(PDest); Dec(LCount); end; // Last (top) limb of this row. PDest^ := TUInt64(Product).Hi; end; Dec(RSize); end; end; {$ELSE !PUREPASCAL} {$IFDEF WIN32)} var SaveResult: PLimb; LRest, LCount: Integer; PRight, PDestRowStart: PLimb; LLeft, LRight: PLimb; asm PUSH ESI PUSH EDI PUSH EBX MOV SaveResult,ECX MOV ESI,LSize MOV EDI,RSize CMP ESI,EDI JA @SkipSwap XCHG EAX,EDX XCHG ESI,EDI MOV LSize,ESI MOV RSize,EDI // The longest loop should ideally be unrolled. After this, Left should be longer or same length. @SkipSwap: MOV LLeft,EAX MOV LRight,EDX // First loop, setting up first row: MOV PRight,EDX MOV EDI,SaveResult MOV PDestRowStart,EDI // EDI = PDest MOV ESI,LLeft // ESI = PLeft // If CurrentLimbRight = 0, we can skip a lot, and simply do a FillChar MOV ECX,[EDX] // CurrentRightLimb XOR EBX,EBX // PreviousProductHi ADD PDestRowStart,CLimbSize ADD PRight,CLimbSize MOV EAX,LSize MOV LCount,EAX // The setup loop fills the row without an attempt to add to the data already in the result. @SetupLoop: MOV EAX,[ESI] MUL EAX,ECX // Uses MUL EAX,ECX syntax because of bug in XE2 assembler. ADD EAX,EBX ADC EDX,0 MOV [EDI],EAX MOV EBX,EDX LEA ESI,[ESI + CLimbSize] LEA EDI,[EDI + CLimbSize] DEC LCount JNE @SetupLoop MOV [EDI],EDX MOV EAX,LSize MOV EDX,EAX SHR EAX,CUnrollShift MOV LSize,EAX AND EDX,CUnrollMask MOV LRest,EDX DEC RSize JE @Exit // The outer loop iterates over the limbs of the shorter operand. After the setup loop, the lowest limb // has already been taken care of. @OuterLoop: MOV ESI,LLeft MOV EDI,PDestRowStart ADD PDestRowStart,CLimbSize MOV EAX,PRight ADD PRight,CLimbSize // If PRight^ is 0, then we can skip multiplication for the entire row. MOV ECX,[EAX] TEST ECX,ECX JE @NextOuterLoop XOR EBX,EBX MOV EAX,LSize MOV LCount,EAX CMP EAX,0 JE @EndInnerLoop @InnerLoop: // Loop unrolled. Approx. 70% faster than simple loop. MOV EAX,[ESI] MUL EAX,ECX ADD EAX,[EDI] ADC EDX,0 ADD EAX,EBX ADC EDX,0 MOV [EDI],EAX MOV EBX,EDX MOV EAX,[ESI + CLimbSize] MUL EAX,ECX ADD EAX,[EDI + CLimbSize] ADC EDX,0 ADD EAX,EBX ADC EDX,0 MOV [EDI + CLimbSize],EAX MOV EBX,EDX MOV EAX,[ESI + 2*CLimbSize] MUL EAX,ECX ADD EAX,[EDI + 2*CLimbSize] ADC EDX,0 ADD EAX,EBX ADC EDX,0 MOV [EDI + 2*CLimbSize],EAX MOV EBX,EDX MOV EAX,[ESI + 3*CLimbSize] MUL EAX,ECX ADD EAX,[EDI + 3*CLimbSize] ADC EDX,0 ADD EAX,EBX ADC EDX,0 MOV [EDI + 3*CLimbSize],EAX MOV EBX,EDX LEA ESI,[ESI + 4*CLimbSize] LEA EDI,[EDI + 4*CLimbSize] DEC LCount JNE @InnerLoop @EndInnerLoop: // The restant limbs to be handled. MOV EAX,LRest MOV LCount,EAX CMP EAX,0 JE @EndInnerRestLoop @InnerRestLoop: MOV EAX,[ESI] MUL EAX,ECX ADD EAX,EBX ADC EDX,0 ADD EAX,[EDI] ADC EDX,0 MOV [EDI],EAX MOV EBX,EDX LEA ESI,[ESI + CLimbSize] LEA EDI,[EDI + CLimbSize] DEC LCount JNE @InnerRestLoop @EndInnerRestLoop: // The last (left) limb gets the top of the 64 bit product. MOV [EDI],EBX @NextOuterLoop: DEC RSize JNE @OuterLoop @Exit: POP EBX POP EDI POP ESI end; {$ELSE WIN64} // This uses 64 bit multiplication as much as possible. The logic handles any odd (top) limbs especially. var LeftOdd, RightOdd: Boolean; // Left, Right (resp.): odd number of limbs? SaveLeft: PLimb; LeftSize, RightSize: Integer; asm .PUSHNV RSI .PUSHNV RDI .PUSHNV RBX MOV EDI,RSize CMP R9D,EDI JAE @SwapEnd XCHG RCX,RDX XCHG R9D,EDI @SwapEnd: MOV SaveLeft,RCX MOV EAX,R9D SHR R9D,1 MOV LeftSize,R9D // Number of double limbs of Left AND AL,1 MOV LeftOdd,AL // Does Left have an odd number of limbs? MOV EAX,EDI SHR EDI,1 MOV RightSize,EDI // Number of double limbs of Right AND AL,1 MOV RightOdd,AL // Does Right have an odd number of limbs? MOV R10,RDX // Current limb to be multiplied XOR RBX,RBX // Top DWORD (EDX) of previous multiplication // If no more 64 bit limbs in Right, we must skip to final odd limb. CMP RightSize,0 JE @FinalOddPart MOV RCX,[R10] // Current Right limb's value MOV RDI,R8 // Result limb pointer MOV RSI,SaveLeft // Left limb pointer ADD R8,DLimbSize // Result's pointer to start of current row ADD R10,DLimbSize // Current Right limb pointer MOV R11D,LeftSize // Loop counter CMP R11D,0 JE @SetupOddPart // Setup loop (64 bit part) @SetupLoop64: MOV RAX,[RSI] MUL RCX ADD RAX,RBX ADC RDX,0 MOV [RDI],RAX MOV RBX,RDX LEA RSI,[RSI + DLimbSize] LEA RDI,[RDI + DLimbSize] DEC R11D JNE @SetupLoop64 // Setup loop, last limb ("odd" part). @SetupOddPart: CMP LeftOdd,0 JE @SkipSetupOddPart MOV EAX,[RSI] // 32 bit register to read odd limb of this loop MUL RCX ADD RAX,RBX ADC RDX,0 MOV [RDI],RAX MOV [RDI + DLimbSize],RDX JMP @SkipSkipSetupOddPart @SkipSetupOddPart: MOV [RDI],RDX @SkipSkipSetupOddPart: DEC RightSize JE @FinalOddPart @OuterLoop: MOV RDI,R8 ADD R8,DLimbSize MOV RCX,[R10] ADD R10,DLimbSize TEST RCX,RCX JE @NextOuterLoop MOV RSI,SaveLeft XOR RBX,RBX MOV R11D,LeftSize CMP R11D,0 JE @InnerLoopOddPart SHR R11D,CUnrollShift JE @InnerTail64 @InnerLoop64: MOV RAX,[RSI] // Get double limb from Left data MUL RCX // multiply it with current Right double limb's value --> RDX:RAX ADD RAX,[RDI] // Add current value in Result data ADC RDX,0 ADD RAX,RBX // Add "carry", i.e. top double limb from previous multiplcation ADC RDX,0 MOV [RDI],RAX // Store in Result MOV RBX,RDX // And save top double limb as "carry". MOV RAX,[RSI + DLimbSize] MUL RCX ADD RAX,[RDI + DLimbSize] ADC RDX,0 ADD RAX,RBX ADC RDX,0 MOV [RDI + DLimbSize],RAX MOV RBX,RDX MOV RAX,[RSI + 2*DLimbSize] MUL RCX ADD RAX,[RDI + 2*DLimbSize] ADC RDX,0 ADD RAX,RBX ADC RDX,0 MOV [RDI + 2*DLimbSize],RAX MOV RBX,RDX MOV RAX,[RSI + 3*DLimbSize] MUL RCX ADD RAX,[RDI + 3*DLimbSize] ADC RDX,0 ADD RAX,RBX ADC RDX,0 MOV [RDI + 3*DLimbSize],RAX MOV RBX,RDX LEA RSI,[RSI + 4*DLimbSize] LEA RDI,[RDI + 4*DLimbSize] DEC R11D JNE @InnerLoop64 @InnerTail64: MOV R11D,LeftSize AND R11D,CUnrollMask JE @InnerLoopOddPart @InnerTailLoop64: MOV RAX,[RSI] MUL RCX ADD RAX,[RDI] ADC RDX,0 ADD RAX,RBX ADC RDX,0 MOV [RDI],RAX MOV RBX,RDX LEA RSI,[RSI + DLimbSize] LEA RDI,[RDI + DLimbSize] DEC R11D JNE @InnerTailLoop64 @InnerLoopOddPart: CMP LeftOdd,0 // If Left's size is odd, handle last limb. JE @InnerLoopLastLimb MOV RAX,[RSI] MUL RCX ADD RAX,[RDI] ADC RDX,0 ADD RAX,RBX ADC RDX,0 MOV [RDI],RAX MOV [RDI + DLimbSize],RDX JMP @NextOuterLoop @InnerLoopLastLimb: MOV [RDI],RDX @NextOuterLoop: DEC RightSize JNE @OuterLoop @FinalOddPart: CMP RightOdd,0 JE @Exit MOV RDI,R8 MOV RSI,SaveLeft MOV RAX,R10 MOV ECX,[RAX] // Right is odd, so read single TLimb XOR RBX,RBX MOV R11D,LeftSize CMP R11D,0 JE @SkipFinalLoop @FinalLoop: MOV RAX,[RSI] MUL RCX ADD RAX,[RDI] ADC RDX,0 ADD RAX,RBX ADC RDX,0 MOV [RDI],RAX MOV RBX,RDX LEA ESI,[ESI + DLimbSize] LEA EDI,[EDI + DLimbSize] DEC R11D JNE @FinalLoop @SkipFinalLoop: CMP LeftOdd,0 JE @LastLimb MOV EAX,[RSI] MUL RCX ADD RAX,[RDI] ADC RDX,0 ADD RAX,RBX ADC RDX,0 MOV [RDI],RAX MOV [RDI + DLimbSize],RDX JMP @Exit @LastLimb: MOV [RDI],RDX @Exit: end; {$ENDIF !WIN32} {$ENDIF !PUREPASCAL} function BigInteger.ToBinaryString: string; begin Result := ToString(2); end; function BigInteger.ToByteArray: TArray<Byte>; var Neg: TMagnitude; Bytes, Bits: Integer; ExtraByte: Byte; begin if IsZero then begin SetLength(Result, 1); Result[0] := 0; Exit; end; Bytes := BitLength; Bits := Bytes and $07; Bytes := (Bytes + 7) shr 3; if FSize > 0 then begin Neg := FData; ExtraByte := $00; end else begin SetLength(Neg, Size); InternalNegate(PLimb(FData), PLimb(Neg), Size); ExtraByte := $FF; end; SetLength(Result, Bytes + Byte(Bits = 0)); Move(Neg[0], Result[0], Bytes); if Bits = 0 then Result[Bytes] := ExtraByte; end; function BigInteger.ToDecimalString: string; begin Result := ToString(10); end; function BigInteger.ToHexString: string; begin Result := ToString(16); end; function BigInteger.ToOctalString: string; begin Result := ToString(8); end; function BigInteger.ToString: string; begin Result := ToString(FBase); end; function BigInteger.ToString(Base: Integer): string; var P: PChar; LBuffer: TArray<Char>; LMagnitude: PLimb; LSize: Integer; begin if not Base in [2..36] then Error(ecInvalidArgument); if FData = nil then begin Result := '0'; Exit; end; LSize := FSize and SizeMask; SetLength(LBuffer, LSize * CStringMaxLengths[Base] + 1); LMagnitude := PLimb(System.Copy(FData)); P := PChar(LBuffer) + Length(LBuffer); Dec(P); P^ := #0; while LSize > 0 do begin Dec(P); P^ := CBaseChars[InternalDivideByBase(LMagnitude, Base, LSize)]; end; if FSize < 0 then begin Dec(P); P^ := '-'; end; Result := P; end; // By default, uses FBase as numeric base, otherwise, if string "starts" with $, 0x, 0b or 0o, uses 16, 16 (both hex), 2 (binary) and 8 (octal) respectively. class function BigInteger.TryParse(const S: string; out Res: BigInteger; aBase : Integer): Boolean; var LTrimmed: string; LIsNegative: Boolean; P: PChar; LBase, LBaseNew: Integer; begin Result := False; LTrimmed := UpperCase(Trim(S)); // Make string case insensitive. if LTrimmed = '' then Exit; LIsNegative := False; P := PChar(LTrimmed); if (P^ = '-') or (P^ = '+') then begin LIsNegative := (P^ = '-'); Inc(P); end; LBase := aBase; // By default, use global numeric base. case P^ of '$': // $ prefix indicates hexadecimal (equivalent to 0x and %16r) begin Inc(P); LBase := 16; end; '0': begin Inc(P); case P^ of #0: begin Res := Zero; Exit(True); end; 'B': // 0b prefix indicates binary (equivalent to %2r) LBase := 2; 'O', 'K': // 0o17, 0k17 prefixes indicate octal (equivalent to %8r) LBase := 8; 'X': // 0x prefix indicates hexadecimal (equivalent to $ and %16r) LBase := 16; 'D': LBase := 10; else Dec(P); end; Inc(P); end; '%': // %nnr prefix indicates base n (nn is always decimal) begin Inc(P); LBaseNew := 0; while P^ <> 'R' do begin if P^ = #0 then Exit; LBaseNew := LBaseNew * 10 + Ord(P^) - CNumBase; Inc(P); end; Inc(P); if not (LBaseNew in [2..36]) then Exit; LBase := LBaseNew; end; end; Result := TryParse(P, LBase, Res); if Result and LIsNegative then Res := -Res; end; class function BigInteger.TryParse(const S: string; Base: TNumberBase; out Res: BigInteger): Boolean; var LIsNegative: Boolean; LTrimmed: string; LVal: Integer; P: PChar; begin Result := False; LTrimmed := Trim(S); if LTrimmed = '' then Exit; LIsNegative := False; Res.FSize := 0; Res.MakeSize(Length(S) div CStringMinLengths[Base] + 4); P := PChar(LTrimmed); if (P^ = '-') or (P^ = '+') then begin LIsNegative := (P^ = '-'); Inc(P); end; while P^ <> #0 do begin if (P^ = '_') or (P^ = ' ') or (P = FormatSettings.ThousandSeparator) then begin Inc(P); Continue; end; LVal := Ord(P^); Inc(P); if LVal in [Ord('0')..Ord('9')] then Dec(LVal, CNumBase) else if LVal >= CAlphaBase then begin if LVal >= Ord('a') then Dec(LVal, 32); Dec(LVal, CAlphaBase - 10); end else Exit; if LVal >= Base then Exit; InternalMultiplyAndAdd(Res.FData, Base, LVal, Res.FData); end; if LIsNegative then Res := -Res; Result := True; // Res.Compact; end; class procedure BigInteger.Decimal; begin FBase := 10; end; class function BigInteger.Divide(const Left: BigInteger; Right: UInt16): BigInteger; var LSign: Integer; begin if Right = 0 then Error(ecDivByZero); if Left.FData = nil then begin ShallowCopy(Zero, Result); Exit; end; LSign := Left.FSize and SignMask; Result.MakeSize(Left.FSize and SizeMask); InternalDivMod16(PLimb(Left.FData), Right, PLImb(Result.FData), nil, Left.FSize and SizeMask); Result.Compact; if Result.FData <> nil then Result.FSize := (Result.FSize and SizeMask) or LSign; end; class function BigInteger.Divide(const Left: BigInteger; Right: UInt32): BigInteger; var LSign: Integer; begin if Right = 0 then Error(ecDivByZero); if Left.FData = nil then begin ShallowCopy(Zero, Result); Exit; end; LSign := Left.FSize and SignMask; Result.MakeSize(Left.FSize and SizeMask); InternalDivMod32(PLimb(Left.FData), Right, PLimb(Result.FData), nil, Left.FSize and SizeMask); Result.Compact; if Result.FData <> nil then Result.FSize := (Result.FSize and SizeMask) or LSign; end; class function BigInteger.Divide(const Left, Right: BigInteger): BigInteger; var Sign, LSize, RSize: Integer; Remainder: BigInteger; begin if Right.FData = nil then Error(ecDivByZero); Sign := (Left.FSize and SignMask) xor (Right.FSize and SignMask); LSize := Left.FSize and SizeMask; RSize := Right.FSize and SizeMask; case InternalCompare(PLimb(Left.FData), PLimb(Right.FData), LSize, RSize) of -1: begin ShallowCopy(Zero, Result); end; 0: begin if Sign = 0 then ShallowCopy(One, Result) else ShallowCopy(MinusOne, Result); end; else begin if ShouldUseBurnikelZiegler(LSize, RSize) then DivModBurnikelZiegler(Left, Right, Result, Remainder) else DivModKnuth(Left, Right, Result, Remainder); if Result.FSize <> 0 then Result.FSize := (Result.FSize and SizeMask) or Sign; end; end; end; function BigInteger.Divide(const Other: BigInteger): PBigInteger; begin Result := @Self; Self := Self div Other; end; class procedure BigInteger.DivMod(const Dividend, Divisor: BigInteger; var Quotient, Remainder: BigInteger); var LSign, RSign: Integer; LSize, RSize: Integer; begin if Divisor.FData = nil then Error(ecDivByZero); LSign := SignBitOf(Dividend.FSize); RSign := SignBitOf(Divisor.FSize); LSize := Dividend.FSize and SizeMask; RSize := Divisor.FSize and SizeMask; case InternalCompare(PLimb(Dividend.FData), PLimb(Divisor.FData), LSize, RSize) of -1: begin ShallowCopy(Dividend, Remainder); ShallowCopy(Zero, Quotient); Exit; end; 0: begin ShallowCopy(Zero, Remainder); if LSign = RSign then ShallowCopy(One, Quotient) else ShallowCopy(MinusOne, Quotient); Exit; end else begin if ShouldUseBurnikelZiegler(LSize, RSize) then DivModBurnikelZiegler(Dividend, Divisor, Quotient, Remainder) else DivModKnuth(Dividend, Divisor, Quotient, Remainder); // if Quotient.FSize <> 0 then // Quotient.FSize := (Quotient.FSize and SizeMask) or (LSign xor RSign); // if Remainder.FSize <> 0 then // Remainder.FSize := (Remainder.FSize and SizeMask) or LSign; end; end; end; class procedure BigInteger.DivModKnuth(const Left, Right: BigInteger; var Quotient, Remainder: BigInteger); var LSign, RSign: Integer; LSize, RSize: Integer; begin if Right.FData = nil then Error(ecDivByZero); LSign := SignBitOf(Left.FSize); RSign := SignBitOf(Right.FSize); LSize := Left.FSize and SizeMask; RSize := Right.FSize and SizeMask; case InternalCompare(PLimb(Left.FData), PLimb(Right.FData), LSize, RSize) of -1: begin ShallowCopy(Left, Remainder); ShallowCopy(Zero, Quotient); Exit; end; 0: begin ShallowCopy(Zero, Remainder); if LSign = RSign then ShallowCopy(One, Quotient) else ShallowCopy(MinusOne, Quotient); Exit; end else begin Quotient.MakeSize(LSize - RSize + 1); Remainder.MakeSize(RSize); if not InternalDivMod(PLimb(Left.FData), PLimb(Right.FData), PLimb(Quotient.FData), PLimb(Remainder.FData), LSize, RSize) then Error(ecInvalidArg); Quotient.Compact; Remainder.Compact; if Quotient.FSize <> 0 then Quotient.FSize := (Quotient.FSize and SizeMask) or (LSign xor RSign); if Remainder.FSize <> 0 then Remainder.FSize := (Remainder.FSize and SizeMask) or LSign; end; end; end; class procedure BigInteger.InternalShiftLeft(Source, Dest: PLimb; Shift, Size: Integer); {$IF DEFINED(PUREPASCAL)} var I: Integer; begin Shift := Shift and 31; if Shift = 0 then CopyLimbs(Source, Dest, Size) else begin Dest[Size] := Source[Size - 1] shr (CLimbBits - Shift); for I := Size - 1 downto 1 do Dest[I] := (Source[I] shl Shift) or (Source[I - 1] shr (CLimbBits - Shift)); Dest[0] := Source[0] shl Shift; end; end; {$ELSEIF DEFINED(WIN32)} asm PUSH ESI PUSH EDI PUSH EBX MOV ESI,EAX MOV EDI,EDX // No need to test for nil. MOV EBX,Size MOV EAX,[ESI + CLimbSize*EBX] DEC EBX JS @LoopEnd @ShiftLoop: MOV EDX,[ESI + CLimbSize*EBX] SHLD EAX,EDX,CL MOV [EDI + CLimbSize*EBX + CLimbSize],EAX MOV EAX,EDX @ShiftStart: DEC EBX JNS @ShiftLoop @LoopEnd: SHL EAX,CL MOV [EDI],EAX @Exit: POP EBX POP EDI POP ESI end; {$ELSE} asm XCHG RCX,R8 MOV R10,RDX MOV EAX,[R8 + CLimbSize*R9] DEC R9D JS @LoopEnd @ShiftLoop: MOV EDX,[R8 + CLimbSize*R9] SHLD EAX,EDX,CL MOV [R10 + CLimbSize*R9 + CLimbSize],EAX MOV EAX,EDX @ShiftStart: DEC R9D JNS @ShiftLoop @LoopEnd: SHL EAX,CL MOV [R10],EAX @Exit: end; {$IFEND} class procedure BigInteger.InternalShiftRight(Source, Dest: PLimb; Shift, Size: Integer); {$IF DEFINED(PUREPASCAL)} var I: Integer; begin Shift := Shift and 31; if Shift = 0 then CopyLimbs(Source, Dest, Size) else begin for I := 0 to Size - 1 do Dest[I] := (Source[I] shr Shift) or (Source[I + 1] shl (CLimbBits - Shift)); Dest[Size - 1] := Source[Size - 1] shr Shift; end; end; {$ELSEIF DEFINED(WIN32)} asm PUSH ESI PUSH EDI PUSH EBX MOV ESI,EAX MOV EDI,EDX MOV EBX,Size MOV EAX,[ESI] LEA ESI,[ESI + CLimbSize] DEC EBX JE @EndLoop @ShiftLoop: MOV EDX,[ESI] SHRD EAX,EDX,CL MOV [EDI],EAX MOV EAX,EDX LEA ESI,[ESI + CLimbSize] LEA EDI,[EDI + CLimbSize] DEC EBX JNE @ShiftLoop @EndLoop: SHR EAX,CL MOV [EDI],EAX @Exit: POP EBX POP EDI POP ESI end; {$ELSE} asm XCHG RCX,R8 // R8 = source, ECX = shift MOV EAX,[R8] LEA R8,[R8 + CLimbSize] DEC R9D JE @LoopEnd @ShiftLoop: MOV R10D,[R8] SHRD EAX,R10D,CL MOV [RDX],EAX MOV EAX,R10D LEA RDX,[RDX + CLimbSize] LEA R8,[R8 + CLimbSize] DEC R9D JNE @ShiftLoop @LoopEnd: SHR EAX,CL MOV [RDX],EAX @Exit: end; {$IFEND} type {$IFDEF CPUX64} TDivLimb = UInt32; TDblLimb = UInt64; {$ELSE} TDivLimb = UInt16; TDblLimb = UInt32; {$ENDIF} PDivLimb = ^TDivLimb; PDblLimb = ^TDblLimb; const CDivLimbBase = TDblLimb(High(TDivLimb)) + 1; CDivLimbBits = SizeOf(TDivLimb) * 8; CDblLimbBits = SizeOf(TDblLimb) * 8; class function BigInteger.InternalDivMod16(Dividend: PLimb; Divisor: UInt16; Quotient, Remainder: PLimb; LSize: Integer): Boolean; {$IFDEF PUREPASCAL} // In PUREPASCAL, using 16-bit division with an intermediate 32-bit result turned out to be faster than // 32-bit division with an intermediate 64-bit result. type PUInt16 = ^UInt16; var J: Integer; LRemainder: UInt16; begin LSize := LSize + LSize; LRemainder := 0; for J := LSize - 1 downto 0 do Math.DivMod(Cardinal(LRemainder shl 16 + PUInt16(Dividend)[J]), Divisor, PUInt16(Quotient)[J], LRemainder); if Remainder <> nil then Remainder[0] := LRemainder; Exit(True); end; {$ELSE !PUREPASCAL} // In assembler, 32 bit division is faster, so promote divisor to 32 bit and use InternalDivMod32. begin Result := InternalDivMod32(Dividend, UInt32(Divisor), Quotient, Remainder, LSize); end; {$ENDIF !PUREPASCAL} class function BigInteger.InternalDivMod32(Dividend: PLimb; Divisor: UInt32; Quotient, Remainder: PLimb; LSize: Integer): Boolean; {$IFDEF PUREPASCAL} {$IFDEF CPUX86} begin // In 32PP, plain division using System.Math.DivMod(UInt64, ...) is much slower than this: Result := InternalDivMod(Dividend, @Divisor, Quotient, Remainder, LSize, 1); end; {$ELSE CPUX64} var J: Integer; LQuotient, LRemainder: UInt64; begin LRemainder := 0; for J := LSize - 1 downto 0 do begin // DivMod(UInt64, UInt64, var UInt64, var UInt64) DivMod64(LRemainder * (UInt64(High(UInt32)) + 1) + Dividend[J], Divisor, LQuotient, LRemainder); Quotient[J] := TLimb(LQuotient); end; if Remainder <> nil then Remainder[0] := TLimb(LRemainder); Exit(True); end; {$ENDIF CPUX64} {$ELSE !PUREPASCAL} {$IFDEF WIN32} asm PUSH ESI PUSH EDI PUSH EBX MOV EBX,EDX MOV EDI,LSize LEA ESI,[EAX + CLimbSize*EDI - CLimbSize] LEA ECX,[ECX + CLimbSize*EDI - CLimbSize] XOR EDX,EDX SHR EDI,CUnrollShift JE @Tail @DivLoop: MOV EAX,[ESI] DIV EAX,EBX MOV [ECX],EAX MOV EAX,[ESI - CLimbSize] DIV EAX,EBX MOV [ECX - CLimbSize],EAX MOV EAX,[ESI - 2 * CLimbSize] DIV EAX,EBX MOV [ECX - 2 * CLimbSize],EAX MOV EAX,[ESI - 3 * CLimbSize] DIV EAX,EBX MOV [ECX - 3 * CLimbSize],EAX LEA ESI,[ESI - 4 * CLimbSize] LEA ECX,[ECX - 4 * CLimbSize] DEC EDI JNE @DivLoop @Tail: MOV EDI,LSize AND EDI,CUnrollMask JE @StoreRemainder @TailLoop: MOV EAX,[ESI] DIV EAX,EBX MOV [ECX],EAX LEA ESI,[ESI - CLimbSize] LEA ECX,[ECX - CLimbSize] DEC EDI JNE @TailLoop @StoreRemainder: MOV EBX,Remainder OR EBX,EBX JE @Exit MOV [EBX],EDX @Exit: POP EBX POP EDI POP ESI end; {$ELSE WIN64} asm MOV R10D,EDX MOV R11D,LSize LEA RCX,[RCX + R11*CLimbSize] LEA R8,[R8 + R11*CLimbSize] XOR EDX,EDX SHR R11D,CUnrollShift JE @Tail @DivLoop: // Note: 64 bit division turned out to be considerably slower! MOV EAX,[RCX - CLimbSize] DIV EAX,R10D // Uses DIV EAX,R10D syntax because of bug in XE 64 bit assembler. MOV [R8 - CLimbSize],EAX MOV EAX,[RCX - 2 * CLimbSize] DIV EAX,R10D MOV [R8 - 2 * CLimbSize],EAX MOV EAX,[RCX - 3 * CLimbSize] DIV EAX,R10D MOV [R8 - 3 * CLimbSize],EAX MOV EAX,[RCX - 4 * CLimbSize] DIV EAX,R10D MOV [R8 - 4 * CLimbSize],EAX LEA RCX,[RCX - 4 * CLimbSize] LEA R8,[R8 - 4 * CLimbSize] DEC R11D JNE @DivLoop @Tail: MOV R11D,LSize AND R11D,CUnrollMask JE @StoreRemainder @TailLoop: MOV EAX,[RCX - ClimbSize] DIV EAX,R10D MOV [R8 - CLimbSize],EAX LEA RCX,[RCX - CLimbSize] LEA R8,[R8 - CLimbSize] DEC R11D JNE @TailLoop @StoreRemainder: OR R9,R9 JE @Exit MOV [R9],EDX @Exit: end; {$ENDIF} {$ENDIF PUREPASCAL} class function BigInteger.InternalDivMod(Dividend, Divisor, Quotient, Remainder: PLimb; LSize, RSize: Integer): Boolean; // Basecase division, see Knuth TAOCP, Vol. 2. {$IF DEFINED(PUREPASCAL)} var PDividend, PDivisor, PQuotient, PRemainder: PDivLimb; NormDividend, NormDivisor: TArray<TDivLimb>; // Normalized dividend and divisor QHat: TDblLimb; // Estimate quotient limb RHat: TDblLimb; // Remainder after calculating QHat Product: TDblLimb; // Product of limb and QHat Shift, RevShift, I, J: Integer; // Help variables NormDividendTop2, NormDivisorTop: TDblLimb; {$IF SizeOf(TDivLimb) = SizeOf(TLimb)} Rem, Quot: UInt64; Carry, Value: Int64; {$ELSE} // Rem: TDivLimb; Carry, Value: Integer; {$IFEND} begin Assert(SizeOf(TDblLimb) = 2 * SizeOf(TDivLimb)); PDividend := PDivLimb(Dividend); PDivisor := PDivLimb(Divisor); PQuotient := PDivLimb(Quotient); PRemainder := PDivLimb(Remainder); {$IF SizeOf(TLimb) > SizeOf(TDivLimb)} LSize := LSize + LSize; RSize := RSize + RSize; if PDivisor[RSize - 1] = 0 then Dec(RSize); {$IFEND} // NOTE: In Win32, this uses 16-bit division (with 32-bit intermediate results) to avoid having to use // 64-bit unsigned integers. This turned out to be (approx. 17%) faster than using 32-bit limbs. // In Win64, this uses 32-bit division with 64-bit intermediate results. if (LSize < RSize) then Exit(False); while (RSize > 0) and (PDivisor[RSize - 1] = 0) do Dec(RSize); if RSize = 0 then Exit(False); while (LSize > 0) and (PDividend[LSize - 1] = 0) do Dec(LSize); //////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Perhaps it makes sense to shift away common trailing zeroes, if divisor > certain size. /// /// Shifting should be pretty simple: simply remove any common zeroes in both dividend and divisor, /// /// generate an offset to the lowest non-zero limb and shift accordingly (when normalizing). /// /// Note that the remainder must be amended accordingly. /// //////////////////////////////////////////////////////////////////////////////////////////////////////////// if RSize = 1 then begin // Handle single-digit divisor. {$IF SizeOf(TDivLimb) = SizeOf(TLimb)} Exit(InternalDivMod32(Dividend, PDivisor[0], Quotient, Remainder, LSize)); {$ELSE} Exit(InternalDivMod16(Dividend, PDivisor[0], Quotient, Remainder, (LSize + 1) div 2)); {$IFEND} // Rem := 0; // for J := LSize - 1 downto 0 do // {$IF SizeOf(TDivLimb) = SizeOf(TLimb)} // begin // // DivMod(UInt64, UInt64, var UInt64, var UInt64) // System.Math.DivMod(Rem * CDivLimbBase + PDividend[J], PDivisor[0], Quot, Rem); // PQuotient[J] := TDivLimb(Quot); // end; // {$ELSE} // // DivMod(Cardinal, Word, var Word, var Word) // System.Math.DivMod(Cardinal(Rem * CDivLimbBase + PDividend[J]), PDivisor[0], PQuotient[J], Rem); // {$IFEND} // if PRemainder <> nil then // PRemainder[0] := TDivLimb(Rem); // Exit(True); end; // Normalize by shifting divisor left just enough so that its high-order bit is set, and shift dividend left the // same amount. A high-order digit is prepended to dividend unconditionally. // Get number of leading zeroes. Shift := Velthuis.Numerics.NumberOfleadingZeros(PDivisor[RSize - 1]); // 0 <= Shift < Bits. RevShift := CDivLimbBits - Shift; // Normalize divisor and shift dividend left accordingly. SetLength(NormDivisor, RSize); SetLength(NormDividend, LSize + 1); if Shift > 0 then begin for I := RSize - 1 downto 1 do NormDivisor[I] := (PDivisor[I] shl Shift) or (PDivisor[I - 1] shr RevShift); NormDivisor[0] := PDivisor[0] shl Shift; NormDividend[LSize] := PDividend[LSize - 1] shr RevShift; for I := LSize - 1 downto 1 do NormDividend[I] := (PDividend[I] shl Shift) or (PDividend[I - 1] shr RevShift); NormDividend[0] := PDividend[0] shl Shift; end else begin // SizeOf(TDivLimb) is not always SizeOf(TLimb), so don't use MoveLimbs() here. Move(PDivisor[0], NormDivisor[0], RSize * SizeOf(TDivLimb)); Move(PDividend[0], NormDividend[0], LSize * SizeOf(TDivLimb)); end; // Knuth's basecase algorithm. // Main loop. for J := LSize - RSize downto 0 do begin NormDivisorTop := NormDivisor[RSize - 1]; NormDividendTop2 := PDblLimb(@NormDividend[J + RSize - 1])^; // QHat -- q^ in TAOCP -- is (first) estimate of Quotient[J] QHat := NormDividendTop2 div NormDivisorTop; // RHat -- r^ in TAOCP -- is remainder belonging to q^. RHat := NormDividendTop2 - QHat * NormDivisorTop; while (QHat * NormDivisor[RSize - 2] > RHat shl CDivLimbBits + NormDividend[J + RSize - 2]) or (QHat >= CDivLimbBase) do begin Dec(QHat); Inc(RHat, NormDivisorTop); if RHat >= CDivLimbBase then Break; end; // Multiply and subtract. Carry := 0; for I := 0 to RSize - 1 do begin Product := QHat * NormDivisor[I]; Value := NormDividend[I + J] - Carry - TDivLimb(Product); NormDividend[I + J] := TDivLimb(Value); {$IF SizeOf(TLimb) = SizeOf(TDivLimb)} // Integer cast to force sign-extension of 'Value shr Bits' Carry := Int64(Product shr CDivLimbBits) - Integer(Value shr CDivLimbBits); {$ELSE} // Smallint cast to force sign-extension of 'Value shr Bits' Carry := Integer(Product shr CDivLimbBits) - Smallint(Value shr CDivLimbBits); {$IFEND} end; Value := NormDividend[J + RSize] - Carry; NormDividend[J + RSize] := Value; if Value < 0 then begin // If too much was subtracted, add back. Dec(QHat); Value := 0; for I := 0 to RSize - 1 do begin Value := NormDividend[I + J] + NormDivisor[I] + Value shr CDivLimbBits; NormDividend[I + J] := TDivLimb(Value); end; Inc(NormDividend[J + RSize], Value shr CDivLimbBits); end; PQuotient[J] := QHat; end; // If the caller wants the remainder, unnormalize it and pass it back. if PRemainder <> nil then if Shift <> 0 then for I := 0 to RSize - 1 do PRemainder[I] := (TDblLimb(NormDividend[I]) shr Shift) or (TDblLimb(NormDividend[I + 1]) shl RevShift) else for I := 0 to RSize - 1 do PRemainder[I] := NormDividend[I]; Result := True; end; {$ELSEIF DEFINED(WIN32)} var LDividend, LDivisor, LQuotient: PLimb; // Local copies of passed registers NormDividend, NormDivisor: PLimb; // Manually managed dynamic arrays QHat, RHat, Product: TUInt64; // 64 bit intermediate results Overflow: TLimb; // "Carry" between multiplications Shift: Integer; // Normalization shift asm PUSH ESI PUSH EDI PUSH EBX // To avoid reference count problems with Delphi's dynamic array types, we do our own, // "old school" dynarrays, using GetMem and FreeMem. XOR EBX,EBX // Set "dynarrays" to nil, so the FreeMem calls won't fail. MOV NormDividend,EBX MOV NormDivisor,EBX MOV LDividend,EAX MOV LDivisor,EDX MOV LQuotient,ECX MOV ESI,LSize MOV EDI,RSize CMP ESI,EDI JL @ExitFalse DEC EDI JS @ExitFalse JNE @MultiLimbDivisor // Simple division // Divisor only contains one single limb: simple division and exit. @SingleLimbDivisor: MOV EBX,[EDX] DEC ESI MOV EDI,EAX XOR EDX,EDX @SingleDivLoop: MOV EAX,[EDI + CLimbSize*ESI] DIV EAX,EBX MOV [ECX + CLimbSize*ESI],EAX DEC ESI JNS @SingleDivLoop MOV EAX,Remainder TEST EAX,EAX JZ @ExitTrue MOV [EAX],EDX JMP @ExitTrue // Multilimb division // Divisor contains more than one limb: basecase division as described in Knuth's TAoCP. @MultiLimbDivisor: MOV EAX,RSize // GetMem(NormDivisor, RSize * CLimbSize); LEA EAX,[EAX*CLimbSize] CALL System.AllocMem MOV NormDivisor,EAX MOV EAX,LSize // GetMem(NormDividend, (LSize + 1) * CLimbSize); INC EAX LEA EAX,[EAX*CLimbSize] CALL System.AllocMem MOV NormDividend,EAX // First: normalize Divisor by shifting left to eliminate leading zeroes // and shift Dividend left by same number of bits. // Get number of leading Divisor zeros (into ECX). MOV ESI,LDivisor MOV EBX,[ESI+CLimbSize*EDI] BSR EBX,EBX MOV ECX,31 SUB ECX,EBX MOV Shift,ECX // Shift Divisor to NormDivisor by CL. MOV EBX,EDI MOV EDI,NormDivisor MOV EAX,[ESI + CLimbSize*EBX] JMP @ShiftDivisor @ShiftDivisorLoop: MOV EDX,[ESI + CLimbSize*EBX] SHLD EAX,EDX,CL MOV [EDI + CLimbSize*EBX + CLimbSize],EAX MOV EAX,EDX @ShiftDivisor: DEC EBX JNS @ShiftDivisorLoop // Handle lowest limb. SHL EAX,CL MOV [EDI],EAX // Shift Dividend to NormDividend by CL. MOV EBX,LSize MOV ESI,LDividend MOV EDI,NormDividend XOR EAX,EAX JMP @ShiftDividend @ShiftDividendLoop: MOV EDX,[ESI + CLimbSize*EBX] SHLD EAX,EDX,CL MOV [EDI + CLimbSize*EBX + CLimbSize],EAX MOV EAX,EDX @ShiftDividend: DEC EBX JNS @ShiftDividendLoop // Handle lowest limb. SHL EAX,CL MOV [EDI],EAX MOV EBX,LSize MOV ECX,RSize MOV ESI,NormDividend MOV EDI,NormDivisor LEA EDI,[EDI + CLimbSize*ECX - CLimbSize] @MainLoop: XOR EDX,EDX MOV EAX,[ESI + CLimbSize*EBX] DIV EAX,[EDI] MOV QHat.Hi,EAX MOV EAX,[ESI + CLimbSize*EBX - CLimbSize] DIV EAX,[EDI] MOV QHat.Lo,EAX MOV RHat.Lo,EDX XOR EDX,EDX MOV RHat.Hi,EDX @CheckAdjust: CMP QHat.Hi,0 JNE @DoAdjust MOV EAX,QHat.Lo MUL EAX,[EDI - CLimbSize] CMP EDX,RHat.Lo JA @DoAdjust JB @AdjustEnd CMP EAX,[ESI + CLimbSize*EBX - 2*CLimbSize] JBE @AdjustEnd @DoAdjust: SUB QHat.Lo,1 SBB QHat.Hi,0 MOV EAX,[EDI] ADD RHat.Lo,EAX ADC RHat.Hi,0 JZ @CheckAdjust @AdjustEnd: // Now multiply NormDivisor by QHat and subtract the product from NormDividend[J]. // Save a few registers. PUSH EDI PUSH EBX PUSH ECX MOV ECX,EBX SUB ECX,RSize LEA EDI,[ESI + CLimbSize*ECX] MOV EAX,LQuotient MOV EDX,QHat.Lo MOV [EAX + CLimbSize*ECX],EDX XOR EBX,EBX MOV Overflow,EBX @SubtractProduct: MOV EAX,NormDivisor MOV EAX,[EAX + CLimbSize*EBX] MUL EAX,QHat.Lo MOV Product.Lo,EAX MOV Product.Hi,EDX XOR EDX,EDX MOV EAX,[EDI + CLimbSize*EBX] SUB EAX,Overflow SBB EDX,0 SUB EAX,Product.Lo SBB EDX,0 MOV [EDI + CLimbSize*EBX],EAX MOV EAX,Product.Hi SUB EAX,EDX MOV Overflow,EAX INC EBX CMP EBX,RSize JL @SubtractProduct @SubtractProductEnd: MOV EBX,[ESP + 4] MOV EDX,[ESI + CLimbSize*EBX] SUB EDX,Overflow MOV [ESI + CLimbSize*EBX],EDX JNC @SkipAddBack // Add normalized divisor back, if necessary: MOV EAX,LQuotient DEC [EAX + CLimbSize*ECX] XOR EBX,EBX MOV Overflow,EBX @AddBackLoop: CMP EBX,RSize JGE @AddBackLoopEnd XOR EDX,EDX MOV EAX,NormDivisor MOV EAX,[EAX + CLimbSize*EBX] ADD EAX,Overflow ADD [EDI + CLimbSize*EBX],EAX ADC EDX,0 MOV Overflow,EDX INC EBX JMP @AddBackLoop @AddBackLoopEnd: MOV EBX,[ESP + 4] ADD [ESI + CLimbSize*EBX],EDX @SkipAddBack: POP ECX POP EBX POP EDI // End of main loop; loop if required. DEC EBX CMP EBX,ECX JGE @MainLoop // NormDividend now contains remainder, scaled by Shift. // If Remainder <> nil, then shift NormDividend down into Remainder. MOV EAX,Remainder TEST EAX,EAX JE @ExitTrue XOR EBX,EBX MOV ESI,NormDividend MOV EDI,EAX MOV ECX,Shift MOV EAX,[ESI + CLimbSize*EBX] @RemainderLoop: MOV EDX,[ESI + CLimbSize*EBX + CLimbSize] SHRD EAX,EDX,CL MOV [EDI + CLimbSize*EBX],EAX MOV EAX,EDX INC EBX CMP EBX,RSize JL @RemainderLoop SHR EDX,CL MOV [EDI + CLimbSize*EBX],EDX JMP @ExitTrue @ExitFalse: MOV BL,0 JMP @Exit @ExitTrue: MOV BL,1 @Exit: // Clear dynamic arrays. MOV EAX,NormDividend CALL System.@FreeMem MOV EAX,NormDivisor CALL System.@FreeMem MOV EAX,EBX POP EBX POP EDI POP ESI end; {$ELSE} var LDividend, LDivisor, LQuotient, LRemainder: PLimb; NormDividend, NormDivisor: PLimb; QHat, RHat, Product: TUInt64; Overflow: TLimb; Shift: Integer; SaveRDI, SaveRBX, SaveRCX: NativeUInt; asm .PUSHNV RSI .PUSHNV RDI .PUSHNV RBX // To avoid reference count problems with Delphi's dynamic array types, we do or own, // "old school" dynarrays, using GetMem and FreeMem. XOR EBX,EBX // Set "dynarrays" to nil, so FreeMem calls won't fail. MOV NormDividend,RBX MOV NormDivisor,RBX MOV LDividend,RCX MOV LDivisor,RDX MOV LQuotient,R8 MOV LRemainder,R9 MOV ESI,LSize MOV EDI,RSize CMP ESI,EDI JL @ExitFalse DEC EDI JS @ExitFalse JNE @MultiLimbDivisor // Simple division // Divisor only contains one single limb: simple division and exit. // NOTE: 32 bit division is easier and probably faster than 64 bit, even in 64 bit mode. This was tested for Decimals.pas. @SingleLimbDivisor: MOV EBX,[RDX] DEC ESI MOV RDI,RCX XOR EDX,EDX @SingleDivLoop: MOV EAX,[RDI + CLimbSize*RSI] // ---------------------------------------------------------------------------------------------------------------------- // // NOTE: In XE2, in 64 bit asm, "DIV <r/m32>" is generated as "DIV <r/m64>", but "DIV EAX,<r/m32>" is generated correctly. // // The same applies to "MUL <r/m32>". // // ---------------------------------------------------------------------------------------------------------------------- // DIV EAX,EBX MOV [R8 + CLimbSize*RSI],EAX DEC ESI JNS @SingleDivLoop MOV RAX,LRemainder TEST RAX,RAX JZ @ExitTrue MOV [RAX],EDX JMP @ExitTrue // MultiLimb division // Divisor contains more than one limb: basecase division as described in Knuth's TAoCP Vol. 2. @MultiLimbDivisor: MOV ECX,RSize ADD ECX,ECX ADD ECX,ECX CALL System.AllocMem MOV NormDivisor,RAX MOV ECX,LSize INC ECX ADD ECX,ECX ADD ECX,ECX CALL System.AllocMem MOV NormDividend,RAX // First: normalize Divisor by shifting left to eliminate leading zeroes // and shift Dividend left by same nubmer of bits. // Get number of leading Divisor zeroes (into ECX). MOV RSI,LDivisor MOV EBX,[RSI + CLimbSize*RDI] BSR EBX,EBX MOV ECX,31 SUB ECX,EBX MOV Shift,ECX // Shift Divisor to NormDivisor by CL. MOV EBX,EDI MOV RDI,NormDivisor MOV EAX,[RSI + CLimbSize*RBX] JMP @ShiftDivisor @ShiftDivisorLoop: MOV EDX,[RSI + CLimbSize*RBX] SHLD EAX,EDX,CL MOV [RDI + CLimbSize*RBX + CLimbSize],EAX MOV EAX,EDX @ShiftDivisor: DEC EBX JNS @ShiftDivisorLoop // Handle lowest limb. SHL EAX,CL MOV [RDI],EAX // Shift Dividend to NormDividend by CL. MOV EBX,LSize MOV RSI,LDividend MOV RDI,NormDividend XOR EAX,EAX JMP @ShiftDividend @ShiftDividendLoop: MOV EDX,[RSI + CLimbSize*RBX] SHLD EAX,EDX,CL MOV [RDI + CLimbSize*RBX + CLimbSize],EAX MOV EAX,EDX @ShiftDividend: DEC EBX JNS @ShiftDividendLoop // Handle lowest limb. SHL EAX,CL MOV [RDI],EAX MOV EBX,LSize MOV ECX,RSize MOV RSI,NormDividend MOV RDI,NormDivisor LEA RDI,[RDI + CLimbSize*RCX - CLimbSize] @MainLoop: XOR EDX,EDX MOV EAX,[RSI + CLimbSize*RBX] DIV EAX,[RDI] MOV QHat.Hi,EAX MOV EAX,[RSI + CLimbSize*RBX - CLimbSize] DIV EAX,[RDI] MOV QHat.Lo,EAX MOV RHat.Lo,EDX XOR EDX,EDX MOV RHat.Hi,EDX @CheckAdjust: CMP QHat.Hi,0 JNE @DoAdjust MOV EAX,QHat.Lo MUL EAX,[RDI - CLimbSize] CMP EDX,RHat.Lo JA @DoAdjust JB @AdjustEnd CMP EAX,[RSI + CLimbSize*RBX - 2*CLimbSize] JBE @AdjustEnd @DoAdjust: SUB QHat.Lo,1 SBB QHat.Hi,0 MOV EAX,[RDI] ADD RHat.Lo,EAX ADC RHat.Hi,0 JZ @CheckAdjust @AdjustEnd: MOV SaveRDI,RDI MOV SaveRBX,RBX MOV SaveRCX,RCX MOV ECX,EBX SUB ECX,RSize LEA RDI,[RSI + CLimbSize*RCX] MOV RAX,LQuotient MOV EDX,QHat.Lo MOV [RAX + CLimbSize*RCX],EDX XOR EBX,EBX MOV Overflow,EBX @SubtractProduct: MOV RAX,NormDivisor MOV EAX,[RAX + CLimbSize*RBX] MUL EAX,QHat.Lo MOV Product.Lo,EAX MOV Product.Hi,EDX XOR EDX,EDX MOV EAX,[RDI + CLimbSize*RBX] SUB EAX,Overflow SBB EDX,0 SUB EAX,Product.Lo SBB EDX,0 MOV [RDI + CLimbSize*RBX],EAX MOV EAX,Product.Hi SUB EAX,EDX MOV Overflow,EAX INC EBX CMP EBX,RSize JL @SubtractProduct @SubtractProductEnd: MOV RBX,SaveRBX MOV EDX,[RSI + CLimbSize*RBX] SUB EDX,Overflow MOV [RSI + CLimbSize*RBX],EDX JNC @SkipAddBack // Add normalized divisor back, if necessary: MOV RAX,LQuotient DEC DWORD PTR [RAX + ClimbSize*RCX] XOR EBX,EBX MOV Overflow,EBX @AddBackLoop: CMP EBX,RSize JGE @AddBackLoopEnd XOR EDX,EDX MOV RAX,NormDivisor MOV EAX,[RAX + CLimbSize*RBX] ADD EAX,Overflow ADD [RDI + CLimbSize*RBX],EAX ADC EDX,0 MOV Overflow,EDX INC EBX JMP @AddBackLoop @AddBackLoopEnd: MOV RBX,SaveRBX ADD [RSI + CLimbSize*RBX],EDX @SkipAddBack: MOV RCX,SaveRCX MOV RBX,SaveRBX MOV RDI,SaveRDI // End of main loop; loop if required DEC EBX CMP EBX,ECX JGE @MainLoop // NormDividend now contains remainder, scaled by Shift. // If Remainder <> nil, then shift NormDividend down into Remainder MOV RAX,LRemainder TEST RAX,RAX JE @ExitTrue XOR EBX,EBX MOV RSI,NormDividend MOV RDI,RAX MOV ECX,Shift MOV EAX,[RSI + CLimbSize*RBX] @RemainderLoop: MOV EDX,[RSI + CLimbSize*RBX + CLimbSize] SHRD EAX,EDX,CL MOV [RDI + CLimbSize*RBX],EAX MOV EAX,EDX INC EBX CMP EBX,RSize JL @RemainderLoop SHR EDX,CL MOV [RDI + CLimbSize*RBX],EDX JMP @ExitTrue @ExitFalse: MOV BL,False JMP @Exit @ExitTrue: MOV BL,True @Exit: // Clear dynamic arrays. MOV RCX,NormDividend CALL System.@FreeMem MOV RCX,NormDivisor CALL System.@FreeMem MOV EAX,EBX end; {$IFEND} // Note: only handles Abs(Self) > 0. class procedure BigInteger.InternalIncrement(Limbs: PLimb; Size: Integer); {$IFDEF PUREPASCAL} var N: TLimb; begin N := MaxInt; while Size > 0 do begin N := Limbs^; Inc(N); Limbs^ := N; if N <> 0 then Break; Inc(Limbs); Dec(Size); end; if N = 0 then begin Limbs^ := 1; end; end; {$ELSE !PUREPASCAL} {$IFDEF WIN32} asm TEST EDX,EDX JE @Exit @Loop: MOV ECX,[EAX] INC ECX MOV [EAX],ECX TEST ECX,ECX JNE @Exit LEA EAX,[EAX + CLimbSize] DEC EDX JNE @Loop @Last: TEST ECX,ECX JNE @Exit MOV TLimb PTR [EAX],1 @Exit: end; {$ELSE !WIN32} asm TEST EDX,EDX JE @Exit @Loop: MOV EAX,[RCX] INC EAX MOV [RCX],EAX TEST EAX,EAX JNE @Exit LEA RCX,[RCX + CLimbSize] DEC EDX JNE @Loop @Last: TEST EAX,EAX JNE @Exit MOV TLimb PTR [RCX],1 @Exit: end; {$ENDIF !WIN32} {$ENDIF !PUREPASCAL} // Note: only handles Abs(Self) > 1 class procedure BigInteger.InternalDecrement(Limbs: PLimb; Size: Integer); {$IFDEF PUREPASCAL} begin repeat Dec(Limbs^); if Limbs^ <> TLimb(-1) then Break; Inc(Limbs); Dec(Size); until Size = 0; end; {$ELSE !PUREPASCAL} {$IFDEF WIN32} asm @Loop: MOV ECX,[EAX] DEC ECX MOV [EAX],ECX CMP ECX,-1 JNE @Exit LEA EAX,[EAX + CLimbSize] DEC EDX JNE @Loop @Exit: end; {$ELSE !WIN32} asm @Loop: MOV EAX,[RCX] DEC EAX MOV [RCX],EAX CMP EAX,-1 JNE @Exit LEA RCX,[RCX + CLimbSize] DEC EDX JNE @Loop @Exit: end; {$ENDIF !WIN32} {$ENDIF !PUREPASCAL} // Divides a magnitude (usually the FData of a TBigInteger) by Base and returns the remainder. class function BigInteger.InternalDivideByBase(Mag: PLimb; Base: Integer; var Size: Integer): UInt32; {$IF DEFINED(PUREPASCAL)} // This routine uses DivMod(Cardinal, Word, Word, Word). // In Win32, that is 14 times faster than the previous version using the DivMod with UInt64 parameters. // In Win64, it is only a little bit slower. type UInt32Rec = record Lo, Hi: UInt16; end; PUInt16 = ^UInt16; var P, PMag: PUInt16; Remainder: UInt16; CurrentWord: UInt32; begin Result := 0; if Size = 0 then Exit; PMag := PUInt16(Mag); P := PMag + Size * 2; Remainder := 0; while P > PMag do begin Dec(P); UInt32Rec(CurrentWord).Lo := P^; UInt32Rec(CurrentWord).Hi := Remainder; Math.DivMod(CurrentWord, Base, P^, Remainder); end; Result := Remainder; if Mag[Size - 1] = 0 then Dec(Size); end; {$ELSEIF DEFINED(WIN32)} asm PUSH ESI PUSH EDI PUSH EBX MOV EBX,ECX // var Size MOV ECX,EDX MOV ESI,EAX // PBase (= Mag) MOV EDX,[EBX] XOR EAX,EAX // Result TEST EDX,EDX JE @Exit LEA EDI,[ESI + CLimbSize*EDX] // P XOR EDX,EDX // Remainder := 0; CMP EDI,ESI // while P > PBase do JBE @CheckSize @Loop: SUB EDI,4 // Dec(P); MOV EAX,[EDI] // DivMod(P^ or (Remainder shl 32), 10, P^, Remainder); DIV EAX,ECX MOV [EDI],EAX CMP EDI,ESI // while P > PBase do JA @Loop @CheckSize: MOV EAX,EDX // if (PBase + Size - 1)^ = 0 then MOV EDX,[EBX] LEA ESI,[ESI + CLimbSize*EDX - CLimbSize] CMP [ESI],0 JNE @Exit DEC DWORD PTR [EBX] // Dec(Size); @Exit: POP EBX POP EDI POP ESI end; {$ELSE} asm .NOFRAME MOV R11,R8 // var Size MOV R9,RCX // PBase := Mag; MOV ECX,EDX XOR EAX,EAX // Result := 0; MOV EDX,[R11] // if Size = 0 then Exit; OR EDX,EDX JE @Exit LEA R10,[R9 + CLimbSize*RDX] // P XOR EDX,EDX // Remainder := 0; CMP R10,R9 // while P > PBase do JBE @CheckSize @Loop: SUB R10,4 // Dec(P) MOV EAX,[R10] // DivMod(P^ or (Remainder shl 32), 10, P^, Remainder); DIV EAX,ECX MOV [R10],EAX CMP R10,R9 // while P > PBase do JA @Loop @CheckSize: MOV EAX,EDX MOV EDX,[R11] CMP [R9 + CLimbSize*RDX - CLimbSize],0 // if (PBase + Size - 1)^ = 0 then JNE @Exit DEC DWORD PTR [R11] // Dec(Size); @Exit: end; {$IFEND} class operator BigInteger.Equal(const Left, Right: BigInteger): Boolean; begin Result := Compare(Left, Right) = 0; end; class procedure BigInteger.Error(ErrorCode: TErrorCode; const ErrorInfo: string); begin case ErrorCode of ecParse: raise EConvertError.CreateFmt(SErrorBigIntegerParsing, [ErrorInfo]); ecDivbyZero: raise EZeroDivide.Create(SDivisionByZero); ecConversion: raise EConvertError.CreateFmt(SConversionFailed, [ErrorInfo]); ecOverflow: raise EOverflow.Create(SOverflow); ecInvalidArgument: raise EInvalidArgument.Create(SInvalidArgumentBase); else raise EInvalidOp.Create(SInvalidOperation); end; end; class operator BigInteger.Explicit(const Int: BigInteger): Cardinal; begin if Int.FData = nil then Result := 0 else Result := Int.FData[0] and High(Cardinal); end; class operator BigInteger.Explicit(const Int: BigInteger): Integer; begin if Int.FData = nil then Result := 0 else begin Result := Int.FData[0] and High(Integer); if Int.FSize < 0 then Result := -Result; end; end; class operator BigInteger.Explicit(const Int: BigInteger): Int64; begin if Int.FData = nil then Result := 0 else begin TUInt64(Result).Lo := Int.FData[0]; if (Int.FSize and SizeMask) > 1 then TUInt64(Result).Hi := Int.FData[1] and High(Integer) else TUInt64(Result).Hi := 0; if Int.FSize < 0 then Result := -Result; end; end; function BigInteger.AsCardinal: Cardinal; begin Result := 0; if not IsNegative and (BitLength <= CCardinalBits) then Result := Cardinal(Self) else Error(ecConversion, 'Cardinal'); end; function GetBitAt(FData: PLimb; BitNum: Integer): Boolean; begin Result := (FData[BitNum div 32] and (1 shl (BitNum and 31))) <> 0 end; function BigInteger.AsDouble: Double; const BitMasks: array[0..31] of Cardinal = // $FFFFFFFF shl (31 - Index) ( $00000001, $00000003, $00000007, $0000000F, $0000001F, $0000003F, $0000007F, $000000FF, $000001FF, $000003FF, $000007FF, $00000FFF, $00001FFF, $00003FFF, $00007FFF, $0000FFFF, $0001FFFF, $0003FFFF, $0007FFFF, $000FFFFF, $001FFFFF, $003FFFFF, $007FFFFF, $00FFFFFF, $01FFFFFF, $03FFFFFF, $07FFFFFF, $0FFFFFFF, $1FFFFFFF, $3FFFFFFF, $7FFFFFFF, $FFFFFFFF ); // The four values below will result in exactly the same value as: Result := StrToFloat(Self.ToString); ExponentBias = 1023; // DO NOT CHANGE!!! SignificandBits = 52; // DO NOT CHANGE!!! GuardOffset = SignificandBits + 2; // DO NOT CHANGE!!! ExponentBits = 11; // DO NOT CHANGE!!! ExponentShift = SignificandBits - CUInt32Bits; ExponentMask = Pred(1 shl ExponentBits); SignificandMask = Pred(1 shl ExponentShift); var BitLen: Integer; StickyIndex: Integer; StickyBits: TLimb; Guard, Round: Boolean; NumLeadingZeroes, K, I: Integer; LSize: Integer; Res: packed record case Byte of 0: (Dbl: Double); 1: (Bits: UInt64); 2: (Lo, Hi: UInt32); end; begin BitLen := BitLength; if BitLen > 1025 then if FSize < 0 then Exit(NegInfinity) else Exit(Infinity); // Error(ecConversion, 'Double'); if BitLen <= CInt64Bits then Result := AsInt64 else begin LSize := Size; // Form significand from top 53 bits of BigInteger. NumLeadingZeroes := (CLimbBits - BitLen) and 31; if NumLeadingZeroes > 11 then begin // 53 bits spread over 3 limbs, e.g.: // FData[LSize-1] FData[LSize-2] FData[LSize-3] // 10----5----0----5----0----5----0 10----5----0----5----0----5----0 10----5----0----5----0----5----0 // 000000000000000000000000000AAAAA BBBBBBBBBBBBBBBbbbbbbbbbbbbbbbbb CCCCCCCCCCCCCCCC**************** K := NumLeadingZeroes - 11; Res.Hi := (FData[LSize - 1] shl K) or (FData[LSize - 2] shr (CLimbBits - K)); { a shl K or b shr (31 - K) } Res.Lo := (FData[LSize - 2] shl K) or (FData[LSize - 3] shr (CLimbBits - K)); { b shl K or c shr (31 - K) } // Res.Hi Res.Lo // 10----5----0----5----0----5----0 10----5----0----5----0----5----0 // 00000000000AAAAABBBBBBBBBBBBBBBB bbbbbbbbbbbbbbbbCCCCCCCCCCCCCCCC end else begin // 53 bits spread over 2 limbs, e.g.: // FData[LSize-1] FData[LSize-2] // 10----5----0----5----0----5----0 10----5----0----5----0----5----0 // 000000AAAAAAAAAAAAAAAAAAAAAaaaaa BBBBBBBBBBBBBBBBBBBBBBBBBBB***** Res.Hi := FData[LSize - 1]; Res.Lo := FData[LSize - 2]; if NumLeadingZeroes < 11 then Res.Bits := Res.Bits shr (11 - NumLeadingZeroes); // Res.Hi Res.Lo // 10----5----0----5----0----5----0 10----5----0----5----0----5----0 // 00000000000AAAAAAAAAAAAAAAAAAAAA aaaaaBBBBBBBBBBBBBBBBBBBBBBBBBBB end; // Rounding, using guard, round and sticky bit. // Guard is below lowest bit of significand, Round bit one below that, and Sticky bit is accumulation of all bits // below the other two. // GRSB - Action (slightly modified; B is lowest bit of significand) // 0xxx - round down = do nothing (x means any bit value, 0 or 1) // 1000 - round down = do nothing // 1001 - round up // 101x - round up // 110x - round up // 111x - round up // Collect all bits below round bit into sticky bit. StickyIndex := BitLen - GuardOffset - 2; StickyBits := 0; // First collect from limbs below sticky bit. for I := 0 to StickyIndex div 32 - 1 do StickyBits := StickyBits or FData[I]; // Then include bits up to the sticky bit. StickyBits := StickyBits or (FData[StickyIndex div CLimbBits] and BitMasks[StickyIndex and (ClimbBits - 1)]); // Get guard and round bits. Round := GetBitAt(PLimb(FData), StickyIndex + 1); Guard := GetBitAt(PLimb(FData), StickyIndex + 2); // See table above. if Guard and (Odd(Res.Lo) or Round or (StickyBits <> 0)) then Res.Bits := Res.Bits + 1; // Beware of overflowing the significand! if Res.Bits > $1FFFFFFFFFFFFF then begin Res.Bits := Res.Bits shr 1; Inc(BitLen); end; // Remove hidden bit and place exponent and sign bit to form a complete Double. Res.Hi := (Res.Hi and SignificandMask) or // top of significand, hidden bit removed UInt32(((BitLen - 1 + ExponentBias) and ExponentMask) shl ExponentShift) or // exponent, unbiased UInt32(SignBitOf(FSize)); // sign bit Result := Res.Dbl; end; end; function BigInteger.AsInt64: Int64; begin Result := 0; if BitLength <= CInt64Bits then Result := Int64(Self) else Error(ecConversion, 'Int64'); end; function BigInteger.AsInteger: Integer; begin Result := 0; if BitLength <= CIntegerBits then Result := Integer(Self) else Error(ecConversion, 'Integer'); end; function BigInteger.AsUInt64: UInt64; begin Result := 0; if not IsNegative and (BitLength <= CUInt64Bits) then Result := UInt64(Self) else Error(ecConversion, 'UInt64'); end; class operator BigInteger.Explicit(const Int: BigInteger): UInt64; begin if Int.FData = nil then Result := 0 else begin TUInt64(Result).Lo := Int.FData[0]; if (Int.FSize and SizeMask) > 1 then TUInt64(Result).Hi := Int.FData[1] and High(Cardinal) else TUInt64(Result).Hi := 0; end; end; class function BigInteger.InternalCompare(Left, Right: PLimb; LSize, RSize: Integer): TValueSign; {$IFDEF PUREPASCAL} var L, R: PLimb; begin if Left = nil then begin if Right = nil then Exit(0) else Exit(-1); end; if Right = nil then Exit(1); if LSize > RSize then Result := 1 else if LSize < RSize then Result := -1 else // Same size, so compare values. Start at the "top" (most significant limb). begin L := Left + LSize - 1; R := Right + LSize - 1; while L >= Left do begin if L^ > R^ then Exit(1) else if L^ < R^ then Exit(-1); Dec(L); Dec(R); end; Exit(0); end; end; {$ELSE !PUREPASCAL} {$IFDEF WIN32} asm PUSH ESI TEST EAX,EAX JNE @LeftNotNil TEST EDX,EDX JZ @ExitZero JMP @ExitNeg @LeftNotNil: TEST EDX,EDX JZ @ExitPos CMP ECX,RSize JA @ExitPos JB @ExitNeg MOV ESI,EAX @Loop: MOV EAX,[ESI + ECX*CLimbSize - CLimbSize] CMP EAX,[EDX + ECX*CLimbSize - CLimbSize] JA @ExitPos JB @ExitNeg DEC ECX JNE @Loop @ExitZero: XOR EAX,EAX JMP @Exit @ExitPos: MOV EAX,1 JMP @Exit @ExitNeg: MOV EAX,-1 @Exit: POP ESI end; {$ELSE WIN64} asm TEST RCX,RCX JNZ @LeftNotNil // Left is nil TEST RDX,RDX JZ @ExitZero // if Right nil too, then equal JMP @ExitNeg // Otherwise, Left < Right @LeftNotNil: TEST RDX,RDX JZ @ExitPos CMP R8D,R9D JA @ExitPos JB @ExitNeg // R8D and R9D are same. LEA RCX,[RCX + R8*CLimbSize] LEA RDX,[RDX + R8*CLimbSize] TEST R8D,1 JZ @NotOdd LEA RCX,[RCX - CLimbSize] LEA RDX,[RDX - CLimbSize] MOV EAX,[RCX] CMP EAX,[RDX] JA @ExitPos JB @ExitNeg DEC R8D @NotOdd: SHR R8D,1 JZ @ExitZero @Loop: LEA RCX,[RCX - DLimbSize] LEA RDX,[RDX - DLimbSize] MOV RAX,[RCX] CMP RAX,[RDX] JA @ExitPos JB @ExitNeg DEC R8D JNE @Loop @ExitZero: XOR EAX,EAX JMP @Exit @ExitPos: MOV EAX,1 JMP @Exit @ExitNeg: MOV EAX,-1 @Exit: end; {$ENDIF WIN64} {$ENDIF !PUREPASCAL} //class function BigInteger.InternalCompareMagnitudes(Left, Right: PLimb; LSize, RSize: Integer): TValueSign; //begin // Result := InternalCompare(Left, Right, LSize, RSize); //end; // {$IFNDEF PUREPASCAL} class procedure BigInteger.InternalSubtractModified(Larger, Smaller, Result: PLimb; LSize, SSize: Integer); {$IFDEF WIN32} asm PUSH ESI PUSH EDI PUSH EBX MOV ESI,EAX // Left MOV EDI,EDX // Right MOV EBX,ECX // Result MOV ECX,SSize MOV EDX,LSize SUB EDX,ECX PUSH EDX XOR EDX,EDX XOR EAX,EAX MOV EDX,ECX AND EDX,CUnrollMask SHR ECX,CUnrollShift CLC JE @MainTail @MainLoop: MOV EAX,[ESI] SBB EAX,[EDI] MOV [EBX],EAX MOV EAX,[ESI + CLimbSize] SBB EAX,[EDI + CLimbSize] MOV [EBX + CLimbSize],EAX MOV EAX,[ESI + 2*CLimbSize] SBB EAX,[EDI + 2*CLimbSize] MOV [EBX + 2*CLimbSize],EAX MOV EAX,[ESI + 3*CLimbSize] SBB EAX,[EDI + 3*CLimbSize] MOV [EBX + 3*CLimbSize],EAX LEA ESI,[ESI + 4*CLimbSize] LEA EDI,[EDI + 4*CLimbSize] LEA EBX,[EBX + 4*CLimbSize] LEA ECX,[ECX - 1] JECXZ @MainTail JMP @Mainloop @MainTail: LEA ESI,[ESI + EDX*CLimbSize] LEA EDI,[EDI + EDX*CLimbSize] LEA EBX,[EBX + EDX*CLimbSize] LEA ECX,[@JumpsMain] JMP [ECX + EDX*TYPE Pointer] // Align jump table manually, with NOPs. Update if necessary. NOP @JumpsMain: DD @DoRestLoop DD @Main1 DD @Main2 DD @Main3 @Main3: MOV EAX,[ESI - 3*CLimbSize] SBB EAX,[EDI - 3*CLimbSize] MOV [EBX - 3*CLimbSize],EAX @Main2: MOV EAX,[ESI - 2*CLimbSize] SBB EAX,[EDI - 2*CLimbSize] MOV [EBX - 2*CLimbSize],EAX @Main1: MOV EAX,[ESI - CLimbSize] SBB EAX,[EDI - CLimbSize] MOV [EBX - CLimbSize],EAX @DoRestLoop: SETC AL // Save Carry Flag XOR EDI,EDI POP ECX MOV EDX,ECX AND EDX,CUnrollMask SHR ECX,CUnrollShift ADD AL,255 // Restore Carry Flag. JECXZ @RestLast3 @RestLoop: MOV EAX,[ESI] SBB EAX,EDI MOV [EBX],EAX MOV EAX,[ESI + CLimbSize] SBB EAX,EDI MOV [EBX + CLimbSize],EAX MOV EAX,[ESI + 2*CLimbSize] SBB EAX,EDI MOV [EBX + 2*CLimbSize],EAX MOV EAX,[ESI + 3*CLimbSize] SBB EAX,EDI MOV [EBX + 3*CLimbSize],EAX LEA ESI,[ESI + 4*CLimbSize] LEA EBX,[EBX + 4*CLimbSize] LEA ECX,[ECX - 1] JECXZ @RestLast3 JMP @RestLoop @RestLast3: LEA ESI,[ESI + EDX*CLimbSize] LEA EBX,[EBX + EDX*CLimbSize] LEA ECX,[@RestJumps] JMP [ECX + EDX*TYPE Pointer] // If necessary, align second jump table with NOPs NOP NOP NOP @RestJumps: DD @Exit DD @Rest1 DD @Rest2 DD @Rest3 @Rest3: MOV EAX,[ESI - 3*CLimbSize] SBB EAX,EDI MOV [EBX - 3*CLimbSize],EAX @Rest2: MOV EAX,[ESI - 2*CLimbSize] SBB EAX,EDI MOV [EBX - 2*CLimbSize],EAX @Rest1: MOV EAX,[ESI - CLimbSize] SBB EAX,EDI MOV [EBX - CLimbSize],EAX @Exit: POP EBX POP EDI POP ESI end; {$ELSE WIN32/WIN64} asm MOV R10,RCX MOV ECX,SSize // R10 = Left, RDX = Right, R8 = Result, R9D = LSize, ECX = SSize CMP R9D,ECX JAE @SkipSwap XCHG ECX,R9D XCHG R10,RDX @SkipSwap: SUB R9D,ECX PUSH R9 MOV R9D,ECX AND R9D,CUnrollMask SHR ECX,CUnrollShift CLC JE @MainTail @MainLoop: MOV RAX,[R10] SBB RAX,[RDX] MOV [R8],RAX MOV RAX,[R10 + DLimbSize] SBB RAX,[RDX + DLimbSize] MOV [R8 + DLimbSize],RAX LEA R10,[R10 + 2*DLimbSize] LEA RDX,[RDX + 2*DLimbSize] LEA R8,[R8 + 2*DLimbSize] LEA RCX,[RCX - 1] JRCXZ @MainTail JMP @MainLoop @MainTail: // Here, code does not add index*CLimbSize and then use negative offsets, because that would take away the advantage of using 64 bit registers. // Each block is separate, no fall through. LEA RCX,[@MainJumps] JMP [RCX + R9*TYPE Pointer] // Align jump table. Update if necessary! DB $90,$90,$90,$90,$90 @MainJumps: DQ @DoRestLoop DQ @Main1 DQ @Main2 DQ @Main3 @Main3: MOV RAX,[R10] SBB RAX,[RDX] MOV [R8],RAX MOV EAX,[R10 + 2*CLimbSize] SBB EAX,[RDX + 2*CLimbSize] MOV [R8 + 2*CLimbSize],EAX LEA R10,[R10 + 3*CLimbSize] LEA RDX,[RDX + 3*CLimbSize] LEA R8,[R8 + 3*CLimbSize] JMP @DoRestLoop @Main2: MOV RAX,[R10] SBB RAX,[RDX] MOV [R8],RAX LEA R10,[R10 + 2*CLimbSize] LEA RDX,[RDX + 2*CLimbSize] LEA R8,[R8 + 2*CLimbSize] JMP @DoRestLoop @Main1: MOV EAX,[R10] SBB EAX,[RDX] MOV [R8],EAX LEA R10,[R10 + CLimbSize] LEA RDX,[RDX + CLimbSize] LEA R8,[R8 + CLimbSize] @DoRestLoop: SETC AL // Save Carry Flag XOR EDX,EDX POP RCX MOV R9D,ECX AND R9D,CUnrollMask SHR ECX,CUnrollShift ADD AL,255 // Restore Carry Flag. JECXZ @RestLast3 @RestLoop: MOV RAX,[R10] SBB RAX,RDX MOV [R8],RAX MOV RAX,[R10 + DLimbSize] SBB RAX,RDX MOV [R8 + DLimbSize],RAX LEA R10,[R10 + 2*DLimbSize] LEA R8,[R8 + 2*DLimbSize] LEA RCX,[RCX - 1] JRCXZ @RestLast3 JMP @RestLoop @RestLast3: LEA RCX,[@RestJumps] JMP [RCX + R9*TYPE Pointer] // If necessary, align second jump table with NOPs DB $90,$90,$90,$90,$90,$90,$90 @RestJumps: DQ @Exit DQ @Rest1 DQ @Rest2 DQ @Rest3 @Rest3: MOV RAX,[R10] SBB RAX,RDX MOV [R8],RAX MOV EAX,[R10 + DLimbSize] SBB EAX,EDX MOV [R8 + DLimbSize],EAX JMP @Exit @Rest2: MOV RAX,[R10] SBB RAX,RDX MOV [R8],RAX JMP @Exit @Rest1: MOV EAX,[R10] SBB EAX,EDX MOV [R8],EAX @Exit: end; {$ENDIF} class procedure BigInteger.InternalSubtractPlain(Larger, Smaller, Result: PLimb; LSize, SSize: Integer); {$IFDEF WIN32} asm PUSH ESI PUSH EDI PUSH EBX MOV ESI,EAX // Left MOV EDI,EDX // Right MOV EBX,ECX // Result MOV ECX,SSize MOV EDX,LSize SUB EDX,ECX PUSH EDX XOR EDX,EDX XOR EAX,EAX MOV EDX,ECX AND EDX,CUnrollMask SHR ECX,CUnrollShift CLC JE @MainTail @MainLoop: // Unrolled 4 times. More times will not improve speed anymore. MOV EAX,[ESI] SBB EAX,[EDI] MOV [EBX],EAX MOV EAX,[ESI + CLimbSize] SBB EAX,[EDI + CLimbSize] MOV [EBX + CLimbSize],EAX MOV EAX,[ESI + 2*CLimbSize] SBB EAX,[EDI + 2*CLimbSize] MOV [EBX + 2*CLimbSize],EAX MOV EAX,[ESI + 3*CLimbSize] SBB EAX,[EDI + 3*CLimbSize] MOV [EBX + 3*CLimbSize],EAX // Update pointers. LEA ESI,[ESI + 4*CLimbSize] LEA EDI,[EDI + 4*CLimbSize] LEA EBX,[EBX + 4*CLimbSize] // Update counter and loop if required. DEC ECX // Note: if INC/DEC must be emulated: LEA ECX,[ECX - 1]; JECXZ @MainTail; JMP @MainLoop JNE @MainLoop @MainTail: // Add index*CLimbSize so @MainX branches can fall through. LEA ESI,[ESI + EDX*CLimbSize] LEA EDI,[EDI + EDX*CLimbSize] LEA EBX,[EBX + EDX*CLimbSize] // Indexed jump. LEA ECX,[@JumpsMain] JMP [ECX + EDX*TYPE Pointer] // Align jump table manually, with NOPs. Update if necessary. NOP // Jump table. @JumpsMain: DD @DoRestLoop DD @Main1 DD @Main2 DD @Main3 @Main3: MOV EAX,[ESI - 3*CLimbSize] // negative offset, because index*CLimbSize was already added. SBB EAX,[EDI - 3*CLimbSize] MOV [EBX - 3*CLimbSize],EAX @Main2: MOV EAX,[ESI - 2*CLimbSize] SBB EAX,[EDI - 2*CLimbSize] MOV [EBX - 2*CLimbSize],EAX @Main1: MOV EAX,[ESI - CLimbSize] SBB EAX,[EDI - CLimbSize] MOV [EBX - CLimbSize],EAX @DoRestLoop: SETC AL // Save Carry Flag XOR EDI,EDI POP ECX MOV EDX,ECX AND EDX,CUnrollMask SHR ECX,CUnrollShift ADD AL,255 // Restore Carry Flag. INC ECX DEC ECX JE @RestLast3 // JECXZ is slower than INC/DEC/JE @RestLoop: MOV EAX,[ESI] SBB EAX,EDI MOV [EBX],EAX MOV EAX,[ESI + CLimbSize] SBB EAX,EDI MOV [EBX + CLimbSize],EAX MOV EAX,[ESI + 2*CLimbSize] SBB EAX,EDI MOV [EBX + 2*CLimbSize],EAX MOV EAX,[ESI + 3*CLimbSize] SBB EAX,EDI MOV [EBX + 3*CLimbSize],EAX LEA ESI,[ESI + 4*CLimbSize] // LEA does not affect the flags, so carry will not be changed. LEA EBX,[EBX + 4*CLimbSize] DEC ECX // DEC does not affect carry flag, but causes partial-flags stall (e.g. when using SBB) on older CPUs. JNE @RestLoop @RestLast3: LEA ESI,[ESI + EDX*CLimbSize] LEA EBX,[EBX + EDX*CLimbSize] LEA ECX,[@RestJumps] JMP [ECX + EDX*TYPE Pointer] // If necessary, align second jump table with NOPs NOP NOP NOP @RestJumps: DD @Exit DD @Rest1 DD @Rest2 DD @Rest3 @Rest3: MOV EAX,[ESI - 3*CLimbSize] SBB EAX,EDI MOV [EBX - 3*CLimbSize],EAX @Rest2: MOV EAX,[ESI - 2*CLimbSize] SBB EAX,EDI MOV [EBX - 2*CLimbSize],EAX @Rest1: MOV EAX,[ESI - CLimbSize] SBB EAX,EDI MOV [EBX - CLimbSize],EAX @Exit: POP EBX POP EDI POP ESI end; {$ELSE WIN32/WIN64} asm MOV R10,RCX // in emulating code, ECX must be used as loop counter! So do not exchange RCX and R10 in the editor. MOV ECX,SSize // R10 = Left, RDX = Right, R8 = Result, R9D = LSize, ECX = SSize CMP R9D,ECX JAE @SkipSwap XCHG ECX,R9D XCHG R10,RDX @SkipSwap: SUB R9D,ECX PUSH R9 MOV R9D,ECX AND R9D,CUnrollMask SHR ECX,CUnrollShift CLC JE @MainTail // ECX = 0, so fewer than 3 limbs to be processed in main @MainLoop: MOV RAX,[R10] // Add two limbs at once, taking advantage of 64 bit registers. SBB RAX,[RDX] MOV [R8],RAX MOV RAX,[R10 + DLimbSize] // And next two limbs too. SBB RAX,[RDX + DLimbSize] MOV [R8 + DLimbSize],RAX LEA R10,[R10 + 2*DLimbSize] LEA RDX,[RDX + 2*DLimbSize] LEA R8,[R8 + 2*DLimbSize] DEC ECX // if INC/DEC must be emulated: LEA ECX,[ECX - 1]; JECXZ @MainTail; JMP @MainLoop JNE @MainLoop @MainTail: // Here, code does not add index*CLimbSize and then use negative offsets, because that would take away the advantage of using 64 bit registers. // Each block is separate, no fall through. LEA RCX,[@MainJumps] JMP [RCX + R9*TYPE Pointer] // Align jump table. Update if necessary! NOP @MainJumps: DQ @DoRestLoop DQ @Main1 DQ @Main2 DQ @Main3 @Main3: MOV RAX,[R10] SBB RAX,[RDX] MOV [R8],RAX MOV EAX,[R10 + DLimbSize] SBB EAX,[RDX + DLimbSize] MOV [R8 + 2*CLimbSize],EAX LEA R10,[R10 + 3*CLimbSize] LEA RDX,[RDX + 3*CLimbSize] LEA R8,[R8 + 3*CLimbSize] JMP @DoRestLoop @Main2: MOV RAX,[R10] SBB RAX,[RDX] MOV [R8],RAX LEA R10,[R10 + DLimbSize] LEA RDX,[RDX + DLimbSize] LEA R8,[R8 + DLimbSize] JMP @DoRestLoop @Main1: MOV EAX,[R10] SBB EAX,[RDX] MOV [R8],EAX LEA R10,[R10 + CLimbSize] LEA RDX,[RDX + CLimbSize] LEA R8,[R8 + CLimbSize] @DoRestLoop: SETC AL // Save Carry Flag XOR EDX,EDX POP RCX MOV R9D,ECX AND R9D,CUnrollMask SHR ECX,CUnrollShift ADD AL,255 // Restore Carry Flag. INC ECX DEC ECX JE @RestLast3 // JECXZ is slower than INC/DEC/JE @RestLoop: MOV RAX,[R10] // Do two limbs at once. SBB RAX,RDX MOV [R8],RAX MOV RAX,[R10 + DLimbSize] // And the next two limbs. SBB RAX,RDX MOV [R8 + DLimbSize],RAX LEA R10,[R10 + 2*DLimbSize] LEA R8,[R8 + 2*DLimbSize] DEC ECX JNE @RestLoop @RestLast3: LEA RCX,[@RestJumps] JMP [RCX + R9*TYPE Pointer] // If necessary, align second jump table with NOPs @RestJumps: DQ @Exit DQ @Rest1 DQ @Rest2 DQ @Rest3 @Rest3: MOV RAX,[R10] SBB RAX,RDX MOV [R8],RAX MOV EAX,[R10 + 2*CLimbSize] SBB EAX,EDX MOV [R8 + 2*CLimbSize],EAX LEA R8,[R8 + 3*CLimbSize] JMP @Exit @Rest2: MOV RAX,[R10] SBB RAX,RDX MOV [R8],RAX LEA R8,[R8 + 2*CLimbSize] JMP @Exit @Rest1: MOV EAX,[R10] SBB EAX,EDX MOV [R8],EAX LEA R8,[R8 + CLimbSize] @Exit: end; {$ENDIF !WIN32} {$ENDIF !PUREPASCAL} {$IFDEF PUREPASCAL} class procedure BigInteger.InternalSubtractPurePascal(Larger, Smaller, Result: PLimb; LSize, SSize: Integer); var Diff: TLimb; Borrow, InterBorrow: TLimb; LTail: Integer; LCount: Integer; {$IFDEF CPUX64} Diff64, Borrow64, InterBorrow64, Larger64: UInt64; {$ENDIF} begin {$IFDEF CPUX64} Borrow64 := 0; {$ELSE} Borrow := 0; {$ENDIF} Dec(LSize, SSize); LTail := SSize and CUnrollMask; LCount := SSize shr CUnrollShift; // Subtract, with borrow, Smallest from Largest and store result in Result. while LCount > 0 do begin /////////////////////////////////////////////////////////////////////////////////// // Tests with 64 bit intermediate results like: // // // // LResult := Int64(Larger[0]) - Smaller[0] + Integer(TUInt64(LResult).Hi); // // Result[0] := TLimb(LResult); // // // // LResult := Int64(Larger[1]) - Smaller[1] + Integer(TUInt64(LResult).Hi); // // Result[1] := TLimb(LResult); // // // etc... // // // // ... turned out to be slower than the following carry emulating code, even // // for 64 bit targets. // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // Tests with loop unrolling by a factor > 4 did not improve results at all. // /////////////////////////////////////////////////////////////////////////////////// {$IFDEF CPUX64} // add UInt64s instead of limbs. Larger64 := PUInt64(Larger)[0]; Diff64 := Larger64 - PUInt64(Smaller)[0]; InterBorrow64 := Ord(Diff64 > Larger64); Diff64 := Diff64 - Borrow64; PUInt64(Result)[0] := Diff64; Borrow64 := InterBorrow64 or Ord(Diff64 = UInt64(-1)) and Borrow64; Larger64 := PUInt64(Larger)[1]; Diff64 := Larger64 - PUInt64(Smaller)[1]; InterBorrow64 := Ord(Diff64 > Larger64); Diff64 := Diff64 - Borrow64; PUInt64(Result)[1] := Diff64; Borrow64 := InterBorrow64 or Ord(Diff64 = UInt64(-1)) and Borrow64; {$ELSE} Diff := Larger[0] - Smaller[0]; InterBorrow := Ord(Diff > Larger[0]); // there was a borrow if R0 > Larger[0]. Diff := Diff - Borrow; Result[0] := Diff; Borrow := InterBorrow or Ord(Diff = $FFFFFFFF) and Borrow; // there was a borrow if R > R0. Diff := Larger[1] - Smaller[1]; InterBorrow := Ord(Diff > Larger[1]); Dec(Diff, Borrow); Result[1] := Diff; Borrow := InterBorrow or Ord(Diff = $FFFFFFFF) and Borrow; Diff := Larger[2] - Smaller[2]; InterBorrow := Ord(Diff > Larger[2]); Dec(Diff, Borrow); Result[2] := Diff; Borrow := InterBorrow or Ord(Diff = $FFFFFFFF) and Borrow; Diff := Larger[3] - Smaller[3]; InterBorrow := Ord(Diff > Larger[3]); Dec(Diff, Borrow); Result[3] := Diff; Borrow := InterBorrow or Ord(Diff = $FFFFFFFF) and Borrow; {$ENDIF} Inc(Larger, CUnrollIncrement); Inc(Smaller, CUnrollIncrement); Inc(Result, CUnrollIncrement); Dec(LCount); end; {$IFDEF CPUX64} Borrow := TLimb(Borrow64); {$ENDIF} while LTail > 0 do begin Diff := Larger[0] - Smaller[0]; InterBorrow := Ord(Diff > Larger[0]); Dec(Diff, Borrow); Result[0] := Diff; Borrow := InterBorrow or Ord(Diff = $FFFFFFFF) and Borrow; Inc(Larger); Inc(Smaller); Inc(Result); Dec(LTail); end; LTail := LSize and CUnrollMask; LCount := LSize shr CUnrollShift; {$IFDEF CPUX64} Borrow64 := Borrow; {$ENDIF} // Subtract, with borrow, 0 from Largest and store result in Result. while LCount > 0 do begin {$IFDEF CPUX64} Diff64 := PUInt64(Larger)[0] - Borrow64; PUInt64(Result)[0] := Diff64; Borrow64 := Ord(Diff64 = UInt64(-1)) and Borrow64; Diff64 := PUInt64(Larger)[1] - Borrow64; PUInt64(Result)[1] := Diff64; Borrow64 := Ord(Diff64 = UInt64(-1)) and Borrow64; {$ELSE} Diff := Larger[0] - Borrow; Result[0] := Diff; Borrow := Ord(Diff = $FFFFFFFF) and Borrow; Diff := Larger[1] - Borrow; Result[1] := Diff; Borrow := Ord(Diff = $FFFFFFFF) and Borrow; Diff := Larger[2] - Borrow; Result[2] := Diff; Borrow := Ord(Diff = $FFFFFFFF) and Borrow; Diff := Larger[3] - Borrow; Result[3] := Diff; Borrow := Ord(Diff = $FFFFFFFF) and Borrow; {$ENDIF} Inc(Larger, CUnrollIncrement); Inc(Result, CUnrollIncrement); Dec(LCount); end; {$IFDEF CPUX64} Borrow := TLimb(Borrow64); {$ENDIF} while LTail > 0 do begin Diff := Larger[0] - Borrow; Result[0] := Diff; Borrow := Ord(Diff = $FFFFFFFF) and Borrow; Inc(Larger); Inc(Result); Dec(LTail); end; end; {$ENDIF} function BigInteger.IsZero: Boolean; begin Result := FData = nil; end; class operator BigInteger.LeftShift(const Value: BigInteger; Shift: Integer): BigInteger; var LimbShift: Integer; LSign: TLimb; begin if Value.FData = nil then Exit(Zero); LSign := SignBitOf(Value.FSize); LimbShift := Shift div CLimbBits; Shift := Shift mod CLimbBits; Result.MakeSize((Value.FSize and SizeMask) + LimbShift + 1); if Shift > 0 then InternalShiftLeft(PLimb(Value.FData), PLimb(Result.FData) + LimbShift, Shift, (Value.FSize and SizeMask)) else CopyLimbs(PLimb(Value.FData), PLimb(Result.FData) + LimbShift, (Value.FSize and SizeMask)); // Move(Value.FData[0], Result.FData[LimbShift], (Value.FSize and SizeMask) * CLimbSize); Result.FSize := (Result.FSize and SizeMask) or Integer(LSign); Result.Compact; // The following can probably be omitted. // if LimbShift > 0 then // FillChar(Result.FData[0], CLimbSize * LimbShift, 0); end; class operator BigInteger.LessThan(const Left, Right: BigInteger): Boolean; begin Result := Compare(Left, Right) < 0; end; class operator BigInteger.LessThanOrEqual(const Left, Right: BigInteger): Boolean; begin Result := Compare(left, Right) <= 0; end; function BigInteger.BitLength: Integer; begin if Self.FData = nil then Result := 0 else begin Result := CLimbBits * (Size - 1) + Velthuis.Numerics.BitLength(FData[Size - 1]); // IsPowerOfTwo is expensive, but probably less expensive than a copy and // subsequent decrement, like in BitCount. if (FSize < 0) and (Self.IsPowerOfTwo) then Dec(Result); end; end; function BigInteger.BitCount: Integer; var Mag: TMagnitude; I: Integer; begin if FData = nil then Exit(0); if FSize > 0 then Mag := FData else begin Mag := Copy(FData); InternalDecrement(PLimb(Mag), FSize and SizeMask); end; Result := 0; for I := 0 to Size - 1 do Result := Result + Velthuis.Numerics.BitCount(Mag[I]); end; // http://stackoverflow.com/a/7982137/95954 class function BigInteger.Ln(const Int: BigInteger): Double; var BLex: Integer; NewInt: BigInteger; begin if Int.IsNegative then Exit(Math.NaN) else if Int.IsZero then Exit(Math.NegInfinity); BLex := Int.BitLength - 1022; if BLex > 0 then NewInt := Int shr BLex else NewInt := Int; Result := System.Ln(NewInt.AsDouble); if BLex > 0 then Result := Result + BLex * System.Ln(2.0); end; class function BigInteger.Log(const Int: BigInteger; Base: Double): Double; begin Result := BigInteger.Ln(Int) / System.Ln(Base); end; class function BigInteger.Log10(const Int: BigInteger): Double; begin Result := Log(Int, 10.0); end; class function BigInteger.Log2(const Int: BigInteger): Double; begin Result := Log(Int, 2.0); end; class operator BigInteger.LogicalNot(const Int: BigInteger): BigInteger; begin Result := Int; Inc(Result); if Result.FSize <> 0 then Result.FSize := Result.FSize xor SignMask; end; class function BigInteger.Max(const Left, Right: BigInteger): BigInteger; begin if Left > Right then ShallowCopy(Left, Result) else ShallowCopy(Right, Result); end; class function BigInteger.Min(const Left, Right: BigInteger): BigInteger; begin if Left < Right then ShallowCopy(Left, Result) else ShallowCopy(Right, Result); end; // http://stackoverflow.com/questions/8496182/calculating-powa-b-mod-n class function BigInteger.ModPow(const ABase, AExponent, AModulus: BigInteger): BigInteger; var Base: BigInteger; Exp: BigInteger; begin Exp := AExponent; Base := ABase mod AModulus; Result := BigInteger.One; while Exp > Zero do begin if not Exp.IsEven then Result := (Result * Base) mod AModulus; Base := (Base * Base) mod AModulus; Exp := Exp shr 1; end; end; class operator BigInteger.Modulus(const Left, Right: BigInteger): BigInteger; begin Result := Remainder(Left, Right); end; class operator BigInteger.Modulus(const Left: BigInteger; Right: UInt32): BigInteger; begin Result := Remainder(Left, Right); end; class operator BigInteger.Modulus(const Left: BigInteger; Right: UInt16): BigInteger; begin Result := Remainder(Left, Right); end; class procedure BigInteger.InternalMultiplyAndAdd(const Multiplicand: TMagnitude; Multiplicator, Addend: Word; const Res: TMagnitude); {$IF DEFINED(PUREPASCAL)} type WordRec = packed record Lo, Hi: Word; end; var I: Cardinal; LProduct: Cardinal; LHighWord: Word; LLength: Cardinal; begin LLength := Cardinal(Length(Multiplicand)) * 2; LHighWord := 0; I := 0; while I < LLength-1 do begin LProduct := PWord(Multiplicand)[I] * Multiplicator + LHighWord; PWord(Res)[I] := WordRec(LProduct).Lo; LHighWord := WordRec(LProduct).Hi; Inc(I); end; PWord(Res)[I] := LHighWord; I := 0; LHighword := 0; while LLength > 0 do begin Res[I] := Res[I] + Addend + LHighword; LHighWord := Word(Res[I] < Addend + LHighword); Addend := 0; Dec(LLength); Inc(I); end; end; {$ELSEIF DEFINED(WIN32)} var LLength: Integer; LExtra: Word; LMultiplicator: Word; LProduct: Cardinal; asm PUSH EBX PUSH ESI PUSH EDI MOV LExtra,CX MOV LMultiplicator,DX MOV ESI,EAX MOV EDI,Res TEST EAX,EAX JZ @NotNil MOV EAX,[EAX - TYPE NativeInt] @NotNil: MOV LLength,EAX XOR ECX,ECX // ECX used for overflow. XOR EBX,EBX // EBX = I CMP EBX,LLength JNB @SkipMult @MultLoop: MOV EAX,[ESI + CLimbSize*EBX] // EAX,EDX required for multiplication. MOVZX EDX,LMultiplicator MUL EDX ADD EAX,ECX // Add in overflow of previous multiplication. ADC EDX,0 MOV [EDI + CLimbSize*EBX],EAX MOV ECX,EDX // Overflow. LEA EBX,[EBX + 1] CMP EBX,LLength JB @MultLoop @SkipMult: MOV [EDI + CLimbSize*EBX],EDX MOV ECX,LLength XOR EBX,EBX MOVZX EAX,LExtra @AddLoop: ADC [EDI + CLimbSize*EBX],EAX JNC @Exit MOV EAX,0 LEA EBX,[EBX + 1] LEA ECX,[ECX - 1] JECXZ @Exit JMP @AddLoop @Exit: POP EDI POP ESI POP EBX end; {$ELSE WIN64} asm .PUSHNV RBX PUSH R8 // PUSH Extra MOVZX R8D,DX // R8W = Multiplicator MOV R10,RCX TEST R10,R10 JZ @@1 MOV R10,[R10-8] // R10D = Length(Multiplicand) @@1: XOR R11D,R11D // R11D = I XOR EBX,EBX CMP R11D,R10D JNB @@3 @@2: MOV EAX,[RCX + CLimbSize*R11] MUL EAX,R8D ADD EAX,EBX ADC EDX,0 MOV [R9 + CLimbSize*R11],EAX MOV EBX,EDX INC R11D CMP R11D,R10D JB @@2 @@3: MOV [R9 + CLimbSize*R11],EDX POP RDX // POP Extra MOVZX EDX,DX XOR EBX,EBX @@4: ADC [R9 + CLimbSize*RBX],EDX MOV EDX,0 // INC EBX // These 3 instructions should not modify the carry flag! DEC R10D // JNE @@4 end; {$IFEND} class operator BigInteger.Multiply(const Left: BigInteger; Right: Word): BigInteger; begin if (Right = 0) or ((Left.FSize and SizeMask) = 0) then Exit(Zero); Result.MakeSize((Left.FSize and SizeMask) + 2); InternalMultiplyAndAdd(Left.FData, Right, 0, Result.FData); Result.FSize := (Left.FSize and SignMask) or (Result.FSize and SizeMask); Result.Compact; end; class operator BigInteger.Multiply(Left: Word; const Right: BigInteger): BigInteger; begin Result := Right * Left; end; class function BigInteger.MultiplyKaratsuba(const Left, Right: BigInteger): BigInteger; var k, LSign: Integer; z0, z1, z2: BigInteger; x, y: TArray<BigInteger>; begin if ((Left.FSize and SizeMask) < KaratsubaThreshold) or ((Right.FSize and SizeMask) < KaratsubaThreshold) then Exit(MultiplyBaseCase(Left, Right)); ////////////////////////////////////////////////////////////////////////////////////////////////// /// This is a so called divide and conquer algorithm, solving a big task by dividing it up /// /// into easier (and hopefully faster, in total) smaller tasks. /// /// /// /// Let's treat a BigInteger as a polynomial, i.e. x = x1 * B + x0, where B is chosen thus, /// /// that the top and the low part of the BigInteger are almost the same in size. /// /// The result R of the multiplication of two such polynomials can be seen as: /// /// /// /// R = (x1 * B + x0) * (y1 * B + y0) = x1 * y1 * B^2 + (x1 * y0 + x0 * y1) * B + x0 * y0 /// /// /// /// say, z0 = x0 * y0 /// /// z1 = x1 * y0 + x0 * y1 /// /// z2 = x1 * y1 /// /// /// /// then /// /// R = z2 * B^2 + z1 * B + z0 /// /// /// /// Karatsuba noted that: /// /// /// /// (x1 + x0) * (y1 + y0) = z2 + z1 + z0, so z1 = (x1 + x0) * (y1 + y0) - (z2 + z0) /// /// /// /// That reduced four multiplications and a few additions to three multiplications, a few /// /// additions and a subtraction. Surely the parts will be multilimb, but this is called /// /// recursively down until the sizes are under a threshold, and then simple base case /// /// (a.k.a. "schoolbook") multiplication is performed. /// ////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// /// Note: it may look tempting to use pointers into the original operands, to use one large /// /// buffer for all results, and to use InternalMultiply directly, but remember that /// /// InternalMultiply performs a basecase multiplication and it does NOT resurse into a /// /// deeper level of MultiplyKaratsuba, so after one level, the advantage gained by reducing /// /// the number of multiplications would be minimal. /// /// /// /// There is an overhead caused by using complete BigIntegers, but it is not as high as it /// /// may look. /// ////////////////////////////////////////////////////////////////////////////////////////////////// LSign := (Left.FSize xor Right.FSize) and SignMask; k := (IntMax(Left.FSize and SizeMask, Right.FSize and SizeMask) + 1) shr 1; x := Left.Split(k, 2); y := Right.Split(k, 2); // Recursion further reduces the number of multiplications! z2 := MultiplyKaratsuba(x[1], y[1]); z0 := MultiplyKaratsuba(x[0], y[0]); z1 := MultiplyKaratsuba(x[1] - x[0], y[0] - y[1]) + (z2 + z0); Result := z0; Result.AddWithOffset(z2, k * 2); Result.AddWithOffset(z1, k); Result.FSize := (Result.FSize and SizeMask) or LSign; end; // Used by Karatsuba, Toom-Cook and Burnikel-Ziegler algorithms. // Splits Self into BlockCount pieces of (at most) BlockSize limbs, starting with the least significant part. function BigInteger.Split(BlockSize, BlockCount: Integer): TArray<BigInteger>; var I: Integer; begin SetLength(Result, BlockCount); for I := 0 to BlockCount - 1 do begin if (Self.FSize and BigInteger.SizeMask) > I * BlockSize then begin Result[I].MakeSize(IntMin(BlockSize, (Self.FSize and SizeMask) - I * BlockSize)); CopyLimbs(PLimb(Self.FData) + I * BlockSize, PLimb(Result[I].FData), IntMin(BlockSize, (Self.FSize and SizeMask) - I * BlockSize)); Result[I].Compact; end else ShallowCopy(Zero, Result[I]); end; end; {$IFNDEF PUREPASCAL} class procedure BigInteger.InternalDivideBy3(Value, Result: PLimb; ASize: Integer); const MultConst = $AAAAAAAB; MultConst2 = $55555556; {$IFDEF WIN32} asm PUSH ESI PUSH EDI PUSH EBX MOV ESI,EAX MOV EDI,EDX XOR EBX,EBX @Loop: MOV EAX,[ESI] SUB EAX,EBX SETC BL MOV EDX,MultConst MUL EAX,EDX MOV [EDI],EAX CMP EAX,MultConst2 JB @SkipInc INC EBX CMP EAX,MultConst JB @SkipInc INC EBX @SkipInc: LEA ESI,[ESI + CLimbSize] LEA EDI,[EDI + CLimbSize] DEC ECX JNE @Loop @Exit: POP EBX POP EDI POP ESI end; {$ELSE WIN64} asm XOR R9D,R9D MOV R10,RDX @Loop: MOV EAX,[RCX] SUB EAX,R9D SETC R9B MOV EDX,MultConst MUL EAX,EDX MOV [R10],EAX CMP EAX,MultConst2 JB @SkipInc INC R9D CMP EAX,MultConst JB @SkipInc INC R9D @SkipInc: LEA RCX,[RCX + CLimbSize] LEA R10,[R10 + CLimbSize] DEC R8D JNE @Loop end; {$ENDIF WIN64} {$ENDIF !PUREPASCAL} // Only works if it is known that there is no remainder and A is positive. class function BigInteger.DivideBy3Exactly(const A: BigInteger): BigInteger; const ModInverse3 = $AAAAAAAB; // Modular inverse of 3 modulo $100000000. ModInverse3t2 = $55555556; // 2 * ModInverse3 {$IFDEF PUREPASCAL} var i: Integer; ai, w, qi, borrow: Int64; begin if A.FData = nil then begin ShallowCopy(Zero, Result); Exit; end; Result.MakeSize(A.FSize and SizeMask); borrow := 0; for i := 0 to (A.FSize and SizeMask) - 1 do begin ai := A.FData[i]; w := ai - borrow; if borrow > ai then borrow := 1 else borrow := 0; qi := (w * ModInverse3) and $FFFFFFFF; Result.FData[i] := UInt32(qi); if qi >= ModInverse3t2 then begin Inc(borrow); if qi >= ModInverse3 then Inc(borrow); end; end; Result.Compact; end; {$ELSE !PUREPASCAL} begin if A.FData = nil then begin ShallowCopy(Zero, Result); Exit; end; Result.MakeSize(A.FSize and SizeMask); InternalDivideBy3(PLimb(A.FData), PLimb(Result.FData), A.FSize and SizeMask); Result.Compact; end; {$ENDIF !PUREPASCAL} class function BigInteger.MultiplyToomCook3(const Left, Right: BigInteger): BigInteger; var k: Integer; a, b: TArray<BigInteger>; a02, b02: BigInteger; v0, v1, vm1, v2, vinf: BigInteger; t1, t2: BigInteger; Sign: Integer; begin // Step 1: if n < threshold then return KaratsubaMultiply(A, B) if ((Left.FSize and SizeMask) < ToomCook3Threshold) and ((Right.FSize and SizeMask) < ToomCook3Threshold) then Exit(MultiplyKaratsuba(Left, Right)); Sign := (Left.FSize xor Right.FSize) and SignMask; // Richard P. Brent and Paul Zimmermann, // "Modern Computer Arithmetic", version 0.5.1 of April 28, 2010 // http://arxiv.org/pdf/1004.4710v1.pdf ////////////////////////////////////////////////////////////////////////////// // Hint to myself: If necessary, take a look at Bodrato's improved version. // // But be aware that most of his *code* is GPL-ed and now part of GMP. // ////////////////////////////////////////////////////////////////////////////// // Step 2: write A = a0 +a1*x + a2*x^2, B = b0 + b1*x + b2*x^2, with x = ß^k. k := (IntMax(Left.FSize and SizeMask, Right.FSize and SizeMask) + 2) div 3; a := Left.Split(k, 3); b := Right.Split(k, 3); // Evaluation at x = -1, 0, 1, 2 and +inf. // Step 3: v0 <- ToomCook3(a0, b0) v0 := MultiplyToomCook3(a[0], b[0]); // Step 4a: a02 <- a0 + a2, b02 <- b0 + b2 a02 := a[0] + a[2]; b02 := b[0] + b[2]; // Step 5: v(-1) <- ToomCook3(a02 - a1, b02 - b1) = ToomCook3(a0 + a2 - a1, b0 + b2 - b1) vm1 := MultiplyToomCook3(a02 - a[1], b02 - b[1]); // Intermediate step: a'02 = a02 + a1, b'02 = b02 + b1 a02 := a02 + a[1]; b02 := b02 + b[1]; // Step 4b: v1 <- ToomCook3(a02 + a1, b02 + b1) = ToomCook3(a'02, b'02) v1 := MultiplyToomCook3(a02, b02); // Step 6: v2 <- ToomCook3(a0 + 2*a1 + 4*a2, b0 + 2*b1 + 4*b2) // Note: first operand is a0 + a1 + a1 + a2 + a2 + a2 + a2 = 2*(a0 + a1 + a2 + a2) - a0 = 2*(a'02 + a2) - a0 v2 := MultiplyToomCook3((a02 + a[2]) shl 1 - a[0], (b02 + b[2]) shl 1 - b[0]); // Step 7: v(inf) <- ToomCook3(a2, b2) vinf := MultiplyToomCook3(a[2], b[2]); // Step 8: t1 <- (3*v0 + 2*v(−1) + v2)/6 − 2 * v(inf), t2 <- (v1 + v(−1))/2 t1 := DivideBy3Exactly(((v0 + vm1) shl 1 + v2 + v0) shr 1) - (vinf shl 1); t2 := (v1 + vm1) shr 1; // Step 9: c0 <- v0, c1 <- v1 - t1, c2 <- t2 - v0 - vinf, c3 <- t1 - t2, c4 <- vinf ShallowCopy(v0, Result); Result.AddWithOffset(vinf, 4*k); Result.AddWithOffset(t1 - t2, 3*k); Result.AddWithOffset(t2 - v0 - vinf, 2*k); Result.AddWithOffset(v1 - t1, k); Result.FSize := (Result.FSize and SizeMask) or Sign; end; {$IFDEF Experimental} class function BigInteger.MultiplyToomCook3Threshold(const Left, Right: BigInteger; Threshold: Integer): BigInteger; var k: Integer; a, b: TArray<BigInteger>; a02, b02: BigInteger; v0, v1, vm1, v2, vinf: BigInteger; t1, t2: BigInteger; c0, c1, c2, c3, c4: BigInteger; Sign: Integer; begin Sign := (Left.FSize xor Right.FSize) and SignMask; // Richard P. Brent and Paul Zimmermann, // "Modern Computer Arithmetic", version 0.5.1 of April 28, 2010 // http://arxiv.org/pdf/1004.4710v1.pdf // Hint to myself: If necessary, take a look at Bodrato's improved version. // But be aware that most of his *code* is GPL-ed and now part of GMP. // Step 1: if n < threshold then return KaratsubaMultiply(A, B) if ((Left.FSize and SizeMask) < Threshold) or ((Right.FSize and SizeMask) < Threshold) then Exit(MultiplyKaratsuba(Left, Right)); // Step 2: write A = a0 +a1*x + a2*x^2, B = b0 + b1*x + b2*x^2, with x = ß^k. k := (IntMax(Left.FSize and SizeMask, Right.FSize and SizeMask) + 2) div 3; a := Left.Split(k, 3); b := Right.Split(k, 3); // Step 3: v0 <- ToomCook3(a0, b0) v0 := MultiplyToomCook3Threshold(a[0], b[0], Threshold); // Step 4a: a02 <- a0 + a2, b02 <- b0 + b2 a02 := a[0] + a[2]; b02 := b[0] + b[2]; // Step 4b: v1 <- ToomCook3(a02 + a1, b02 + b1) v1 := MultiplyToomCook3Threshold(a02 + a[1], b02 + b[1], Threshold); // Step 5: v(-1) <- ToomCook3(a02 - a1, b02 - b1) vm1 := MultiplyToomCook3Threshold(a02 - a[1], b02 - b[1], Threshold); // Step 6: v2 <- ToomCook3(a0 + 2*a1 + 4*a2, b0 + 2*b1 + 4*b2) v2 := MultiplyToomCook3Threshold(a[0] + a[1] shl 1 + a[2] shl 2, b[0] + b[1] shl 1 + b[2] shl 2, Threshold); // Step 7: v(inf) <- ToomCook3(a2, b2) vinf := MultiplyToomCook3Threshold(a[2], b[2], Threshold); // Step 8: t1 <- (3*v0 + 2*v(-1) + v2) / 6 - 2*v(inf), t2 <- (v1 + v(-1)) / 2 t1 := ((v0 shl 1 + v0 + vm1 shl 1 + v2) shr 1) div BigInteger(3) - vinf shl 1; // $$RV make exactdiv3 or divbyword with constant t2 := (v1 + vm1) shr 1; // Step 9: c0 := v0; c1 := v1 - t1; c2 := t2 - v0 - vinf; c3 := t1 - t2; c4 := vinf; // Output: AB = c0 + c1*ß^k + c2*ß^2*k + c3*ß^3*k + c4*ß^4*k Result := c0; if c4.FData <> nil then Result.AddWithOffset(c4, 4 * k); if c1.FData <> nil then Result.AddWithOffset(c1, k); if c2.FData <> nil then Result.AddWithOffset(c2, 2 * k); if c3.FData <> nil then Result.AddWithOffset(c3, 3 * k); Result.FSize := (Result.FSize and SizeMask) or Sign; end; class function BigInteger.MultiplyKaratsubaThreshold(const Left, Right: BigInteger; Threshold: Integer): BigInteger; var NDiv2Shift, NDiv2: Integer; LeftUpper, RightUpper: BigInteger; LeftLower, RightLower: BigInteger; Upper, Middle, Lower: BigInteger; LSize, LSign: Integer; begin if (Left.Size < Threshold) or (Right.Size < Threshold) then Exit(MultiplyBaseCase(Left, Right)); LSign := (Left.FSize xor Right.FSize) and SignMask; LSize := IntMax((Left.FSize and SizeMask), (Right.FSize and SizeMask)); NDiv2Shift := (LSize and $FFFFFFFE) shl 4; // := LSize div 2 * SizeOf(TLimb); NDiv2 := LSize div 2; // Split Left if (Left.FSize and SizeMask) > NDiv2 then begin LeftLower.MakeSize(NDiv2); CopyLimbs(PLimb(Left.FData), PLimb(LeftLower.FData), NDiv2); LeftUpper.MakeSize((Left.FSize and SizeMask) - NDiv2); CopyLimbs(PLimb(Left.FData) + NDiv2, PLimb(LeftUpper.FData), (Left.FSize and SizeMask) - NDiv2); LeftLower.Compact; end else begin ShallowCopy(Zero, LeftUpper); ShallowCopy(Left, LeftLower); end; // Split Right if (Right.FSize and SizeMask) > NDiv2 then begin RightLower.MakeSize(NDiv2); CopyLimbs(PLimb(Right.FData), PLimb(RightLower.FData), NDiv2); RightUpper.MakeSize((Right.FSize and SizeMask) - NDiv2); CopyLimbs(PLimb(Right.FData) + NDiv2, PLimb(RightUpper.FData), (Right.FSize and SizeMask) - NDiv2); RightLower.Compact; end else begin ShallowCopy(Zero, RightUpper); ShallowCopy(Right, RightLower) end; Upper := MultiplyKaratsubaThreshold(LeftUpper, RightUpper, Threshold); Lower := MultiplyKaratsubaThreshold(LeftLower, RightLower, Threshold); Middle := MultiplyKaratsubaThreshold(LeftUpper - LeftLower, RightLower - RightUpper, Threshold) + (Lower + Upper); // Can't just move these values into place, because they still overlap when shifted. Result := Upper shl (NDiv2Shift + NDiv2Shift) + Middle shl NDiv2Shift + Lower; Result.FSize := (Result.FSize and SizeMask) or LSign; end; {$ENDIF Experimental} class function BigInteger.SqrKaratsuba(const Value: BigInteger): BigInteger; var NDiv2Shift, NDiv2: Integer; ValueUpper: BigInteger; ValueLower: BigInteger; Upper, Middle, Lower: BigInteger; LSize: Integer; begin LSize := (Value.FSize and SizeMask); NDiv2Shift := (LSize and $FFFFFFFE) shl 4; // := LSize div 2 * SizeOf(TLimb); NDiv2 := LSize div 2; ValueLower.MakeSize(NDiv2); CopyLimbs(PLimb(Value.FData), PLimb(ValueLower.FData), NDiv2); ValueUpper.MakeSize((Value.FSize and SizeMask) - NDiv2); CopyLimbs(PLimb(Value.FData) + NDiv2, PLimb(ValueUpper.FData), (Value.FSize and SizeMask) - NDiv2); ValueLower.Compact; Upper := Sqr(ValueUpper); Lower := Sqr(ValueLower); Middle := (ValueUpper * ValueLower) shl 1; // Can't simply move these values into place, because they still overlap when shifted. Result := Upper shl (NDiv2Shift + NDiv2Shift) + Middle shl NDiv2Shift + Lower; Result.FSize := Result.FSize and SizeMask; end; class function BigInteger.SqrKaratsubaThreshold(const Value: BigInteger; Threshold: Integer): BigInteger; var k: Integer; // x0, x1: BigInteger; x: TArray<BigInteger>; z2, z1, z0: BigInteger; LSize: Integer; begin LSize := (Value.FSize and SizeMask); if LSize < Threshold then begin Exit(MultiplyKaratsuba(Value, Value)); end; k := LSize div 2; x := Value.Split(k, 2); z2 := SqrKaratsubaThreshold(x[1], Threshold); z0 := SqrKaratsubaThreshold(x[0], Threshold); z1 := (x[1] * x[0]) shl 1; Result := z0; if z2.FData <> nil then Result.AddWithOffset(z2, 2*k); if z1.FData <> nil then Result.AddWithOffset(z1, k); Result.FSize := Result.FSize and SizeMask; end; class function BigInteger.Multiply(const Left, Right: BigInteger): BigInteger; var LResult: BigInteger; // Avoid prematurely overwriting result when it is same as one of the operands. begin if (Left.FData = nil) or (Right.FData = nil) then begin ShallowCopy(BigInteger.Zero, Result); Exit; end; if ((Left.FSize and SizeMask) < KaratsubaThreshold) or ((Right.FSize and SizeMask) < KaratsubaThreshold) then begin // The following block is "Result := MultiplyBaseCase(Left, Right);" written out in full. LResult.MakeSize((Left.FSize and SizeMask) + (Right.FSize and SizeMask) + 1); InternalMultiply(PLimb(Left.FData), PLimb(Right.FData), PLimb(LResult.FData), (Left.FSize and SizeMask), (Right.FSize and SizeMask)); LResult.Compact; LResult.FSize := (LResult.FSize and SizeMask) or ((Left.FSize xor Right.FSize) and SignMask); ShallowCopy(LResult, Result); end else begin if ((Left.FSize and SizeMask) < ToomCook3Threshold) and ((Right.FSize and SizeMask) < ToomCook3Threshold) then Result := MultiplyKaratsuba(Left, Right) else Result := MultiplyToomCook3(Left, Right); end; end; class function BigInteger.MultiplyThreshold(const Left, Right: BigInteger; Threshold: Integer): BigInteger; var LResult: BigInteger; // Avoid prematurely overwriting result when it is same as one of the operands. begin if (Left.FData = nil) or (Right.FData = nil) then begin ShallowCopy(BigInteger.Zero, Result); Exit; end; if ((Left.FSize and SizeMask) < Threshold) or ((Right.FSize and SizeMask) < Threshold) then begin LResult.MakeSize((Left.FSize and SizeMask) + (Right.FSize and SizeMask) + 1); InternalMultiply(PLimb(Left.FData), PLimb(Right.FData), PLimb(LResult.FData), (Left.FSize and SizeMask), (Right.FSize and SizeMask)); LResult.Compact; LResult.SetSign(SignBitOf(Left.FSize) xor SignBitOf(Right.FSize)); ShallowCopy(LResult, Result); end else Result := MultiplyKaratsubaThreshold(Left, Right, Threshold); end; class function BigInteger.MultiplyBaseCase(const Left, Right: BigInteger): BigInteger; var LResult: BigInteger; // Avoid prematurely overwriting result when it is same as one of the operands. begin if (Left.FData = nil) or (Right.FData = nil) then begin ShallowCopy(Zero, Result); Exit; end; LResult.MakeSize((Left.FSize and SizeMask) + (Right.FSize and SizeMask) + 1); InternalMultiply(PLimb(Left.FData), PLimb(Right.FData), PLimb(LResult.FData), (Left.FSize and SizeMask), (Right.FSize and SizeMask)); LResult.Compact; LResult.SetSign(SignBitOf(Left.FSize) xor SignBitOf(Right.FSize)); ShallowCopy(LResult, Result); end; class operator BigInteger.Multiply(const Left, Right: BigInteger): BigInteger; begin Result := Multiply(Left, Right); end; class procedure BigInteger.SetBase(const Value: TNumberBase); begin FBase := Value; end; procedure BigInteger.SetSign(Value: Integer); begin FSize := (FSize and SizeMask) or (Ord(Value < 0) * SignMask); end; function BigInteger.Subtract(const Other: BigInteger): PBigInteger; var MinusOther: BigInteger; begin ShallowCopy(Other, MinusOther); MinusOther.FSize := MinusOther.FSize xor SignMask; Result := Add(MinusOther); end; class function BigInteger.Subtract(const Left, Right: BigInteger): BigInteger; const BoolMasks: array[Boolean] of Integer = (SignMask, 0); var Largest, Smallest: PBigInteger; Res: BigInteger; Comparison: TValueSign; begin if Left.FData = nil then begin ShallowCopy(Right, Result); if Result.FSize <> 0 then Result.FSize := Result.FSize xor SignMask; Exit; end; if Right.FData = nil then begin ShallowCopy(Left, Result); Exit; end; Comparison := InternalCompare(PLimb(Left.FData), PLimb(Right.FData), (Left.FSize and SizeMask), (Right.FSize and SizeMask)); if (Comparison = 0) and (Left.Sign = Right.Sign) then begin ShallowCopy(Zero, Result); Exit; end; if Comparison > 0 then begin Largest := @Left; Smallest := @Right; end else begin Largest := @Right; Smallest := @Left; end; Res.MakeSize((Largest^.FSize and SizeMask) + 1); if Largest^.Sign = Smallest^.Sign then FInternalSubtract(PLimb(Largest^.FData), PLimb(Smallest^.FData), PLimb(Res.FData), (Largest^.FSize and SizeMask), (Smallest^.FSize and SizeMask)) else FInternalAdd(PLimb(Largest^.FData), PLimb(Smallest^.FData), PLimb(Res.FData), (Largest^.FSize and SizeMask), (Smallest^.FSize and SizeMask)); Res.FSize := (Res.FSize and SizeMask) or BoolMasks[(Largest^.FSize < 0) xor (Largest = @Left)]; Res.Compact; Result := Res; end; class operator BigInteger.Subtract(const Left, Right: BigInteger): BigInteger; begin Result := Subtract(Left, Right); end; procedure BigInteger.EnsureSize(RequiredSize: Integer); begin RequiredSize := RequiredSize and SizeMask; if RequiredSize > Length(FData) then SetLength(FData, (RequiredSize + 4) and CapacityMask); FSize := (FSize and SignMask) or RequiredSize; end; procedure BigInteger.MakeSize(RequiredSize: Integer); begin SetLength(FData, (RequiredSize + 4) and CapacityMask); FillChar(FData[0], Length(FData) * CLimbSize, 0); FSize := (FSize and SignMask) or RequiredSize; end; // In Win32, we keep what we have. In Win64, we switch, depending on Size. At 25 limbs or above, the unrolled loop version is faster. class procedure BigInteger.InternalNegate(Source, Dest: PLimb; Size: Integer); {$IFDEF PUREPASCAL} var R: TLimb; begin R := 0; while R = 0 do begin R := (not Source^) + 1; Dest^ := R; Inc(Source); Inc(Dest); Dec(Size); if Size = 0 then Exit; end; while Size > 0 do begin Dest^ := not Source^; Inc(Source); Inc(Dest); Dec(Size); end; end; {$ELSE} {$IFDEF WIN32} // This is faster than an unrolled loop with NOT and ADC, especially for smaller BigIntegers. asm PUSH ESI @Loop: MOV ESI,[EAX] NOT ESI INC ESI MOV [EDX],ESI LEA EAX,[EAX + CLimbSize] LEA EDX,[EDX + CLimbSize] DEC ECX JE @Exit TEST ESI,ESI // Only if ESI is 0, a carry occurred. JE @Loop @RestLoop: // No more carry. We can stop incrementing. MOV ESI,[EAX] NOT ESI MOV [EDX],ESI LEA EAX,[EAX + CLimbSize] LEA EDX,[EDX + CLimbSize] DEC ECX JNE @RestLoop @Exit: POP ESI end; {$ELSE WIN64} asm CMP R8D,25 JA @Unrolled // Plain version. Faster for small BigIntegers (<= 25 limbs). @Loop: MOV EAX,[RCX] NOT EAX INC EAX MOV [RDX],EAX LEA RCX,[RCX + CLimbSize] LEA RDX,[RDX + CLimbSize] DEC R8D JE @Exit TEST EAX,EAX JE @Loop @RestLoop: MOV EAX,[RCX] NOT EAX MOV [RDX],EAX LEA RCX,[RCX + CLimbSize] LEA RDX,[RDX + CLimbSize] DEC R8D JNE @RestLoop JMP @Exit // Unrolled version. Faster for larger BigIntegers. @Unrolled: TEST RCX,RCX JE @Exit XCHG R8,RCX MOV R9,RDX XOR EDX,EDX MOV R10D,ECX AND R10D,CUnrollMask SHR ECX,CUnrollShift STC JE @Rest @LoopU: MOV RAX,[R8] NOT RAX ADC RAX,RDX MOV [R9],RAX MOV RAX,[R8 + DLimbSize] NOT RAX ADC RAX,RDX MOV [R9 + DLimbSize],RAX LEA R8,[R8 + 2*DLimbSize] LEA R9,[R9 + 2*DLimbSize] LEA ECX,[ECX - 1] JECXZ @Rest JMP @LoopU @Rest: LEA RAX,[@JumpTable] JMP [RAX + R10*TYPE Pointer] // Align jump table with NOPs NOP @JumpTable: DQ @Exit DQ @Rest1 DQ @Rest2 DQ @Rest3 @Rest3: MOV RAX,[R8] NOT RAX ADC RAX,RDX MOV [R9],RAX MOV EAX,[R8 + DLimbSize] NOT EAX ADC EAX,EDX MOV [R9 + DLimbSize],EAX JMP @Exit @Rest2: MOV RAX,[R8] NOT RAX ADC RAX,RDX MOV [R9],RAX JMP @Exit @Rest1: MOV EAX,[R8] NOT EAX ADC EAX,EDX MOV [R9],EAX @Exit: end; {$ENDIF WIN64} {$ENDIF !PUREPASCAL} // Needed for Karatsuba, ToomCook and Burnikel-Ziegler // Assumes non-negative parameters and non-negative self. procedure BigInteger.AddWithOffset(const Addend: BigInteger; Offset: Integer); begin Self.EnsureSize(IntMax(Offset + (Addend.FSize and SizeMask), Self.FSize and SizeMask)); if Offset >= (Self.FSize and SizeMask) then CopyLimbs(PLimb(Addend.FData), PLimb(Self.FData) + Offset, Addend.FSize and SizeMask) else FInternalAdd(PLimb(Self.FData) + Offset, PLimb(Addend.FData), PLimb(Self.FData) + Offset, (Self.FSize and SizeMask) - Offset, Addend.FSize and SizeMask); Self.Compact; end; class procedure BigInteger.InternalBitwise(const Left, Right: BigInteger; var Result: BigInteger; PlainOp, OppositeOp, InversionOp: TDyadicOperator); //---------------------------------------------------------------------------------------------------------------// // // // The code for the bitwise operators AND, OR and XOR does not differ much. // // Since the results should be the results for two's complement, two's complement semantics are emulated. // // Originally, this meant that the magnitudes of negative bigintegers were negated, then the // // operation was performed and if the result had to be negative, the magnitude of the result was negated. // // These negation steps were slow, so now this code uses some logical shortcuts. // // // // The rules used are like follows. // // // // In the following, A and B represent positive integer values, so -A and -B represent negative values. // // Note that, to keep this simple, 0 -- i.e. FData = nil -- is not handled at all. That is handled // // by the caller and then this routine is not called. // // // // Relation between negation and inversion of an integer/magnitude: // // -A = not A + 1 => not A = -A - 1 // // -A = not (A - 1) // // // // Note: A and B are magnitudes here. Negating a BigInteger is as simple as flipping the sign bit. That // // does not work for magnitudes. // // // // Boolean (and bitwise) rules followed: // // not not A = A // // not (A and B) = not A or not B // // not (A or B) = not A and not B // // not (A xor B) = not A xor B = A xor not B // // not A xor not B = A xor B // // // // Expressions used here: // // // // A and B = A and B ; both positive, plain operation // // A and -B = A and not (B - 1) ; one positive, one negative, result positive // // -(-A and -B) = -(not (A - 1) and not (B - 1)) ; both negative, result is negative too // // = - not ((A - 1) or (B - 1))) // // = (A - 1) or (B - 1) + 1 // // // // A or B = A or B ; both positive // // -(A or -B) = -(A or not (B - 1)) ; one positive, one negative, result is negative too // // = - not (not A and (B - 1)) // // = ((B - 1) and not A) + 1 // // -(-A or -B) = -(not (A - 1) or not (B - 1)) ; both negative, result is negative too // // = not (not (A - 1) or not (B - 1) + 1 // // = (A - 1) and (B - 1) + 1 // // // // A xor B = A xor B ; both positive // // -(A xor -B) = -(A xor not (B - 1)) ; one positive, one negative, result is negative too // // = not (A xor not (B - 1)) + 1 // // = A xor (B - 1) + 1 // // -A xor -B = not (A - 1) xor not (B - 1) ; both negative, result is positive // // = (A - 1) xor (B - 1) // // // // So the only "primitives" required are routines for AND, OR, XOR and AND NOT. The latter is not really // // a primitive, but it is so easy to implement, that it can be considered one. NOT is cheap, does not require // // complicated carry handling. // // Routines like Inc and Dec are cheap too: you only loop as long as there is a carry (or borrow). Often, that // // is only over very few limbs. // // // // Primitives (InternalAnd(), etc.) routines were optimized too. Loops were unrolled, 64 bit registers used // // where possible, both sizes are passed, so the operations can be done on the original data. The latter // // reduces the need for copying into internal buffers. // // // // These optimizations made bitwise operators 2-3 times as fast as with the simple implementations before. // // // //---------------------------------------------------------------------------------------------------------------// var LSize, RSize, MinSize, MaxSize: Integer; LPtr, RPtr: PLimb; begin LSize := Left.FSize and SizeMask; RSize := Right.FSize and SizeMask; MinSize := IntMin(LSize, RSize); MaxSize := IntMax(LSize, RSize); if ((Left.FSize xor Right.FSize) and SignMask) = 0 then begin if (Left.FSize > 0) then begin if @PlainOp = @InternalAnd then Result.MakeSize(MinSize) else Result.MakeSize(MaxSize); PlainOp(PLimb(Left.FData), PLimb(Right.FData), PLimb(Result.FData), LSize, RSize); end else begin LPtr := AllocLimbs(LSize + RSize); // LPtr := Copy(Left); RPtr := LPtr + LSize; // RPtr := Coyp(Right); CopyLimbs(PLimb(Left.FData), LPtr, LSize); CopyLimbs(PLimb(Right.FData), RPtr, RSize); InternalDecrement(LPtr, LSize); // LPtr^ := LPtr^ - 1 InternalDecrement(RPtr, RSize); // RPtr^ := RPtr^ - 1 Result.FSize := 0; Result.MakeSize(MaxSize); OppositeOp(LPtr, RPtr, PLimb(Result.FData), LSize, RSize); // Opposite op: AND --> OR, OR --> AND, XOR --> XOR if @PlainOp = @InternalXor then Result.FSize := Result.FSize and SizeMask // Make positive. else begin InternalIncrement(PLimb(Result.FData), MaxSize); // Result := Result + 1 Result.FSize := Result.FSize or SignMask; // Make negative. end; FreeMem(LPtr); end; end else begin if (Left.FSize > 0) then begin RPtr := AllocLimbs(RSize); CopyLimbs(PLimb(Right.FData), RPtr, RSize); InternalDecrement(RPtr, RSize); Result.FSize := 0; if @PlainOp = @InternalOr then Result.MakeSize(RSize) else Result.MakeSize(MaxSize); InversionOp(PLimb(Left.FData), RPtr, PLimb(Result.FData), LSize, RSize); // Inversion op: AND --> AND NOT, OR --> NOT AND, XOR --> XOR if @PlainOp = @InternalAnd then Result.FSize := Result.FSize and SizeMask // Make positive. else begin InternalIncrement(PLimb(Result.FData), (Result.FSize and SizeMask)); Result.FSize := Result.FSize or SignMask; // Make negative. end; FreeMem(RPtr); end else begin LPtr := AllocLimbs(LSize); CopyLimbs(PLimb(Left.FData), LPtr, LSize); InternalDecrement(LPtr, LSize); Result.FSize := 0; if @PlainOp = @InternalOr then Result.MakeSize(LSize) else Result.MakeSize(MaxSize); InversionOp(PLimb(Right.FData), LPtr, PLimb(Result.FData), RSize, LSize); if @PlainOp = @InternalAnd then Result.FSize := Result.FSize and SizeMask else begin InternalIncrement(PLimb(Result.FData), (Result.FSize and SizeMask)); Result.FSize := Result.FSize or SignMask; end; FreeMem(LPtr); end; end; Result.Compact; end; class operator BigInteger.Negative(const Int: BigInteger): BigInteger; begin // Magnitude is not modified, so a shallow copy is enough! ShallowCopy(Int, Result); if Result.FSize <> 0 then Result.FSize := Result.FSize xor SignMask; end; class function BigInteger.Parse(const S: string; aBase : Integer): BigInteger; var TryResult: BigInteger; begin if TryParse(S, TryResult, aBase) then Result := TryResult else Error(ecParse, S); end; class function BigInteger.Pow(const ABase: BigInteger; AExponent: Integer): BigInteger; var Base: BigInteger; begin Base := ABase; Result := One; while AExponent > 0 do begin if Odd(AExponent) then Result := Result * Base; Base := Sqr(Base); AExponent := AExponent shr 1; end; end; class operator BigInteger.NotEqual(const Left, Right: BigInteger): Boolean; begin Result := Compare(Left, Right) <> 0; end; class procedure BigInteger.Octal; begin FBase := 8; end; class function BigInteger.Remainder(const Left: BigInteger; Right: UInt16): BigInteger; var LQuotient: TMagnitude; begin if Right = 0 then Error(ecDivByZero); Result.MakeSize(1); SetLength(LQuotient, (Left.FSize and SizeMask)); if not InternalDivMod32(PLimb(Left.FData), Right, PLimb(LQuotient), PLimb(Result.FData), (Left.FSize and SizeMask)) then Error(ecInvalidArg); Result.Compact; if Result.FSize <> 0 then Result.FSize := (Result.FSize and SizeMask) or SignBitOf(Left.FSize); end; class function BigInteger.Remainder(const Left: BigInteger; Right: UInt32): BigInteger; var LQuotient: TMagnitude; begin if Right = 0 then Error(ecDivByZero); Result.MakeSize(1); SetLength(LQuotient, (Left.FSize and SizeMask)); if not InternalDivMod32(PLimb(Left.FData), Right, PLimb(LQuotient), PLimb(Result.FData), (Left.FSize and SizeMask)) then Error(ecInvalidArg); Result.Compact; if Result.FSize <> 0 then Result.FSize := (Result.FSize and SizeMask) or SignBitOf(Left.FSize); end; class function BigInteger.Remainder(const Left, Right: BigInteger): BigInteger; var Quotient: BigInteger; LSize, RSize: Integer; begin if Right.FData = nil then Error(ecDivByZero); LSize := Left.FSize and SizeMask; RSize := Right.FSize and SizeMask; case InternalCompare(PLimb(Left.FData), PLimb(Right.FData), LSize, RSize) of -1: begin ShallowCopy(Left, Result); Exit; end; 0: begin ShallowCopy(Zero, Result); Exit; end; else begin if ShouldUseBurnikelZiegler(LSize, RSize) then DivModBurnikelZiegler(Left, Right, Quotient, Result) else DivModKnuth(Left, Right, Quotient, Result); // In Delphi, sign of remainder is sign of dividend. if Result.FSize <> 0 then Result.FSize := (Result.FSize and SizeMask) or SignBitOf(Left.FSize); end; end; end; function BigInteger.Remainder(const Other: BigInteger): PBigInteger; begin Result := @Self; Self := Self mod Other; end; class operator BigInteger.RightShift(const Value: BigInteger; Shift: Integer): BigInteger; // Note: this emulates two's complement, more or less like the bitwise operators. var LSize: Integer; ShiftOffset: Integer; RSize: Integer; P: PLimb; begin if Value.FData = nil then begin ShallowCopy(Zero, Result); Exit; end; if Value.FSize > 0 then begin LSize := (Value.FSize and SizeMask); ShiftOffset := Shift shr 5; RSize := LSize - ShiftOffset; if RSize <= 0 then begin ShallowCopy(Zero, Result); Exit; end; Shift := Shift and $1F; Result.MakeSize(RSize); if Shift > 0 then InternalShiftRight(PLimb(Value.FData) + ShiftOffset, PLimb(Result.FData), Shift, RSize) else CopyLimbs(PLimb(Value.FData) + ShiftOffset, PLimb(Result.FData), RSize); Result.Compact; end else begin //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // This branch had to be written out completely. Using any local BigInteger, even a hidden BigInteger (to do // // something like "Inc(Result);" a hidden BigInteger is allocated) will slow this down enormously. // // The mere presence of a BigInteger causes InitializeArray and FinalizeArray to be compiled in, // // and a hidden try-finally to be placed around the routine. // // Removing all local BigIntegers sped up this branch by a factor of 3 and the entire routine by a factor of 2. // // // // Original code: // // Result := MinusOne - ((MinusOne - Value) shr Shift); // // // // See: http://blogs.teamb.com/rudyvelthuis/2015/10/04/27826 // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// LSize := (Value.FSize and SizeMask); P := AllocLimbs(LSize); // try CopyLimbs(PLimb(Value.FData), P, LSize); InternalDecrement(P, LSize); while (LSize > 0) and (P[LSize - 1] = 0) do Dec(LSize); if LSize = 0 then begin ShallowCopy(MinusOne, Result); Exit; end; ShiftOffset := Shift shr 5; if ShiftOffset >= LSize then begin ShallowCopy(MinusOne, Result); Exit; end; Shift := Shift and $1F; Result.FSize := 0; Result.MakeSize(LSize - ShiftOffset); if Shift = 0 then CopyLimbs(P + ShiftOffset, PLimb(Result.FData), LSize - ShiftOffset) else BigInteger.InternalShiftRight(P + ShiftOffset, PLimb(Result.FData), Shift, LSize - ShiftOffset); // finally FreeMem(P); // end; Result.Compact; if Result.FData = nil then begin ShallowCopy(MinusOne, Result); Exit; end; InternalIncrement(PLimb(Result.FData), (Result.FSize and SizeMask)); Result.FSize := (Result.FSize and SizeMask) or SignMask; end; end; class operator BigInteger.Implicit(const Value: string): BigInteger; begin if not TryParse(Value, Result, FBase) then Error(ecParse, Value); end; class operator BigInteger.Explicit(const Int: BigInteger): Double; begin Result := Int.AsDouble; end; class operator BigInteger.Explicit(const ADouble: Double): BigInteger; begin Result.Create(ADouble); end; class operator BigInteger.Inc(const Int: BigInteger): BigInteger; begin if Int.FData = nil then begin ShallowCopy(One, Result); Exit; end; Result.FData := Copy(Int.FData); Result.FSize := Int.FSize; if Result.FSize > 0 then begin Result.EnsureSize((Result.FSize and SizeMask) + 1); InternalIncrement(PLimb(Result.FData), (Result.FSize and SizeMask)); end else InternalDecrement(PLimb(Result.FData), (Result.FSize and SizeMask)); Result.Compact; end; class operator BigInteger.Dec(const Int: BigInteger): BigInteger; begin if Int.FData = nil then begin ShallowCopy(MinusOne, Result); Exit; end; Result.FData := Copy(Int.FData); Result.FSize := Int.FSize; if Result.FSize < 0 then begin Result.EnsureSize((Result.FSize and SizeMask) + 1); InternalIncrement(PLimb(Result.FData), (Result.FSize and SizeMask)); end else InternalDecrement(PLimb(Result.FData), (Result.FSize and SizeMask)); Result.Compact; end; procedure BigInteger.FromString(const Value: string; aBase : Integer); begin if not TryParse(Value, Self, aBase) then begin Self.FData := nil; Self.FSize := 0; end; end; function BigInteger.Add(const Other: BigInteger): PBigInteger; var SelfSize, OtherSize: Integer; Comparison: TValueSign; begin Result := @Self; if Other.IsZero then Exit; if Self.IsZero then begin Self := Other; Exit; end; FData := Copy(FData); SelfSize := FSize and SizeMask; OtherSize := Other.FSize and SizeMask; if Self.IsNegative = Other.IsNegative then begin EnsureSize(IntMax(SelfSize, OtherSize) + 1); FInternalAdd(PLimb(Self.FData), PLimb(Other.FData), PLimb(Self.FData), SelfSize, OtherSize); end else begin // Different signs, so subtract. EnsureSize(IntMax(SelfSize, OtherSize)); Comparison := InternalCompare(PLimb(Self.FData), PLimb(Other.FData), (Self.FSize and SizeMask), (Other.FSize and SizeMask)); if Comparison = 0 then begin Self := Zero; Exit; end; if Comparison > 0 then begin FInternalSubtract(PLimb(Self.FData), PLimb(Other.FData), PLimb(Self.FData), SelfSize, OtherSize); end else begin FInternalSubtract(PLimb(Other.FData), PLimb(Self.FData), PLimb(Self.FData), OtherSize, SelfSize); Self.FSize := Self.FSize xor SignMask; end; end; Compact; end; class procedure BigInteger.AvoidPartialFlagsStall(Value: Boolean); {$IFDEF PUREPASCAL} begin FInternalAdd := InternalAddPurePascal; FInternalSubtract := InternalSubtractPurePascal; end; {$ELSE} begin FAvoidStall := Value; if Value then begin FInternalAdd := InternalAddModified; FInternalSubtract := InternalSubtractModified; end else begin FInternalAdd := InternalAddPlain; FInternalSubtract := InternalSubtractPlain; end; end; {$ENDIF} function BigInteger.Multiply(const Other: BigInteger): PBigInteger; begin Result := @Self; Self := Self * Other; end; procedure FlipBigIntegerBit(var B: BigInteger; Index: Integer); inline; begin B.FData := Copy(B.FData); B.EnsureSize(IntMax(Index shr 5 + 1, B.FSize and BigInteger.SizeMask)); B.FData[Index shr 5] := B.FData[Index shr 5] xor (1 shl (Index and $1F)); B.Compact; end; function BigInteger.TestBit(Index: Integer): Boolean; /////////////////////////////////////////////////////////////////////// // Two's complement semantics are required. // // // // Note: -A = not (A - 1) = not A + 1 // // // // Example, assuming 16 bit limbs, negating goes like follows: // // // // -$1234 5678 9ABC 0000 0000 -> $EDCB A987 6544 0000 0000 // // 0: 0000 -> FFFF + 1 // // 1: 0000 -> FFFF + 1 // // 2: 9ABC -> 6543 + 1 // // 3: 5678 -> A987 // // 4: 1234 -> EDCB // // // // So accessing limb 4 or 3: Data := not Data // // accessing limb 2, 1 or 0: Data := not Data + 1 // /////////////////////////////////////////////////////////////////////// var I: Integer; Mask: TLimb; Data: TLimb; begin if FData = nil then // Zero, so no bit set. Return False. Result := False else if Index >= BitLength then // Beyond bit length, so return sign Result := (FSize and SignMask) <> 0 else begin Mask := 1 shl (Index and $1F); Index := Index shr 5; Data := FData[Index]; // Emulate negation if this BigInteger is negative. // Not necessary if BigInteger is positive. if (FSize and SignMask) <> 0 then begin // -A = not A + 1. Data := not Data; // Wait with the + 1, see below. I := 0; // See if carry propagates from lowest limb to limb containing the bit. If so, increment Data. while (I <= Index) and (FData[I] = 0) do Inc(I); if Index <= I then Inc(Data); end; // Get the bit. Result := (Data and Mask) <> 0; end; end; function BigInteger.SetBit(Index: Integer): BigInteger; begin Result := Self; if not TestBit(Index) then FlipBigIntegerBit(Result, Index); end; function BigInteger.ClearBit(Index: Integer): BigInteger; begin Result := Self; if TestBit(Index) then FlipBigIntegerBit(Result, Index); end; function BigInteger.FlipBit(Index: Integer): BigInteger; begin Result := Self; FlipBigIntegerBit(Result, Index); end; class function BigInteger.NthRoot(const Radicand: BigInteger; Nth: Integer): BigInteger; // http://stackoverflow.com/a/32541958/95954 var Estimate, EstimateToNthPower, NewEstimateToNthPower, TwoToNthPower: BigInteger; AdditionalBit: Integer; begin if Radicand = BigInteger.One then Exit(BigInteger.One); if Nth = 0 then Exit(BigInteger.Zero); // Error: there is no zeroth root. if Nth = 1 then Exit(Radicand); TwoToNthPower := BigInteger.Pow(2, Nth); // First estimate. Very likely closer to final value than the original BigInteger.One. Estimate := BigInteger.One shl (Radicand.BitLength div Nth); // EstimateToNthPower is Estimate ^ Nth EstimateToNthPower := BigInteger.Pow(Estimate, Nth); // Shift Estimate right until Estimate ^ Nth >= Value. while EstimateToNthPower < Radicand do begin Estimate := Estimate shl 1; EstimateToNthPower := TwoToNthPower * EstimateToNthPower; end; // EstimateToNthPower is the lowest power of two such that EstimateToNthPower >= Value if EstimateToNthPower = Radicand then // Answer is a power of two. Exit(Estimate); // Estimate is highest power of two such that Estimate ^ Nth < Value Estimate := Estimate shr 1; AdditionalBit := Estimate.BitLength - 2; if AdditionalBit < 0 then Exit(Estimate); EstimateToNthPower := BigInteger.Pow(Estimate, Nth); // We already have the top bit. Now repeatedly add decreasingly significant bits and check if // that addition is not too much. If so, remove the bit again. while Radicand > EstimateToNthPower do begin Estimate := Estimate.SetBit(AdditionalBit); NewEstimateToNthPower := BigInteger.Pow(Estimate, Nth); if NewEstimateToNthPower > Radicand then // Did we add too much? If so, remove bit. Estimate := Estimate.ClearBit(AdditionalBit) else EstimateToNthPower := NewEstimateToNthPower; // Otherwise update EstimateToNthPower (= Estimate^Nth). Dec(AdditionalBit); if AdditionalBit < 0 then Break; end; // All bits covered, so we have our result. Result := Estimate; end; class procedure BigInteger.NthRootRemainder(const Radicand: BigInteger; Nth: Integer; var Root, Remainder: BigInteger); begin Root := NthRoot(Radicand, Nth); Remainder := Radicand - Pow(Root, Nth); end; class function BigInteger.Sqr(const Value: BigInteger): BigInteger; begin if (Value.FSize and SizeMask) < KaratsubaSqrThreshold then Result := Value * Value else Result := SqrKaratsuba(Value); end; class function BigInteger.Sqrt(const Radicand: BigInteger): BigInteger; var Estimate: BigInteger; AdditionalBit: Integer; EstimateSquared: BigInteger; Temp: BigInteger; begin if Radicand = BigInteger.One then Exit(BigInteger.One); if Radicand.IsNegative then raise EInvalidOp.Create(SSqrtBigInteger); Estimate := BigInteger.One shl ((Radicand.BitLength) shr 1); EstimateSquared := Sqr(Estimate); while EstimateSquared < Radicand do begin Estimate := Estimate shl 1; EstimateSquared := EstimateSquared shl 2; end; if EstimateSquared = Radicand then Exit(Estimate); Estimate := Estimate shr 1; EstimateSquared := EstimateSquared shr 2; AdditionalBit := Estimate.BitLength - 2; if AdditionalBit < 0 then Exit(Estimate); while Radicand > EstimateSquared do begin ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Instead of multiplying two large BigIntegers, i.e. (Estimate + 2 ^ AdditionalBit) ^ 2, we try to be clever: // // If A = Estimate; B = 2 ^ AdditionalBit then: // // sqr(A + B) = A*A + 2*A*B + B*B = sqrA + (A * 2 + B)*B, so // // Temp := EstimateSquared + (Estimate * 2 + 2 ^ AdditionalBit) * 2 ^ AdditionalBit // // Since 2 ^ AdditionalBit and the multiplication can be done with shifts, we finally get the following. // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Temp := Estimate shl 1; Temp := Temp.SetBit(AdditionalBit); Temp := Temp shl AdditionalBit + EstimateSquared; if Temp <= Radicand then begin ShallowCopy(Temp, EstimateSquared); Estimate := Estimate.SetBit(AdditionalBit); end; Dec(AdditionalBit); if AdditionalBit < 0 then Break; end; Result := Estimate; end; class procedure BigInteger.SqrtRemainder(const Radicand: BigInteger; var Root, Remainder: BigInteger); begin Root := Sqrt(Radicand); Remainder := Radicand - Root * Root; end; class procedure BigInteger.DivThreeHalvesByTwo(const LeftUpperMid, LeftLower, Right, RightUpper, RightLower: BigInteger; N: Integer; var Quotient, Remainder: BigInteger); var Q, R: BigInteger; begin Q := BigInteger.Zero; R := BigInteger.Zero; if (LeftUpperMid shr N) = RightUpper then begin Q := (BigInteger.One shl N) - BigInteger.One; R := LeftUpperMid - (RightUpper shl N) + RightUpper; end else DivTwoDigitsByOne(LeftUpperMid, RightUpper, N, Q, R); Quotient := Q; Remainder := ((R shl N) or LeftLower) - Q * RightLower; while Remainder < 0 do begin Dec(Quotient); Remainder := Remainder + Right; end; end; class procedure BigInteger.DivTwoDigitsByOne(const Left, Right: BigInteger; N: Integer; var Quotient, Remainder: BigInteger); var NIsOdd: Boolean; LeftCopy, RightCopy: BigInteger; HalfN: Integer; HalfMask: BigInteger; RightUpper, RightLower: BigInteger; QuotientUpper, QuotientLower: BigInteger; Quot, Rem: BigInteger; begin Quot := BigInteger.Zero; Rem := BigInteger.Zero; if N <= BigInteger.BurnikelZieglerThreshold * 32 then begin BigInteger.DivModKnuth(Left, Right, Quot, Rem); Quotient := Quot; Remainder := Rem; Exit; end; NIsOdd := Odd(N); if NIsOdd then begin LeftCopy := Left shl 1; RightCopy := Right shl 1; Inc(N); end else begin LeftCopy := Left; RightCopy := Right; end; HalfN := N shr 1; HalfMask := (BigInteger.One shl HalfN) - BigInteger.One; RightUpper := RightCopy shr HalfN; RightLower := RightCopy and HalfMask; DivThreeHalvesByTwo(LeftCopy shr N, (LeftCopy shr HalfN) and HalfMask, RightCopy, RightUpper, RightLower, HalfN, QuotientUpper, Rem); DivThreeHalvesByTwo(Rem, LeftCopy and HalfMask, RightCopy, RightUpper, RightLower, HalfN, QuotientLower, Rem); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // Grade school division, but with (very) large digits, dividing [a1,a2,a3,a4] by [b1,b2]: // // // // +----+----+----+----+ +----+----+ +----+ // // | a1 | a2 | a3 | a4 | / | b1 | b2 | = | q1 | DivideThreeHalvesByTwo(a1a2, a3, b1b2, n, q1, r1r2) // // +----+----+----+----+ +----+----+ +----+ // // +--------------+ | | // // | b1b2 * q1 | | | // // +--------------+ | | // // - ================ v | // // +----+----+----+ +----+----+ | +----+ // // | r1 | r2 | a4 | / | b1 | b2 | = | q2 | DivideThreeHalvesByTwo(r1r2, a4, b1b2, n, q1, r1r2) // // +----+----+----+ +----+----+ | +----+ // // +--------------+ | | // // | b1b2 * q2 | | | // // +--------------+ | | // // - ================ v v // // +----+----+ +----+----+ // // | r1 | r2 | | q1 | q2 | r1r2 = a1a2a3a4 mod b1b2, q1q2 = a1a2a3a4 div b1b2 // // +----+----+ +----+----+ , // // // // Note: in the diagram above, a1, b1, q1, r1 etc. are the most significant "digits" of their numbers. // // // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if NIsOdd then Rem := Rem shr 1; Remainder := Rem; Quotient := (QuotientUpper shl HalfN) or QuotientLower; end; class procedure BigInteger.InternalDivModBurnikelZiegler(const Left, Right: BigInteger; var Quotient, Remainder: BigInteger); var LCopy: BigInteger; N: Integer; DigitMask: BigInteger; LeftDigits: array of BigInteger; LeftDigitsIndex : Integer; QuotientDigit: BigInteger; begin LCopy := Left; N := Right.BitLength; DigitMask := (BigInteger.One shl N) - BigInteger.One; LeftDigitsIndex := 0; while not LCopy.IsZero do begin if LeftDigitsIndex=Length(LeftDigits) then SetLength(LeftDigits, LeftDigitsIndex+8); LeftDigits[LeftDigitsIndex] := LCopy and DigitMask; Inc(LeftDigitsIndex); LCopy := LCopy shr N; end; if (LeftDigitsIndex > 0) and (LeftDigits[LeftDigitsIndex-1] >= Right) then Remainder := BigInteger.Zero else begin Remainder := LeftDigits[LeftDigitsIndex-1]; Dec(LeftDigitsIndex); end; QuotientDigit := BigInteger.Zero; Quotient := BigInteger.Zero; while LeftDigitsIndex > 0 do begin DivTwoDigitsByOne((Remainder shl N) + LeftDigits[LeftDigitsIndex-1], Right, N, QuotientDigit, Remainder); Dec(LeftDigitsIndex); Quotient := (Quotient shl N) + QuotientDigit; end; end; class procedure BigInteger.DivModBurnikelZiegler(const Left, Right: BigInteger; var Quotient, Remainder: BigInteger); var Q, R: BigInteger; begin if Right.IsZero then raise Exception.Create('Division by zero') else if Right.IsNegative then begin DivModBurnikelZiegler(-Left, -Right, Q, R); Quotient := Q; Remainder := -R; Exit; end else if Left.IsNegative then begin DivModBurnikelZiegler(not Left, Right, Q, R); Quotient := not Q; Remainder := Right + not R; Exit; end else if Left.IsZero then begin Quotient := BigInteger.Zero; Remainder := BigInteger.Zero; Exit; end else begin InternalDivModBurnikelZiegler(Left, Right, Q, R); Quotient := Q; Remainder := R; Exit; end; end; end.
29.190855
172
0.530119
47c2fd0fe49fa3c0303aee70dfd892ecc57e2abe
33,577
pas
Pascal
Bitmaps2Video/EncoderClassWin/UBitmaps2Video.pas
atkins126/Bitmaps2Video
da0b24b51db6582ca93e6dbfb501e8df7290fb20
[ "Apache-2.0" ]
null
null
null
Bitmaps2Video/EncoderClassWin/UBitmaps2Video.pas
atkins126/Bitmaps2Video
da0b24b51db6582ca93e6dbfb501e8df7290fb20
[ "Apache-2.0" ]
null
null
null
Bitmaps2Video/EncoderClassWin/UBitmaps2Video.pas
atkins126/Bitmaps2Video
da0b24b51db6582ca93e6dbfb501e8df7290fb20
[ "Apache-2.0" ]
null
null
null
{ ***************************************************************************** This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. A copy of this licence is found in the root directory of this project in the file LICENCE.txt or alternatively 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. Version 0.2 Copyright 2020 Renate Schaaf ***************************************************************************** } unit UBitmaps2Video; interface uses Winapi.Windows, System.SysUtils, FFMpeg, VCL.Graphics, System.types, UTools, UFormats; type /// <summary> Libav-Scaling used if bitmapsize<>videosize </summary> TVideoScaling = (vsFastBilinear, vsBilinear, vsBiCubic, vsLanczos); /// <summary> Zoom algorithms, the higher the better and slower /// zoAAx2: Antialising factor 2 /// zoAAx4: Antialising factor 4 /// zoAAx6: Antialising factor 6 /// zoResample: "Bicubic" resampling, almost perfect but slow.</summary> TZoomOption = (zoAAx2, zoAAx4, zoAAx6, zoResample); const ScaleFunction: array [TVideoScaling] of integer = (SWS_FAST_BILINEAR, SWS_BILINEAR, SWS_BICUBIC, SWS_LANCZOS); FilterName: array [TVideoScaling] of string = ('Fast Bilinear', 'Bilinear', 'Bicubic', 'Lanczos'); type TVideoProgressEvent = procedure(Videotime: int64) of object; TBitmapEncoder = class private fWidth, fHeight, fRate: integer; fQuality: byte; fFilename: string; fFrameCount: integer; fVideoFrameCount, fVideoFrameStart: integer; fVideoScaling: TVideoScaling; fCodecId: TAVCodecId; fInputVideoTimebase: TAVRational; VideoPts, VideoDts: int64; oc: PAVFormatContext; stream: PAVStream; codec: PAVCodec; c: PAVCodecContext; yuvpic: PAVFrame; CodecSetup: TBaseCodecSetup; fOnProgress: TVideoProgressEvent; procedure encode(frame: PAVFrame; FromVideo: boolean); procedure BitmapToFrame(const bm: TBitmap); public /// <param name="filename"> Output filename. Extension picks the container format (.mp4 .avi .mkv ..) /// </param> /// <param name="Width"> Video size in pixels (multiples of 2)</param> /// <param name="Height"> Video size in pixels (multiples of 2)</param> /// <param name="FrameRate"> Frames per second (can be slightly off in the resulting file)</param> /// <param name="Quality"> Encoding quality, scale from 0 to 100. 0 gives marginally acceptable quality </param> /// <param name="CodecId"> (TAVCodecID see UFormats.pas) Identifier of the codec to use. AV_CODEC_ID_NONE picks the default codec for the file extension. </param> /// <param name="VideoScaling">Resample algo used if video size differs from bitmap size </param> constructor Create(const filename: string; Width, Height: integer; FrameRate: integer; Quality: byte; CodecId: TAVCodecId = AV_CODEC_ID_NONE; VideoScaling: TVideoScaling = vsFastBilinear); /// <summary> Use to resume work on a partially created video. All encoding, size and format settings will be read off the input file InFile. /// There are still some open problems with this routine.</summary> constructor CreateFromVideo(const InFilename, OutFilename: string; VideoScaling: TVideoScaling = vsFastBilinear); /// <summary> Turn a Bitmap into a movie frame. If the aspect ratio does not match the video's one, black borders will be added. </summary> /// <param name="bm"> Bitmap(TBitmap) to be fed to the video. Will be converted to pf32bit if not already </param> procedure AddFrame(const bm: TBitmap); /// <summary> Add an existing video to the video stream. It will be resized and reencoded with the current settings. /// The format of the video can be anything that VLC-player plays. </summary> procedure AddVideo(const VideoInput: string); /// <summary> Hold the last frame </summary> /// <param name="EffectTime"> Displaytime(integer) in ms </param> procedure Freeze(EffectTime: integer); /// <summary> Add a picture which is displayed for a certain time </summary> /// <param name="bm"> Bitmap(TBitmap) of the picture to be displayed </param> /// <param name="ShowTime"> Time(integer) in ms for the display </param> procedure AddStillImage(const bm: TBitmap; ShowTime: integer); /// <summary> Make a smooth transition from SourceR to TargetR within EffectTime.</summary> /// <param name="bm"> The Bitmap(TBitmap) to be animated </param> /// <param name="SourceR"> Beginning rectangle(TRectF) within rect(0,0,bm.width,bm.height) </param> /// <param name="TargetR"> End rectangle(TRectF) within rect(0,0,bm.width,bm.height) </param> /// <param name="EffectTime"> Duration(integer) of the animation in ms </param> /// <param name="ZoomOption"> Quality of the zoom (zoAAx2, zoAAx4, zoAAx6, zoResample). </param> /// <param name="SpeedEnvelope"> Modifies the speed during EffectTime. (zeFastSlow, zeSlowFast, zeSlowSlow, zeLinear) </param> procedure ZoomPan(const bm: TBitmap; SourceR, TargetR: TRectF; EffectTime: integer; ZoomOption: TZoomOption; SpeedEnvelope: TZoomSpeedEnvelope = zeLinear); /// <summary> Close the file and make the output file usable. </summary> procedure CloseFile; destructor Destroy; override; /// <summary> how many frames have been added to the movie so far </summary> property FrameCount: integer read fFrameCount; property VideoWidth: integer read fWidth; property VideoHeight: integer read fHeight; property FrameRate: integer read fRate; /// <summary> Frame count of the last video added, use for grabbing thumbnails or timing </summary> property LastVideoFrameCount: integer read fVideoFrameCount; /// <summary> Event which fires every second of video time while writing. Use it to update a progressbar etc.. </summary> property OnProgress: TVideoProgressEvent read fOnProgress write fOnProgress; // Application.Processmessages can be called safely in this event (I hope). // Audio must be added by muxing, see below // Threads: Seems to be threadsafe when an instance is not used across threads // Needs to be tested further // Canvas procedures must be protected by Lock/Unlock. end; /// <summary> Combine the video stream from VideoFile with the audio from Audiofile. The streams will just be copied, not encoded. /// Audio is clipped to video length. Raises exception if the format of the audio file is not supported.</summary> /// <param name="VideoFile"> (string) File which contains a video stream. Any audio stream present will be ignored. </param> /// <param name="AudioFile"> (string) Genuine audio file (.wav .mp3 .aac) the audio of which shall be added to the video in VideoFile. </param> /// <param name="OutputFile"> (string) Name of the file containing the newly combined video and audio. </param> procedure MuxStreams2(const VideoFile, AudioFile: string; const OutputFile: string); /// <summary> Returns the expected video size for the given Codec, Width, Height, Frame-rate and Quality. </summary> function VideoSizeInMB(Videotime: int64; CodecId: TAVCodecId; Width, Height, Rate: integer; Quality: byte): double; implementation uses VCL.Forms; { TBitmapEncoder } function VideoSizeInMB(Videotime: int64; CodecId: TAVCodecId; Width, Height, Rate: integer; Quality: byte): double; var Setup: TBaseCodecSetup; TimeSec: integer; begin TimeSec := Videotime div 1000; if CodecSetupClass(CodecId) = nil then begin Raise Exception.Create('Codec-Id is not supported'); exit; end; Setup := CodecSetupClass(CodecId).Create(CodecId); try result := 0.001 * 1 / 8 * 1 / 1024 * Setup.QualityToBitrate(Quality, Width, Height, Rate) * TimeSec; finally Setup.Free; end; end; procedure TBitmapEncoder.encode(frame: PAVFrame; FromVideo: boolean); var ret: integer; pkt: TAvPacket; begin inc(fFrameCount); if fFrameCount mod fRate = 0 then // update once per second if assigned(fOnProgress) then fOnProgress(fFrameCount * 1000 div fRate); av_init_packet(@pkt); pkt.data := nil; pkt.size := 0; if frame <> nil then begin frame.pts := fFrameCount; end; ret := avcodec_send_frame(c, frame); while ret >= 0 do begin ret := avcodec_receive_packet(c, @pkt); if (ret = AVERROR_EAGAIN) or (ret = AVERROR_EOF) then begin exit; end else if ret < 0 then begin Raise Exception.Create('Package read error'); exit; end; // Adjust the frame rate, now works if FromVideo then begin pkt.dts := VideoDts; pkt.pts := VideoPts; av_packet_rescale_ts(@pkt, fInputVideoTimebase, c.time_base); pkt.pts := fVideoFrameStart + pkt.pts; pkt.dts := fVideoFrameStart + pkt.dts; fFrameCount := pkt.dts; end else begin pkt.pts := fFrameCount; pkt.dts := fFrameCount; end; av_packet_rescale_ts(@pkt, c.time_base, stream.time_base); pkt.stream_index := stream.index; // Write the encoded frame to the video file. // Can fail without causing harm, but should be checked in the debugger if frames are missing ret := av_interleaved_write_frame(oc, @pkt); av_packet_unref(@pkt); end; end; procedure TBitmapEncoder.Freeze(EffectTime: integer); var frametime: double; time: double; begin frametime := 1000 / fRate; time := 0; while time < EffectTime do begin encode(yuvpic, False); time := time + frametime; end; end; procedure TBitmapEncoder.ZoomPan(const bm: TBitmap; SourceR, TargetR: TRectF; EffectTime: integer; ZoomOption: TZoomOption; SpeedEnvelope: TZoomSpeedEnvelope = zeLinear); var am, cm: TBitmap; fact, asp: double; aw, ah: integer; // antialiased width height elapsed: integer; src, trg, mid: TRectF; targetTime: integer; frametime, t: double; evf: TEnvelopeFunction; bw, bh: integer; begin evf := EnvelopeFunction[SpeedEnvelope]; bw := bm.Width; bh := bm.Height; am := TBitmap.Create; // Antialias bitmap try am.PixelFormat := pf32bit; ah := bm.Height; // suppress compiler warning case ZoomOption of zoAAx2: ah := 2 * 1080; // 2* my screen.height better setting? zoAAx4: ah := 4 * 1080; zoAAx6: ah := 6 * 1080; // 6*screen.height might give an EOutOfResources if there is no // suffiently large memory block available, less likely under Win64 zoResample: ah := bm.Height + 100; end; asp := bw / bh; aw := round(ah * asp); am.SetSize(aw, ah); // upscale nicely ZoomResampleTripleOnly(bm, am, Rect(0, 0, bw, bh), 1.8); fact := aw / bw; src := ScaleRect(SourceR, fact); trg := ScaleRect(TargetR, fact); // scale rects to antialias-size frametime := 1000 / fRate; elapsed := 0; targetTime := round(EffectTime - 0.5 * frametime); cm := TBitmap.Create; try cm.PixelFormat := pf32bit; cm.SetSize(bw, bh); cm.PixelFormat := pf32bit; while elapsed < targetTime do begin t := elapsed / EffectTime; mid := Interpolate(src, trg, evf(t)); case ZoomOption of zoAAx2, zoAAx4, zoAAx6: ZoomDeleteScansTripleOnly(am, cm, mid); zoResample: ZoomResampleTripleOnly(am, cm, mid, 1.6); // radius 1.6 is good enough end; // feed cm to the encoder AddFrame(cm); elapsed := round(elapsed + frametime); end; finally cm.Free; end; finally am.Free; end; end; procedure TBitmapEncoder.BitmapToFrame(const bm: TBitmap); var rgbpic: PAVFrame; convertCtx: PSwsContext; x, y: integer; ps: PRGBQuad; row: PByte; w, h, bps: integer; px, py: PByte; jump: integer; ret: integer; AspectDiffers: boolean; nw, nh: integer; cm: TBitmap; r: TRectF; r1: TRect; const Epsilon = 0.1; begin bm.PixelFormat := pf32bit; w := bm.Width; h := bm.Height; cm := TBitmap.Create; try AspectDiffers := abs(w / h - fWidth / fHeight) > Epsilon; if AspectDiffers then begin if w / h < fWidth / fHeight then // Add black left and right begin nh := h; nw := round(nh * fWidth / fHeight); end else // Add black top and bottom begin nw := w; nh := round(nw * fHeight / fWidth); end; cm.PixelFormat := pf32bit; cm.SetSize(nw, nh); r := RectF(0, 0, w, h); CenterRect(r, RectF(0, 0, nw, nh)); r1 := r.round; bm.Canvas.Lock; // in case this is in a thread cm.Canvas.Lock; BitBlt(cm.Canvas.Handle, 0, 0, nw, nh, 0, 0, 0, BLACKNESS); BitBlt(cm.Canvas.Handle, r1.Left, r1.Top, w, h, bm.Canvas.Handle, 0, 0, SRCCopy); cm.Canvas.Unlock; bm.Canvas.Unlock; w := nw; h := nh; end else cm.Assign(bm); // Set up conversion to YUV convertCtx := sws_getContext(w, h, AV_PIX_FMT_BGR24, fWidth, fHeight, c.pix_fmt, ScaleFunction[fVideoScaling], nil, nil, nil); // Video ignores the alpha-channel. Size will be scaled if necessary, // proportionality will now always be preserved assert(convertCtx <> nil); // Allocate storage for the rgb-frame rgbpic := av_frame_alloc(); assert(rgbpic <> nil); try rgbpic.Format := Ord(AV_PIX_FMT_BGR24); rgbpic.Width := w; rgbpic.Height := h; av_frame_get_buffer(rgbpic, 0); // Store the bm in the frame ret := av_frame_make_writable(rgbpic); assert(ret >= 0); row := cm.ScanLine[0]; bps := ((w * 32 + 31) and not 31) div 8; py := @PByte(rgbpic.data[0])[0]; // it's faster with pointers instead of array jump := rgbpic.linesize[0]; for y := 0 to h - 1 do begin ps := PRGBQuad(row); px := py; for x := 0 to w - 1 do begin PRGBTriple(px)^ := PRGBTriple(ps)^; // works with BGR24 format inc(px, 3); inc(ps); end; dec(row, bps); inc(py, jump); end; // Convert the rgb-frame to yuv-frame ret := av_frame_make_writable(yuvpic); assert(ret >= 0); ret := sws_scale(convertCtx, @rgbpic.data, @rgbpic.linesize, 0, h, @yuvpic.data, @yuvpic.linesize); assert(ret >= 0); finally sws_freeContext(convertCtx); av_frame_free(@rgbpic); // needs to be freed and recreated for each frame // since the bm's could have different dimensions end; finally cm.Free; end; end; procedure TBitmapEncoder.AddFrame(const bm: TBitmap); begin // Store the Bitmap in the yuv-frame BitmapToFrame(bm); // Encode the yuv-frame encode(yuvpic, False); end; procedure TBitmapEncoder.AddStillImage(const bm: TBitmap; ShowTime: integer); begin BitmapToFrame(bm); // Encode the yuv-frame repeatedly Freeze(ShowTime); end; procedure TBitmapEncoder.AddVideo(const VideoInput: string); var fmt_ctx: PAVFormatContext; video_dec_ctx: PAVCodecContext; Width, Height: integer; pix_fmt: TAVPixelFormat; video_stream_idx: integer; frame: PAVFrame; pkt: TAvPacket; ret: integer; got_frame: integer; video_dst_data: array [0 .. 3] of PByte; video_dst_linesize: array [0 .. 3] of integer; video_stream: PAVStream; convertCtx: PSwsContext; rgbpic: PAVFrame; x, y: integer; ps: PRGBQuad; row: PByte; px, py: PByte; jump: integer; bps: integer; bm: TBitmap; p: PPAVStream; AspectDiffers: boolean; const Epsilon = 0.1; begin assert(UpperCase(fFilename) <> UpperCase(VideoInput), 'Output file name must be different from input file name'); fmt_ctx := nil; video_dec_ctx := nil; frame := nil; rgbpic := nil; for x := 0 to 3 do video_dst_data[x] := nil; (* open input file, and allocate format context *) ret := avformat_open_input(@fmt_ctx, PAnsiChar(AnsiString(VideoInput)), nil, nil); assert(ret >= 0); (* retrieve stream information *) ret := avformat_find_stream_info(fmt_ctx, nil); assert(ret >= 0); open_decoder_context(@video_stream_idx, @video_dec_ctx, fmt_ctx, AVMEDIA_TYPE_VIDEO); p := fmt_ctx.streams; inc(p, video_stream_idx); video_stream := p^; fInputVideoTimebase := video_stream.time_base; (* allocate image where the decoded image will be put *) Width := video_dec_ctx.Width; Height := video_dec_ctx.Height; pix_fmt := video_dec_ctx.pix_fmt; ret := av_image_alloc(@video_dst_data[0], @video_dst_linesize[0], Width, Height, pix_fmt, 1); assert(ret >= 0); AspectDiffers := abs(fWidth / fHeight - Width / Height) > Epsilon; // If the aspect differs we convert to bitmap and copyrect to bitmap with black borders. if AspectDiffers then begin convertCtx := sws_getContext(Width, Height, pix_fmt, Width, Height, AV_PIX_FMT_BGR24, ScaleFunction[fVideoScaling], nil, nil, nil); // Allocate storage for the rgb-frame rgbpic := av_frame_alloc(); assert(rgbpic <> nil); rgbpic.Format := Ord(AV_PIX_FMT_BGR24); rgbpic.Width := Width; rgbpic.Height := Height; av_frame_get_buffer(rgbpic, 0); end else convertCtx := sws_getContext(Width, Height, pix_fmt, fWidth, fHeight, c.pix_fmt, ScaleFunction[fVideoScaling], nil, nil, nil); frame := av_frame_alloc(); assert(frame <> nil); try (* initialize packet, set data to NULL, let the demuxer fill it *) av_init_packet(@pkt); pkt.data := nil; pkt.size := 0; (* read frames from the file *) fVideoFrameStart := fFrameCount + 1; fVideoFrameCount := 0; while true do begin ret := av_read_frame(fmt_ctx, @pkt); if ret < 0 then break; if pkt.stream_index <> video_stream_idx then begin av_packet_unref(@pkt); Continue; end; (* decode video frame *) // !avcodec_decode_video2 is deprecated, but I couldn't get // the replacement avcode_send_packet and avcodec_receive_frame to work got_frame := 0; ret := avcodec_decode_video2(video_dec_ctx, frame, @got_frame, @pkt); assert(ret >= 0); // This is needed to give the frames the right decoding- and presentation- timestamps // see encode for FromVideo = true VideoPts := pkt.pts; VideoDts := pkt.dts; if VideoPts < VideoDts then VideoPts := VideoDts; // for different aspect store frame in bitamp if AspectDiffers then begin // Convert the yuv-frame to rgb-frame ret := av_frame_make_writable(rgbpic); assert(ret >= 0); ret := sws_scale(convertCtx, @frame.data, @frame.linesize, 0, Height, @rgbpic.data, @rgbpic.linesize); assert(ret >= 0); bm := TBitmap.Create; try bm.PixelFormat := pf32bit; bm.SetSize(Width, Height); row := bm.ScanLine[0]; bps := ((Width * 32 + 31) and not 31) div 8; py := @PByte(rgbpic.data[0])[0]; jump := rgbpic.linesize[0]; for y := 0 to Height - 1 do begin ps := PRGBQuad(row); px := py; for x := 0 to Width - 1 do begin PRGBTriple(ps)^ := PRGBTriple(px)^; inc(px, 3); inc(ps); end; dec(row, bps); inc(py, jump); end; BitmapToFrame(bm); finally bm.Free; end; end else begin // if aspect fits, scale the frame and change the pixel format, if necessary ret := av_frame_make_writable(yuvpic); assert(ret >= 0); ret := sws_scale(convertCtx, @frame.data, @frame.linesize, 0, Height, @yuvpic.data, @yuvpic.linesize); assert(ret >= 0); end; encode(yuvpic, true); inc(fVideoFrameCount); av_packet_unref(@pkt); end; // while true finally if assigned(rgbpic) then av_frame_free(@rgbpic); av_frame_free(@frame); avcodec_free_context(@video_dec_ctx); sws_freeContext(convertCtx); avformat_close_input(@fmt_ctx); end; end; procedure TBitmapEncoder.CloseFile; var ret: integer; begin // flush the encoder encode(nil, False); ret := av_write_trailer(oc); // Writing the end of the file. assert(ret >= 0); if ((oc.oformat.flags and AVFMT_NOFILE) = 0) then begin ret := avio_closep(@oc.pb); // Closing the file. assert(ret >= 0); end; ret := avcodec_close(stream.codec); assert(ret >= 0); end; constructor TBitmapEncoder.Create(const filename: string; Width, Height, FrameRate: integer; Quality: byte; CodecId: TAVCodecId = AV_CODEC_ID_NONE; VideoScaling: TVideoScaling = vsFastBilinear); var ret: integer; begin fFilename := filename; fWidth := Width; fHeight := Height; fRate := FrameRate; fQuality := Quality; fVideoScaling := VideoScaling; fFrameCount := 0; if CodecId = AV_CODEC_ID_NONE then fCodecId := PreferredCodec(ExtractFileExt(fFilename)) else fCodecId := CodecId; CodecSetup := CodecSetupClass(fCodecId).Create(fCodecId); oc := nil; ret := avformat_alloc_output_context2(@oc, nil, nil, PAnsiChar(AnsiString(filename))); assert(ret >= 0, 'avformat_alloc.. error' + inttostr(ret)); stream := avformat_new_stream(oc, nil); assert(stream <> nil, 'avformat_new_stream failed'); codec := CodecSetup.codec; assert(codec <> nil, 'codec not found'); c := avcodec_alloc_context3(codec); c.Width := fWidth; c.Height := fHeight; c.time_base.num := 1; c.time_base.den := fRate; c.FrameRate.num := fRate; c.FrameRate.den := 1; c.pix_fmt := CodecSetup.OutputPixelFormat; CodecSetup.CodecContextProps(c); c.bit_rate := CodecSetup.QualityToBitrate(fQuality, fWidth, fHeight, fRate); // c.bit_rate_tolerance := 0; Left at defaults. More research needed :) if (oc.oformat.flags and AVFMT_GLOBALHEADER) <> 0 then c.flags := c.flags or AV_CODEC_FLAG_GLOBAL_HEADER; ret := avcodec_open2(c, codec, @CodecSetup.OptionsDictionary); assert(ret >= 0); stream.time_base := c.time_base; ret := avcodec_parameters_from_context(stream.codecpar, c); // replaces avcodec_get_context_defaults3 assert(ret >= 0); ret := avio_open(@oc.pb, PAnsiChar(AnsiString(filename)), AVIO_FLAG_WRITE); assert(ret >= 0); ret := avformat_write_header(oc, @CodecSetup.OptionsDictionary); assert(ret >= 0); // Allocating memory for conversion output YUV frame: yuvpic := av_frame_alloc(); assert(yuvpic <> nil); yuvpic.Format := Ord(CodecSetup.OutputPixelFormat); yuvpic.Width := fWidth; yuvpic.Height := fHeight; ret := av_frame_get_buffer(yuvpic, 0); assert(ret >= 0); end; constructor TBitmapEncoder.CreateFromVideo(const InFilename, OutFilename: string; VideoScaling: TVideoScaling); var ret: integer; ifmt_ctx: PAVFormatContext; in_filename, out_filename: PAnsiChar; in_stream: PAVStream; in_codecpar: PAVCodecParameters; pkt, lastVideoPkt: TAvPacket; p: PPAVStream; numstreams, sn: Cardinal; begin fVideoScaling := VideoScaling; // The extension must match InputFile fFilename := ExtractFilePath(OutFilename) + ExtractFileName(OutFilename) + ExtractFileExt(InFilename); assert(UpperCase(fFilename) <> UpperCase(InFilename), 'Output file name must be different from input file name'); ifmt_ctx := nil; oc := nil; // Read the input video in_filename := PAnsiChar(AnsiString(InFilename)); ret := avformat_open_input(@ifmt_ctx, in_filename, nil, nil); assert(ret = 0, Format('Could not open input file ''%s''', [in_filename])); // Read Codec Info ret := avformat_find_stream_info(ifmt_ctx, nil); assert(ret = 0, 'Failed to retrieve input stream information'); numstreams := ifmt_ctx.nb_streams; // Create Output file with oc = global output context out_filename := PAnsiChar(AnsiString(fFilename)); avformat_alloc_output_context2(@oc, nil, nil, out_filename); assert(assigned(oc), 'Could not create output context'); // Copy codec parameters from InFile to OutFile // First find the first video-stream p := ifmt_ctx.streams; sn := 0; while (p^.codec.codec_type <> AVMEDIA_TYPE_VIDEO) and (sn < numstreams) do begin inc(p); inc(sn); end; assert(sn < numstreams, 'No video stream found in ' + InFilename); in_stream := p^; in_codecpar := in_stream.codecpar; stream := avformat_new_stream(oc, nil); assert(assigned(stream)); ret := avcodec_parameters_copy(stream.codecpar, in_codecpar); assert(ret = 0, 'Failed to copy codec parameters'); stream.codecpar^.codec_tag.tag := 0; stream.time_base.num := in_stream.time_base.num; stream.time_base.den := in_stream.time_base.den; // Read properties from InFile fWidth := in_codecpar.Width; fHeight := in_codecpar.Height; fCodecId := in_codecpar.codec_id; if CodecSetupClass(fCodecId) <> nil then CodecSetup := CodecSetupClass(fCodecId).Create(fCodecId) else Raise Exception.Create('Input video codec is not supported'); stream.codec.flags := in_stream.codec.flags; if (oc.oformat.flags and AVFMT_GLOBALHEADER) <> 0 then stream.codec.flags := stream.codec.flags or AV_CODEC_FLAG_GLOBAL_HEADER; if in_stream.avg_frame_rate.den > 0 then fRate := round(in_stream.avg_frame_rate.num / in_stream.avg_frame_rate.den) else fRate := in_stream.r_frame_rate.num; // Copy frames from input to output, keep track of framecount if (oc.oformat.flags and AVFMT_NOFILE) = 0 then begin ret := avio_open(@oc.pb, out_filename, AVIO_FLAG_WRITE); assert(ret = 0, Format('Could not open output file ''%s''', [out_filename])); end else Raise Exception.Create(Format('Could not open output file ''%s''', [out_filename])); ret := avformat_write_header(oc, nil); assert(ret = 0, 'Error occurred when opening output file'); fFrameCount := 0; while true do begin av_init_packet(@pkt); pkt.size := 0; pkt.data := nil; ret := av_read_frame(ifmt_ctx, @pkt); if ret < 0 then break; if (pkt.stream_index <> 0) then begin av_packet_unref(@pkt); Continue; end; pkt.stream_index := 0; (* copy packet *) // should not be necessary, the time bases are identical // rather keep it, avio_open can change the time base av_packet_rescale_ts(@pkt, in_stream.time_base, stream.time_base); lastVideoPkt := pkt; pkt.pos := -1; av_interleaved_write_frame(oc, @pkt); // inc(fFrameCount); av_packet_unref(@pkt); end; // Create encoding context and fill with codec info using c=global encoding context codec := CodecSetup.codec; assert(codec <> nil); c := avcodec_alloc_context3(codec); CodecSetup.CodecContextProps(c); // needed for the h264-Dictionary c.bit_rate := in_codecpar.bit_rate; c.codec_id := fCodecId; c.codec_type := AVMEDIA_TYPE_VIDEO; // c needs to have the real frame rate as time base // otherwise the encoding of a single frame fails // with error in av_receive_packet c.time_base.num := 1; c.time_base.den := fRate; c.FrameRate.num := fRate; c.FrameRate.den := 1; c.Width := fWidth; c.Height := fHeight; c.pix_fmt := in_stream.codec.pix_fmt; c.flags := in_stream.codec.flags; av_packet_rescale_ts(@lastVideoPkt, stream.time_base, c.time_base); fFrameCount := lastVideoPkt.dts; avformat_close_input(@ifmt_ctx); // if we set the global_header flag here, writing fails. { if (oc.oformat.flags and AVFMT_GLOBALHEADER) <> 0 then c.flags := c.flags or AV_CODEC_FLAG_GLOBAL_HEADER; } // make output file ready to receive new encoded frames ret := avcodec_open2(c, codec, @CodecSetup.OptionsDictionary); assert(ret >= 0); // Allocating memory for conversion output YUV frame: yuvpic := av_frame_alloc(); assert(yuvpic <> nil); yuvpic.Format := Ord(c.pix_fmt); yuvpic.Width := fWidth; yuvpic.Height := fHeight; ret := av_frame_get_buffer(yuvpic, 0); assert(ret >= 0); end; function FloatToFrac(x: double; acc: byte): string; var fact: integer; // acc not too large b: byte; num, den: integer; begin fact := 1; for b := 1 to acc do fact := 10 * fact; num := round(x * fact); den := fact; result := inttostr(num) + '/' + inttostr(den); end; procedure MuxStreams2(const VideoFile, AudioFile: string; const OutputFile: string); var ofmt: PAVOutputFormat; ifmt_ctx1, ifmt_ctx2, ofmt_ctx: PAVFormatContext; pkt: TAvPacket; in_filename1, in_filename2, out_filename: PAnsiChar; ret: integer; out_streamV, out_streamA: PAVStream; in_streamV, in_streamA: PAVStream; in_codecpar: PAVCodecParameters; Videotime, AudioTime: int64; p: PPAVStream; begin ifmt_ctx1 := nil; ifmt_ctx2 := nil; ofmt_ctx := nil; in_filename1 := PAnsiChar(AnsiString(VideoFile)); in_filename2 := PAnsiChar(AnsiString(AudioFile)); out_filename := PAnsiChar(AnsiString(OutputFile)); ret := avformat_open_input(@ifmt_ctx1, in_filename1, nil, nil); assert(ret = 0, Format('Could not open input file ''%s''', [in_filename1])); ret := avformat_open_input(@ifmt_ctx2, in_filename2, nil, nil); assert(ret = 0, Format('Could not open input file ''%s''', [in_filename2])); ret := avformat_find_stream_info(ifmt_ctx1, nil); assert(ret = 0, 'Failed to retrieve input stream information'); ret := avformat_find_stream_info(ifmt_ctx2, nil); assert(ret = 0, 'Failed to retrieve input stream information'); avformat_alloc_output_context2(@ofmt_ctx, nil, nil, out_filename); assert(assigned(ofmt_ctx), 'Could not create output context'); ofmt := ofmt_ctx.oformat; in_streamV := ifmt_ctx1.streams^; in_codecpar := in_streamV.codecpar; out_streamV := avformat_new_stream(ofmt_ctx, nil); assert(assigned(out_streamV)); ret := avcodec_parameters_copy(out_streamV.codecpar, in_codecpar); assert(ret = 0, 'Failed to copy codec parameters'); out_streamV.codecpar^.codec_tag.tag := 0; out_streamV.time_base.num := in_streamV.time_base.num; out_streamV.time_base.den := in_streamV.time_base.den; // Handle the audio stream from file 2 in_streamA := ifmt_ctx2.streams^; in_codecpar := in_streamA.codecpar; out_streamA := avformat_new_stream(ofmt_ctx, nil); assert(assigned(out_streamA)); ret := avcodec_parameters_copy(out_streamA.codecpar, in_codecpar); assert(ret = 0, 'Failed to copy codec parameters'); out_streamA.codecpar^.codec_tag.tag := 0; if (ofmt.flags and AVFMT_NOFILE) = 0 then begin ret := avio_open(@ofmt_ctx.pb, out_filename, AVIO_FLAG_WRITE); assert(ret = 0, Format('Could not open output file ''%s''', [out_filename])); end; ret := avformat_write_header(ofmt_ctx, nil); assert(ret = 0, 'Error occurred when opening output file'); p := ofmt_ctx.streams; out_streamV := p^; inc(p, 1); out_streamA := p^; AudioTime := 0; while true do begin ret := av_read_frame(ifmt_ctx1, @pkt); if ret < 0 then break; if (pkt.stream_index <> 0) then begin av_packet_unref(@pkt); Continue; end; pkt.stream_index := 0; // PPtrIdx(stream_mapping, pkt.stream_index); (* copy packet *) pkt.pts := av_rescale_q_rnd(pkt.pts, in_streamV.time_base, out_streamV.time_base, Ord(AV_ROUND_NEAR_INF) or Ord(AV_ROUND_PASS_MINMAX)); pkt.dts := av_rescale_q_rnd(pkt.dts, in_streamV.time_base, out_streamV.time_base, Ord(AV_ROUND_NEAR_INF) or Ord(AV_ROUND_PASS_MINMAX)); pkt.duration := av_rescale_q(pkt.duration, in_streamV.time_base, out_streamV.time_base); pkt.pos := -1; ret := av_interleaved_write_frame(ofmt_ctx, @pkt); assert(ret >= 0); Videotime := av_stream_get_end_pts(out_streamV); while AudioTime < Videotime do begin ret := av_read_frame(ifmt_ctx2, @pkt); if ret < 0 then break; if (pkt.stream_index <> 0) then begin av_packet_unref(@pkt); Continue; end; pkt.stream_index := 1; (* copy packet *) pkt.pts := av_rescale_q_rnd(pkt.pts, in_streamA.time_base, out_streamA.time_base, Ord(AV_ROUND_NEAR_INF) or Ord(AV_ROUND_PASS_MINMAX)); pkt.dts := av_rescale_q_rnd(pkt.dts, in_streamA.time_base, out_streamA.time_base, Ord(AV_ROUND_NEAR_INF) or Ord(AV_ROUND_PASS_MINMAX)); pkt.duration := av_rescale_q(pkt.duration, in_streamA.time_base, out_streamA.time_base); pkt.pos := -1; ret := av_interleaved_write_frame(ofmt_ctx, @pkt); assert(ret >= 0); av_packet_unref(@pkt); AudioTime := av_rescale_q(av_stream_get_end_pts(out_streamA), out_streamA.time_base, out_streamV.time_base); end; end; av_write_trailer(ofmt_ctx); avformat_close_input(@ifmt_ctx1); avformat_close_input(@ifmt_ctx2); (* close output *) if assigned(ofmt_ctx) and ((ofmt.flags and AVFMT_NOFILE) = 0) then avio_closep(@ofmt_ctx.pb); avformat_free_context(ofmt_ctx); assert((ret >= 0) or (ret = AVERROR_EOF)); end; destructor TBitmapEncoder.Destroy; begin CodecSetup.Free; av_frame_free(@yuvpic); avformat_free_context(oc); avcodec_free_context(@c); inherited; end; end.
31.947669
166
0.669982
f1de8ef1ee4f736c098baf2f7e40247e66bd8714
34,321
pas
Pascal
Packages/IconFontsImageListEditorUnit.pas
edwinyzh/IconFontsImageList
0484b95e480d391ddf9bf719dc77a01a5a79a6e5
[ "Apache-2.0" ]
null
null
null
Packages/IconFontsImageListEditorUnit.pas
edwinyzh/IconFontsImageList
0484b95e480d391ddf9bf719dc77a01a5a79a6e5
[ "Apache-2.0" ]
null
null
null
Packages/IconFontsImageListEditorUnit.pas
edwinyzh/IconFontsImageList
0484b95e480d391ddf9bf719dc77a01a5a79a6e5
[ "Apache-2.0" ]
null
null
null
{******************************************************************************} { } { Icon Fonts ImageList: An extended ImageList for Delphi } { to simplify use of Icons (resize, colors and more...) } { } { Copyright (c) 2019-2022 (Ethea S.r.l.) } { Contributors: } { Carlo Barazzetta } { Nicola Tambascia } { } { https://github.com/EtheaDev/IconFontsImageList } { } {******************************************************************************} { } { 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 IconFontsImageListEditorUnit; interface {$INCLUDE ..\Source\IconFontsImageList.inc} uses Windows , Messages , SysUtils , Graphics , Forms , StdCtrls , ExtCtrls , Controls , Classes , Dialogs , ComCtrls , ImgList , ExtDlgs , Spin , IconFontsCharMapUnit , IconFontsImageList , IconFontsImageListBase , IconFontsVirtualImageList , IconFontsImageCollection , IconFontsItems , IconFontsImage; type TIconFontsImageListEditor = class(TForm) paImages: TPanel; CategorySplitter: TSplitter; Panel1: TPanel; SetCategoriesButton: TButton; ImagesPanel: TPanel; CategoryGroupBox: TGroupBox; CategoryListBox: TListBox; PropertiesGroupBox: TGroupBox; ImageListGroup: TGroupBox; ImageView: TListView; AddButton: TButton; DeleteButton: TButton; ClearAllButton: TButton; ExportButton: TButton; WinCharMapButton: TButton; ShowCharMapButton: TButton; DefaultFontNameLabel: TLabel; DefaultFontName: TComboBox; DefaultFontColorLabel: TLabel; DefaultFontColorColorBox: TColorBox; DefaultMaskColorLabel: TLabel; DefaultMaskColorColorBox: TColorBox; StoreBitmapCheckBox: TCheckBox; BottomPanel: TPanel; OKButton: TButton; ApplyButton: TButton; CancelButton: TButton; HelpButton: TButton; ImageListGroupBox: TGroupBox; SizeLabel: TLabel; WidthLabel: TLabel; HeightLabel: TLabel; SizeSpinEdit: TSpinEdit; WidthSpinEdit: TSpinEdit; HeightSpinEdit: TSpinEdit; BottomSplitter: TSplitter; ItemGroupBox: TGroupBox; LeftIconPanel: TPanel; IconPanel: TPanel; IconImage: TIconFontImage; IconClientPanel: TPanel; IconBuilderGroupBox: TGroupBox; FromHexNumLabel: TLabel; ToHexNumLabel: TLabel; CharsEditLabel: TLabel; CharsEdit: TEdit; BuildButton: TButton; BuildFromHexButton: TButton; FromHexNum: TEdit; ToHexNum: TEdit; FontNameLabel: TLabel; FontName: TComboBox; FontIconHexLabel: TLabel; FontIconHex: TEdit; FontIconDecLabel: TLabel; FontIconDec: TSpinEdit; FontColorLabel: TLabel; FontColor: TColorBox; MaskColorLabel: TLabel; MaskColor: TColorBox; NameLabel: TLabel; NameEdit: TEdit; CategoryLabel: TLabel; CategoryEdit: TEdit; IconLeftMarginPanel: TPanel; ZoomLabel: TLabel; ZoomSpinEdit: TSpinEdit; procedure FormCreate(Sender: TObject); procedure ApplyButtonClick(Sender: TObject); procedure ClearAllButtonClick(Sender: TObject); procedure DeleteButtonClick(Sender: TObject); procedure AddButtonClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FontColorChange(Sender: TObject); procedure MaskColorChange(Sender: TObject); procedure HelpButtonClick(Sender: TObject); procedure FontNameChange(Sender: TObject); procedure NameEditExit(Sender: TObject); procedure FontIconDecChange(Sender: TObject); procedure ShowCharMapButtonClick(Sender: TObject); procedure ImageViewSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BuildButtonClick(Sender: TObject); procedure SizeSpinEditChange(Sender: TObject); procedure StoreBitmapCheckBoxClick(Sender: TObject); procedure DefaultFontColorColorBoxChange(Sender: TObject); procedure DefaultMaskColorColorBoxChange(Sender: TObject); procedure BuildFromHexButtonClick(Sender: TObject); procedure EditChangeUpdateGUI(Sender: TObject); procedure ImageViewKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ExportButtonClick(Sender: TObject); procedure DefaultFontNameSelect(Sender: TObject); procedure FontIconHexExit(Sender: TObject); procedure FormShow(Sender: TObject); procedure ImageViewDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure ImageViewDragDrop(Sender, Source: TObject; X, Y: Integer); procedure WidthSpinEditChange(Sender: TObject); procedure HeightSpinEditChange(Sender: TObject); procedure WinCharMapButtonClick(Sender: TObject); procedure CategoryListBoxClick(Sender: TObject); procedure SetCategoriesButtonClick(Sender: TObject); procedure CategoryEditExit(Sender: TObject); procedure ZoomSpinEditChange(Sender: TObject); private FSelectedCategory: string; FSourceList, FEditingList: TIconFontsImageListBase; FCharMap: TIconFontsCharMapForm; FIconIndexLabel: string; FTotIconsLabel: string; FUpdating: Boolean; FChanged: Boolean; FModified: Boolean; procedure IconFontsImageListFontMissing(const AFontName: TFontName); procedure CloseCharMap(Sender: TObject; var Action: TCloseAction); procedure BuildList(Selected: Integer); procedure AddColor(const S: string); procedure UpdateCategories; procedure UpdateSizeGUI; procedure AddNewItem; procedure DeleteSelectedItem; procedure Apply; procedure UpdateGUI; procedure UpdateCharsToBuild; {$IFNDEF GDI+} procedure SetImageMaskColor(Color: TColor); {$ENDIF} procedure SetImageFontColor(Color: TColor); procedure SetImageFontIconDec(IconDec: Integer); procedure SetImageFontIconHex(IconHex: String); procedure SetImageIconName(Name: String); procedure SetImageFontName(FontName: TFontName); function SelectedIcon: TIconFontItem; procedure InitGUI; public destructor Destroy; override; property Modified: Boolean read FModified; property IconFontsImageList: TIconFontsImageListBase read FEditingList; end; function EditIconFontsImageList(const AImageList: TIconFontsImageListBase): Boolean; function EditIconFontsVirtualImageList(const AImageList: TIconFontsVirtualImageList): Boolean; function EditIconFontsImageCollection(const AImageCollection: TIconFontsImageCollection): Boolean; implementation {$R *.dfm} uses CommCtrl {$WARN UNIT_PLATFORM OFF} , FileCtrl , TypInfo , ShellApi {$IFDEF DXE3+} , UITypes , System.Types , System.Character {$ENDIF} //WARNING: you must define this directive to use this unit outside the IDE {$IFNDEF UseIconFontEditorsAtRunTime} {$IF (CompilerVersion >= 24.0)} , Vcl.Themes , ToolsAPI {$IFEND} {$IF (CompilerVersion >= 32.0)} , IDETheme.Utils , BrandingAPI {$IFEND} {$ENDIF} , IconFontsUtils; const crColorPick = -100; var SavedBounds: TRect = (Left: 0; Top: 0; Right: 0; Bottom: 0); function EditIconFontsImageList(const AImageList: TIconFontsImageListBase): Boolean; var LEditor: TIconFontsImageListEditor; begin LEditor := TIconFontsImageListEditor.Create(nil); with LEditor do begin try Screen.Cursor := crHourglass; try FSourceList := AImageList; FEditinglist.Assign(AImageList); InitGUI; finally Screen.Cursor := crDefault; end; Result := ShowModal = mrOk; if Result then begin Screen.Cursor := crHourglass; try AImageList.Assign(FEditingList); finally Screen.Cursor := crDefault; end; end; SavedBounds := BoundsRect; finally Free; end; end; end; function EditIconFontsVirtualImageList(const AImageList: TIconFontsVirtualImageList): Boolean; var LEditor: TIconFontsImageListEditor; begin if AImageList.ImageCollection = nil then begin Result := false; Exit; end; LEditor := TIconFontsImageListEditor.Create(nil); with LEditor do begin try Screen.Cursor := crHourglass; try FSourceList := TIconFontsImageList.Create(LEditor); FSourceList.Assign(AImageList); FEditingList.Assign(AImageList); InitGUI; finally Screen.Cursor := crDefault; end; Result := ShowModal = mrOk; if Result then begin Screen.Cursor := crHourglass; try AImageList.ImageCollection.IconFontItems.Assign(LEditor.FEditingList.IconFontItems); AImageList.Assign(LEditor.FEditingList); finally Screen.Cursor := crDefault; end; end; SavedBounds := BoundsRect; finally Free; end; end; end; function EditIconFontsImageCollection(const AImageCollection: TIconFontsImageCollection): Boolean; var LEditor: TIconFontsImageListEditor; begin LEditor := TIconFontsImageListEditor.Create(nil); with LEditor do begin try Screen.Cursor := crHourglass; try FSourceList := TIconFontsImageList.Create(LEditor); FSourceList.IconFontItems.Assign(AImageCollection.IconFontItems); FSourceList.Size := 64; //Force 64 pixel size for image collection icons FSourceList.FontName := AImageCollection.FontName; FSourceList.FontColor := AImageCollection.FontColor; FSourceList.MaskColor := AImageCollection.MaskColor; FSourceList.Zoom := AImageCollection.Zoom; ImageListGroupBox.Visible := False; FSourceList.IconFontItems.Assign(AImageCollection.IconFontItems); FEditingList.Assign(FSourceList); InitGUI; finally Screen.Cursor := crDefault; end; Result := ShowModal = mrOk; if Result then begin Screen.Cursor := crHourglass; try AImageCollection.IconFontItems.Assign(LEditor.FEditingList.IconFontItems); AImageCollection.FontName := DefaultFontName.Text; AImageCollection.FontColor := DefaultFontColorColorBox.Selected; AImageCollection.MaskColor := DefaultMaskColorColorBox.Selected; AImageCollection.Zoom := ZoomSpinEdit.Value; finally Screen.Cursor := crDefault; end; end; SavedBounds := BoundsRect; finally Free; end; end; end; { TIconFontsImageListEditor } procedure TIconFontsImageListEditor.UpdateSizeGUI; begin WidthSpinEdit.Value := FEditingList.Width; HeightSpinEdit.Value := FEditingList.Height; SizeSpinEdit.Value := FEditingList.Size; if FEditingList.Width = FEditingList.Height then begin SizeSpinEdit.Enabled := True; IconPanel.Align := alClient; end else begin SizeSpinEdit.Enabled := False; if FEditingList.Width > FEditingList.Height then begin IconPanel.Align := alTop; IconPanel.Height := Round(IconPanel.Width * FEditingList.Height / FEditingList.Width); end else begin IconPanel.Align := alLeft; IconPanel.Height := Round(IconPanel.Height * FEditingList.Width / FEditingList.Height); end; end; end; procedure TIconFontsImageListEditor.HelpButtonClick(Sender: TObject); begin ShellExecute(handle, 'open', PChar('https://github.com/EtheaDev/IconFontsImageList/wiki/Component-Editor-(VCL)'), nil, nil, SW_SHOWNORMAL) end; {$IFNDEF GDI+} procedure TIconFontsImageListEditor.SetImageMaskColor(Color: TColor); begin SelectedIcon.MaskColor := Color; UpdateGUI; end; {$ENDIF} procedure TIconFontsImageListEditor.ShowCharMapButtonClick(Sender: TObject); begin ShowCharMapButton.SetFocus; if not Assigned(FCharMap) then begin FCharMap := TIconFontsCharMapForm.CreateForImageList(Self, FEditingList, FontName.Text); FCharMap.OnClose := CloseCharMap; end; FCharMap.AssignImageList(FEditingList, FontName.Text); FCharMap.Show; end; procedure TIconFontsImageListEditor.StoreBitmapCheckBoxClick(Sender: TObject); begin {$IFDEF HasStoreBitmapProperty} FEditingList.StoreBitmap := StoreBitmapCheckBox.Checked; FChanged := True; {$ENDIF} end; procedure TIconFontsImageListEditor.SetImageFontColor(Color: TColor); begin SelectedIcon.FontColor := Color; UpdateGUI; end; procedure TIconFontsImageListEditor.SetImageFontIconDec(IconDec: Integer); begin SelectedIcon.FontIconDec := IconDec; BuildList(SelectedIcon.Index); end; procedure TIconFontsImageListEditor.SetImageFontIconHex(IconHex: String); begin SelectedIcon.FontIconHex := IconHex; BuildList(SelectedIcon.Index); end; procedure TIconFontsImageListEditor.SetImageIconName(Name: String); begin SelectedIcon.Name := Name; BuildList(SelectedIcon.Index); end; procedure TIconFontsImageListEditor.SetImageFontName(FontName: TFontName); begin SelectedIcon.FontName := FontName; BuildList(SelectedIcon.Index); end; procedure TIconFontsImageListEditor.FontColorChange(Sender: TObject); begin if FUpdating then Exit; SetImageFontColor(FontColor.Selected); end; procedure TIconFontsImageListEditor.FontIconDecChange(Sender: TObject); begin if FUpdating then Exit; SetImageFontIconDec(FontIconDec.Value); end; procedure TIconFontsImageListEditor.FontIconHexExit(Sender: TObject); var LText: string; begin if FUpdating then Exit; LText := (Sender as TEdit).Text; if (Length(LText) = 4) or (Length(LText) = 5) or (Length(LText)=0) then begin if Sender = FontIconHex then SetImageFontIconHex(FontIconHex.Text); end; end; procedure TIconFontsImageListEditor.FontNameChange(Sender: TObject); begin if FUpdating then Exit; if (FontName.Text = '') or (Screen.Fonts.IndexOf(FontName.Text) >= 0) then begin SetImageFontName(FontName.Text); UpdateCharsToBuild; end; end; procedure TIconFontsImageListEditor.UpdateCharsToBuild; begin CharsEdit.Font.Size := 12; if FontName.Text <> '' then begin CharsEdit.Font.Name := FontName.Text; CharsEdit.Enabled := True; end else if DefaultFontName.Text <> '' then begin CharsEdit.Font.Name := DefaultFontName.Text; CharsEdit.Enabled := True; end else begin CharsEdit.Enabled := False; BuildButton.Enabled := False; end; end; procedure TIconFontsImageListEditor.UpdateCategories; var I: Integer; LCategory: string; begin CategoryListBox.Items.Clear; CategoryListBox.AddItem('All', nil); for I := 0 to FEditingList.IconFontItems.Count -1 do begin LCategory := FEditingList.IconFontItems[I].Category; if (LCategory <> '') and (CategoryListBox.Items.IndexOf(LCategory)<0) then CategoryListBox.AddItem(LCategory,nil); end; if (FSelectedCategory <> '') then begin I := CategoryListBox.Items.IndexOf(FSelectedCategory); if I >= 0 then CategoryListBox.Selected[I] := True; end else CategoryListBox.Selected[0] := True; end; procedure TIconFontsImageListEditor.UpdateGUI; var LIsItemSelected: Boolean; LItemFontName: TFontName; LIconFontItem: TIconFontItem; begin FUpdating := True; try UpdateCategories; LIconFontItem := SelectedIcon; LIsItemSelected := LIconFontItem <> nil; ClearAllButton.Enabled := FEditingList.Count > 0; ExportButton.Enabled := FEditingList.Count > 0; BuildButton.Enabled := CharsEdit.Text <> ''; BuildFromHexButton.Enabled := (Length(FromHexNum.Text) in [4,5]) and (Length(ToHexNum.Text) in [4,5]); DeleteButton.Enabled := LIsItemSelected; SetCategoriesButton.Enabled := LIsItemSelected; ApplyButton.Enabled := FChanged; FontColor.Enabled := LIsItemSelected; MaskColor.Enabled := LIsItemSelected; FontName.Enabled := LIsItemSelected; FontIconDec.Enabled := LIsItemSelected; FontIconHex.Enabled := LIsItemSelected; NameEdit.Enabled := LIsItemSelected; CategoryEdit.Enabled := LIsItemSelected; ShowCharMapButton.Enabled := (FEditingList.FontName <> ''); ImageListGroup.Caption := Format(FTotIconsLabel, [FEditingList.Count]); if LIsItemSelected then begin IconImage.ImageIndex := SelectedIcon.Index; ItemGroupBox.Caption := Format(FIconIndexLabel,[LIconFontItem.Index]); {$IFNDEF GDI+} if LIconFontItem.MaskColor <> FEditingList.MaskColor then MaskColor.Selected := LIconFontItem.MaskColor else MaskColor.Selected := clNone; {$ELSE} MaskColor.Selected := clNone; MaskColor.Enabled := False; {$ENDIF} if LIconFontItem.FontColor <> FEditingList.FontColor then FontColor.Selected := LIconFontItem.FontColor else FontColor.Selected := clDefault; LItemFontName := LIconFontItem.FontName; FontName.ItemIndex := FontName.Items.IndexOf(LItemFontName); NameEdit.Text := LIconFontItem.Name; CategoryEdit.Text := LIconFontItem.Category; FontIconDec.Value := LIconFontItem.FontIconDec; FontIconHex.Text := LIconFontItem.FontIconHex; IconPanel.Invalidate; //Draw Icon IconImage.Invalidate; end else begin FontColor.Selected := clDefault; MaskColor.Selected := clNone; FontName.ItemIndex := -1; IconImage.ImageIndex := -1; ItemGroupBox.Caption := ''; NameEdit.Text := ''; CategoryEdit.Text := ''; FontIconDec.Value := 0; FontIconHex.Text := ''; end; finally FUpdating := False; end; end; procedure TIconFontsImageListEditor.WidthSpinEditChange(Sender: TObject); begin if FUpdating then Exit; FEditingList.Width := WidthSpinEdit.Value; UpdateSizeGUI; end; procedure TIconFontsImageListEditor.WinCharMapButtonClick(Sender: TObject); begin WinCharMapButton.SetFocus; ShellExecute(Handle, 'open', 'charmap', '', '', SW_SHOWNORMAL); end; procedure TIconFontsImageListEditor.ZoomSpinEditChange(Sender: TObject); begin FEditingList.Zoom := ZoomSpinEdit.Value; IconImage.Zoom := ZoomSpinEdit.Value; FChanged := True; UpdateGUI; end; procedure TIconFontsImageListEditor.ImageViewDragDrop(Sender, Source: TObject; X, Y: Integer); var LTargetItem: TListItem; LItem: TCollectionItem; SIndex, DIndex: Integer; begin LTargetItem := ImageView.GetItemAt(X, Y); if not Assigned(LTargetItem) then LTargetItem := ImageView.GetNearestItem(Point(X, Y), sdRight); if Assigned(LTargetItem) then DIndex := LTargetItem.ImageIndex else DIndex := ImageView.Items.Count - 1; SIndex := ImageView.Items[ImageView.ItemIndex].ImageIndex; LItem := FEditingList.IconFontItems[SIndex]; LItem.Index := DIndex; BuildList(LItem.Index); if SIndex <> DIndex then FChanged := True; end; procedure TIconFontsImageListEditor.ImageViewDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin Accept := Source = Sender; end; procedure TIconFontsImageListEditor.DeleteSelectedItem; var LSelectedImageIndex: Integer; begin LSelectedImageIndex := ImageView.Items[ImageView.Selected.Index].ImageIndex; FEditingList.Delete(ImageView.Selected.Index); FChanged := True; BuildList(LSelectedImageIndex); FChanged := True; end; destructor TIconFontsImageListEditor.Destroy; begin FCharMap.Free; inherited; end; procedure TIconFontsImageListEditor.CategoryListBoxClick(Sender: TObject); var LIndex: Integer; begin if SelectedIcon <> nil then LIndex := SelectedIcon.Index else LIndex := -1; if CategoryListBox.ItemIndex <= 0 then FSelectedCategory := '' else FSelectedCategory := CategoryListBox.Items[CategoryListBox.ItemIndex]; BuildList(LIndex); end; procedure TIconFontsImageListEditor.CloseCharMap(Sender: TObject; var Action: TCloseAction); var LImageIndex: Integer; LIconFontItem: TIconFontItem; begin if FCharMap.ModalResult = mrOK then begin if FCharMap.CharsEdit.Text <> '' then begin FEditingList.AddIcons(FCharMap.CharsEdit.Text, FCharMap.DefaultFontName.Text); FChanged := True; LImageIndex := ImageView.Items.Count-1; if LImageIndex >= 0 then BuildList(ImageView.Items[LImageIndex].ImageIndex) else BuildList(-1); end else if FCharMap.SelectedIconFont <> nil then begin LIconFontItem := FEditingList.AddIcon(FCharMap.SelectedIconFont.FontIconDec); FChanged := True; BuildList(LIconFontItem.Index); end; end; end; procedure TIconFontsImageListEditor.ClearAllButtonClick(Sender: TObject); begin Screen.Cursor := crHourGlass; try ImageView.Clear; FEditingList.ClearIcons; FChanged := True; UpdateGUI; finally Screen.Cursor := crDefault; end; end; procedure TIconFontsImageListEditor.IconFontsImageListFontMissing( const AFontName: TFontName); begin MessageDlg(Format(ERR_ICONFONTS_FONT_NOT_INSTALLED,[AFontName]), mtError, [mbOK], 0); end; procedure TIconFontsImageListEditor.NameEditExit(Sender: TObject); begin if FUpdating then Exit; SetImageIconName(NameEdit.Text); UpdateGUI; end; procedure TIconFontsImageListEditor.ImageViewKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_INSERT) and (Shift = []) then AddNewItem else if (Key = VK_DELETE) and (Shift = []) then DeleteSelectedItem; end; function TIconFontsImageListEditor.SelectedIcon: TIconFontItem; begin if (ImageView.Selected <> nil) and (ImageView.Selected.Index < FEditingList.IconFontItems.Count) then Result := FEditingList.IconFontItems[ImageView.Selected.ImageIndex] else Result := nil; end; procedure TIconFontsImageListEditor.SetCategoriesButtonClick(Sender: TObject); var LIndex: Integer; Selected: Integer; LIconFontItem: TIconFontItem; LCategoryName: string; begin LCategoryName := InputBox('Set Category', 'Name', FSelectedCategory); if (LCategoryName = FSelectedCategory) then Exit; Screen.Cursor := crHourGlass; try FSelectedCategory := LCategoryName; Selected := ImageView.ItemIndex; FEditingList.StopDrawing(True); try for LIndex := ImageView.Items.Count - 1 downto 0 do begin if ImageView.Items[LIndex].Selected then begin LIconFontItem := FEditingList.IconFontItems[ImageView.Items[LIndex].ImageIndex]; LIconFontItem.Category := FSelectedCategory; end; end; finally FEditingList.StopDrawing(False); end; FChanged := True; BuildList(Selected); finally Screen.Cursor := crDefault; end; end; procedure TIconFontsImageListEditor.ImageViewSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin if Selected then UpdateGUI; end; procedure TIconFontsImageListEditor.InitGUI; begin SizeSpinEdit.Value := FEditinglist.Size; DefaultFontName.ItemIndex := DefaultFontName.Items.IndexOf(FEditingList.FontName); DefaultFontColorColorBox.Selected := FEditingList.FontColor; {$IFNDEF GDI+} DefaultMaskColorColorBox.Selected := FEditingList.MaskColor; {$ELSE} DefaultMaskColorColorBox.Enabled := False; {$ENDIF} {$IFDEF HasStoreBitmapProperty} StoreBitmapCheckBox.Checked := FEditingList.StoreBitmap; {$endif} ZoomSpinEdit.Value := FEditingList.Zoom; IconImage.Zoom := FEditingList.Zoom; BuildList(0); UpdateCharsToBuild; end; procedure TIconFontsImageListEditor.SizeSpinEditChange(Sender: TObject); begin if FUpdating then Exit; if FEditingList.Width = FEditingList.Height then FEditingList.Size := SizeSpinEdit.Value; FChanged := True; UpdateSizeGUI; end; procedure TIconFontsImageListEditor.BuildList(Selected: Integer); begin UpdateIconFontListView(ImageView, FSelectedCategory); if Selected < -1 then Selected := -1 else if (Selected = -1) and (ImageView.Items.Count > 0) then Selected := 0 else if Selected >= ImageView.Items.Count then Selected := ImageView.Items.Count - 1; ImageView.ItemIndex := Selected; if (FSelectedCategory <> '') and (SelectedIcon <> nil) and (SelectedIcon.Category <> FSelectedCategory) then begin FSelectedCategory := SelectedIcon.Category; BuildList(SelectedIcon.Index); end else UpdateGUI; end; procedure TIconFontsImageListEditor.DefaultFontColorColorBoxChange( Sender: TObject); begin FEditingList.FontColor := DefaultFontColorColorBox.Selected; FChanged := True; UpdateGUI; end; procedure TIconFontsImageListEditor.DefaultFontNameSelect(Sender: TObject); begin FEditingList.FontName := DefaultFontName.Text; FChanged := True; UpdateCharsToBuild; UpdateGUI; end; procedure TIconFontsImageListEditor.DefaultMaskColorColorBoxChange( Sender: TObject); begin FEditingList.MaskColor := DefaultMaskColorColorBox.Selected; FChanged := True; UpdateGUI; end; procedure TIconFontsImageListEditor.DeleteButtonClick(Sender: TObject); begin DeleteSelectedItem; end; procedure TIconFontsImageListEditor.MaskColorChange(Sender: TObject); begin {$IFNDEF GDI+} if FUpdating then Exit; SetImageMaskColor(MaskColor.Selected); {$ENDIF} end; procedure TIconFontsImageListEditor.FormClose(Sender: TObject; var Action: TCloseAction); begin if ModalResult = mrOK then OKButton.SetFocus else CancelButton.SetFocus; end; procedure TIconFontsImageListEditor.FormCreate(Sender: TObject); {$IFNDEF UseIconFontEditorsAtRunTime} {$IF (CompilerVersion >= 32.0)} var LStyle: TCustomStyleServices; {$IFEND} {$ENDIF} procedure InitColorBox(AColorBox: TColorBox; AColor: TColor); begin {$IFDEF UNICODE} AColorBox.Style := [cbStandardColors, cbExtendedColors, cbSystemColors, cbIncludeNone, cbIncludeDefault, cbCustomColor, cbCustomColors, cbPrettyNames]; {$ENDIF} AColorBox.Selected := AColor; end; begin {$IFNDEF UseIconFontEditorsAtRunTime} {$IF (CompilerVersion >= 32.0)} {$IF (CompilerVersion <= 34.0)} if UseThemeFont then Self.Font.Assign(GetThemeFont); {$IFEND} {$IF CompilerVersion > 34.0} if TIDEThemeMetrics.Font.Enabled then Self.Font.Assign(TIDEThemeMetrics.Font.GetFont); {$IFEND} if ThemeProperties <> nil then begin LStyle := ThemeProperties.StyleServices; StyleElements := StyleElements - [seClient]; Color := LStyle.GetSystemColor(clWindow); BottomPanel.StyleElements := BottomPanel.StyleElements - [seClient]; BottomPanel.ParentBackground := False; BottomPanel.Color := LStyle.GetSystemColor(clBtnFace); IDEThemeManager.RegisterFormClass(TIconFontsImageListEditor); ThemeProperties.ApplyTheme(Self); end; {$IFEND} {$ENDIF} {$IF (CompilerVersion >= 24.0)} CategoryListBox.AlignWithMargins := True; CategoryListBox.Margins.Top := 6; ImageView.AlignWithMargins := True; ImageView.Margins.Top := 6; IconPanel.AlignWithMargins := True; IconPanel.Margins.Top := 6; {$IFEND} {$IFNDEF UNICODE} CharsEditLabel.Visible := False; CharsEdit.Visible := False; BuildButton.Visible := False; IconBuilderGroupBox.Height := IconBuilderGroupBox.Height - BuildButton.Height -4; FontIconHex.MaxLength := 4; ExportButton.Visible := False; {$ENDIF} InitColorBox(DefaultFontColorColorBox, clDefault); InitColorBox(DefaultMaskColorColorBox, clNone); InitColorBox(FontColor, clDefault); InitColorBox(MaskColor, clNone); Caption := Format(Caption, [IconFontsImageListVersion]); FUpdating := True; FEditingList := TIconFontsImageList.Create(nil); ImageView.LargeImages := FEditingList; IconImage.ImageList := FEditingList; FEditingList.OnFontMissing := IconFontsImageListFontMissing; GetColorValues(AddColor); FontColor.ItemIndex := -1; MaskColor.ItemIndex := -1; FontName.Items := Screen.Fonts; DefaultFontName.Items := Screen.Fonts; FIconIndexLabel := ItemGroupBox.Caption; FTotIconsLabel := ImageListGroup.Caption; FChanged := False; FModified := False; {$IFNDEF HasStoreBitmapProperty} StoreBitmapCheckBox.Visible := False; {$ENDIF} end; procedure TIconFontsImageListEditor.Apply; begin if not FChanged then Exit; Screen.Cursor := crHourGlass; try FSourceList.StopDrawing(True); Try FSourceList.Assign(FEditingList); FChanged := False; FModified := True; Finally FSourceList.StopDrawing(False); FSourceList.RedrawImages; End; finally Screen.Cursor := crDefault; end; end; procedure TIconFontsImageListEditor.FormDestroy(Sender: TObject); begin FreeAndNil(FEditingList); Screen.Cursors[crColorPick] := 0; end; procedure TIconFontsImageListEditor.FormShow(Sender: TObject); begin UpdateSizeGUI; {$IFDEF DXE8+} if SavedBounds.Right - SavedBounds.Left > 0 then SetBounds(SavedBounds.Left, SavedBounds.Top, SavedBounds.Width, SavedBounds.Height); {$ELSE} if SavedBounds.Right - SavedBounds.Left > 0 then SetBounds(SavedBounds.Left, SavedBounds.Top, SavedBounds.Right-SavedBounds.Left, SavedBounds.Bottom-SavedBounds.Top); {$ENDIF} if ImageView.CanFocus then ImageView.SetFocus; end; procedure TIconFontsImageListEditor.EditChangeUpdateGUI(Sender: TObject); begin UpdateGUI; end; procedure TIconFontsImageListEditor.ExportButtonClick(Sender: TObject); var LFolder: string; LCount: Integer; begin LFolder := ExtractFileDrive(Application.ExeName); if SelectDirectory(LFolder, [sdAllowCreate, sdPerformCreate, sdPrompt], 0) then begin Screen.Cursor := crHourGlass; try LCount := FEditingList.SaveToPngFiles(LFolder); finally Screen.Cursor := crDefault; end; MessageDlg(Format(MSG_ICONS_EXPORTED, [LCount, LFolder]), mtInformation, [mbOK], 0); end; end; procedure TIconFontsImageListEditor.AddButtonClick(Sender: TObject); begin AddNewItem; end; procedure TIconFontsImageListEditor.CategoryEditExit(Sender: TObject); begin if FUpdating then Exit; if SelectedIcon.Category <> CategoryEdit.Text then begin SelectedIcon.Category := CategoryEdit.Text; if FSelectedCategory <> SelectedIcon.Category then begin FSelectedCategory := SelectedIcon.Category; UpdateCategories; BuildList(SelectedIcon.Index); end else UpdateIconFontListViewCaptions(ImageView); end; end; procedure TIconFontsImageListEditor.AddNewItem; var LInsertIndex: Integer; begin if (ImageView.Selected <> nil) then LInsertIndex := ImageView.Selected.Index +1 else LInsertIndex := ImageView.Items.Count; ImageView.Selected := nil; FEditingList.IconFontItems.Insert(LInsertIndex); FChanged := True; BuildList(LInsertIndex); end; procedure TIconFontsImageListEditor.ApplyButtonClick(Sender: TObject); begin Apply; UpdateGUI; end; procedure TIconFontsImageListEditor.AddColor(const S: string); begin FontColor.Items.Add(S); MaskColor.Items.Add(S); end; procedure TIconFontsImageListEditor.HeightSpinEditChange(Sender: TObject); begin if FUpdating then Exit; FEditingList.Height := HeightSpinEdit.Value; UpdateSizeGUI; end; procedure TIconFontsImageListEditor.BuildButtonClick(Sender: TObject); begin {$IFDEF UNICODE} FEditingList.AddIcons(CharsEdit.Text); FChanged := True; BuildList(ImageView.Items[ImageView.Items.Count-1].ImageIndex); {$ENDIF} end; procedure TIconFontsImageListEditor.BuildFromHexButtonClick(Sender: TObject); begin Screen.Cursor := crHourGlass; try FEditingList.AddIcons( StrToInt('$' + FromHexNum.Text), //From Chr StrToInt('$' + ToHexNum.Text), //To Chr FontName.Text ); FChanged := True; if ImageView.Items.Count > 0 then BuildList(ImageView.Items[ImageView.Items.Count-1].ImageIndex) else BuildList(0); finally Screen.Cursor := crDefault; end; end; end.
30.480462
111
0.679642
47243c6f16f1158d038b6f7163e2dcb87c957a34
3,228
pas
Pascal
source/DesignPatterns/Fido.Gui.Fmx.DesignPatterns.Observer.Anon.pas
atkins126/FidoLib
219fb0e1b78599251248971234ddac0913c912b1
[ "MIT" ]
27
2021-09-26T18:14:51.000Z
2022-01-04T09:26:42.000Z
source/DesignPatterns/Fido.Gui.Fmx.DesignPatterns.Observer.Anon.pas
atkins126/FidoLib
219fb0e1b78599251248971234ddac0913c912b1
[ "MIT" ]
5
2021-11-08T19:20:29.000Z
2022-01-29T18:50:23.000Z
source/DesignPatterns/Fido.Gui.Fmx.DesignPatterns.Observer.Anon.pas
atkins126/FidoLib
219fb0e1b78599251248971234ddac0913c912b1
[ "MIT" ]
7
2021-09-26T17:30:40.000Z
2022-02-14T02:19:05.000Z
(* * Copyright 2021 Mirko Bianco (email: writetomirko@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *) unit Fido.Gui.Fmx.DesignPatterns.Observer.Anon; interface uses System.SysUtils, System.Classes, Fmx.Forms, Spring, Spring.Collections, Fido.Utilities, Fido.DesignPatterns.Observer.Intf, Fido.DesignPatterns.Observer.Notification.Intf, Fido.Gui.Types, Fido.Gui.Fmx.NotifyEvent.Delegated; type TAnonObserver<T: class> = class(TInterfacedObject, IObserver) strict private class var FObservers: IList<Iobserver>; strict private FTarget: Weak<T>; FNotifyProc: TProc<T, INotification>; public class constructor Create; class destructor Destroy; constructor Create(const Target: T; const NotifyProc: TProc<T, INotification>; const Form: TForm = nil); // IObserver procedure Notify(const Sender: IInterface; const Notification: INotification); end; TAnonSyncObserver<T: class> = class(TAnonObserver<T>, ISyncObserver); implementation { TAnonObserver<T> } constructor TAnonObserver<T>.Create( const Target: T; const NotifyProc: TProc<T, INotification>; const Form: TForm); var LForm: TForm; begin FTarget := Utilities.CheckNotNullAndSet<T>(Target, 'Target'); FNotifyProc := Utilities.CheckNotNullAndSet<TProc<T, INotification>>(NotifyProc, 'NotifyProc'); FObservers.Add(Self); if (Target as TObject).InheritsFrom(TComponent) and (Target as TComponent).Owner.InheritsFrom(TForm) then LForm := (Target as TComponent).Owner as TForm else LForm := Form; if Assigned(LForm) then DelegatedNotifyEvent.Setup( LForm, LForm, 'OnDestroy', procedure(Sender: TObject) begin FObservers.Remove(Self); Self := nil; end, oeetAfter); end; class destructor TAnonObserver<T>.Destroy; begin FObservers := nil; end; class constructor TAnonObserver<T>.Create; begin FObservers := TCollections.CreateList<Iobserver>; end; procedure TAnonObserver<T>.Notify( const Sender: IInterface; const Notification: INotification); var Target: T; begin if FTarget.TryGetTarget(Target) then FNotifyProc(Target, Notification); end; end.
27.355932
108
0.736369
85f4584ff3978090973d80f4d163dc7cea22fe38
135
pas
Pascal
examples/a.pas
zengljnwpu/yaspc
5e85efb5fb8bee02471814b10e950dfb5b04c5d5
[ "MIT" ]
null
null
null
examples/a.pas
zengljnwpu/yaspc
5e85efb5fb8bee02471814b10e950dfb5b04c5d5
[ "MIT" ]
null
null
null
examples/a.pas
zengljnwpu/yaspc
5e85efb5fb8bee02471814b10e950dfb5b04c5d5
[ "MIT" ]
null
null
null
program programsasasa; var i: integer; function foo(i: integer):integer; begin foo := i+1; end; begin i := foo(2); writeln(i); end.
12.272727
33
0.674074
47cfbe6a42a52ae1029fa0235688076e16d1b1ba
183
dpr
Pascal
KBuch.dpr
Matt-17/KBuch
a8f8d6f97d394117c230100d970e95db4a9a14a7
[ "MIT" ]
null
null
null
KBuch.dpr
Matt-17/KBuch
a8f8d6f97d394117c230100d970e95db4a9a14a7
[ "MIT" ]
null
null
null
KBuch.dpr
Matt-17/KBuch
a8f8d6f97d394117c230100d970e95db4a9a14a7
[ "MIT" ]
null
null
null
program KBuch; uses Forms, Main in 'Main.pas' {Form1}; {$R *.res} begin Application.Initialize; Application.CreateForm(TForm1, Form1); Application.Run; end.
13.071429
41
0.644809
47d0225957716fa0eca8ee951a664f9a26ab20f9
6,702
pas
Pascal
src/umrulist.pas
flutomax/ChladniPlate2
5684464979da9a6990874f3a9007d8791e12843c
[ "Zlib" ]
4
2022-02-16T15:49:50.000Z
2022-02-17T07:25:57.000Z
src/umrulist.pas
flutomax/ChladniPlate2
5684464979da9a6990874f3a9007d8791e12843c
[ "Zlib" ]
null
null
null
src/umrulist.pas
flutomax/ChladniPlate2
5684464979da9a6990874f3a9007d8791e12843c
[ "Zlib" ]
null
null
null
{ This file is part of the ChladniPlate2. See LICENSE.txt for more info. Copyright (c) 2022 by Vasily Makarov } unit uMRUList; {$mode objfpc}{$H+} interface uses Classes, Controls, SysUtils, Graphics, Menus, IniFiles, FileCtrl, Forms, ExtCtrls, ImgList; type TRecentMenuItem = class(TMenuItem) private fFileName: string; public property FileName: string read fFileName; end; TRecentMenuItemClass = class of TRecentMenuItem; TOnRecentFileEvent = procedure(Sender: TObject; const aFileName: string) of object; { TMRUList } TMRUList = class(TComponent) private fRecent: TStrings; fMaxRecent: integer; fMIRecent: TMenuItem; fTopSepar: TMenuItem; fBotSepar: TMenuItem; fMinimizeWidth: integer; fOnRecent: TOnRecentFileEvent; function CreateMenuItem(aOwner: TComponent): TRecentMenuItem; function CreateMenuCaption(aIndex: integer; const aFileName: string): string; procedure DoOnRecentClick(Sender: TObject); procedure SetMaxRecent(AValue: integer); procedure SetTopSepar(const aValue: TMenuItem); procedure SetBotSepar(const aValue: TMenuItem); procedure SetMIRecent(const aValue: TMenuItem); procedure SetRecent(const aValue: TStrings); protected procedure Loaded; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Clear; procedure AddToRecent(const aFileName: string); procedure RemoveFromRecent(const aFileName: string); procedure UpdateRecentFiles; procedure LoadFromIni(Ini: TCustomIniFile; const aSection: string); procedure SaveToIni(Ini: TCustomIniFile; const aSection: string); published property MaxRecent: integer read fMaxRecent write SetMaxRecent default 10; property MinimizeWidth: integer read fMinimizeWidth write fMinimizeWidth default 200; property MIRecent: TMenuItem read fMIRecent write SetMIRecent; property TopSepar: TMenuItem read fTopSepar write SetTopSepar; property BotSepar: TMenuItem read fBotSepar write SetBotSepar; property OnRecent: TOnRecentFileEvent read fOnRecent write fOnRecent; end; implementation const KeyMaxRecent = 'MaxRecent'; KeyCount = 'Count'; KeyFile = 'File%d'; { TMRUList } constructor TMRUList.Create(AOwner: TComponent); begin inherited Create(AOwner); fRecent := TStringList.Create; fMaxRecent := 10; fMinimizeWidth := 200; end; destructor TMRUList.Destroy; begin FreeAndNil(fRecent); inherited Destroy; end; procedure TMRUList.Clear; begin fRecent.Clear; UpdateRecentFiles; end; procedure TMRUList.UpdateRecentFiles; var i, a, b, n: integer; m: TRecentMenuItem; begin if (not Assigned(fMIRecent)) or (not Assigned(fTopSepar)) or (not Assigned(fBotSepar)) then exit; a := fMIRecent.IndexOf(fTopSepar) + 1; b := fMIRecent.IndexOf(fBotSepar) - 1; for i := b downto a do fMIRecent.Delete(i); n := 0; for i := 0 to fRecent.Count - 1 do begin m := CreateMenuItem(self.Owner); m.Caption := CreateMenuCaption(i, fRecent[i]); m.fFileName := fRecent[i]; m.OnClick := @DoOnRecentClick; fMIRecent.Insert(a + i, m); Inc(n); end; fBotSepar.Visible := n > 0; end; procedure TMRUList.AddToRecent(const aFileName: string); var i: integer; s: string; begin s := ExpandFileName(aFileName); i := fRecent.IndexOf(s); if i > -1 then begin if i > 0 then fRecent.Exchange(0, i); end else begin while fRecent.Count >= fMaxRecent do fRecent.Delete(fRecent.Count - 1); fRecent.Insert(0, s); end; UpdateRecentFiles; end; procedure TMRUList.RemoveFromRecent(const aFileName: string); var i: integer; begin i := fRecent.IndexOf(ExpandFileName(aFileName)); if i > -1 then fRecent.Delete(i); end; procedure TMRUList.LoadFromIni(Ini: TCustomIniFile; const aSection: string); var i, c: integer; s: string; begin fRecent.Clear; fMaxRecent := Ini.ReadInteger(aSection, KeyMaxRecent, 10); c := Ini.ReadInteger(aSection, KeyCount, 0); for i := 1 to c do begin s := Ini.ReadString(aSection, Format(KeyFile, [i]), ''); if s <> '' then fRecent.Add(s); end; end; procedure TMRUList.SaveToIni(Ini: TCustomIniFile; const aSection: string); var i: integer; begin Ini.EraseSection(aSection); Ini.WriteInteger(aSection, KeyMaxRecent, fMaxRecent); Ini.WriteInteger(aSection, KeyCount, fRecent.Count); for i := 0 to fRecent.Count - 1 do Ini.WriteString(aSection, Format(KeyFile, [i + 1]), fRecent[i]); Ini.UpdateFile; end; function TMRUList.CreateMenuItem(aOwner: TComponent): TRecentMenuItem; begin Result := TRecentMenuItem.Create(aOwner); end; function TMRUList.CreateMenuCaption(aIndex: integer; const aFileName: string): string; begin if (fMinimizeWidth > 0) and Assigned(Application.MainForm) then Result := Format('%d. %s', [aIndex + 1, MiniMizeName(aFileName, Application.MainForm.Canvas, fMinimizeWidth)]) else Result := Format('%d. %s', [aIndex + 1, aFileName]); end; procedure TMRUList.DoOnRecentClick(Sender: TObject); var s: string; begin if Assigned(Sender) and (Sender is TRecentMenuItem) then s := (Sender as TRecentMenuItem).FileName; if (s <> '') and Assigned(fOnRecent) then fOnRecent(self, s); end; procedure TMRUList.SetMaxRecent(AValue: integer); var i: integer; begin if fMaxRecent = AValue then Exit; fMaxRecent := AValue; for i := fRecent.Count - 1 downto fMaxRecent do fRecent.Delete(i); UpdateRecentFiles; end; procedure TMRUList.SetTopSepar(const aValue: TMenuItem); begin if fTopSepar = aValue then exit; if Assigned(fTopSepar) then fTopSepar.RemoveFreeNotification(Self); fTopSepar := aValue; if Assigned(fTopSepar) then fTopSepar.FreeNotification(Self); UpdateRecentFiles; end; procedure TMRUList.SetBotSepar(const aValue: TMenuItem); begin if fBotSepar = aValue then exit; if Assigned(fBotSepar) then fBotSepar.RemoveFreeNotification(Self); fBotSepar := aValue; if Assigned(fBotSepar) then fBotSepar.FreeNotification(Self); UpdateRecentFiles; end; procedure TMRUList.SetMIRecent(const aValue: TMenuItem); begin if fMIRecent = aValue then exit; if Assigned(fMIRecent) then fMIRecent.RemoveFreeNotification(Self); fMIRecent := aValue; if Assigned(fMIRecent) then fMIRecent.FreeNotification(Self); UpdateRecentFiles; end; procedure TMRUList.SetRecent(const aValue: TStrings); begin if fRecent = aValue then exit; fRecent.Assign(aValue); UpdateRecentFiles; end; procedure TMRUList.Loaded; begin inherited Loaded; if (fRecent.Count > 0) and Assigned(fMIRecent) then UpdateRecentFiles; end; end.
24.639706
89
0.723665
f11d8a643ce757a0c2d7e6181d5d8e3558927993
328
dfm
Pascal
LeeCurvas.dfm
hsuderow/Scanning-Tunneling-Spectroscopy
ddf208a369f66a3218cebff42731ed5bb8e6ee8d
[ "CC0-1.0" ]
null
null
null
LeeCurvas.dfm
hsuderow/Scanning-Tunneling-Spectroscopy
ddf208a369f66a3218cebff42731ed5bb8e6ee8d
[ "CC0-1.0" ]
null
null
null
LeeCurvas.dfm
hsuderow/Scanning-Tunneling-Spectroscopy
ddf208a369f66a3218cebff42731ed5bb8e6ee8d
[ "CC0-1.0" ]
null
null
null
object Form1: TForm1 Left = 357 Top = 145 Width = 696 Height = 480 Caption = 'Form1' Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False PixelsPerInch = 96 TextHeight = 13 end
19.294118
33
0.637195